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

"""CPU plugin."""
A
Alessio Sergi 已提交
21

22
from glances.logger import logger
23
from glances.timer import getTimeSinceLastUpdate
24 25
from glances.compat import iterkeys
from glances.cpu_percent import cpu_percent
26 27
from glances.globals import LINUX
from glances.plugins.glances_core import Plugin as CorePlugin
A
flake8  
Alessio Sergi 已提交
28 29 30
from glances.plugins.glances_plugin import GlancesPlugin

import psutil
31

N
nicolargo 已提交
32
# Fields description
N
nicolargo 已提交
33 34 35 36 37
# description: human readable description
# short_name: shortname to use un UI
# unit: unit type
# rate: is it a rate ? If yes, // by time_since_update when displayed,
# min_symbol: Auto unit should be used if value > than 1 'X' (K, M, G)...
N
nicolargo 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
fields_description = {
    'total': {'description': 'Sum of all CPU percentages (except idle).',
              'unit': 'percent'},
    'system': {'description': 'percent time spent in kernel space. System CPU time is the \
time spent running code in the Operating System kernel.',
               'unit': 'percent'},
    'user': {'description': 'CPU percent time spent in user space. \
User CPU time is the time spent on the processor running your program\'s code (or code in libraries).',
             'unit': 'percent'},
    'iowait': {'description': '*(Linux)*: percent time spent by the CPU waiting for I/O \
operations to complete.',
               'unit': 'percent'},
    'idle': {'description': 'percent of CPU used by any program. Every program or task \
that runs on a computer system occupies a certain amount of processing \
time on the CPU. If the CPU has completed all tasks it is idle.',
             'unit': 'percent'},
    'irq': {'description': '*(Linux and BSD)*: percent time spent servicing/handling \
hardware/software interrupts. Time servicing interrupts (hardware + \
software).',
            'unit': 'percent'},
    'nice': {'description': '*(Unix)*: percent time occupied by user level processes with \
a positive nice value. The time the CPU has spent running users\' \
processes that have been *niced*.',
             'unit': 'percent'},
    'steal': {'description': '*(Linux)*: percentage of time a virtual CPU waits for a real \
CPU while the hypervisor is servicing another virtual processor.',
              'unit': 'percent'},
N
nicolargo 已提交
65
    'ctx_switches': {'description': 'number of context switches (voluntary + involuntary) per \
N
nicolargo 已提交
66 67 68
second. A context switch is a procedure that a computer\'s CPU (central \
processing unit) follows to change from one task (or process) to \
another while ensuring that the tasks do not conflict.',
N
nicolargo 已提交
69 70 71 72
                     'unit': 'number',
                     'rate': True,
                     'min_symbol': 'K',
                     'short_name': 'ctx_sw'},
N
nicolargo 已提交
73
    'interrupts': {'description': 'number of interrupts per second.',
N
nicolargo 已提交
74 75 76 77
                   'unit': 'number',
                   'rate': True,
                   'min_symbol': 'K',
                   'short_name': 'inter'},
N
nicolargo 已提交
78
    'soft_interrupts': {'description': 'number of software interrupts per second. Always set to \
N
nicolargo 已提交
79
0 on Windows and SunOS.',
N
nicolargo 已提交
80 81 82 83
                        'unit': 'number',
                        'rate': True,
                        'min_symbol': 'K',
                        'short_name': 'sw_int'},
N
nicolargo 已提交
84
    'cpucore': {'description': 'Total number of CPU core.',
N
nicolargo 已提交
85
                'unit': 'number'},
N
nicolargo 已提交
86 87
    'time_since_update': {'description': 'Number of seconds since last update.',
                          'unit': 'seconds'},
N
nicolargo 已提交
88 89
}

N
Nicolargo 已提交
90 91 92 93
# SNMP OID
# percentage of user CPU time: .1.3.6.1.4.1.2021.11.9.0
# percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
# percentages of idle CPU time: .1.3.6.1.4.1.2021.11.11.0
N
Nicolargo 已提交
94 95
snmp_oid = {'default': {'user': '1.3.6.1.4.1.2021.11.9.0',
                        'system': '1.3.6.1.4.1.2021.11.10.0',
N
Nicolargo 已提交
96
                        'idle': '1.3.6.1.4.1.2021.11.11.0'},
N
Nicolargo 已提交
97
            'windows': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
N
Nicolargo 已提交
98
            'esxi': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
N
Nicolargo 已提交
99 100
            'netapp': {'system': '1.3.6.1.4.1.789.1.2.1.3.0',
                       'idle': '1.3.6.1.4.1.789.1.2.1.5.0',
N
nicolargo 已提交
101
                       'cpucore': '1.3.6.1.4.1.789.1.2.1.6.0'}}
A
Alessio Sergi 已提交
102

103
# Define the history items list
104
# - 'name' define the stat identifier
N
Nicolargo 已提交
105
# - 'y_unit' define the Y label
106 107 108 109 110 111
items_history_list = [{'name': 'user',
                       'description': 'User CPU usage',
                       'y_unit': '%'},
                      {'name': 'system',
                       'description': 'System CPU usage',
                       'y_unit': '%'}]
112

A
PEP 257  
Alessio Sergi 已提交
113

N
Nicolargo 已提交
114
class Plugin(GlancesPlugin):
A
Alessio Sergi 已提交
115 116 117 118
    """Glances CPU plugin.

    'stats' is a dictionary that contains the system-wide CPU utilization as a
    percentage.
A
Alessio Sergi 已提交
119 120
    """

121
    def __init__(self, args=None, config=None):
A
PEP 257  
Alessio Sergi 已提交
122
        """Init the CPU plugin."""
123 124
        super(Plugin, self).__init__(args=args,
                                     config=config,
N
nicolargo 已提交
125 126
                                     items_history_list=items_history_list,
                                     fields_description=fields_description)
A
Alessio Sergi 已提交
127 128 129 130

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

131 132 133 134 135 136
        # Call CorePlugin in order to display the core number
        try:
            self.nb_log_core = CorePlugin(args=self.args).update()["log"]
        except Exception:
            self.nb_log_core = 1

137
    @GlancesPlugin._check_decorator
138
    @GlancesPlugin._log_result_decorator
A
Alessio Sergi 已提交
139
    def update(self):
A
PEP 257  
Alessio Sergi 已提交
140
        """Update CPU stats using the input method."""
141
        # Grab stats into self.stats
142
        if self.input_method == 'local':
143
            stats = self.update_local()
144
        elif self.input_method == 'snmp':
145 146 147 148 149 150
            stats = self.update_snmp()
        else:
            stats = self.get_init_value()

        # Update the stats
        self.stats = stats
A
Alessio Sergi 已提交
151 152 153

        return self.stats

154
    def update_local(self):
A
Alessio Sergi 已提交
155
        """Update CPU stats using psutil."""
156 157 158 159 160
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
        # Get all possible values for CPU stats: user, system, idle,
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
        # The following stats are returned by the API but not displayed in the UI:
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)
161 162 163 164 165

        # Init new stats
        stats = self.get_init_value()

        stats['total'] = cpu_percent.get()
166 167
        # Grab: 'user', 'system', 'idle', 'nice', 'iowait',
        #       'irq', 'softirq', 'steal', 'guest', 'guest_nice'
168
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
169 170
        for stat in cpu_times_percent._fields:
            stats[stat] = getattr(cpu_times_percent, stat)
171

A
Alessio Sergi 已提交
172
        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
173 174 175 176
        # - ctx_switches: number of context switches (voluntary + involuntary) since boot.
        # - interrupts: number of interrupts since boot.
        # - soft_interrupts: number of software interrupts since boot. Always set to 0 on Windows and SunOS.
        # - syscalls: number of system calls since boot. Always set to 0 on Linux.
A
Alessio Sergi 已提交
177
        cpu_stats = psutil.cpu_stats()
178

A
Alessio Sergi 已提交
179 180 181
        # By storing time data we enable Rx/s and Tx/s calculations in the
        # XML/RPC API, which would otherwise be overly difficult work
        # for users of the API
182 183 184 185
        stats['time_since_update'] = getTimeSinceLastUpdate('cpu')

        # Core number is needed to compute the CTX switch limit
        stats['cpucore'] = self.nb_log_core
A
Alessio Sergi 已提交
186 187 188

        # Previous CPU stats are stored in the cpu_stats_old variable
        if not hasattr(self, 'cpu_stats_old'):
189 190 191 192
            # Init the stats (needed to have the key name for export)
            for stat in cpu_stats._fields:
                # @TODO: better to set it to None but should refactor views and UI...
                stats[stat] = 0
193
        else:
194
            # Others calls...
A
Alessio Sergi 已提交
195 196
            for stat in cpu_stats._fields:
                if getattr(cpu_stats, stat) is not None:
197
                    stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat)
A
Alessio Sergi 已提交
198

199 200
        # Save stats to compute next step
        self.cpu_stats_old = cpu_stats
201

202 203
        return stats

204 205
    def update_snmp(self):
        """Update CPU stats using SNMP."""
206 207 208 209

        # Init new stats
        stats = self.get_init_value()

210 211 212 213 214 215 216 217 218 219 220 221
        # Update stats using SNMP
        if self.short_system_name in ('windows', 'esxi'):
            # Windows or VMWare ESXi
            # You can find the CPU utilization of windows system by querying the oid
            # Give also the number of core (number of element in the table)
            try:
                cpu_stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
                                                bulk=True)
            except KeyError:
                self.reset()

            # Iter through CPU and compute the idle CPU stats
222 223
            stats['nb_log_core'] = 0
            stats['idle'] = 0
224 225
            for c in cpu_stats:
                if c.startswith('percent'):
226 227 228 229 230 231
                    stats['idle'] += float(cpu_stats['percent.3'])
                    stats['nb_log_core'] += 1
            if stats['nb_log_core'] > 0:
                stats['idle'] = stats['idle'] / stats['nb_log_core']
            stats['idle'] = 100 - stats['idle']
            stats['total'] = 100 - stats['idle']
232 233 234 235

        else:
            # Default behavor
            try:
236
                stats = self.get_stats_snmp(
237 238
                    snmp_oid=snmp_oid[self.short_system_name])
            except KeyError:
239
                stats = self.get_stats_snmp(
240 241
                    snmp_oid=snmp_oid['default'])

242
            if stats['idle'] == '':
243 244 245 246
                self.reset()
                return self.stats

            # Convert SNMP stats to float
247 248 249 250 251
            for key in iterkeys(stats):
                stats[key] = float(stats[key])
            stats['total'] = 100 - stats['idle']

        return stats
252

253
    def update_views(self):
A
PEP 257  
Alessio Sergi 已提交
254
        """Update stats views."""
255
        # Call the father's method
A
Alessio Sergi 已提交
256
        super(Plugin, self).update_views()
257 258 259

        # Add specifics informations
        # Alert and log
260
        for key in ['user', 'system', 'iowait', 'total']:
261 262 263
            if key in self.stats:
                self.views[key]['decoration'] = self.get_alert_log(self.stats[key], header=key)
        # Alert only
264
        for key in ['steal']:
265 266
            if key in self.stats:
                self.views[key]['decoration'] = self.get_alert(self.stats[key], header=key)
267 268 269 270
        # Alert only but depend on Core number
        for key in ['ctx_switches']:
            if key in self.stats:
                self.views[key]['decoration'] = self.get_alert(self.stats[key], maximum=100 * self.stats['cpucore'], header=key)
271
        # Optional
272
        for key in ['nice', 'irq', 'idle', 'steal', 'ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls']:
273 274 275
            if key in self.stats:
                self.views[key]['optional'] = True

276
    def msg_curse(self, args=None, max_width=None):
A
PEP 257  
Alessio Sergi 已提交
277
        """Return the list to display in the UI."""
A
Alessio Sergi 已提交
278 279 280
        # Init the return message
        ret = []

281
        # Only process if stats exist and plugin not disable
N
nicolargo 已提交
282
        if not self.stats or self.args.percpu or self.is_disable():
N
Nicolas Hennion 已提交
283 284
            return ret

N
Nicolargo 已提交
285 286
        # If user stat is not here, display only idle / total CPU usage (for
        # exemple on Windows OS)
287
        idle_tag = 'user' not in self.stats
288

N
nicolargo 已提交
289 290
        # First line
        # Total + (idle) + ctx_sw
291
        msg = '{}'.format('CPU')
A
Alessio Sergi 已提交
292
        ret.append(self.curse_add_line(msg, "TITLE"))
293 294 295 296 297 298 299 300
        trend_user = self.get_trend('user')
        trend_system = self.get_trend('system')
        if trend_user is None or trend_user is None:
            trend_cpu = None
        else:
            trend_cpu = trend_user + trend_system
        msg = ' {:4}'.format(self.trend_msg(trend_cpu))
        ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
301
        # Total CPU usage
302
        msg = '{:5.1f}%'.format(self.stats['total'])
303 304 305
        ret.append(self.curse_add_line(
            msg, self.get_views(key='total', option='decoration')))
        # Idle CPU
N
nicolargo 已提交
306
        if not idle_tag:
N
nicolargo 已提交
307
            ret.extend(self.curse_add_stat('idle', width=15, header='  '))
N
nicolargo 已提交
308 309
        # ctx_switches
        ret.extend(self.curse_add_stat('ctx_switches', width=15, header='  '))
310

N
nicolargo 已提交
311 312
        # Second line
        # user|idle + irq + interrupts
A
Alessio Sergi 已提交
313 314
        ret.append(self.curse_new_line())
        # User CPU
N
nicolargo 已提交
315
        if not idle_tag:
N
nicolargo 已提交
316
            ret.extend(self.curse_add_stat('user', width=15))
317
        elif 'idle' in self.stats:
N
nicolargo 已提交
318
            ret.extend(self.curse_add_stat('idle', width=15))
A
Alessio Sergi 已提交
319
        # IRQ CPU
N
nicolargo 已提交
320 321 322
        ret.extend(self.curse_add_stat('irq', width=15, header='  '))
        # interrupts
        ret.extend(self.curse_add_stat('interrupts', width=15, header='  '))
323

N
nicolargo 已提交
324 325
        # Third line
        # system|core + nice + sw_int
A
Alessio Sergi 已提交
326 327
        ret.append(self.curse_new_line())
        # System CPU
N
nicolargo 已提交
328
        if not idle_tag:
N
nicolargo 已提交
329
            ret.extend(self.curse_add_stat('system', width=15))
330
        else:
N
nicolargo 已提交
331
            ret.extend(self.curse_add_stat('core', width=15))
332
        # Nice CPU
N
nicolargo 已提交
333 334 335
        ret.extend(self.curse_add_stat('nice', width=15, header='  '))
        # soft_interrupts
        ret.extend(self.curse_add_stat('soft_interrupts', width=15, header='  '))
336

N
nicolargo 已提交
337 338
        # Fourth line
        # iowat + steal + syscalls
A
Alessio Sergi 已提交
339
        ret.append(self.curse_new_line())
340
        # IOWait CPU
N
nicolargo 已提交
341 342 343
        ret.extend(self.curse_add_stat('iowait', width=15))
        # Steal CPU usage
        ret.extend(self.curse_add_stat('steal', width=15, header='  '))
344
        # syscalls: number of system calls since boot. Always set to 0 on Linux. (do not display)
N
nicolargo 已提交
345
        if not LINUX:
N
nicolargo 已提交
346
            ret.extend(self.curse_add_stat('syscalls', width=15, header='  '))
A
Alessio Sergi 已提交
347 348 349

        # Return the message with decoration
        return ret