glances_processlist.py 19.4 KB
Newer Older
A
Alessio Sergi 已提交
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
A
Alessio Sergi 已提交
4
#
5
# Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com>
A
Alessio Sergi 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

A
PEP 257  
Alessio Sergi 已提交
20 21
"""Process list plugin."""

N
Nicolas Hennion 已提交
22
# Import sys libs
23
import operator
24
import os
A
Alessio Sergi 已提交
25 26
from datetime import timedelta

N
Nicolas Hennion 已提交
27
# Import Glances libs
A
Alessio Sergi 已提交
28 29
from glances.core.glances_globals import is_windows
from glances.core.glances_processes import glances_processes
A
Alessio Sergi 已提交
30
from glances.plugins.glances_plugin import GlancesPlugin
A
Alessio Sergi 已提交
31

D
desbma 已提交
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46
def convert_timedelta(delta):
    """Convert timedelta to human-readable time."""
    # Python 2.7+:
    # total_seconds = delta.total_seconds()
    # hours = total_seconds // 3600
    days, total_seconds = delta.days, delta.seconds
    hours = days * 24 + total_seconds // 3600
    minutes = (total_seconds % 3600) // 60
    seconds = str(total_seconds % 60).zfill(2)
    microseconds = str(delta.microseconds)[:2].zfill(2)

    return hours, minutes, seconds, microseconds


A
Alessio Sergi 已提交
47
class Plugin(GlancesPlugin):
A
PEP 257  
Alessio Sergi 已提交
48 49

    """Glances' processes plugin.
A
Alessio Sergi 已提交
50 51 52 53

    stats is a list
    """

54
    def __init__(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
55
        """Init the plugin."""
56
        GlancesPlugin.__init__(self, args=args)
A
Alessio Sergi 已提交
57 58 59 60

        # We want to display the stat in the curse interface
        self.display_curse = True

61 62 63
        # Trying to display proc time
        self.tag_proc_time = True

64
        # Note: 'glances_processes' is already init in the glances_processes.py script
65

66
    def get_key(self):
A
PEP 257  
Alessio Sergi 已提交
67
        """Return the key of the list."""
68 69
        return 'pid'

70
    def reset(self):
A
PEP 257  
Alessio Sergi 已提交
71
        """Reset/init the stats."""
72
        self.stats = []
73 74

    def update(self):
A
PEP 257  
Alessio Sergi 已提交
75
        """Update processes stats using the input method."""
76 77
        # Reset stats
        self.reset()
78

79
        if self.input_method == 'local':
80 81 82
            # Update stats using the standard system lib
            # Note: Update is done in the processcount plugin
            # Just return the processes list
83
            if glances_processes.is_tree_enabled():
D
desbma 已提交
84 85 86
                self.stats = glances_processes.gettree()
            else:
                self.stats = glances_processes.getlist()
87
        elif self.input_method == 'snmp':
N
Nicolargo 已提交
88
            # No SNMP grab for processes
89
            pass
90

91
        return self.stats
92

93
    def get_process_tree_curses_data(self, node, args, first_level=True, max_node_count=None):
A
PEP 257  
Alessio Sergi 已提交
94
        """Get curses data to display for a process tree."""
D
desbma 已提交
95
        ret = []
96
        node_count = 0
N
nicolargo 已提交
97
        if not node.is_root and ((max_node_count is None) or (max_node_count > 0)):
D
desbma 已提交
98
            node_data = self.get_process_curses_data(node.stats, False, args)
99
            node_count += 1
D
desbma 已提交
100
            ret.extend(node_data)
A
Alessio Sergi 已提交
101
        for child in node.iter_children():
102
            # stop if we have enough nodes to display
N
nicolargo 已提交
103
            if max_node_count is not None and node_count >= max_node_count:
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
                break

            if max_node_count is None:
                children_max_node_count = None
            else:
                children_max_node_count = max_node_count - node_count
            child_data = self.get_process_tree_curses_data(child,
                                                           args,
                                                           first_level=node.is_root,
                                                           max_node_count=children_max_node_count)
            if max_node_count is None:
                node_count += len(child)
            else:
                node_count += min(children_max_node_count, len(child))

D
desbma 已提交
119
            if not node.is_root:
D
desbma 已提交
120
                child_data = self.add_tree_decoration(child_data, child is node.children[-1], first_level)
D
desbma 已提交
121 122 123
            ret.extend(child_data)
        return ret

D
desbma 已提交
124
    def add_tree_decoration(self, child_data, is_last_child, first_level):
A
PEP 257  
Alessio Sergi 已提交
125
        """Add tree curses decoration and indentation to a subtree."""
D
desbma 已提交
126 127 128
        # find process command indices in messages
        pos = []
        for i, m in enumerate(child_data):
N
nicolargo 已提交
129
            if m["msg"] == "\n" and m is not child_data[-1]:
D
desbma 已提交
130 131 132 133
                # new line pos + 12
                # TODO find a way to get rid of hardcoded 12 value
                pos.append(i + 12)

D
desbma 已提交
134 135 136 137 138 139 140 141 142 143 144
        # add new curses items for tree decoration
        new_child_data = []
        new_pos = []
        for i, m in enumerate(child_data):
            if i in pos:
                new_pos.append(len(new_child_data))
                new_child_data.append(self.curse_add_line(""))
            new_child_data.append(m)
        child_data = new_child_data
        pos = new_pos

D
desbma 已提交
145 146 147 148 149
        # draw node prefix
        if is_last_child:
            prefix = "└─"
        else:
            prefix = "├─"
D
desbma 已提交
150
        child_data[pos[0]]["msg"] = prefix
D
desbma 已提交
151 152 153

        # add indentation
        for i in pos:
D
desbma 已提交
154
            spacing = 2
D
desbma 已提交
155
            if first_level:
D
desbma 已提交
156 157 158 159 160
                spacing = 1
            elif is_last_child and (i is not pos[0]):
                # compensate indentation for missing '│' char
                spacing = 3
            child_data[i]["msg"] = "%s%s" % (" " * spacing, child_data[i]["msg"])
D
desbma 已提交
161 162 163 164 165 166 167 168

        if not is_last_child:
            # add '│' tree decoration
            for i in pos[1:]:
                old_str = child_data[i]["msg"]
                if first_level:
                    child_data[i]["msg"] = " │" + old_str[2:]
                else:
D
desbma 已提交
169
                    child_data[i]["msg"] = old_str[:2] + "│" + old_str[3:]
D
desbma 已提交
170 171
        return child_data

D
desbma 已提交
172
    def get_process_curses_data(self, p, first, args):
A
PEP 257  
Alessio Sergi 已提交
173
        """Get curses data to display for a process."""
174
        ret = [self.curse_new_line()]
D
desbma 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        # CPU
        if 'cpu_percent' in p and p['cpu_percent'] is not None and p['cpu_percent'] != '':
            msg = '{0:>6.1f}'.format(p['cpu_percent'])
            ret.append(self.curse_add_line(msg,
                                           self.get_alert(p['cpu_percent'], header="cpu")))
        else:
            msg = '{0:>6}'.format('?')
            ret.append(self.curse_add_line(msg))
        # MEM
        if 'memory_percent' in p and p['memory_percent'] is not None and p['memory_percent'] != '':
            msg = '{0:>6.1f}'.format(p['memory_percent'])
            ret.append(self.curse_add_line(msg,
                                           self.get_alert(p['memory_percent'], header="mem")))
        else:
            msg = '{0:>6}'.format('?')
            ret.append(self.curse_add_line(msg))
        # VMS/RSS
        if 'memory_info' in p and p['memory_info'] is not None and p['memory_info'] != '':
            # VMS
            msg = '{0:>6}'.format(self.auto_unit(p['memory_info'][1], low_precision=False))
            ret.append(self.curse_add_line(msg, optional=True))
            # RSS
            msg = '{0:>6}'.format(self.auto_unit(p['memory_info'][0], low_precision=False))
            ret.append(self.curse_add_line(msg, optional=True))
        else:
            msg = '{0:>6}'.format('?')
            ret.append(self.curse_add_line(msg))
            ret.append(self.curse_add_line(msg))
        # PID
        msg = '{0:>6}'.format(p['pid'])
        ret.append(self.curse_add_line(msg))
        # USER
        if 'username' in p:
            # docker internal users are displayed as ints only, therefore str()
            msg = ' {0:9}'.format(str(p['username'])[:9])
            ret.append(self.curse_add_line(msg))
        else:
            msg = ' {0:9}'.format('?')
            ret.append(self.curse_add_line(msg))
        # NICE
        if 'nice' in p:
            nice = p['nice']
            if nice is None:
                nice = '?'
            msg = '{0:>5}'.format(nice)
            if isinstance(nice, int) and ((is_windows and nice != 32) or
                                          (not is_windows and nice != 0)):
                ret.append(self.curse_add_line(msg, decoration='NICE'))
            else:
                ret.append(self.curse_add_line(msg))
        else:
            msg = '{0:>5}'.format('?')
            ret.append(self.curse_add_line(msg))
        # STATUS
        if 'status' in p:
            status = p['status']
            msg = '{0:>2}'.format(status)
            if status == 'R':
                ret.append(self.curse_add_line(msg, decoration='STATUS'))
            else:
                ret.append(self.curse_add_line(msg))
        else:
            msg = '{0:>2}'.format('?')
            ret.append(self.curse_add_line(msg))
        # TIME+
        if self.tag_proc_time:
            try:
242
                delta = timedelta(seconds=sum(p['cpu_times']))
243
            except OverflowError:
D
desbma 已提交
244 245 246 247
                # Catched on some Amazon EC2 server
                # See https://github.com/nicolargo/glances/issues/87
                self.tag_proc_time = False
            else:
248 249
                hours, minutes, seconds, microseconds = convert_timedelta(delta)
                if hours:
250 251
                    msg = '{0:>4}h'.format(hours)
                    ret.append(self.curse_add_line(msg, decoration='CPU_TIME', optional=True))
252
                    msg = '{0}:{1}'.format(str(minutes).zfill(2), seconds)
253
                else:
254
                    msg = '{0:>4}:{1}.{2}'.format(minutes, seconds, microseconds)
D
desbma 已提交
255
        else:
256
            msg = '{0:>10}'.format('?')
D
desbma 已提交
257 258 259 260
        ret.append(self.curse_add_line(msg, optional=True))
        # IO read/write
        if 'io_counters' in p:
            # IO read
261
            io_rs = int((p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update'])
D
desbma 已提交
262 263 264
            if io_rs == 0:
                msg = '{0:>6}'.format("0")
            else:
265
                msg = '{0:>6}'.format(self.auto_unit(io_rs, low_precision=True))
D
desbma 已提交
266 267
            ret.append(self.curse_add_line(msg, optional=True, additional=True))
            # IO write
268
            io_ws = int((p['io_counters'][1] - p['io_counters'][3]) / p['time_since_update'])
D
desbma 已提交
269 270 271
            if io_ws == 0:
                msg = '{0:>6}'.format("0")
            else:
272
                msg = '{0:>6}'.format(self.auto_unit(io_ws, low_precision=True))
D
desbma 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
            ret.append(self.curse_add_line(msg, optional=True, additional=True))
        else:
            msg = '{0:>6}'.format("?")
            ret.append(self.curse_add_line(msg, optional=True, additional=True))
            ret.append(self.curse_add_line(msg, optional=True, additional=True))

        # Command line
        # If no command line for the process is available, fallback to
        # the bare process name instead
        cmdline = p['cmdline']
        if cmdline == "" or args.process_short_name:
            msg = ' {0}'.format(p['name'])
            ret.append(self.curse_add_line(msg, splittable=True))
        else:
            try:
                cmd = cmdline.split()[0]
                argument = ' '.join(cmdline.split()[1:])
                path, basename = os.path.split(cmd)
                if os.path.isdir(path):
                    msg = ' {0}'.format(path) + os.sep
                    ret.append(self.curse_add_line(msg, splittable=True))
                    ret.append(self.curse_add_line(basename, decoration='PROCESS', splittable=True))
                else:
                    msg = ' {0}'.format(basename)
                    ret.append(self.curse_add_line(msg, decoration='PROCESS', splittable=True))
                msg = " {0}".format(argument)
                ret.append(self.curse_add_line(msg, splittable=True))
            except UnicodeEncodeError:
                ret.append(self.curse_add_line("", splittable=True))

        # Add extended stats but only for the top processes
        # !!! CPU consumption ???
        # TODO: extended stats into the web interface
        if first and 'extended_stats' in p:
            # Left padding
            xpad = ' ' * 13
            # First line is CPU affinity
            if 'cpu_affinity' in p and p['cpu_affinity'] is not None:
                ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
312
                msg = xpad + 'CPU affinity: ' + str(len(p['cpu_affinity'])) + ' cores'
D
desbma 已提交
313 314 315 316
                ret.append(self.curse_add_line(msg, splittable=True))
            # Second line is memory info
            if 'memory_info_ex' in p and p['memory_info_ex'] is not None:
                ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
317
                msg = xpad + 'Memory info: '
D
desbma 已提交
318 319 320 321 322
                for k, v in p['memory_info_ex']._asdict().items():
                    # Ignore rss and vms (already displayed)
                    if k not in ['rss', 'vms'] and v is not None:
                        msg += k + ' ' + self.auto_unit(v, low_precision=False) + ' '
                if 'memory_swap' in p and p['memory_swap'] is not None:
A
Alessio Sergi 已提交
323
                    msg += 'swap ' + self.auto_unit(p['memory_swap'], low_precision=False)
D
desbma 已提交
324 325 326 327
                ret.append(self.curse_add_line(msg, splittable=True))
            # Third line is for open files/network sessions
            msg = ''
            if 'num_threads' in p and p['num_threads'] is not None:
A
Alessio Sergi 已提交
328
                msg += 'threads ' + str(p['num_threads']) + ' '
D
desbma 已提交
329
            if 'num_fds' in p and p['num_fds'] is not None:
A
Alessio Sergi 已提交
330
                msg += 'files ' + str(p['num_fds']) + ' '
D
desbma 已提交
331
            if 'num_handles' in p and p['num_handles'] is not None:
A
Alessio Sergi 已提交
332
                msg += 'handles ' + str(p['num_handles']) + ' '
D
desbma 已提交
333
            if 'tcp' in p and p['tcp'] is not None:
A
Alessio Sergi 已提交
334
                msg += 'TCP ' + str(p['tcp']) + ' '
D
desbma 已提交
335
            if 'udp' in p and p['udp'] is not None:
A
Alessio Sergi 已提交
336
                msg += 'UDP ' + str(p['udp']) + ' '
D
desbma 已提交
337 338
            if msg != '':
                ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
339
                msg = xpad + 'Open: ' + msg
D
desbma 已提交
340 341 342 343
                ret.append(self.curse_add_line(msg, splittable=True))
            # Fouth line is IO nice level (only Linux and Windows OS)
            if 'ionice' in p and p['ionice'] is not None:
                ret.append(self.curse_new_line())
A
Alessio Sergi 已提交
344 345
                msg = xpad + 'IO nice: '
                k = 'Class is '
D
desbma 已提交
346 347 348 349 350 351 352 353 354
                v = p['ionice'].ioclass
                # Linux: The scheduling class. 0 for none, 1 for real time, 2 for best-effort, 3 for idle.
                # Windows: On Windows only ioclass is used and it can be set to 2 (normal), 1 (low) or 0 (very low).
                if is_windows:
                    if v == 0:
                        msg += k + 'Very Low'
                    elif v == 1:
                        msg += k + 'Low'
                    elif v == 2:
A
Alessio Sergi 已提交
355
                        msg += 'No specific I/O priority'
D
desbma 已提交
356 357 358 359
                    else:
                        msg += k + str(v)
                else:
                    if v == 0:
A
Alessio Sergi 已提交
360
                        msg += 'No specific I/O priority'
D
desbma 已提交
361 362 363 364 365 366 367 368 369 370 371
                    elif v == 1:
                        msg += k + 'Real Time'
                    elif v == 2:
                        msg += k + 'Best Effort'
                    elif v == 3:
                        msg += k + 'IDLE'
                    else:
                        msg += k + str(v)
                #  value is a number which goes from 0 to 7.
                # The higher the value, the lower the I/O priority of the process.
                if hasattr(p['ionice'], 'value') and p['ionice'].value != 0:
A
Alessio Sergi 已提交
372
                    msg += ' (value %s/7)' % str(p['ionice'].value)
D
desbma 已提交
373 374 375 376
                ret.append(self.curse_add_line(msg, splittable=True))

        return ret

A
Alessio Sergi 已提交
377
    def msg_curse(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
378
        """Return the dict to display in the curse interface."""
A
Alessio Sergi 已提交
379 380 381
        # Init the return message
        ret = []

382
        # Only process if stats exist and display plugin enable...
D
desbma 已提交
383
        if not self.stats or args.disable_process:
384 385
            return ret

A
Alessio Sergi 已提交
386
        # Compute the sort key
387
        process_sort_key = glances_processes.sort_key
388
        sort_style = 'SORT'
A
Alessio Sergi 已提交
389 390

        # Header
A
Alessio Sergi 已提交
391
        msg = '{0:>6}'.format('CPU%')
A
Alessio Sergi 已提交
392
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'cpu_percent' else 'DEFAULT'))
A
Alessio Sergi 已提交
393
        msg = '{0:>6}'.format('MEM%')
A
Alessio Sergi 已提交
394
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'memory_percent' else 'DEFAULT'))
A
Alessio Sergi 已提交
395
        msg = '{0:>6}'.format('VIRT')
A
Alessio Sergi 已提交
396
        ret.append(self.curse_add_line(msg, optional=True))
A
Alessio Sergi 已提交
397
        msg = '{0:>6}'.format('RES')
A
Alessio Sergi 已提交
398
        ret.append(self.curse_add_line(msg, optional=True))
A
Alessio Sergi 已提交
399
        msg = '{0:>6}'.format('PID')
400
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
401
        msg = ' {0:10}'.format('USER')
A
Alessio Sergi 已提交
402
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'username' else 'DEFAULT'))
A
Alessio Sergi 已提交
403
        msg = '{0:>4}'.format('NI')
404
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
405
        msg = '{0:>2}'.format('S')
406
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
407
        msg = '{0:>10}'.format('TIME+')
408
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'cpu_times' else 'DEFAULT', optional=True))
A
Alessio Sergi 已提交
409
        msg = '{0:>6}'.format('IOR/s')
410
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
A
Alessio Sergi 已提交
411
        msg = '{0:>6}'.format('IOW/s')
412
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
A
Alessio Sergi 已提交
413
        msg = ' {0:8}'.format('Command')
414
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'name' else 'DEFAULT'))
A
Alessio Sergi 已提交
415

416
        if glances_processes.is_tree_enabled():
A
Alessio Sergi 已提交
417 418 419
            ret.extend(self.get_process_tree_curses_data(
                self.sort_stats(process_sort_key), args, first_level=True,
                max_node_count=glances_processes.max_processes))
D
desbma 已提交
420 421 422
        else:
            # Loop over processes (sorted by the sort key previously compute)
            first = True
A
Alessio Sergi 已提交
423
            for p in self.sort_stats(process_sort_key):
D
desbma 已提交
424
                ret.extend(self.get_process_curses_data(p, first, args))
N
Nicolargo 已提交
425 426 427
                # End of extended stats
                first = False

A
Alessio Sergi 已提交
428 429
        # Return the message with decoration
        return ret
430

A
Alessio Sergi 已提交
431
    def sort_stats(self, sortedby=None):
A
PEP 257  
Alessio Sergi 已提交
432
        """Return the stats sorted by sortedby variable."""
433
        if sortedby is None:
434 435 436
            # No need to sort...
            return self.stats

437 438 439
        tree = glances_processes.is_tree_enabled()

        if sortedby == 'io_counters' and not tree:
440 441 442 443
            # Specific case for io_counters
            # Sum of io_r + io_w
            try:
                # Sort process by IO rate (sum IO read + IO write)
D
desbma 已提交
444 445 446
                self.stats.sort(key=lambda process: process[sortedby][0] -
                                process[sortedby][2] + process[sortedby][1] -
                                process[sortedby][3],
A
Alessio Sergi 已提交
447
                                reverse=glances_processes.sort_reverse)
448
            except Exception:
449
                self.stats.sort(key=operator.itemgetter('cpu_percent'),
A
Alessio Sergi 已提交
450
                                reverse=glances_processes.sort_reverse)
451 452
        else:
            # Others sorts
453
            if tree:
A
Alessio Sergi 已提交
454
                self.stats.set_sorting(sortedby, glances_processes.sort_reverse)
455 456
            else:
                try:
457
                    self.stats.sort(key=operator.itemgetter(sortedby),
A
Alessio Sergi 已提交
458
                                    reverse=glances_processes.sort_reverse)
459
                except (KeyError, TypeError):
460
                    self.stats.sort(key=operator.itemgetter('name'),
D
desbma 已提交
461
                                    reverse=False)
462

A
Alessio Sergi 已提交
463
        return self.stats