Test Failed
Push — master ( ee826a...d9056e )
by Nicolas
03:09
created

glances.plugins.cpu.PluginModel.update()   A

Complexity

Conditions 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nop 1
dl 0
loc 16
rs 9.9
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""CPU plugin."""
11
12
from glances.globals import LINUX, WINDOWS, SUNOS, iterkeys
13
from glances.cpu_percent import cpu_percent
14
from glances.plugins.core import PluginModel as CorePluginModel
15
from glances.plugins.plugin.model import GlancesPluginModel
16
17
import psutil
18
19
# Fields description
20
# description: human readable description
21
# short_name: shortname to use un UI
22
# unit: unit type
23
# rate: if True then compute and add *_gauge and *_rate_per_is fields
24
# min_symbol: Auto unit should be used if value > than 1 'X' (K, M, G)...
25
fields_description = {
26
    'total': {'description': 'Sum of all CPU percentages (except idle).', 'unit': 'percent'},
27
    'system': {
28
        'description': 'Percent time spent in kernel space. System CPU time is the \
29
time spent running code in the Operating System kernel.',
30
        'unit': 'percent',
31
    },
32
    'user': {
33
        'description': 'CPU percent time spent in user space. \
34
User CPU time is the time spent on the processor running your program\'s code (or code in libraries).',
35
        'unit': 'percent',
36
    },
37
    'iowait': {
38
        'description': '*(Linux)*: percent time spent by the CPU waiting for I/O \
39
operations to complete.',
40
        'unit': 'percent',
41
    },
42
    'dpc': {
43
        'description': '*(Windows)*: time spent servicing deferred procedure calls (DPCs)',
44
        'unit': 'percent',
45
    },
46
    'idle': {
47
        'description': 'percent of CPU used by any program. Every program or task \
48
that runs on a computer system occupies a certain amount of processing \
49
time on the CPU. If the CPU has completed all tasks it is idle.',
50
        'unit': 'percent',
51
    },
52
    'irq': {
53
        'description': '*(Linux and BSD)*: percent time spent servicing/handling \
54
hardware/software interrupts. Time servicing interrupts (hardware + \
55
software).',
56
        'unit': 'percent',
57
    },
58
    'nice': {
59
        'description': '*(Unix)*: percent time occupied by user level processes with \
60
a positive nice value. The time the CPU has spent running users\' \
61
processes that have been *niced*.',
62
        'unit': 'percent',
63
    },
64
    'steal': {
65
        'description': '*(Linux)*: percentage of time a virtual CPU waits for a real \
66
CPU while the hypervisor is servicing another virtual processor.',
67
        'unit': 'percent',
68
    },
69
    'guest': {
70
        'description': '*(Linux)*: time spent running a virtual CPU for guest operating \
71
systems under the control of the Linux kernel.',
72
        'unit': 'percent',
73
    },
74
    'ctx_switches': {
75
        'description': 'number of context switches (voluntary + involuntary) per \
76
second. A context switch is a procedure that a computer\'s CPU (central \
77
processing unit) follows to change from one task (or process) to \
78
another while ensuring that the tasks do not conflict.',
79
        'unit': 'number',
80
        'rate': True,
81
        'min_symbol': 'K',
82
        'short_name': 'ctx_sw',
83
    },
84
    'interrupts': {
85
        'description': 'number of interrupts per second.',
86
        'unit': 'number',
87
        'rate': True,
88
        'min_symbol': 'K',
89
        'short_name': 'inter',
90
    },
91
    'soft_interrupts': {
92
        'description': 'number of software interrupts per second. Always set to \
93
0 on Windows and SunOS.',
94
        'unit': 'number',
95
        'rate': True,
96
        'min_symbol': 'K',
97
        'short_name': 'sw_int',
98
    },
99
    'syscalls': {
100
        'description': 'number of system calls per second. Always 0 on Linux OS.',
101
        'unit': 'number',
102
        'rate': True,
103
        'min_symbol': 'K',
104
        'short_name': 'sys_call',
105
    },
106
    'cpucore': {'description': 'Total number of CPU core.', 'unit': 'number'},
107
    'time_since_update': {'description': 'Number of seconds since last update.', 'unit': 'seconds'},
108
}
109
110
# SNMP OID
111
# percentage of user CPU time: .1.3.6.1.4.1.2021.11.9.0
112
# percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
113
# percentages of idle CPU time: .1.3.6.1.4.1.2021.11.11.0
114
snmp_oid = {
115
    'default': {
116
        'user': '1.3.6.1.4.1.2021.11.9.0',
117
        'system': '1.3.6.1.4.1.2021.11.10.0',
118
        'idle': '1.3.6.1.4.1.2021.11.11.0',
119
    },
120
    'windows': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
121
    'esxi': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
122
    'netapp': {
123
        'system': '1.3.6.1.4.1.789.1.2.1.3.0',
124
        'idle': '1.3.6.1.4.1.789.1.2.1.5.0',
125
        'cpucore': '1.3.6.1.4.1.789.1.2.1.6.0',
126
    },
127
}
128
129
# Define the history items list
130
# - 'name' define the stat identifier
131
# - 'y_unit' define the Y label
132
items_history_list = [
133
    {'name': 'user', 'description': 'User CPU usage', 'y_unit': '%'},
134
    {'name': 'system', 'description': 'System CPU usage', 'y_unit': '%'},
135
]
136
137
138
class PluginModel(GlancesPluginModel):
139
    """Glances CPU plugin.
140
141
    'stats' is a dictionary that contains the system-wide CPU utilization as a
142
    percentage.
143
    """
144
145
    def __init__(self, args=None, config=None):
146
        """Init the CPU plugin."""
147
        super(PluginModel, self).__init__(
148
            args=args, config=config, items_history_list=items_history_list, fields_description=fields_description
149
        )
150
151
        # We want to display the stat in the curse interface
152
        self.display_curse = True
153
154
        # Call CorePluginModel in order to display the core number
155
        try:
156
            self.nb_log_core = CorePluginModel(args=self.args).update()["log"]
157
        except Exception:
158
            self.nb_log_core = 1
159
160
    @GlancesPluginModel._check_decorator
161
    @GlancesPluginModel._log_result_decorator
162
    def update(self):
163
        """Update CPU stats using the input method."""
164
        # Grab stats into self.stats
165
        if self.input_method == 'local':
166
            stats = self.update_local()
167
        elif self.input_method == 'snmp':
168
            stats = self.update_snmp()
169
        else:
170
            stats = self.get_init_value()
171
172
        # Update the stats
173
        self.stats = stats
174
175
        return self.stats
176
177
    @GlancesPluginModel._manage_rate
178
    def update_local(self):
179
        """Update CPU stats using psutil."""
180
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
181
        # Get all possible values for CPU stats: user, system, idle,
182
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
183
        # The following stats are returned by the API but not displayed in the UI:
184
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)
185
186
        # Init new stats
187
        stats = self.get_init_value()
188
189
        stats['total'] = cpu_percent.get()
190
191
        # Standards stats
192
        # - user: time spent by normal processes executing in user mode; on Linux this also includes guest time
193
        # - system: time spent by processes executing in kernel mode
194
        # - idle: time spent doing nothing
195
        # - nice (UNIX): time spent by niced (prioritized) processes executing in user mode
196
        #                on Linux this also includes guest_nice time
197
        # - iowait (Linux): time spent waiting for I/O to complete.
198
        #                   This is not accounted in idle time counter.
199
        # - irq (Linux, BSD): time spent for servicing hardware interrupts
200
        # - softirq (Linux): time spent for servicing software interrupts
201
        # - steal (Linux 2.6.11+): time spent by other operating systems running in a virtualized environment
202
        # - guest (Linux 2.6.24+): time spent running a virtual CPU for guest operating systems under
203
        #                          the control of the Linux kernel
204
        # - guest_nice (Linux 3.2.0+): time spent running a niced guest (virtual CPU for guest operating systems
205
        #                              under the control of the Linux kernel)
206
        # - interrupt (Windows): time spent for servicing hardware interrupts ( similar to “irq” on UNIX)
207
        # - dpc (Windows): time spent servicing deferred procedure calls (DPCs)
208
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
209
        # Filter stats to keep only the fields we want (define in fields_description)
210
        # It will also convert psutil objects to a standard Python dict
211
        stats.update(self.filter_stats(cpu_times_percent))
212
213
        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
214
        # - ctx_switches: number of context switches (voluntary + involuntary) since boot.
215
        # - interrupts: number of interrupts since boot.
216
        # - soft_interrupts: number of software interrupts since boot. Always set to 0 on Windows and SunOS.
217
        # - syscalls: number of system calls since boot. Always set to 0 on Linux.
218
        cpu_stats = psutil.cpu_stats()
219
        # Filter stats to keep only the fields we want (define in fields_description)
220
        # It will also convert psutil objects to a standard Python dict
221
        stats.update(self.filter_stats(cpu_stats))
222
        # Core number is needed to compute the CTX switch limit
223
        stats['cpucore'] = self.nb_log_core
224
225
        return stats
226
227
    def update_snmp(self):
228
        """Update CPU stats using SNMP."""
229
230
        # Init new stats
231
        stats = self.get_init_value()
232
233
        # Update stats using SNMP
234
        if self.short_system_name in ('windows', 'esxi'):
235
            # Windows or VMWare ESXi
236
            # You can find the CPU utilization of windows system by querying the oid
237
            # Give also the number of core (number of element in the table)
238
            try:
239
                cpu_stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], bulk=True)
240
            except KeyError:
241
                self.reset()
242
243
            # Iter through CPU and compute the idle CPU stats
244
            stats['nb_log_core'] = 0
245
            stats['idle'] = 0
246
            for c in cpu_stats:
247
                if c.startswith('percent'):
248
                    stats['idle'] += float(cpu_stats['percent.3'])
249
                    stats['nb_log_core'] += 1
250
            if stats['nb_log_core'] > 0:
251
                stats['idle'] = stats['idle'] / stats['nb_log_core']
252
            stats['idle'] = 100 - stats['idle']
253
            stats['total'] = 100 - stats['idle']
254
255
        else:
256
            # Default behavior
257
            try:
258
                stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name])
259
            except KeyError:
260
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])
261
262
            if stats['idle'] == '':
263
                self.reset()
264
                return self.stats
265
266
            # Convert SNMP stats to float
267
            for key in iterkeys(stats):
268
                stats[key] = float(stats[key])
269
            stats['total'] = 100 - stats['idle']
270
271
        return stats
272
273
    def update_views(self):
274
        """Update stats views."""
275
        # Call the father's method
276
        super(PluginModel, self).update_views()
277
278
        # Add specifics information
279
        # Alert and log
280
        for key in ['user', 'system', 'iowait', 'dpc', 'total']:
281
            if key in self.stats:
282
                self.views[key]['decoration'] = self.get_alert_log(self.stats[key], header=key)
283
        # Alert only
284
        for key in ['steal']:
285
            if key in self.stats:
286
                self.views[key]['decoration'] = self.get_alert(self.stats[key], header=key)
287
        # Alert only but depend on Core number
288
        for key in ['ctx_switches']:
289
            # Skip alert if no timespan to measure
290
            if self.stats.get('time_since_update', 0) == 0:
291
                continue
292
            if key in self.stats:
293
                self.views[key]['decoration'] = self.get_alert(
294
                    self.stats[key], maximum=100 * self.stats['cpucore'], header=key
295
                )
296
        # Optional
297
        for key in [
298
            'nice',
299
            'irq',
300
            'idle',
301
            'steal',
302
            'guest',
303
            'ctx_switches',
304
            'interrupts',
305
            'soft_interrupts',
306
            'syscalls',
307
        ]:
308
            if key in self.stats:
309
                self.views[key]['optional'] = True
310
311
    def msg_curse(self, args=None, max_width=None):
312
        """Return the list to display in the UI."""
313
        # Init the return message
314
        ret = []
315
316
        # Only process if stats exist and plugin not disable
317
        if not self.stats or self.args.percpu or self.is_disabled():
318
            return ret
319
320
        # Some tag to enable/disable stats (example: idle_tag triggered on Windows OS)
321
        idle_tag = 'user' not in self.stats
322
323
        # First line
324
        # Total + (idle) + ctx_sw
325
        msg = '{:8}'.format('CPU')
326
        ret.append(self.curse_add_line(msg, "TITLE"))
327
        # Total CPU usage
328
        msg = '{:5.1f}%'.format(self.stats['total'])
329
        ret.append(self.curse_add_line(msg, self.get_views(key='total', option='decoration')))
330
        # Idle CPU
331
        if 'idle' in self.stats and not idle_tag:
332
            msg = '  {:8}'.format('idle')
333
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', option='optional')))
334
            msg = '{:4.1f}%'.format(self.stats['idle'])
335
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='idle', option='optional')))
336
        # ctx_switches
337
        # On WINDOWS/SUNOS the ctx_switches is displayed in the third line
338
        if not WINDOWS and not SUNOS:
339
            ret.extend(self.curse_add_stat('ctx_switches', width=15, header='  '))
340
341
        # Second line
342
        # user|idle + irq + interrupts
343
        ret.append(self.curse_new_line())
344
        # User CPU
345
        if not idle_tag:
346
            ret.extend(self.curse_add_stat('user', width=15))
347
        elif 'idle' in self.stats:
348
            ret.extend(self.curse_add_stat('idle', width=15))
349
        # IRQ CPU
350
        ret.extend(self.curse_add_stat('irq', width=14, header='  '))
351
        # interrupts
352
        ret.extend(self.curse_add_stat('interrupts', width=15, header='  '))
353
354
        # Third line
355
        # system|core + nice + sw_int
356
        ret.append(self.curse_new_line())
357
        # System CPU
358
        if not idle_tag:
359
            ret.extend(self.curse_add_stat('system', width=15))
360
        else:
361
            ret.extend(self.curse_add_stat('core', width=15))
362
        # Nice CPU
363
        ret.extend(self.curse_add_stat('nice', width=14, header='  '))
364
        # soft_interrupts
365
        if not WINDOWS and not SUNOS:
366
            ret.extend(self.curse_add_stat('soft_interrupts', width=15, header='  '))
367
        else:
368
            ret.extend(self.curse_add_stat('ctx_switches', width=15, header='  '))
369
370
        # Fourth line
371
        # iowait + steal + (syscalls or guest)
372
        ret.append(self.curse_new_line())
373
        if 'iowait' in self.stats:
374
            # IOWait CPU
375
            ret.extend(self.curse_add_stat('iowait', width=15))
376
        elif 'dpc' in self.stats:
377
            # DPC CPU
378
            ret.extend(self.curse_add_stat('dpc', width=15))
379
        # Steal CPU usage
380
        ret.extend(self.curse_add_stat('steal', width=14, header='  '))
381
        if not LINUX:
382
            # syscalls: number of system calls since boot. Always set to 0 on Linux. (do not display)
383
            ret.extend(self.curse_add_stat('syscalls', width=15, header='  '))
384
        else:
385
            # So instead on Linux we display the guest CPU usage (see #2667)
386
            # guest: time spent running a virtual CPU for guest operating systems under
387
            ret.extend(self.curse_add_stat('guest', width=14, header='  '))
388
389
        # Return the message with decoration
390
        return ret
391