summaryrefslogtreecommitdiffstats
path: root/glances/plugins/cpu/model.py
blob: 70c82c83b8d47da902b7dfae9d47cffe28b849f9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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
348
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
389
390
391
392
393
394
395
396
397
398
399
# -*- coding: utf-8 -*-
#
# This file is part of Glances.
#
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <nicolas@nicolargo.com>
#
# SPDX-License-Identifier: LGPL-3.0-only
#

"""CPU plugin."""

from glances.timer import getTimeSinceLastUpdate
from glances.globals import LINUX, WINDOWS, SUNOS, iterkeys
from glances.cpu_percent import cpu_percent
from glances.plugins.core.model import PluginModel as CorePluginModel
from glances.plugins.plugin.model import GlancesPluginModel

import psutil

# Fields description
# 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)...
fields_description = {
    'total': {
        'getter': 'compute',
        'description': 'Sum of all CPU percentages (except idle).',
        'unit': 'percent'
    },
    'system': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        'description': 'percent time spent in kernel space. System CPU time is the \
time spent running code in the Operating System kernel.',
        'unit': 'percent',
    },
    'user': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        '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': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        'description': '*(Linux)*: percent time spent by the CPU waiting for I/O \
operations to complete.',
        'unit': 'percent',
    },
    'dpc': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        'description': '*(Windows)*: time spent servicing deferred procedure calls (DPCs)',
        'unit': 'percent',
    },
    'idle': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        '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': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        'description': '*(Linux and BSD)*: percent time spent servicing/handling \
hardware/software interrupts. Time servicing interrupts (hardware + \
software).',
        'unit': 'percent',
    },
    'nice': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        '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': {
        'getter': {'fct': 'psutil.cpu_times_percent', 'arg': {'interval': 0.0}},
        'description': '*(Linux)*: percentage of time a virtual CPU waits for a real \
CPU while the hypervisor is servicing another virtual processor.',
        'unit': 'percent',
    },
    'ctx_switches': {
        'getter': {'fct': 'psutil.cpu_stats', 'arg': {}},
        'description': 'number of context switches (voluntary + involuntary) per \
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.',
        'unit': 'number',
        'rate': True,
        'min_symbol': 'K',
        'short_name': 'ctx_sw',
    },
    'interrupts': {
        'getter': {'fct': 'psutil.cpu_stats', 'arg': {}},
        'description': 'number of interrupts per second.',
        'unit': 'number',
        'rate': True,
        'min_symbol': 'K',
        'short_name': 'inter',
    },
    'soft_interrupts': {
        'getter': {'fct': 'psutil.cpu_stats', 'arg': {}},
        'description': 'number of software interrupts per second. Always set to \
0 on Windows and SunOS.',
        'unit': 'number',
        'rate': True,
        'min_symbol': 'K',
        'short_name': 'sw_int',
    },
    'syscalls': {
        'getter': {'fct': 'psutil.cpu_stats', 'arg': {}},
        'description': 'number of system calls per second. Always 0 on Linux OS.',
        'unit': 'number',
        'rate': True,
        'min_symbol': 'K',
        'short_name': 'sys_call',
    },
    'cpucore': {
        'getter': 'compute',
        'description': 'Total number of CPU core.',
        'unit': 'number'
    },
    'time_since_update': {
        'getter': 'compute',
        'description': 'Number of seconds since last update.',
        'unit': 'seconds'
    },
}

# 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
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',
        'idle': '1.3.6.1.4.1.2021.11.11.0',
    },
    'windows': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
    'esxi': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
    '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',
        'cpucore': '1.3.6.1.4.1.789.1.2.1.6.0',
    },
}

# Define the history items list
# - 'name' define the stat identifier
# - 'y_unit' define the Y label
items_history_list = [
    {'name': 'user', 'description': 'User CPU usage', 'y_unit': '%'},
    {'name': 'system', 'description': 'System CPU usage', 'y_unit': '%'},
]


class PluginModel(GlancesPluginModel):
    """Glances CPU plugin.

    'stats' is a dictionary that contains the system-wide CPU utilization as a
    percentage.
    """

    def __init__(self, args=None, config=None):
        """Init the CPU plugin."""
        super(PluginModel, self).__init__(
            args=args, config=config, items_history_list=items_history_list, fields_description=fields_description
        )

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

        # Call CorePluginModel in order to display the core number
        try:
            self.nb_log_core = CorePluginModel(args=self.args).update()["log"]
        except Exception:
            self.nb_log_core = 1

    def cpucore(self, stats):
        """Core number is needed to compute the CTX switch limit"""
        return self.nb_log_core

    def total(self, stats):
        """Return the sum of all CPU percentages (except idle)
        Use a function shared with percpu plugin"""
        return cpu_percent.get()

    @GlancesPluginModel._check_decorator
    @GlancesPluginModel._log_result_decorator
    def update(self):
        """Update CPU stats using the input method."""
        # Grab stats into self.stats
        if self.input_method == 'local':
            stats = self.update_cpu_local()
        elif self.input_method == 'snmp':
            stats = self.update_cpu_snmp()
        else:
            stats = self.get_init_value()

        # Update the stats
        self.stats = stats

        return self.stats

    def update_cpu_local(self):
        """Update CPU stats using psutil."""

        # Init new stats
        stats = self.get_init_value()

        # 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+)
        #
        # Standards stats
        # - user: time spent by normal processes executing in user mode; on Linux this also includes guest time
        # - system: time spent by processes executing in kernel mode
        # - idle: time spent doing nothing
        # - nice (UNIX): time spent by niced (prioritized) processes executing in user mode
        #                on Linux this also includes guest_nice time
        # - iowait (Linux): time spent waiting for I/O to complete.
        #                   This is not accounted in idle time counter.
        # - irq (Linux, BSD): time spent for servicing hardware interrupts
        # - softirq (Linux): time spent for servicing software interrupts
        # - steal (Linux 2.6.11+): time spent by other operating systems running in a virtualized environment
        # - guest (Linux 2.6.24+): time spent running a virtual CPU for guest operating systems under
        #                          the control of the Linux kernel
        # - guest_nice (Linux 3.2.0+): time spent running a niced guest (virtual CPU for guest operating systems
        #                              under the control of the Linux kernel)
        # - interrupt (Windows): time spent for servicing hardware interrupts ( similar to “irq” on UNIX)
        # - dpc (Windows): time spent servicing deferred procedure calls (DPCs)
        #
        # Additional CPU stats (number of events not as a %; psutil>=4.1.0)
        # - 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.
        self.update_local(stats)

        return stats

    def update_cpu_snmp(self):
        """Update CPU stats using SNMP."""

        # Init new stats
        stats = self.get_init_value()

        # 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
            stats['nb_log_core'] = 0
            stats['idle'] = 0
            for c in cpu_stats:
                if c.startswith('percent'):
                    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']

        else:
            # Default behavior
            try:
                stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name])
            except KeyError:
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])

            if stats['idle'] == '':
                self.reset()
                return self.stats

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

        return stats

    def update_views(self):
        """Update stats views."""
        # Call the father's method
        super(PluginModel, self).update_views()

        # Add specifics information
        # Alert and log
        for key in ['user', 'system', 'iowait', 'dpc', 'total']:
            if key in self.stats:
                self.views[key]['decoration'] = self.get_alert_log(self.stats[key], header=key)
        # Alert only
        for key in ['steal']:
            if key in self.stats:
                self.views[key]['decoration'] = self.get_alert(self.stats[key],