Test Failed
Push — develop ( 1e7e0c...5f3110 )
by Nicolas
02:53 queued 14s
created

glances.plugins.cpu.CpuPlugin.update_local()   A

Complexity

Conditions 1

Size

Total Lines 49
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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