glances.py 86.7 KB
Newer Older
A
asergi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#!/usr/bin/env python
#
# Glances is a simple textual monitoring tool
#
# Pre-requisites: Python 2.6+ and PsUtil 0.4.0+ (for full functions)
#
# Copyright (C) Nicolargo 2012 <nicolas@nicolargo.com>
#
# 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/>.";
#

__appname__ = 'glances'
23
__version__ = "1.4.2b"
A
asergi 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
__author__ = "Nicolas Hennion <nicolas@nicolargo.com>"
__licence__ = "LGPL"

# Libraries
#==========

import os
import sys
import platform
import getopt
import signal
import time
from datetime import datetime, timedelta
import gettext

# International
#==============

gettext.install(__appname__)

# Test methods
#=============

try:
    import curses
    import curses.panel
except ImportError:
51 52 53
    print(_('Curses module not found. Glances cannot start.'))
    print(_('Glances requires at least Python 2.6 or higher.'))
    print()
A
asergi 已提交
54 55 56 57 58
    sys.exit(1)

try:
    import psutil
except ImportError:
59 60 61 62 63 64 65 66
    print(_('PsUtil module not found. Glances cannot start.'))
    print()
    print(_('On Ubuntu 12.04 or higher:'))
    print(_('$ sudo apt-get install python-psutil'))
    print()
    print(_('To install PsUtil using pip (as root):'))
    print(_('# pip install psutil'))
    print()
A
asergi 已提交
67 68 69 70 71 72 73 74 75 76
    sys.exit(1)

try:
    # get_cpu_percent method only available with PsUtil 0.2.0+
    psutil.Process(os.getpid()).get_cpu_percent(interval=0)
except Exception:
    psutil_get_cpu_percent_tag = False
else:
    psutil_get_cpu_percent_tag = True

77 78 79 80 81 82 83 84
try:
    # get_io_counter only available on Linux and FreeBSD
    psutil.Process(os.getpid()).get_io_counters()
except Exception:
    psutil_get_io_counter_tag = False
else:
    psutil_get_io_counter_tag = True

A
asergi 已提交
85
try:
86 87 88 89 90 91 92 93 94 95 96 97
    # virtual_memory() is only available with PsUtil 0.6+
    psutil.virtual_memory()
except:    
    try:
        # (phy|virt)mem_usage methods only available with PsUtil 0.3.0+
        psutil.phymem_usage()
        psutil.virtmem_usage()
    except Exception:
        psutil_mem_usage_tag = False
    else:
        psutil_mem_usage_tag = True
        psutil_mem_vm = False
A
asergi 已提交
98 99
else:
    psutil_mem_usage_tag = True
100
    psutil_mem_vm = True
A
asergi 已提交
101 102 103 104 105 106 107 108 109 110 111 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

try:
    # disk_(partitions|usage) methods only available with PsUtil 0.3.0+
    psutil.disk_partitions()
    psutil.disk_usage('/')
except Exception:
    psutil_fs_usage_tag = False
else:
    psutil_fs_usage_tag = True

try:
    # disk_io_counters method only available with PsUtil 0.4.0+
    psutil.disk_io_counters()
except Exception:
    psutil_disk_io_tag = False
else:
    psutil_disk_io_tag = True

try:
    # network_io_counters method only available with PsUtil 0.4.0+
    psutil.network_io_counters()
except Exception:
    psutil_network_io_tag = False
else:
    psutil_network_io_tag = True

try:
    # HTML output
    import jinja2
except ImportError:
    jinja_tag = False
else:
    jinja_tag = True

try:
    # CSV output
    import csv
except ImportError:
    csvlib_tag = False
else:
    csvlib_tag = True


# Classes
#========

class Timer:
    """
    The timer class
    """

    def __init__(self, duration):
        self.started(duration)

    def started(self, duration):
        self.target = time.time() + duration

    def finished(self):
        return time.time() > self.target


class glancesLimits:
    """
    Manage the limit OK,CAREFUL,WARNING,CRITICAL for each stats
    """

    # The limit list is stored in an hash table:
    #  limits_list[STAT] = [CAREFUL, WARNING, CRITICAL]
    # Exemple:
    #  limits_list['STD'] = [50, 70, 90]

    #_______________________________CAREFUL WARNING CRITICAL
    __limits_list = {'STD': [50, 70, 90],
                     'LOAD': [0.7, 1.0, 5.0]}

    def __init__(self, careful=50, warning=70, critical=90):
        self.__limits_list['STD'] = [careful, warning, critical]

    def getSTDCareful(self):
        return self.__limits_list['STD'][0]

    def getSTDWarning(self):
        return self.__limits_list['STD'][1]

    def getSTDCritical(self):
        return self.__limits_list['STD'][2]

    def getLOADCareful(self, core=1):
        return self.__limits_list['LOAD'][0] * core

    def getLOADWarning(self, core=1):
        return self.__limits_list['LOAD'][1] * core

    def getLOADCritical(self, core=1):
        return self.__limits_list['LOAD'][2] * core


class glancesLogs:
    """
    The main class to manage logs inside the Glances software
    Logs is a list of list:
    [["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM",
      MAX, AVG, MIN, SUM, COUNT],...]
    """

    def __init__(self):
        """
        Init the logs classe
        """
        # Maximum size of the logs list
        self.logs_max = 10

        # Init the logs list
        self.logs_list = []

    def get(self):
        """
        Return the logs list (RAW)
        """
        return self.logs_list

    def len(self):
        """
        Return the number of item in the log list
        """
        return self.logs_list.__len__()

    def __itemexist__(self, item_type):
        """
        An item exist in the list if:
        * end is < 0
        * item_type is matching
        """
234
        for i in range(self.len()):
A
asergi 已提交
235 236 237 238 239
            if (self.logs_list[i][1] < 0 and
                self.logs_list[i][3] == item_type):
                return i
        return -1

240
    def add(self, item_state, item_type, item_value, proc_list = []):
A
asergi 已提交
241 242
        """
        item_state = "OK|CAREFUL|WARNING|CRITICAL"
N
Nicolas Hennion 已提交
243
        item_type = "CPU*|LOAD|MEM"
A
asergi 已提交
244 245 246
        item_value = value
        Item is defined by:
          ["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM",
247 248
           MAX, AVG, MIN, SUM, COUNT,
           [top3 process list]]
A
asergi 已提交
249 250 251 252 253
        If item is a 'new one':
          Add the new item at the beginning of the logs list
        Else:
          Update the existing item
        """
N
Nicolas Hennion 已提交
254 255 256 257
        
        # Add Top process sort depending on alert type
        if (item_type.startswith("MEM")):
            # MEM
258
            sortby = 'memory_percent'
N
Nicolas Hennion 已提交
259 260 261 262 263 264
        else:
            # CPU* and LOAD
            sortby = 'cpu_percent'
        topprocess = sorted(proc_list, key=lambda process: process[sortby], reverse=True)

        # Add or update the log
A
asergi 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
        item_index = self.__itemexist__(item_type)
        if item_index < 0:
            # Item did not exist, add if WARNING or CRITICAL
            if (item_state == "WARNING" or
                item_state == "CRITICAL"):
                # Time is stored in Epoch format
                # Epoch -> DMYHMS = datetime.fromtimestamp(epoch)
                item = []
                item.append(time.mktime(datetime.now().timetuple()))
                item.append(-1)
                item.append(item_state)     # STATE: WARNING|CRITICAL
                item.append(item_type)      # TYPE: CPU, LOAD, MEM...
                item.append(item_value)     # MAX
                item.append(item_value)     # AVG
                item.append(item_value)     # MIN
                item.append(item_value)     # SUM
                item.append(1)              # COUNT
N
Nicolas Hennion 已提交
282
                item.append(topprocess[0:3]) # TOP 3 PROCESS LIST
A
asergi 已提交
283 284 285 286 287 288 289 290 291 292
                self.logs_list.insert(0, item)
                if self.len() > self.logs_max:
                    self.logs_list.pop()
        else:
            # Item exist, update
            if (item_state == "OK" or
                item_state == "CAREFUL"):
                # Close the item
                self.logs_list[item_index][1] = time.mktime(
                    datetime.now().timetuple())
N
Nicolas Hennion 已提交
293 294
                # TOP PROCESS LIST
                self.logs_list[item_index][9] = []
A
asergi 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
            else:
                # Update the item
                # State
                if item_state == "CRITICAL":
                    self.logs_list[item_index][2] = item_state
                # Value
                if item_value > self.logs_list[item_index][4]:
                    # MAX
                    self.logs_list[item_index][4] = item_value
                elif item_value < self.logs_list[item_index][6]:
                    # MIN
                    self.logs_list[item_index][6] = item_value
                # AVG
                self.logs_list[item_index][7] += item_value
                self.logs_list[item_index][8] += 1
                self.logs_list[item_index][5] = (
                    self.logs_list[item_index][7] /
                    self.logs_list[item_index][8])
N
Nicolas Hennion 已提交
313 314
                # TOP PROCESS LIST
                self.logs_list[item_index][9] = topprocess[0:3]
A
asergi 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

        return self.len()


class glancesGrabFs:
    """
    Get FS stats
    """

    def __init__(self):
        """
        Init FS stats
        """

        # Ignore the following FS name
        self.ignore_fsname = ('', 'none', 'gvfs-fuse-daemon', 'fusectl',
                              'cgroup')

        # Ignore the following FS type
        self.ignore_fstype = ('binfmt_misc', 'devpts', 'iso9660', 'none',
                              'proc', 'sysfs', 'usbfs', 'rootfs', 'autofs',
                              'devtmpfs')

    def __update__(self):
        """
        Update the stats
        """

        # Reset the list
        self.fs_list = []

        # Open the current mounted FS
        fs_stat = psutil.disk_partitions(True)
348
        for fs in range(len(fs_stat)):
A
asergi 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            fs_current = {}
            fs_current['device_name'] = fs_stat[fs].device
            if fs_current['device_name'] in self.ignore_fsname:
                continue
            fs_current['fs_type'] = fs_stat[fs].fstype
            if fs_current['fs_type'] in self.ignore_fstype:
                continue
            fs_current['mnt_point'] = fs_stat[fs].mountpoint
            try:
                fs_usage = psutil.disk_usage(fs_current['mnt_point'])
            except Exception:
                continue
            fs_current['size'] = fs_usage.total
            fs_current['used'] = fs_usage.used
            fs_current['avail'] = fs_usage.free
            self.fs_list.append(fs_current)

    def get(self):
        self.__update__()
        return self.fs_list


class glancesStats:
    """
    This class store, update and give stats
    """

    def __init__(self):
        """
        Init the stats
        """

        # Init the fs stats
        try:
            self.glancesgrabfs = glancesGrabFs()
        except Exception:
            self.glancesgrabfs = {}

        # Process list refresh
        self.process_list_refresh = True
N
Nicolas Hennion 已提交
389 390
        
        # Cached informations (no need to be refreshed)
A
asergi 已提交
391 392 393 394 395 396 397

        # Host and OS informations
        self.host = {}
        self.host['os_name'] = platform.system()
        self.host['hostname'] = platform.node()
        self.host['platform'] = platform.architecture()[0]
        is_archlinux = os.path.exists(os.path.join("/", "etc", "arch-release"))
N
Nicolas Hennion 已提交
398 399 400
        if self.host['os_name'] == "Linux":
            if is_archlinux:
                self.host['linux_distro'] = "Arch Linux"
A
asergi 已提交
401
            else:
N
Nicolas Hennion 已提交
402 403 404 405 406 407 408 409 410 411 412
                linux_distro = platform.linux_distribution()
                self.host['linux_distro'] = " ".join(linux_distro[:2])
            self.host['os_version'] = platform.release()
        elif self.host['os_name'] == "FreeBSD":
            self.host['os_version'] = platform.release()
        elif self.host['os_name'] == "Darwin":
            self.host['os_version'] = platform.mac_ver()[0]
        elif self.host['os_name'] == "Windows":
            os_version = platform.win32_ver()
            self.host['os_version'] = " ".join(os_version[::2])
        else:
A
asergi 已提交
413 414
            self.host['os_version'] = ""

415 416 417 418 419
    def __get_process_statsNEW__(self, proc):
        """
        Get process (proc) statistics
        !!! Waiting PATCH for PsUtil
        !!! http://code.google.com/p/psutil/issues/detail?id=329
420
        !!! Performance gap ???
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
        """
        procstat = proc.as_dict(['memory_info', 'cpu_percent', 'memory_percent',
                                 'io_counters', 'pid', 'username', 'nice',
                                 'cpu_times', 'name', 'status', 'cmdline'])
      
        procstat['status'] = str(procstat['status'])[:1].upper()
        procstat['cmdline'] = " ".join(procstat['cmdline'])
        
        return procstat

        
    def __get_process_stats__(self, proc):
        """
        Get process (proc) statistics
        """
        procstat = {}
        
        procstat['memory_info'] = proc.get_memory_info()
        
        if psutil_get_cpu_percent_tag:
            procstat['cpu_percent'] = \
                proc.get_cpu_percent(interval=0)

        procstat['memory_percent'] = proc.get_memory_percent()

        if psutil_get_io_counter_tag:
            procstat['io_counters']  = proc.get_io_counters()

        procstat['pid'] = proc.pid
        procstat['username'] = proc.username

        try:
            # Deprecated in PsUtil 0.5.0
            procstat['nice'] = proc.nice
        except:
            # Specific for PsUtil 0.5.0+
            procstat['nice'] = proc.get_nice()

        procstat['status'] = str(proc.status)[:1].upper()
        procstat['cpu_times'] = proc.get_cpu_times()
        procstat['name'] = proc.name
        procstat['cmdline'] = " ".join(proc.cmdline)
        
        return procstat

N
Nicolas Hennion 已提交
466 467 468 469 470 471

    def __update__(self):
        """
        Update the stats
        """

A
asergi 已提交
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        # CPU
        try:
            self.cputime_old
        except Exception:
            self.cputime_old = psutil.cpu_times()
            self.cputime_total_old = (self.cputime_old.user +
                                      self.cputime_old.system +
                                      self.cputime_old.idle)
            # Only available on some OS
            try:
                self.cputime_total_old += self.cputime_old.nice
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.iowait
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.irq
            except Exception:
                pass
            try:
                self.cputime_total_old += self.cputime_old.softirq
            except Exception:
                pass
            self.cpu = {}
        else:
            try:
                self.cputime_new = psutil.cpu_times()
                self.cputime_total_new = (self.cputime_new.user +
                                          self.cputime_new.system +
                                          self.cputime_new.idle)
                # Only available on some OS
                try:
                    self.cputime_total_new += self.cputime_new.nice
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.iowait
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.irq
                except Exception:
                    pass
                try:
                    self.cputime_total_new += self.cputime_new.softirq
                except Exception:
                    pass
                percent = 100 / (self.cputime_total_new -
                                 self.cputime_total_old)
                self.cpu = {'kernel':
                                (self.cputime_new.system -
                                 self.cputime_old.system) * percent,
                            'user':
                                (self.cputime_new.user -
                                 self.cputime_old.user) * percent,
                            'idle':
                                (self.cputime_new.idle -
                                 self.cputime_old.idle) * percent,
                            'nice':
                                (self.cputime_new.nice -
                                 self.cputime_old.nice) * percent}
                self.cputime_old = self.cputime_new
                self.cputime_total_old = self.cputime_total_new
            except Exception:
                self.cpu = {}

N
Nicolas Hennion 已提交
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
        # PerCPU
        try:
            self.percputime_old
        except Exception:
            self.percputime_old = psutil.cpu_times(percpu = True)
            self.percputime_total_old = []
            for i in range(len(self.percputime_old)):                
                self.percputime_total_old.append(self.percputime_old[i].user +
                                                 self.percputime_old[i].system +
                                                 self.percputime_old[i].idle)
            # Only available on some OS
            try:
                for i in range(len(self.percputime_old)):                
                    self.percputime_total_old[i] += self.percputime_old[i].nice
            except Exception:
                pass
            try:
N
Nicolas Hennion 已提交
557
                for i in range(len(self.percputime_old)):                
N
Nicolas Hennion 已提交
558 559 560 561
                    self.percputime_total_old[i] += self.percputime_old[i].iowait
            except Exception:
                pass
            try:
N
Nicolas Hennion 已提交
562
                for i in range(len(self.percputime_old)):                                
N
Nicolas Hennion 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                    self.percputime_total_old[i] += self.percputime_old[i].irq
            except Exception:
                pass
            try:
               for i in range(len(self.percputime_old)):                                
                    self.percputime_total_old[i] += self.percputime_old[i].softirq
            except Exception:
                pass
            self.percpu = []
        else:
            try:
                self.percputime_new = psutil.cpu_times(percpu = True)
                self.percputime_total_new = []
                for i in range(len(self.percputime_new)):                
                    self.percputime_total_new.append(self.percputime_new[i].user +
                                                     self.percputime_new[i].system +
                                                     self.percputime_new[i].idle)                    
                # Only available on some OS
                try:
                    for i in range(len(self.percputime_new)):                
                        self.percputime_total_new[i] += self.percputime_new[i].nice
                except Exception:
                    pass
                try:
                    for i in range(len(self.percputime_new)):                
                        self.percputime_total_new[i] += self.percputime_new[i].iowait
                except Exception:
                    pass
                try:
                    for i in range(len(self.percputime_new)):                
                        self.percputime_total_new[i] += self.percputime_new[i].irq
                except Exception:
                    pass
                try:
                    for i in range(len(self.percputime_new)):                
                        self.percputime_total_new[i] += self.percputime_new[i].softirq
                except Exception:
                    pass
                perpercent = []
                self.percpu = []
                for i in range(len(self.percputime_new)):                
                    perpercent.append(100 / (self.percputime_total_new[i] -
                                             self.percputime_total_old[i]))
                    self.percpu.append(
                               {'kernel':
                                    (self.percputime_new[i].system -
                                     self.percputime_old[i].system) * perpercent[i],
                                'user':
                                    (self.percputime_new[i].user -
                                     self.percputime_old[i].user) * perpercent[i],
                                'idle':
                                    (self.percputime_new[i].idle -
                                     self.percputime_old[i].idle) * perpercent[i],
                                'nice':
                                    (self.percputime_new[i].nice -
                                     self.percputime_old[i].nice) * perpercent[i]} )                
                self.percputime_old = self.percputime_new
                self.percputime_total_old = self.percputime_total_new
            except Exception:
                self.percpu = []

A
asergi 已提交
624 625 626 627 628 629 630 631 632 633
        # LOAD
        try:
            getload = os.getloadavg()
            self.load = {'min1': getload[0],
                         'min5': getload[1],
                         'min15': getload[2]}
        except Exception:
            self.load = {}

        # MEM
634 635 636 637
        if psutil_mem_vm:
            # If PsUtil 0.6+
            phymem = psutil.virtual_memory()
            self.mem = {'cache': phymem.cached + phymem.buffers,
A
asergi 已提交
638 639 640 641
                        'total': phymem.total,
                        'used': phymem.used,
                        'free': phymem.free,
                        'percent': phymem.percent}
642
            virtmem = psutil.swap_memory()
A
asergi 已提交
643 644 645
            self.memswap = {'total': virtmem.total,
                            'used': virtmem.used,
                            'free': virtmem.free,
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
                            'percent': virtmem.percent}            
        else:
            # For olders PsUtil version
            try:
                phymem = psutil.phymem_usage()
                try:
                    # Cache stat only available for Linux
                    cachemem = psutil.cached_phymem() + psutil.phymem_buffers()
                except Exception:
                    cachemem = 0
                self.mem = {'cache': cachemem,
                            'total': phymem.total,
                            'used': phymem.used,
                            'free': phymem.free,
                            'percent': phymem.percent}
            except Exception:
                self.mem = {}
            try:
                virtmem = psutil.virtmem_usage()
                self.memswap = {'total': virtmem.total,
                                'used': virtmem.used,
                                'free': virtmem.free,
                                'percent': virtmem.percent}
            except Exception:
                self.memswap = {}
A
asergi 已提交
671 672 673 674 675 676 677

        # NET
        if psutil_network_io_tag:
            self.network = []
            try:
                self.network_old
            except Exception:
678
                self.network_old = psutil.network_io_counters(True)
A
asergi 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
            else:
                try:
                    self.network_new = psutil.network_io_counters(True)
                except Exception:
                    pass
                else:
                    for net in self.network_new:
                        try:
                            netstat = {}
                            netstat['interface_name'] = net
                            netstat['rx'] = (self.network_new[net].bytes_recv -
                                             self.network_old[net].bytes_recv)
                            netstat['tx'] = (self.network_new[net].bytes_sent -
                                             self.network_old[net].bytes_sent)
                        except Exception:
                            continue
                        else:
                            self.network.append(netstat)
                    self.network_old = self.network_new

        # DISK I/O
        if psutil_disk_io_tag:
            self.diskio = []
            try:
                self.diskio_old
            except Exception:
                if psutil_disk_io_tag:
                    self.diskio_old = psutil.disk_io_counters(True)
            else:
                try:
                    self.diskio_new = psutil.disk_io_counters(True)
                except Exception:
                    pass
                else:
                    for disk in self.diskio_new:
                        try:
                            diskstat = {}
                            diskstat['disk_name'] = disk
                            diskstat['read_bytes'] = (
                                self.diskio_new[disk].read_bytes -
                                self.diskio_old[disk].read_bytes)
                            diskstat['write_bytes'] = (
                                self.diskio_new[disk].write_bytes -
                                self.diskio_old[disk].write_bytes)
                        except Exception:
                            continue
                        else:
                            self.diskio.append(diskstat)
                    self.diskio_old = self.diskio_new

        # FILE SYSTEM
        if psutil_fs_usage_tag:
            try:
                self.fs = self.glancesgrabfs.get()
            except Exception:
                self.fs = {}

        # PROCESS
        # Initialiation of the running processes list
        # Data are refreshed every two cycle (refresh_time * 2)
        if self.process_list_refresh:
            self.process_first_grab = False
            try:
                self.process_all
            except Exception:
                self.process_all = [proc for proc in psutil.process_iter()]
                self.process_first_grab = True
            self.process = []
            self.processcount = {'total': 0, 'running': 0, 'sleeping': 0}
            # Manage new processes
            process_new = [proc.pid for proc in self.process_all]
            for proc in psutil.process_iter():
                if proc.pid not in process_new:
                    self.process_all.append(proc)
            # Grab stats from process list
            for proc in self.process_all[:]:
                try:
                    if not proc.is_running():
                        try:
                            self.process_all.remove(proc)
                        except Exception:
                            pass
                except psutil.error.NoSuchProcess:
                    try:
                        self.process_all.remove(proc)
                    except Exception:
                        pass
                else:
                    # Global stats
                    try:
                        self.processcount[str(proc.status)] += 1
                    except psutil.error.NoSuchProcess:
                        # Process non longer exist
                        pass
                    except KeyError:
                        # Key did not exist, create it
                        self.processcount[str(proc.status)] = 1
                    finally:
                        self.processcount['total'] += 1
                    # Per process stats
                    try:
780
                        self.process.append(self.__get_process_stats__(proc))
A
asergi 已提交
781 782
                    except Exception:
                        pass
783
                        
A
asergi 已提交
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
            # If it is the first grab then empty process list
            if self.process_first_grab:
                self.process = []

        self.process_list_refresh = not self.process_list_refresh

        # Get the current date/time
        self.now = datetime.now()

        # Get the number of core (CPU) (Used to display load alerts)
        self.core_number = psutil.NUM_CPUS

    def update(self):
        # Update the stats
        self.__update__()

    def getHost(self):
        return self.host

    def getSystem(self):
        return self.host

    def getCpu(self):
        return self.cpu

N
Nicolas Hennion 已提交
809 810 811
    def getPerCpu(self):
        return self.percpu

A
asergi 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
    def getCore(self):
        return self.core_number

    def getLoad(self):
        return self.load

    def getMem(self):
        return self.mem

    def getMemSwap(self):
        return self.memswap

    def getNetwork(self):
        if psutil_network_io_tag:
            return sorted(self.network,
                          key=lambda network: network['interface_name'])
        else:
            return 0

    def getDiskIO(self):
        if psutil_disk_io_tag:
            return sorted(self.diskio, key=lambda diskio: diskio['disk_name'])
        else:
            return 0

    def getFs(self):
        if psutil_fs_usage_tag:
            return sorted(self.fs, key=lambda fs: fs['mnt_point'])
        else:
            return 0

    def getProcessCount(self):
        return self.processcount

    def getProcessList(self, sortedby='auto'):
        """
        Return the sorted process list
        """

        sortedReverse = True
        if sortedby == 'auto':
            if psutil_get_cpu_percent_tag:
                sortedby = 'cpu_percent'
            else:
856
                sortedby = 'memory_percent'
A
asergi 已提交
857 858 859 860 861 862 863 864 865 866
            # Auto selection
            # If global MEM > 70% sort by MEM usage
            # else sort by CPU usage
            real_used_phymem = self.mem['used'] - self.mem['cache']
            try:
                memtotal = (real_used_phymem * 100) / self.mem['total']
            except Exception:
                pass
            else:
                if memtotal > limits.getSTDWarning():
867 868
                    sortedby = 'memory_percent'
        elif sortedby == 'name':
A
asergi 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
            sortedReverse = False

        return sorted(self.process, key=lambda process: process[sortedby],
                      reverse=sortedReverse)

    def getNow(self):
        return self.now


class glancesScreen:
    """
    This class manage the screen (display and key pressed)
    """

    # By default the process list is automatically sorted
    # If global CPU > WANRING => Sorted by CPU usage
    # If global used MEM > WARINING => Sorted by MEM usage
    __process_sortedby = 'auto'

    def __init__(self, refresh_time=1):
        # Global information to display
        self.__version = __version__

        # Init windows positions
        self.term_w = 80
        self.term_h = 24
        self.system_x = 0
        self.system_y = 0
        self.cpu_x = 0
        self.cpu_y = 2
        self.load_x = 19
        self.load_y = 2
        self.mem_x = 39
        self.mem_y = 2
        self.network_x = 0
        self.network_y = 7
        self.diskio_x = 0
        self.diskio_y = -1
        self.fs_x = 0
        self.fs_y = -1
        self.process_x = 29
        self.process_y = 7
        self.log_x = 0
        self.log_y = -1
        self.help_x = 0
        self.help_y = 0
        self.now_x = 79
        self.now_y = 3
        self.caption_x = 0
        self.caption_y = 3

        # Init the curses screen
        self.screen = curses.initscr()
        if not self.screen:
923
            print(_("Error: Cannot init the curses library.\n"))
A
asergi 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

        curses.start_color()
        if hasattr(curses, 'use_default_colors'):
            try:
                curses.use_default_colors()
            except Exception:
                pass
        if hasattr(curses, 'noecho'):
            try:
                curses.noecho()
            except Exception:
                pass
        if hasattr(curses, 'cbreak'):
            try:
                curses.cbreak()
            except Exception:
                pass
        if hasattr(curses, 'curs_set'):
            try:
                curses.curs_set(0)
            except Exception:
                pass

        # Init colors
        self.hascolors = False
        if curses.has_colors() and curses.COLOR_PAIRS > 8:
            self.hascolors = True
            # FG color, BG color
            curses.init_pair(1, curses.COLOR_WHITE, -1)
            curses.init_pair(2, curses.COLOR_WHITE, curses.COLOR_RED)
            curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_GREEN)
            curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLUE)
            curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_MAGENTA)
            curses.init_pair(6, curses.COLOR_RED, -1)
            curses.init_pair(7, curses.COLOR_GREEN, -1)
            curses.init_pair(8, curses.COLOR_BLUE, -1)
            curses.init_pair(9, curses.COLOR_MAGENTA, -1)
        else:
            self.hascolors = False

        self.title_color = curses.A_BOLD | curses.A_UNDERLINE
        self.help_color = curses.A_BOLD
        if self.hascolors:
            # Colors text styles
            self.no_color = curses.color_pair(1)
            self.default_color = curses.color_pair(3) | curses.A_BOLD
            self.ifCAREFUL_color = curses.color_pair(4) | curses.A_BOLD
            self.ifWARNING_color = curses.color_pair(5) | curses.A_BOLD
            self.ifCRITICAL_color = curses.color_pair(2) | curses.A_BOLD
            self.default_color2 = curses.color_pair(7) | curses.A_BOLD
            self.ifCAREFUL_color2 = curses.color_pair(8) | curses.A_BOLD
            self.ifWARNING_color2 = curses.color_pair(9) | curses.A_BOLD
            self.ifCRITICAL_color2 = curses.color_pair(6) | curses.A_BOLD
        else:
            # B&W text styles
            self.no_color = curses.A_NORMAL
            self.default_color = curses.A_NORMAL
            self.ifCAREFUL_color = curses.A_UNDERLINE
            self.ifWARNING_color = curses.A_BOLD
            self.ifCRITICAL_color = curses.A_REVERSE
            self.default_color2 = curses.A_NORMAL
            self.ifCAREFUL_color2 = curses.A_UNDERLINE
            self.ifWARNING_color2 = curses.A_BOLD
            self.ifCRITICAL_color2 = curses.A_REVERSE

        # Define the colors list (hash table) for logged stats
        self.__colors_list = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': self.no_color,
            'OK': self.default_color,
            'CAREFUL': self.ifCAREFUL_color,
            'WARNING': self.ifWARNING_color,
            'CRITICAL': self.ifCRITICAL_color
        }

        # Define the colors list (hash table) for non logged stats
        self.__colors_list2 = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': self.no_color,
            'OK': self.default_color2,
            'CAREFUL': self.ifCAREFUL_color2,
            'WARNING': self.ifWARNING_color2,
            'CRITICAL': self.ifCRITICAL_color2
        }

        # What are we going to display
        self.network_tag = psutil_network_io_tag
        self.diskio_tag = psutil_disk_io_tag
        self.fs_tag = psutil_fs_usage_tag
        self.log_tag = True
        self.help_tag = False
1015
        self.percpu_tag = True
A
asergi 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

        # Init main window
        self.term_window = self.screen.subwin(0, 0)

        # Init refresh time
        self.__refresh_time = refresh_time

        # Catch key pressed with non blocking mode
        self.term_window.keypad(1)
        self.term_window.nodelay(1)
        self.pressedkey = -1

    def setProcessSortedBy(self, sorted):
        self.__process_sortedautoflag = False
        self.__process_sortedby = sorted

    def getProcessSortedBy(self):
        return self.__process_sortedby

    def __autoUnit(self, val):
        """
        Convert val to string and concatenate the good unit
        Exemples:
            960 -> 960
            142948 -> 143K
            560745673 -> 561M
            ...
        """
        symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
        prefix = {
1046 1047 1048 1049 1050
            'Y': 1208925819614629174706176,
            'Z': 1180591620717411303424,
            'E': 1152921504606846976,
            'P': 1125899906842624,
            'T': 1099511627776,
A
asergi 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
            'G': 1073741824,
            'M': 1048576,
            'K': 1024
        }

        for key in reversed(symbols):
            if val >= prefix[key]:
                value = float(val) / prefix[key]
                if key == "M" or key == "K":
                    return "{0:.0f}{1}".format(value, key)
                else:
                    return "{0:.1f}{1}".format(value, key)

1064
        return "{0!s}".format(val)
A
asergi 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

    def __getAlert(self, current=0, max=100):
        # If current < CAREFUL of max then alert = OK
        # If current > CAREFUL of max then alert = CAREFUL
        # If current > WARNING of max then alert = WARNING
        # If current > CRITICAL of max then alert = CRITICAL
        try:
            (current * 100) / max
        except ZeroDivisionError:
            return 'DEFAULT'

        variable = (current * 100) / max

        if variable > limits.getSTDCritical():
            return 'CRITICAL'
        elif variable > limits.getSTDWarning():
            return 'WARNING'
        elif variable > limits.getSTDCareful():
            return 'CAREFUL'

        return 'OK'

    def __getColor(self, current=0, max=100):
        """
        Return colors for logged stats
        """
        return self.__colors_list[self.__getAlert(current, max)]

    def __getColor2(self, current=0, max=100):
        """
        Return colors for non logged stats
        """
        return self.__colors_list2[self.__getAlert(current, max)]

    def __getCpuAlert(self, current=0, max=100):
        return self.__getAlert(current, max)

    def __getCpuColor(self, current=0, max=100):
        return self.__getColor(current, max)

    def __getLoadAlert(self, current=0, core=1):
        # If current < CAREFUL*core of max then alert = OK
        # If current > CAREFUL*core of max then alert = CAREFUL
        # If current > WARNING*core of max then alert = WARNING
        # If current > CRITICAL*core of max then alert = CRITICAL

        if current > limits.getLOADCritical(core):
            return 'CRITICAL'
        elif current > limits.getLOADWarning(core):
            return 'WARNING'
        elif current > limits.getLOADCareful(core):
            return 'CAREFUL'

        return 'OK'

    def __getLoadColor(self, current=0, core=1):
        return self.__colors_list[self.__getLoadAlert(current, core)]

    def __getMemAlert(self, current=0, max=100):
        return self.__getAlert(current, max)

    def __getMemColor(self, current=0, max=100):
        return self.__getColor(current, max)

    def __getNetColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __getFsColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __getProcessColor(self, current=0, max=100):
        return self.__getColor2(current, max)

    def __catchKey(self):
        # Get key
        self.pressedkey = self.term_window.getch()

        # Actions...
        if (self.pressedkey == 27 or
            self.pressedkey == 113):
            # 'ESC'|'q' > Quit
            end()
1147 1148 1149
        elif self.pressedkey == 49:
            # '1' > Switch between CPU and PerCPU information
            self.percpu_tag = not self.percpu_tag
A
asergi 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        elif self.pressedkey == 97:
            # 'a' > Sort processes automatically
            self.setProcessSortedBy('auto')
        elif self.pressedkey == 99 and psutil_get_cpu_percent_tag:
            # 'c' > Sort processes by CPU usage
            self.setProcessSortedBy('cpu_percent')
        elif self.pressedkey == 100 and psutil_disk_io_tag:
            # 'd' > Show/hide disk I/O stats
            self.diskio_tag = not self.diskio_tag
        elif self.pressedkey == 102 and psutil_fs_usage_tag:
            # 'f' > Show/hide fs stats
            self.fs_tag = not self.fs_tag
        elif self.pressedkey == 104:
            # 'h' > Show/hide help
            self.help_tag = not self.help_tag
        elif self.pressedkey == 108:
            # 'l' > Show/hide log messages
            self.log_tag = not self.log_tag
        elif self.pressedkey == 109:
            # 'm' > Sort processes by MEM usage
1170
            self.setProcessSortedBy('memory_percent')
A
asergi 已提交
1171 1172 1173 1174 1175
        elif self.pressedkey == 110 and psutil_network_io_tag:
            # 'n' > Show/hide network stats
            self.network_tag = not self.network_tag
        elif self.pressedkey == 112:
            # 'p' > Sort processes by name
1176
            self.setProcessSortedBy('name')
A
asergi 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188

        # Return the key code
        return self.pressedkey

    def end(self):
        # Shutdown the curses window
        curses.echo()
        curses.nocbreak()
        curses.curs_set(1)
        curses.endwin()

    def display(self, stats):
N
Nicolas Hennion 已提交
1189 1190 1191
        # Get stats for processes (used in another functions for logs)
        processcount = stats.getProcessCount()
        processlist = stats.getProcessList(screen.getProcessSortedBy())
A
asergi 已提交
1192 1193
        # Display stats
        self.displaySystem(stats.getHost(), stats.getSystem())
N
Nicolas Hennion 已提交
1194 1195 1196
        cpu_offset = self.displayCpu(stats.getCpu(), stats.getPerCpu(), processlist)
        self.displayLoad(stats.getLoad(), stats.getCore(), processlist, cpu_offset)
        self.displayMem(stats.getMem(), stats.getMemSwap(), processlist, cpu_offset)
A
asergi 已提交
1197 1198 1199 1200 1201 1202 1203 1204
        network_count = self.displayNetwork(stats.getNetwork())
        diskio_count = self.displayDiskIO(stats.getDiskIO(),
                                          self.network_y + network_count)
        fs_count = self.displayFs(stats.getFs(),
                                  self.network_y + network_count +
                                  diskio_count)
        log_count = self.displayLog(self.network_y + network_count +
                                    diskio_count + fs_count)
N
Nicolas Hennion 已提交
1205
        self.displayProcess(processcount, processlist, log_count)
A
asergi 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        self.displayCaption()
        self.displayNow(stats.getNow())
        self.displayHelp()

    def erase(self):
        # Erase the content of the screen
        self.term_window.erase()

    def flush(self, stats):
        # Flush display
        self.erase()
        self.display(stats)

    def update(self, stats):
        # flush display
        self.flush(stats)

        # Wait
        countdown = Timer(self.__refresh_time)
        while (not countdown.finished()):
            # Getkey
            if self.__catchKey() > -1:
                # flush display
                self.flush(stats)
            # Wait 100ms...
            curses.napms(100)

    def displaySystem(self, host, system):
        # System information
        if not host or not system:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.system_y and
            screen_x > self.system_x + 79):
            if host['os_name'] == "Linux":
                system_msg = _("{0} {1} with {2} {3} on {4}").format(
                    system['linux_distro'], system['platform'],
                    system['os_name'], system['os_version'],
                    host['hostname'])
            else:
                system_msg = _("{0} {1} {2} on {3}").format(
                    system['os_name'], system['os_version'],
                    system['platform'], host['hostname'])
            self.term_window.addnstr(self.system_y, self.system_x +
                                     int(screen_x / 2) - len(system_msg) / 2,
                                     system_msg, 80, curses.A_UNDERLINE)

N
Nicolas Hennion 已提交
1254
    def displayCpu(self, cpu, percpu, proclist):
A
asergi 已提交
1255 1256 1257
        # CPU %
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
N
Nicolas Hennion 已提交
1258 1259 1260 1261 1262 1263 1264
        
        tag_percpu = False
        offset_x = 0
        if screen_x >  self.cpu_x + 79 + (len(percpu)-1)*10:
            tag_percpu = True
            offset_x = (len(percpu)-1)*10
        
1265 1266 1267 1268 1269
        # If space id available (tag_percpu)
        # and global Per CPU tag (percpu_tag)
        # then display detailled informations for CPU
        tag_percpu = tag_percpu and self.percpu_tag
        
N
Nicolas Hennion 已提交
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
        if (screen_y > self.cpu_y + 5 and tag_percpu):
            # Display extended information whenspace is available (perCpu)
            self.term_window.addnstr(self.cpu_y, self.cpu_x, _("PerCPU"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)

            if not percpu:
                self.term_window.addnstr(self.cpu_y + 1, self.cpu_x,
                                         _("Compute data..."), 15)
                return 0

            self.term_window.addnstr(self.cpu_y + 1, self.cpu_x, _("User:"), 8)
            self.term_window.addnstr(self.cpu_y + 2, self.cpu_x, _("Kernel:"), 8)
            self.term_window.addnstr(self.cpu_y + 3, self.cpu_x, _("Nice:"), 8)

            for i in range(len(percpu)):
                self.term_window.addnstr(self.cpu_y, self.cpu_x + 10 + i*10,
                                         "%.1f%%" % (100 - percpu[i]['idle']), 8)

                alert = self.__getCpuAlert(percpu[i]['user'])
N
Nicolas Hennion 已提交
1290
                logs.add(alert, "CPU-%d user" % i, percpu[i]['user'], proclist)
N
Nicolas Hennion 已提交
1291 1292 1293 1294 1295
                self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 10 + i*10,
                                         "%.1f" % percpu[i]['user'], 8,
                                         self.__colors_list[alert])

                alert = self.__getCpuAlert(percpu[i]['kernel'])
N
Nicolas Hennion 已提交
1296
                logs.add(alert, "CPU-%d kernel" % i, percpu[i]['kernel'], proclist)
N
Nicolas Hennion 已提交
1297 1298 1299 1300 1301
                self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 10 + i*10,
                                         "%.1f" % percpu[i]['kernel'], 8,
                                         self.__colors_list[alert])

                alert = self.__getCpuAlert(percpu[i]['nice'])
N
Nicolas Hennion 已提交
1302
                logs.add(alert, "CPU-%d nice" % i, percpu[i]['nice'], proclist)
N
Nicolas Hennion 已提交
1303 1304 1305 1306 1307 1308 1309
                self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 10 + i*10,
                                         "%.1f" % percpu[i]['nice'], 8,
                                         self.__colors_list[alert])

        elif (screen_y > self.cpu_y + 5 and
              screen_x > self.cpu_x + 18):
            # Display summary information
A
asergi 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
            self.term_window.addnstr(self.cpu_y, self.cpu_x, _("CPU"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)

            if not cpu:
                self.term_window.addnstr(self.cpu_y + 1, self.cpu_x,
                                         _("Compute data..."), 15)
                return 0

            self.term_window.addnstr(self.cpu_y, self.cpu_x + 10,
                                     "%.1f%%" % (100 - cpu['idle']), 8)
            self.term_window.addnstr(self.cpu_y + 1, self.cpu_x, _("User:"), 8)
            self.term_window.addnstr(self.cpu_y + 2, self.cpu_x,
                                     _("Kernel:"), 8)
            self.term_window.addnstr(self.cpu_y + 3, self.cpu_x, _("Nice:"), 8)

            alert = self.__getCpuAlert(cpu['user'])
N
Nicolas Hennion 已提交
1327
            logs.add(alert, "CPU user", cpu['user'], proclist)
A
asergi 已提交
1328 1329 1330 1331 1332
            self.term_window.addnstr(self.cpu_y + 1, self.cpu_x + 10,
                                     "%.1f" % cpu['user'], 8,
                                     self.__colors_list[alert])

            alert = self.__getCpuAlert(cpu['kernel'])
N
Nicolas Hennion 已提交
1333
            logs.add(alert, "CPU kernel", cpu['kernel'], proclist)
A
asergi 已提交
1334 1335 1336 1337 1338
            self.term_window.addnstr(self.cpu_y + 2, self.cpu_x + 10,
                                     "%.1f" % cpu['kernel'], 8,
                                     self.__colors_list[alert])

            alert = self.__getCpuAlert(cpu['nice'])
N
Nicolas Hennion 已提交
1339
            logs.add(alert, "CPU nice", cpu['nice'], proclist)
A
asergi 已提交
1340 1341 1342 1343
            self.term_window.addnstr(self.cpu_y + 3, self.cpu_x + 10,
                                     "%.1f" % cpu['nice'], 8,
                                     self.__colors_list[alert])

N
Nicolas Hennion 已提交
1344 1345 1346
        # Return the X offset to display Load and Mem
        return offset_x

N
Nicolas Hennion 已提交
1347
    def displayLoad(self, load, core, proclist, offset_x=0):
A
asergi 已提交
1348 1349 1350 1351 1352 1353
        # Load %
        if not load:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.load_y + 5 and
N
Nicolas Hennion 已提交
1354 1355
            screen_x > self.load_x + offset_x + 18):
            self.term_window.addnstr(self.load_y, self.load_x + offset_x, _("Load"), 8,
A
asergi 已提交
1356 1357
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
N
Nicolas Hennion 已提交
1358
            self.term_window.addnstr(self.load_y, self.load_x + offset_x + 10,
A
asergi 已提交
1359
                                     str(core) + _("-Core"), 8)
N
Nicolas Hennion 已提交
1360
            self.term_window.addnstr(self.load_y + 1, self.load_x + offset_x,
A
asergi 已提交
1361
                                     _("1 min:"), 8)
N
Nicolas Hennion 已提交
1362
            self.term_window.addnstr(self.load_y + 2, self.load_x + offset_x,
A
asergi 已提交
1363
                                     _("5 min:"), 8)
N
Nicolas Hennion 已提交
1364
            self.term_window.addnstr(self.load_y + 3, self.load_x + offset_x,
A
asergi 已提交
1365 1366
                                     _("15 min:"), 8)

N
Nicolas Hennion 已提交
1367
            self.term_window.addnstr(self.load_y + 1, self.load_x + offset_x + 10,
1368
                                     "{0:.2f}".format(load['min1']), 8)
A
asergi 已提交
1369 1370

            alert = self.__getLoadAlert(load['min5'], core)
N
Nicolas Hennion 已提交
1371
            logs.add(alert, "LOAD 5-min", load['min5'], proclist)
N
Nicolas Hennion 已提交
1372
            self.term_window.addnstr(self.load_y + 2, self.load_x + offset_x + 10,
1373
                                     "{0:.2f}".format(load['min5']), 8,
A
asergi 已提交
1374 1375 1376
                                     self.__colors_list[alert])

            alert = self.__getLoadAlert(load['min15'], core)
N
Nicolas Hennion 已提交
1377
            logs.add(alert, "LOAD 15-min", load['min15'], proclist)
N
Nicolas Hennion 已提交
1378
            self.term_window.addnstr(self.load_y + 3, self.load_x + offset_x + 10,
1379
                                     "{0:.2f}".format(load['min15']), 8,
A
asergi 已提交
1380 1381
                                     self.__colors_list[alert])

N
Nicolas Hennion 已提交
1382
    def displayMem(self, mem, memswap, proclist, offset_x=0):
A
asergi 已提交
1383 1384 1385 1386 1387 1388
        # MEM
        if not mem or not memswap:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.mem_y + 5 and
N
Nicolas Hennion 已提交
1389 1390
            screen_x > self.mem_x + offset_x + 38):
            self.term_window.addnstr(self.mem_y, self.mem_x + offset_x, _("Mem"), 8,
A
asergi 已提交
1391 1392
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
N
Nicolas Hennion 已提交
1393
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + offset_x,
1394 1395 1396
                                     _("Total:"), 6)
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + offset_x, _("Used:"), 6)
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + offset_x, _("Free:"), 6)
A
asergi 已提交
1397

N
Nicolas Hennion 已提交
1398
            self.term_window.addnstr(self.mem_y, self.mem_x + offset_x + 9,
1399
                                     "{0:.1%}".format(mem['percent'] / 100), 8)
N
Nicolas Hennion 已提交
1400
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + offset_x + 9,
A
asergi 已提交
1401
                                     self.__autoUnit(mem['total']), 8)
N
Nicolas Hennion 已提交
1402
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + offset_x + 9,
A
asergi 已提交
1403
                                     self.__autoUnit(mem['used']), 8)
N
Nicolas Hennion 已提交
1404
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + offset_x + 9,
A
asergi 已提交
1405 1406 1407 1408 1409 1410
                                     self.__autoUnit(mem['free']), 8)

            # real memory usage
            real_used_phymem = mem['used'] - mem['cache']
            real_free_phymem = mem['free'] + mem['cache']
            alert = self.__getMemAlert(real_used_phymem, mem['total'])
N
Nicolas Hennion 已提交
1411
            logs.add(alert, "MEM real", real_used_phymem, proclist)
A
asergi 已提交
1412
            self.term_window.addnstr(
N
Nicolas Hennion 已提交
1413
                self.mem_y + 2, self.mem_x + offset_x + 15,
A
asergi 已提交
1414 1415 1416
                "({0})".format(self.__autoUnit(real_used_phymem)), 8,
                self.__colors_list[alert])
            self.term_window.addnstr(
N
Nicolas Hennion 已提交
1417
                self.mem_y + 3, self.mem_x + offset_x + 15,
A
asergi 已提交
1418 1419 1420
                "({0})".format(self.__autoUnit(real_free_phymem)), 8)

            # Swap
N
Nicolas Hennion 已提交
1421
            self.term_window.addnstr(self.mem_y, self.mem_x + offset_x + 25, _("Swap"), 8,
A
asergi 已提交
1422 1423
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
N
Nicolas Hennion 已提交
1424
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + offset_x + 25,
1425
                                     _("Total:"), 6)
N
Nicolas Hennion 已提交
1426
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + offset_x + 25,
1427
                                     _("Used:"), 6)
N
Nicolas Hennion 已提交
1428
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + offset_x + 25,
1429
                                     _("Free:"), 6)
A
asergi 已提交
1430

N
Nicolas Hennion 已提交
1431
            self.term_window.addnstr(self.mem_y, self.mem_x + offset_x + 34,
1432
                                     "{0:.1%}".format(memswap['percent'] / 100),
A
asergi 已提交
1433 1434
                                     8)
            alert = self.__getMemAlert(memswap['used'], memswap['total'])
N
Nicolas Hennion 已提交
1435
            logs.add(alert, "MEM swap", memswap['used'], proclist)
N
Nicolas Hennion 已提交
1436
            self.term_window.addnstr(self.mem_y + 1, self.mem_x + offset_x + 34,
A
asergi 已提交
1437
                                     self.__autoUnit(memswap['total']), 8)
N
Nicolas Hennion 已提交
1438
            self.term_window.addnstr(self.mem_y + 2, self.mem_x + offset_x + 34,
A
asergi 已提交
1439 1440
                                     self.__autoUnit(memswap['used']), 8,
                                     self.__colors_list[alert])
N
Nicolas Hennion 已提交
1441
            self.term_window.addnstr(self.mem_y + 3, self.mem_x + offset_x + 34,
A
asergi 已提交
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
                                     self.__autoUnit(memswap['free']), 8)

    def displayNetwork(self, network):
        """
        Display the network interface bitrate
        Return the number of interfaces
        """
        # Network interfaces bitrate
        if not self.network_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.network_y + 3 and
            screen_x > self.network_x + 28):
            # Network interfaces bitrate
            self.term_window.addnstr(self.network_y, self.network_x,
                                     _("Network"), 8, self.title_color if
                                     self.hascolors else curses.A_UNDERLINE)
            self.term_window.addnstr(self.network_y, self.network_x + 10,
D
Daniel M. Drucker 已提交
1461
                                     _("Rx/s"), 8)
A
asergi 已提交
1462
            self.term_window.addnstr(self.network_y, self.network_x + 19,
D
Daniel M. Drucker 已提交
1463
                                     _("Tx/s"), 8)
A
asergi 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473

            # If there is no data to display...
            if not network:
                self.term_window.addnstr(self.network_y + 1, self.network_x,
                                         _("Compute data..."), 15)
                return 3

            # Adapt the maximum interface to the screen
            ret = 2
            net_num = min(screen_y - self.network_y - 3, len(network))
1474
            for i in range(0, net_num):
A
asergi 已提交
1475 1476 1477 1478
                elapsed_time = max(1, self.__refresh_time)
                self.term_window.addnstr(
                    self.network_y + 1 + i, self.network_x,
                    network[i]['interface_name'] + ':', 8)
1479 1480 1481 1482 1483 1484
                if (network_bytepersec_tag):
                    rx = self.__autoUnit(network[i]['rx'] / elapsed_time)
                    tx = self.__autoUnit(network[i]['tx'] / elapsed_time)
                else:
                    rx = self.__autoUnit(network[i]['rx'] / elapsed_time * 8) + "b"
                    tx = self.__autoUnit(network[i]['tx'] / elapsed_time * 8) + "b"
A
asergi 已提交
1485
                self.term_window.addnstr(
1486
                    self.network_y + 1 + i, self.network_x + 10, rx, 8)
A
asergi 已提交
1487
                self.term_window.addnstr(
1488
                    self.network_y + 1 + i, self.network_x + 19, tx, 8)
A
asergi 已提交
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
                ret = ret + 1
            return ret
        return 0

    def displayDiskIO(self, diskio, offset_y=0):
        # Disk input/output rate
        if not self.diskio_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.diskio_y = offset_y
        if (screen_y > self.diskio_y + 3 and
            screen_x > self.diskio_x + 28):
            self.term_window.addnstr(self.diskio_y, self.diskio_x,
                                     _("Disk I/O"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            self.term_window.addnstr(self.diskio_y, self.diskio_x + 10,
D
Daniel M. Drucker 已提交
1507
                                     _("In/s"), 8)
A
asergi 已提交
1508
            self.term_window.addnstr(self.diskio_y, self.diskio_x + 19,
D
Daniel M. Drucker 已提交
1509
                                     _("Out/s"), 8)
A
asergi 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

            # If there is no data to display...
            if not diskio:
                self.term_window.addnstr(self.diskio_y + 1, self.diskio_x,
                                         _("Compute data..."), 15)
                return 3

            # Adapt the maximum disk to the screen
            disk = 0
            disk_num = min(screen_y - self.diskio_y - 3, len(diskio))
1520
            for disk in range(0, disk_num):
A
asergi 已提交
1521 1522 1523 1524 1525 1526 1527
                elapsed_time = max(1, self.__refresh_time)
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x,
                    diskio[disk]['disk_name'] + ':', 8)
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x + 10,
                    self.__autoUnit(
1528
                        diskio[disk]['write_bytes'] / elapsed_time), 8)
A
asergi 已提交
1529 1530 1531
                self.term_window.addnstr(
                    self.diskio_y + 1 + disk, self.diskio_x + 19,
                    self.__autoUnit(
1532
                        diskio[disk]['read_bytes'] / elapsed_time), 8)
A
asergi 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
            return disk + 3
        return 0

    def displayFs(self, fs, offset_y=0):
        # Filesystem stats
        if not fs or not self.fs_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.fs_y = offset_y
        if (screen_y > self.fs_y + 3 and
            screen_x > self.fs_x + 28):
            self.term_window.addnstr(self.fs_y, self.fs_x, _("Mount"), 8,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
N
Nicolas Hennion 已提交
1548 1549
            self.term_window.addnstr(self.fs_y, self.fs_x + 10, _("Total"), 7)
            self.term_window.addnstr(self.fs_y, self.fs_x + 19, _("Used"), 7)
A
asergi 已提交
1550 1551 1552 1553

            # Adapt the maximum disk to the screen
            mounted = 0
            fs_num = min(screen_y - self.fs_y - 3, len(fs))
1554
            for mounted in range(0, fs_num):
A
asergi 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x, fs[mounted]['mnt_point'], 8)
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x + 10, self.__autoUnit(fs[mounted]['size']), 8)
                self.term_window.addnstr(
                    self.fs_y + 1 + mounted,
                    self.fs_x + 19, self.__autoUnit(fs[mounted]['used']), 8,
                    self.__getFsColor(fs[mounted]['used'],
                                      fs[mounted]['size']))
            return mounted + 3
        return 0

    def displayLog(self, offset_y=0):
        # Logs
        if logs.len() == 0 or not self.log_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        self.log_y = offset_y
        if (screen_y > self.log_y + 3 and
            screen_x > self.log_x + 79):
            self.log_y = max(offset_y, screen_y - 3 -
                             min(offset_y - 3, screen_y - self.log_y,
                                 logs.len()))
            logtodisplay_count = min(screen_y - self.log_y - 3, logs.len())
            logmsg = _("WARNING|CRITICAL logs for CPU|LOAD|MEM")
            if (logtodisplay_count > 1):
                logmsg += (_(" (lasts ") + str(logtodisplay_count) +
                           _(" entries)"))
            else:
                logmsg += _(" (one entry)")
            self.term_window.addnstr(self.log_y, self.log_x, logmsg, 79,
                                     self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)

            # Adapt the maximum log to the screen
            logcount = 0
            log = logs.get()
1595
            for logcount in range(0, logtodisplay_count):
A
asergi 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                logmsg = "  " + str(datetime.fromtimestamp(log[logcount][0]))
                if (log[logcount][1] > 0):
                    logmark = ' '
                    logmsg += (" > " +
                               str(datetime.fromtimestamp(log[logcount][1])))
                else:
                    logmark = '~'
                    logmsg += " > " + "%19s" % "___________________"
                if log[logcount][3][:3] == "MEM":
                    logmsg += " {0} ({1}/{2}/{3})".format(
                        log[logcount][3],
                        self.__autoUnit(log[logcount][6]),
                        self.__autoUnit(log[logcount][5]),
                        self.__autoUnit(log[logcount][4]))
                else:
                    logmsg += " {0} ({1:.1f}/{2:.1f}/{3:.1f})".format(
                        log[logcount][3], log[logcount][6],
                        log[logcount][5], log[logcount][4])
N
Nicolas Hennion 已提交
1614 1615 1616
                # Add top process
                if (log[logcount][9] != []):
                    logmsg += " - Top process: {0}".format(
1617
                            log[logcount][9][0]['name'])
N
Nicolas Hennion 已提交
1618
                # Display the log
A
asergi 已提交
1619
                self.term_window.addnstr(self.log_y + 1 + logcount,
N
Nicolas Hennion 已提交
1620
                                         self.log_x, logmsg, len(logmsg))
A
asergi 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
                self.term_window.addnstr(self.log_y + 1 + logcount,
                                         self.log_x, logmark, 1,
                                         self.__colors_list[log[logcount][2]])
            return logcount + 3
        return 0

    def displayProcess(self, processcount, processlist, log_count=0):
        # Process
        if not processcount:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        # If there is no network & diskio & fs stats
        # then increase process window
        if (not self.network_tag and
            not self.diskio_tag and
            not self.fs_tag):
            process_x = 0
        else:
            process_x = self.process_x
        # Display the process summary
1642
        if (screen_y > self.process_y + 4 and
A
asergi 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662
            screen_x > process_x + 48):
            # Processes sumary
            self.term_window.addnstr(self.process_y, process_x, _("Processes"),
                                     9, self.title_color if self.hascolors else
                                     curses.A_UNDERLINE)
            other = (processcount['total'] -
                     stats.getProcessCount()['running'] -
                     stats.getProcessCount()['sleeping'])
            self.term_window.addnstr(
                self.process_y, process_x + 10,
                "{0}, {1} {2}, {3} {4}, {5} {6}".format(
                    str(processcount['total']),
                    str(processcount['running']),
                    _("running"),
                    str(processcount['sleeping']),
                    _("sleeping"),
                    str(other),
                    _("other")), 42)

        # Processes detail
1663
        if (screen_y > self.process_y + 4 and
A
asergi 已提交
1664
            screen_x > process_x + 49):
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

            # Display the process detail
            tag_pid = False
            tag_uid = False
            tag_nice = False
            tag_status = False
            tag_proc_time = False
            tag_io = False
            if screen_x > process_x + 55:
                tag_pid = True
            if screen_x > process_x + 64:
                tag_uid = True
            if screen_x > process_x + 70:
                tag_nice = True
            if screen_x > process_x + 74:
                tag_status = True
            if screen_x > process_x + 77:
                tag_proc_time = True
            if screen_x > process_x + 97:
1684
                tag_io = True
N
Nicolas Hennion 已提交
1685 1686 1687

            if not psutil_get_io_counter_tag:
                tag_io = False
1688
                
A
asergi 已提交
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705
            # VMS
            self.term_window.addnstr(
                self.process_y + 2, process_x,
                _("VIRT"), 5)
            # RSS
            self.term_window.addnstr(
                self.process_y + 2, process_x + 7,
                _("RES"), 5)
            # CPU%
            self.term_window.addnstr(
                self.process_y + 2, process_x + 14,
                _("CPU%"), 5, curses.A_UNDERLINE
                if self.getProcessSortedBy() == 'cpu_percent' else 0)
            # MEM%
            self.term_window.addnstr(
                self.process_y + 2, process_x + 21,
                _("MEM%"), 5, curses.A_UNDERLINE
1706
                if self.getProcessSortedBy() == 'memory_percent' else 0)
A
asergi 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
            process_name_x = 28
            # If screen space (X) is available then:
            # PID
            if tag_pid:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("PID"), 6)
                process_name_x += 7
            # UID
            if tag_uid:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("USER"), 8)
                process_name_x += 10
            # NICE
            if tag_nice:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("NI"), 3)
                process_name_x += 4
            # STATUS
            if tag_status:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("S"), 1)
                process_name_x += 3
            # TIME+
            if tag_proc_time:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("TIME+"), 8)
                process_name_x += 10
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
            # IO
            if tag_io:
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("IO Read"), 8)
                process_name_x += 10
                self.term_window.addnstr(
                    self.process_y + 2, process_x + process_name_x,
                    _("IO Write"), 8)
                process_name_x += 10               
A
asergi 已提交
1749 1750 1751 1752
            # PROCESS NAME
            self.term_window.addnstr(
                self.process_y + 2, process_x + process_name_x,
                _("NAME"), 12, curses.A_UNDERLINE
1753
                if self.getProcessSortedBy() == 'name' else 0)
A
asergi 已提交
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763

            # If there is no data to display...
            if not processlist:
                self.term_window.addnstr(self.process_y + 3, self.process_x,
                                         _("Compute data..."), 15)
                return 6

            proc_num = min(screen_y - self.term_h +
                           self.process_y - log_count + 5,
                           len(processlist))
1764
            for processes in range(0, proc_num):
A
asergi 已提交
1765
                # VMS
1766
                process_size = processlist[processes]['memory_info'].vms
A
asergi 已提交
1767 1768 1769 1770
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x,
                    self.__autoUnit(process_size), 5)
                # RSS
1771
                process_resident = processlist[processes]['memory_info'].rss
A
asergi 已提交
1772 1773 1774 1775 1776 1777 1778 1779
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x + 7,
                    self.__autoUnit(process_resident), 5)
                # CPU%
                cpu_percent = processlist[processes]['cpu_percent']
                if psutil_get_cpu_percent_tag:
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 14,
1780
                        "{0:.1f}".format(cpu_percent), 5,
A
asergi 已提交
1781 1782 1783 1784 1785
                        self.__getProcessColor(cpu_percent))
                else:
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x, "N/A", 8)
                # MEM%
1786
                memory_percent = processlist[processes]['memory_percent']
A
asergi 已提交
1787 1788
                self.term_window.addnstr(
                    self.process_y + 3 + processes, process_x + 21,
1789 1790
                    "{0:.1f}".format(memory_percent), 5,
                    self.__getProcessColor(memory_percent))
A
asergi 已提交
1791 1792 1793 1794 1795 1796 1797 1798 1799
                # If screen space (X) is available then:
                # PID
                if tag_pid:
                    pid = processlist[processes]['pid']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 28,
                        str(pid), 6)
                # UID
                if tag_uid:
1800
                    uid = processlist[processes]['username']
A
asergi 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 35,
                        str(uid), 8)
                # NICE
                if tag_nice:
                    nice = processlist[processes]['nice']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 45,
                        str(nice), 3)
                # STATUS
                if tag_status:
                    status = processlist[processes]['status']
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 49,
                        str(status), 1)
                # TIME+
                if tag_proc_time:
1818
                    process_time = processlist[processes]['cpu_times']
A
asergi 已提交
1819 1820 1821 1822 1823 1824 1825 1826
                    dtime = timedelta(seconds=sum(process_time))
                    dtime = "{0}:{1}.{2}".format(
                                str(dtime.seconds // 60 % 60).zfill(2),
                                str(dtime.seconds % 60).zfill(2),
                                str(dtime.microseconds)[:2])
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 52,
                        dtime, 8)
1827 1828 1829
                # IO
                if tag_io:
                    # Processes are only refresh every 2 refresh_time
N
Nicolas Hennion 已提交
1830
                    #~ elapsed_time = max(1, self.__refresh_time) * 2
1831
                    io_read = processlist[processes]['io_counters'].read_bytes
1832 1833
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 62,
1834
                        self.__autoUnit(io_read), 8)
1835
                    io_write = processlist[processes]['io_counters'].write_bytes
1836 1837
                    self.term_window.addnstr(
                        self.process_y + 3 + processes, process_x + 72,
1838
                        self.__autoUnit(io_write), 8)
N
Nicolas Hennion 已提交
1839
                        
A
asergi 已提交
1840 1841
                # display process command line
                max_process_name = screen_x - process_x - process_name_x
1842 1843
                process_name = processlist[processes]['name']
                process_cmdline = processlist[processes]['cmdline']
A
asergi 已提交
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
                if (len(process_cmdline) > max_process_name or
                    len(process_cmdline) == 0):
                    command = process_name
                else:
                    command = process_cmdline
                self.term_window.addnstr(self.process_y + 3 + processes,
                                         process_x + process_name_x,
                                         command, max_process_name)

    def displayCaption(self):
        # Caption
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        msg = _("Press 'h' for help")
        if (screen_y > self.caption_y and
            screen_x > self.caption_x + 32):
            self.term_window.addnstr(max(self.caption_y, screen_y - 1),
                                     self.caption_x, msg, self.default_color)

    def displayHelp(self):
        """
        Show the help panel
        """
        if not self.help_tag:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.help_y + 23 and
            screen_x > self.help_x + 79):
            # Console 80x24 is mandatory to display the help message
            self.erase()

            self.term_window.addnstr(
                self.help_y, self.help_x,
                _("Glances {0} with PsUtil {1}").format(
                    self.__version, psutil.__version__),
                79, self.title_color if self.hascolors else 0)

            self.term_window.addnstr(self.help_y + 2, self.help_x,
                                     _("Captions: "), 79)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 10,
                                     _("   OK   "), 8, self.default_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 18,
                                     _("CAREFUL "), 8, self.ifCAREFUL_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 26,
                                     _("WARNING "), 8, self.ifWARNING_color)
            self.term_window.addnstr(self.help_y + 2, self.help_x + 34,
                                     _("CRITICAL"), 8, self.ifCRITICAL_color)

            width = 5
            self.term_window.addnstr(
                self.help_y + 4, self.help_x,
                "{0:^{width}} {1}".format(
                    _("Key"), _("Function"), width=width),
                79, self.title_color if self.hascolors else 0)
            self.term_window.addnstr(
                self.help_y + 5, self.help_x,
                "{0:^{width}} {1}".format(
                    _("a"), _("Sort processes automatically "
                              "(need PsUtil 0.2.0+)"), width=width),
                79, self.ifCRITICAL_color2
                    if not psutil_get_cpu_percent_tag else 0)
            self.term_window.addnstr(
                self.help_y + 6, self.help_x,
                "{0:^{width}} {1}".format(
                    _("c"), _("Sort processes by CPU% "
                              "(need PsUtil 0.2.0+)"), width=width),
                79, self.ifCRITICAL_color2
                    if not psutil_get_cpu_percent_tag else 0)
            self.term_window.addnstr(
                self.help_y + 7, self.help_x,
                "{0:^{width}} {1}".format(
                    _("m"), _("Sort processes by MEM%"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 8, self.help_x,
                "{0:^{width}} {1}".format(
                    _("p"), _("Sort processes by name"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 9, self.help_x,
                "{0:^{width}} {1}".format(
                    _("d"), _("Show/hide disk I/O stats "
                              "(need PsUtil 0.4.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_disk_io_tag else 0)
            self.term_window.addnstr(
                self.help_y + 10, self.help_x,
                "{0:^{width}} {1}".format(
                    _("f"), _("Show/hide file system stats "
                              "(need PsUtil 0.3.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_fs_usage_tag else 0)
            self.term_window.addnstr(
                self.help_y + 11, self.help_x,
                "{0:^{width}} {1}".format(
                    _("n"), _("Show/hide network stats "
                              "(need PsUtil 0.3.0+)"), width=width),
                79, self.ifCRITICAL_color2 if not psutil_network_io_tag else 0)
            self.term_window.addnstr(
                self.help_y + 12, self.help_x,
                "{0:^{width}} {1}".format(
                    _("l"), _("Show/hide log messages (only available "
                              "if display > 24 lines)"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 13, self.help_x,
                "{0:^{width}} {1}".format(
1947
                    _("1"), _("Switch between global CPU and per core stats"), width=width), 79)
A
asergi 已提交
1948 1949
            self.term_window.addnstr(
                self.help_y + 14, self.help_x,
1950 1951 1952 1953
                "{0:^{width}} {1}".format(
                    _("h"), _("Show/hide this help message"), width=width), 79)
            self.term_window.addnstr(
                self.help_y + 15, self.help_x,
A
asergi 已提交
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
                "{0:^{width}} {1}".format(
                    _("q"), _("Quit (Esc and Ctrl-C also work)"), width=width),
                79)

    def displayNow(self, now):
        # Display the current date and time (now...) - Center
        if not now:
            return 0
        screen_x = self.screen.getmaxyx()[1]
        screen_y = self.screen.getmaxyx()[0]
        if (screen_y > self.now_y and
            screen_x > self.now_x):
            now_msg = now.strftime(_("%Y-%m-%d %H:%M:%S"))
            self.term_window.addnstr(
                max(self.now_y, screen_y - 1),
                max(self.now_x, screen_x - 1) - len(now_msg),
                now_msg, len(now_msg))


class glancesHtml:
    """
    This class manages the HTML output
    """

    def __init__(self, htmlfolder="/usr/share", refresh_time=1):
        # Global information to display

        # Init refresh time
        self.__refresh_time = refresh_time

        # Set the templates path
        environment = jinja2.Environment(
            loader=jinja2.FileSystemLoader(htmlfolder + '/html'),
            extensions=['jinja2.ext.loopcontrols'])

        # Open the template
        self.template = environment.get_template('default.html')

        # Define the colors list (hash table) for logged stats
        self.__colors_list = {
            #         CAREFUL WARNING CRITICAL
            'DEFAULT': "bgcdefault fgdefault",
            'OK': "bgcok fgok",
            'CAREFUL': "bgccareful fgcareful",
            'WARNING': "bgcwarning fgcwarning",
            'CRITICAL': "bgcritical fgcritical"
        }

    def __getAlert(self, current=0, max=100):
        # If current < CAREFUL of max then alert = OK
        # If current > CAREFUL of max then alert = CAREFUL
        # If current > WARNING of max then alert = WARNING
        # If current > CRITICAL of max then alert = CRITICAL
        try:
            (current * 100) / max
        except ZeroDivisionError:
            return 'DEFAULT'

        variable = (current * 100) / max

        if variable > limits.getSTDCritical():
            return 'CRITICAL'
        elif variable > limits.getSTDWarning():
            return 'WARNING'
        elif variable > limits.getSTDCareful():
            return 'CAREFUL'

        return 'OK'

    def __getColor(self, current=0, max=100):
        """
        Return colors for logged stats
        """
        return self.__colors_list[self.__getAlert(current, max)]

    def __getCpuColor(self, cpu, max=100):
        cpu['user_color'] = self.__getColor(cpu['user'], max)
        cpu['kernel_color'] = self.__getColor(cpu['kernel'], max)
        cpu['nice_color'] = self.__getColor(cpu['nice'], max)
        return cpu

    def __getLoadAlert(self, current=0, core=1):
        # If current < CAREFUL*core of max then alert = OK
        # If current > CAREFUL*core of max then alert = CAREFUL
        # If current > WARNING*core of max then alert = WARNING
        # If current > CRITICAL*core of max then alert = CRITICAL
        if current > limits.getLOADCritical(core):
            return 'CRITICAL'
        elif current > limits.getLOADWarning(core):
            return 'WARNING'
        elif current > limits.getLOADCareful(core):
            return 'CAREFUL'
        return 'OK'

    def __getLoadColor(self, load, core=1):
        load['min1_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min1'], core)])
        load['min5_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min5'], core)])
        load['min15_color'] = (
            self.__colors_list[self.__getLoadAlert(load['min15'], core)])
        return load

    def __getMemColor(self, mem):
        real_used_phymem = mem['used'] - mem['cache']
        mem['used_color'] = self.__getColor(real_used_phymem, mem['total'])

        return mem

    def __getMemSwapColor(self, memswap):
        memswap['used_color'] = self.__getColor(memswap['used'],
                                                memswap['total'])
        return memswap

    def __getFsColor(self, fs):
        mounted = 0
2070
        for mounted in range(0, len(fs)):
A
asergi 已提交
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
            fs[mounted]['used_color'] = self.__getColor(fs[mounted]['used'],
                                                        fs[mounted]['size'])
        return fs

    def update(self, stats):
        if stats.getCpu():
            # Open the output file
            f = open('glances.html', 'w')

            # Process color

            # Render it
            # HTML Refresh is set to 1.5 * refresh_time
            # ... to avoid display while page rendering
            data = self.template.render(
                refresh=int(self.__refresh_time * 1.5),
                host=stats.getHost(),
                system=stats.getSystem(),
                cpu=self.__getCpuColor(stats.getCpu()),
                load=self.__getLoadColor(stats.getLoad(), stats.getCore()),
                core=stats.getCore(),
                mem=self.__getMemColor(stats.getMem()),
                memswap=self.__getMemSwapColor(stats.getMemSwap()),
                net=stats.getNetwork(),
                diskio=stats.getDiskIO(),
                fs=self.__getFsColor(stats.getFs()),
                proccount=stats.getProcessCount(),
                proclist=stats.getProcessList())

            # Write data into the file
            f.write(data)

            # Close the file
            f.close()


class glancesCsv:
    """
    This class manages the Csv output
    """

    def __init__(self, cvsfile="./glances.csv", refresh_time=1):
        # Global information to display

        # Init refresh time
        self.__refresh_time = refresh_time

        # Set the ouput (CSV) path
        try:
            self.__cvsfile_fd = open("%s" % cvsfile, "wb")
            self.__csvfile = csv.writer(self.__cvsfile_fd)
2122 2123
        except IOError as error:
            print("Can not create the output CSV file: ", error[1])
A
asergi 已提交
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
            sys.exit(0)

    def exit(self):
        self.__cvsfile_fd.close()

    def update(self, stats):
        if stats.getCpu():
            # Update CSV with the CPU stats
            cpu = stats.getCpu()
            self.__csvfile.writerow(["cpu", cpu['user'], cpu['kernel'],
                                     cpu['nice']])
        if stats.getLoad():
            # Update CSV with the LOAD stats
            load = stats.getLoad()
            self.__csvfile.writerow(["load", load['min1'], load['min5'],
                                     load['min15']])
        if (stats.getMem() and
            stats.getMemSwap()):
            # Update CSV with the MEM stats
            mem = stats.getMem()
            self.__csvfile.writerow(["mem", mem['total'], mem['used'],
                                     mem['free']])
            memswap = stats.getMemSwap()
            self.__csvfile.writerow(["swap", memswap['total'], memswap['used'],
                                     memswap['free']])
        self.__cvsfile_fd.flush()

# Global def
#===========


def printVersion():
2156
    print(_("Glances version ") + __version__)
A
asergi 已提交
2157 2158 2159 2160


def printSyntax():
    printVersion()
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
    print(_("Usage: glances [-f file] [-o output] [-t sec] [-h] [-v]"))
    print("")
    print(_("\t-b\t\tDisplay network rate in Byte per second"))
    print(_("\t-d\t\tDisable disk I/O module"))
    print(_("\t-f file\t\tSet the output folder (HTML) or file (CSV)"))
    print(_("\t-h\t\tDisplay the syntax and exit"))
    print(_("\t-m\t\tDisable mount module"))
    print(_("\t-n\t\tDisable network module"))
    print(_("\t-o output\tDefine additional output (available: HTML or CSV)"))
    print(_("\t-t sec\t\tSet the refresh time in seconds (default: %d)" %
            refresh_time))
    print(_("\t-v\t\tDisplay the version and exit"))
A
asergi 已提交
2173 2174 2175 2176


def init():
    global psutil_disk_io_tag, psutil_fs_usage_tag, psutil_network_io_tag
2177
    global network_bytepersec_tag
A
asergi 已提交
2178 2179 2180 2181 2182 2183
    global limits, logs, stats, screen
    global htmloutput, csvoutput
    global html_tag, csv_tag
    global refresh_time

    # Set default tags
2184
    network_bytepersec_tag = False
A
asergi 已提交
2185 2186
    html_tag = False
    csv_tag = False
2187
    
A
asergi 已提交
2188 2189 2190 2191 2192
    # Set the default refresh time
    refresh_time = 2

    # Manage args
    try:
2193
        opts, args = getopt.getopt(sys.argv[1:], "bdmnho:f:t:v",
A
asergi 已提交
2194 2195
                                   ["help", "output", "file",
                                    "time", "version"])
2196
    except getopt.GetoptError as err:
A
asergi 已提交
2197
        # Print help information and exit:
2198
        print(str(err))
A
asergi 已提交
2199 2200 2201 2202 2203 2204 2205
        printSyntax()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-v", "--version"):
            printVersion()
            sys.exit(0)
        elif opt in ("-o", "--output"):
N
Nicolas Hennion 已提交
2206 2207
            if arg.lower() == "html":
                # Test if the Jinja lib is available
A
asergi 已提交
2208 2209 2210
                if jinja_tag:
                    html_tag = True
                else:
2211 2212 2213
                    print(_("Error: Need Jinja2 library to export into HTML"))
                    print()
                    print(_("Try to install the python-jinja2 package"))
A
asergi 已提交
2214
                    sys.exit(2)
N
Nicolas Hennion 已提交
2215 2216
            elif arg.lower() == "csv":
                # Test if the Cvs lib is available
A
asergi 已提交
2217 2218 2219
                if csvlib_tag:
                    csv_tag = True
                else:
2220
                    print(_("Error: Need CSV library to export to CSV"))
A
asergi 已提交
2221 2222
                    sys.exit(2)
            else:
2223
                print(_("Error: Unknown output %s" % arg))
N
Nicolas Hennion 已提交
2224
                printSyntax()
A
asergi 已提交
2225 2226 2227 2228 2229 2230 2231 2232
                sys.exit(2)
        elif opt in ("-f", "--file"):
            output_file = arg
            output_folder = arg
        elif opt in ("-t", "--time"):
            if int(arg) >= 1:
                refresh_time = int(arg)
            else:
2233
                print(_("Error: Refresh time should be a positive integer"))
A
asergi 已提交
2234 2235 2236 2237 2238 2239 2240
                sys.exit(2)
        elif opt in ("-d", "--diskio"):
            psutil_disk_io_tag = False
        elif opt in ("-m", "--mount"):
            psutil_fs_usage_tag = False
        elif opt in ("-n", "--netrate"):
            psutil_network_io_tag = False
2241 2242
        elif opt in ("-b", "--bytepersec"):
            network_bytepersec_tag = True
A
asergi 已提交
2243 2244 2245 2246 2247 2248 2249 2250 2251
        else:
            printSyntax()
            sys.exit(0)

    # Check options
    if html_tag:
        try:
            output_folder
        except UnboundLocalError:
2252 2253
            print(_("Error: HTML export (-o html) need"
                    "output folder definition (-f <folder>)"))
A
asergi 已提交
2254 2255 2256 2257 2258 2259
            sys.exit(2)

    if csv_tag:
        try:
            output_file
        except UnboundLocalError:
2260 2261
            print(_("Error: CSV export (-o csv) need "
                    "output file definition (-f <file>)"))
A
asergi 已提交
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
            sys.exit(2)

    # Catch CTRL-C
    signal.signal(signal.SIGINT, signal_handler)

    # Init Limits
    limits = glancesLimits()

    # Init Logs
    logs = glancesLogs()

    # Init stats
    stats = glancesStats()

    # Init HTML output
    if html_tag:
        htmloutput = glancesHtml(htmlfolder=output_folder,
                                 refresh_time=refresh_time)

    # Init CSV output
    if csv_tag:
        csvoutput = glancesCsv(cvsfile=output_file,
                               refresh_time=refresh_time)

    # Init screen
    screen = glancesScreen(refresh_time=refresh_time)


def main():
N
Nicolas Hennion 已提交
2291
    
A
asergi 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
    # Init stuff
    init()

    # Main loop
    while True:
        # Get informations from libstatgrab and others...
        stats.update()

        # Update the screen
        screen.update(stats)

        # Update the HTML output
        if html_tag:
            htmloutput.update(stats)

        # Update the CSV output
        if csv_tag:
            csvoutput.update(stats)


def end():
    screen.end()

    if csv_tag:
        csvoutput.exit()

    sys.exit(0)


def signal_handler(signal, frame):
    end()

N
Nicolas Hennion 已提交
2324

A
asergi 已提交
2325 2326 2327 2328 2329 2330 2331
# Main
#=====

if __name__ == "__main__":
    main()

# The end...