glances.plugins.cpu.CpuPlugin.__init__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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