glances_processlist.py 17.7 KB
Newer Older
A
Alessio Sergi 已提交
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
A
Alessio Sergi 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#
# Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com>
#
# 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 os
A
Alessio Sergi 已提交
24 25
from datetime import timedelta

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


D
desbma 已提交
31 32 33
PROCESS_TREE = True  # TODO remove that and take command line parameter


A
Alessio Sergi 已提交
34
class Plugin(GlancesPlugin):
A
PEP 257  
Alessio Sergi 已提交
35 36

    """Glances' processes plugin.
A
Alessio Sergi 已提交
37 38 39 40

    stats is a list
    """

41
    def __init__(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
42
        """Init the plugin."""
43
        GlancesPlugin.__init__(self, args=args)
A
Alessio Sergi 已提交
44 45 46 47

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

48
        # Note: 'glances_processes' is already init in the glances_processes.py script
49

50
    def reset(self):
A
PEP 257  
Alessio Sergi 已提交
51
        """Reset/init the stats."""
52
        self.stats = []
53 54

    def update(self):
A
PEP 257  
Alessio Sergi 已提交
55
        """Update processes stats using the input method."""
56 57
        # Reset stats
        self.reset()
58

59
        if self.get_input() == 'local':
60 61 62
            # Update stats using the standard system lib
            # Note: Update is done in the processcount plugin
            # Just return the processes list
D
desbma 已提交
63 64 65 66
            if PROCESS_TREE:
                self.stats = glances_processes.gettree()
            else:
                self.stats = glances_processes.getlist()
67
        elif self.get_input() == 'snmp':
N
Nicolargo 已提交
68
            # No SNMP grab for processes
69
            pass
70

71
        return self.stats
72

D
desbma 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    def get_process_tree_curses_data(self, node, args, first_level=True):
        ret = []
        if not node.is_root:
            node_data = self.get_process_curses_data(node.stats, False, args)
            ret.extend(node_data)
        for i, child in enumerate(node.children):
            has_other_children = False
            if ((len(node.children) == 1) or   # only one child process
                (i == len(node.children) - 1)):  # last child process
                prefix = "└─"
            else:
                prefix = "├─"
                has_other_children = True
            child_data = self.get_process_tree_curses_data(child, args, node.is_root)
            if not node.is_root:
                # TODO remove msg index hardcoding
                child_data[12]["msg"] = "%s%s" % (prefix, child_data[12]["msg"])
D
desbma 已提交
90
                # TODO this code is an ugly hack and should be reworked
D
desbma 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
                i = 0
                for m in child_data:
                    if m["msg"] == "\n":
                        i = 0
                    elif i == 12:
                        if first_level:
                            m["msg"] = " %s" % (m["msg"])
                        else:
                            m["msg"] = "   %s" % (m["msg"])
                    i += 1
                if has_other_children:
                    add = False
                    i = 0
                    for m in child_data:
                        if m["msg"] == "\n":
                            i = 0
                        elif i == 12:
                            if add:
                                old_str = m["msg"]
                                if first_level:
D
desbma 已提交
111
                                    m["msg"] = " │" + old_str[2:]
D
desbma 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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 312 313 314 315 316 317 318 319 320 321
                                else:
                                    m["msg"] = old_str[:3] + "│" + old_str[4:]
                            else:
                                add = True
                        i += 1
            ret.extend(child_data)
        return ret

    def get_process_curses_data(self, p, first, args):
        ret = []
        ret.append(self.curse_new_line())
        # 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:
                dtime = timedelta(seconds=sum(p['cpu_times']))
            except Exception:
                # Catched on some Amazon EC2 server
                # See https://github.com/nicolargo/glances/issues/87
                self.tag_proc_time = False
            else:
                msg = '{0}:{1}.{2}'.format(str(dtime.seconds // 60 % 60),
                                           str(dtime.seconds % 60).zfill(2),
                                           str(dtime.microseconds)[:2].zfill(2))
        else:
            msg = ' '
        msg = '{0:>9}'.format(msg)
        ret.append(self.curse_add_line(msg, optional=True))
        # IO read/write
        if 'io_counters' in p:
            # IO read
            io_rs = (p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update']
            if io_rs == 0:
                msg = '{0:>6}'.format("0")
            else:
                msg = '{0:>6}'.format(self.auto_unit(io_rs, low_precision=False))
            ret.append(self.curse_add_line(msg, optional=True, additional=True))
            # IO write
            io_ws = (p['io_counters'][1] - p['io_counters'][3]) / p['time_since_update']
            if io_ws == 0:
                msg = '{0:>6}'.format("0")
            else:
                msg = '{0:>6}'.format(self.auto_unit(io_ws, low_precision=False))
            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())
                msg = xpad + _('CPU affinity: ') + str(len(p['cpu_affinity'])) + _(' cores')
                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())
                msg = xpad + _('Memory info: ')
                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:
                    msg += _('swap ') + self.auto_unit(p['memory_swap'], low_precision=False)
                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:
                msg += _('threads ') + str(p['num_threads']) + ' '
            if 'num_fds' in p and p['num_fds'] is not None:
                msg += _('files ') + str(p['num_fds']) + ' '
            if 'num_handles' in p and p['num_handles'] is not None:
                msg += _('handles ') + str(p['num_handles']) + ' '
            if 'tcp' in p and p['tcp'] is not None:
                msg += _('TCP ') + str(p['tcp']) + ' '
            if 'udp' in p and p['udp'] is not None:
                msg += _('UDP ') + str(p['udp']) + ' '
            if msg != '':
                ret.append(self.curse_new_line())
                msg = xpad + _('Open: ') + msg
                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())
                msg = xpad + _('IO nice: ')
                k = _('Class is ')
                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:
                        msg += _('No specific I/O priority')
                    else:
                        msg += k + str(v)
                else:
                    if v == 0:
                        msg += _('No specific I/O priority')
                    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:
                    msg += _(' (value %s/7)') % str(p['ionice'].value)
                ret.append(self.curse_add_line(msg, splittable=True))

        return ret

A
Alessio Sergi 已提交
322
    def msg_curse(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
323
        """Return the dict to display in the curse interface."""
A
Alessio Sergi 已提交
324 325 326
        # Init the return message
        ret = []

327
        # Only process if stats exist and display plugin enable...
328
        if self.stats == [] or args.disable_process:
329 330
            return ret

A
Alessio Sergi 已提交
331
        # Compute the sort key
N
Nicolargo 已提交
332 333
        if glances_processes.getmanualsortkey() is None:
            process_sort_key = glances_processes.getautosortkey()
A
Alessio Sergi 已提交
334
        else:
N
Nicolargo 已提交
335
            process_sort_key = glances_processes.getmanualsortkey()
336
        sort_style = 'SORT'
A
Alessio Sergi 已提交
337 338

        # Header
A
Alessio Sergi 已提交
339
        msg = '{0:>6}'.format(_("CPU%"))
A
Alessio Sergi 已提交
340
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'cpu_percent' else 'DEFAULT'))
A
Alessio Sergi 已提交
341
        msg = '{0:>6}'.format(_("MEM%"))
A
Alessio Sergi 已提交
342
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'memory_percent' else 'DEFAULT'))
A
Alessio Sergi 已提交
343
        msg = '{0:>6}'.format(_("VIRT"))
A
Alessio Sergi 已提交
344
        ret.append(self.curse_add_line(msg, optional=True))
A
Alessio Sergi 已提交
345
        msg = '{0:>6}'.format(_("RES"))
A
Alessio Sergi 已提交
346
        ret.append(self.curse_add_line(msg, optional=True))
A
Alessio Sergi 已提交
347
        msg = '{0:>6}'.format(_("PID"))
348
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
349
        msg = ' {0:10}'.format(_("USER"))
350
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
351
        msg = '{0:>4}'.format(_("NI"))
352
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
353
        msg = '{0:>2}'.format(_("S"))
354
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
355
        msg = '{0:>9}'.format(_("TIME+"))
A
Alessio Sergi 已提交
356
        ret.append(self.curse_add_line(msg, optional=True))
A
Alessio Sergi 已提交
357
        msg = '{0:>6}'.format(_("IOR/s"))
358
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
A
Alessio Sergi 已提交
359
        msg = '{0:>6}'.format(_("IOW/s"))
360
        ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
A
Alessio Sergi 已提交
361
        msg = ' {0:8}'.format(_("Command"))
362
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
363 364

        # Trying to display proc time
D
desbma 已提交
365 366 367 368 369 370 371 372 373
        self.tag_proc_time = True

        if PROCESS_TREE:
            ret.extend(self.get_process_tree_curses_data(self.sortlist(process_sort_key), args))
        else:
            # Loop over processes (sorted by the sort key previously compute)
            first = True
            for p in self.sortlist(process_sort_key):
                ret.extend(self.get_process_curses_data(p, first, args))
N
Nicolargo 已提交
374 375 376
                # End of extended stats
                first = False

A
Alessio Sergi 已提交
377 378
        # Return the message with decoration
        return ret
379 380

    def sortlist(self, sortedby=None):
A
PEP 257  
Alessio Sergi 已提交
381
        """Return the stats sorted by sortedby variable."""
382
        if sortedby is None:
383 384 385
            # No need to sort...
            return self.stats

D
desbma 已提交
386 387 388
        if PROCESS_TREE:
            return self.stats  # TODO fix that and implement dynamic sorting

389
        sortedreverse = True
390
        if sortedby == 'name':
391 392
            sortedreverse = False

393
        if sortedby == 'io_counters':
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
            # Specific case for io_counters
            # Sum of io_r + io_w
            try:
                # Sort process by IO rate (sum IO read + IO write)
                listsorted = sorted(self.stats,
                                    key=lambda process: process[sortedby][0] -
                                    process[sortedby][2] + process[sortedby][1] -
                                    process[sortedby][3],
                                    reverse=sortedreverse)
            except Exception:
                listsorted = sorted(self.stats,
                                    key=lambda process: process['cpu_percent'],
                                    reverse=sortedreverse)
        else:
            # Others sorts
N
Nicolargo 已提交
409 410 411 412
            try:
                listsorted = sorted(self.stats,
                                    key=lambda process: process[sortedby],
                                    reverse=sortedreverse)
413
            except (KeyError, TypeError):
N
Nicolargo 已提交
414 415 416
                listsorted = sorted(self.stats,
                                    key=lambda process: process['name'],
                                    reverse=False)
417 418 419

        self.stats = listsorted

A
Alessio Sergi 已提交
420
        return self.stats