Completed
Push — master ( 2b80fa...6ea077 )
by Nicolas
01:22
created

glances/plugins/glances_cpu.py (5 issues)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2017 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""CPU plugin."""
21
22
from glances.timer import getTimeSinceLastUpdate
23
from glances.compat import iterkeys
24
from glances.cpu_percent import cpu_percent
25
from glances.globals import LINUX
26
from glances.plugins.glances_core import Plugin as CorePlugin
27
from glances.plugins.glances_plugin import GlancesPlugin
28
29
import psutil
30
31
# SNMP OID
32
# percentage of user CPU time: .1.3.6.1.4.1.2021.11.9.0
33
# percentages of system CPU time: .1.3.6.1.4.1.2021.11.10.0
34
# percentages of idle CPU time: .1.3.6.1.4.1.2021.11.11.0
35
snmp_oid = {'default': {'user': '1.3.6.1.4.1.2021.11.9.0',
36
                        'system': '1.3.6.1.4.1.2021.11.10.0',
37
                        'idle': '1.3.6.1.4.1.2021.11.11.0'},
38
            'windows': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
39
            'esxi': {'percent': '1.3.6.1.2.1.25.3.3.1.2'},
40
            'netapp': {'system': '1.3.6.1.4.1.789.1.2.1.3.0',
41
                       'idle': '1.3.6.1.4.1.789.1.2.1.5.0',
42
                       'nb_log_core': '1.3.6.1.4.1.789.1.2.1.6.0'}}
43
44
# Define the history items list
45
# - 'name' define the stat identifier
46
# - 'color' define the graph color in #RGB format
47
# - 'y_unit' define the Y label
48
# All items in this list will be historised if the --enable-history tag is set
49
items_history_list = [{'name': 'user',
50
                       'description': 'User CPU usage',
51
                       'color': '#00FF00',
52
                       'y_unit': '%'},
53
                      {'name': 'system',
54
                       'description': 'System CPU usage',
55
                       'color': '#FF0000',
56
                       'y_unit': '%'}]
57
58
59
class Plugin(GlancesPlugin):
60
61
    """Glances CPU plugin.
62
63
    'stats' is a dictionary that contains the system-wide CPU utilization as a
64
    percentage.
65
    """
66
67
    def __init__(self, args=None):
68
        """Init the CPU plugin."""
69
        super(Plugin, self).__init__(args=args, items_history_list=items_history_list)
70
71
        # We want to display the stat in the curse interface
72
        self.display_curse = True
73
74
        # Init stats
75
        self.reset()
76
77
        # Call CorePlugin in order to display the core number
78
        try:
79
            self.nb_log_core = CorePlugin(args=self.args).update()["log"]
80
        except Exception:
81
            self.nb_log_core = 1
82
83
    def reset(self):
84
        """Reset/init the stats."""
85
        self.stats = {}
86
87
    @GlancesPlugin._check_decorator
88
    @GlancesPlugin._log_result_decorator
89
    def update(self):
90
        """Update CPU stats using the input method."""
91
92
        # Reset stats
93
        self.reset()
94
95
        # Grab stats into self.stats
96
        if self.input_method == 'local':
97
            self.update_local()
98
        elif self.input_method == 'snmp':
99
            self.update_snmp()
100
101
        return self.stats
102
103
    def update_local(self):
104
        """Update CPU stats using PSUtil."""
105
        # Grab CPU stats using psutil's cpu_percent and cpu_times_percent
106
        # Get all possible values for CPU stats: user, system, idle,
107
        # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+)
108
        # The following stats are returned by the API but not displayed in the UI:
109
        # softirq (Linux), guest (Linux 2.6.24+), guest_nice (Linux 3.2.0+)
110
        self.stats['total'] = cpu_percent.get()
111
        cpu_times_percent = psutil.cpu_times_percent(interval=0.0)
112
        for stat in ['user', 'system', 'idle', 'nice', 'iowait',
113
                     'irq', 'softirq', 'steal', 'guest', 'guest_nice']:
114
            if hasattr(cpu_times_percent, stat):
115
                self.stats[stat] = getattr(cpu_times_percent, stat)
116
117
        # Additionnal CPU stats (number of events / not as a %)
118
        # ctx_switches: number of context switches (voluntary + involuntary) per second
119
        # interrupts: number of interrupts per second
120
        # soft_interrupts: number of software interrupts per second. Always set to 0 on Windows and SunOS.
121
        # syscalls: number of system calls since boot. Always set to 0 on Linux.
122
        try:
123
            cpu_stats = psutil.cpu_stats()
124
        except AttributeError:
125
            # cpu_stats only available with PSUtil 4.1 or +
126
            pass
127
        else:
128
            # By storing time data we enable Rx/s and Tx/s calculations in the
129
            # XML/RPC API, which would otherwise be overly difficult work
130
            # for users of the API
131
            time_since_update = getTimeSinceLastUpdate('cpu')
132
133
            # Previous CPU stats are stored in the cpu_stats_old variable
134
            if not hasattr(self, 'cpu_stats_old'):
135
                # First call, we init the cpu_stats_old var
136
                self.cpu_stats_old = cpu_stats
137
            else:
138
                for stat in cpu_stats._fields:
139
                    if getattr(cpu_stats, stat) is not None:
140
                        self.stats[stat] = getattr(cpu_stats, stat) - getattr(self.cpu_stats_old, stat)
141
142
                self.stats['time_since_update'] = time_since_update
143
144
                # Core number is needed to compute the CTX switch limit
145
                self.stats['cpucore'] = self.nb_log_core
146
147
                # Save stats to compute next step
148
                self.cpu_stats_old = cpu_stats
149
150
    def update_snmp(self):
151
        """Update CPU stats using SNMP."""
152
        # Update stats using SNMP
153
        if self.short_system_name in ('windows', 'esxi'):
154
            # Windows or VMWare ESXi
155
            # You can find the CPU utilization of windows system by querying the oid
156
            # Give also the number of core (number of element in the table)
157
            try:
158
                cpu_stats = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
159
                                                bulk=True)
160
            except KeyError:
161
                self.reset()
162
163
            # Iter through CPU and compute the idle CPU stats
164
            self.stats['nb_log_core'] = 0
165
            self.stats['idle'] = 0
166
            for c in cpu_stats:
167
                if c.startswith('percent'):
168
                    self.stats['idle'] += float(cpu_stats['percent.3'])
169
                    self.stats['nb_log_core'] += 1
170
            if self.stats['nb_log_core'] > 0:
171
                self.stats['idle'] = self.stats[
172
                    'idle'] / self.stats['nb_log_core']
173
            self.stats['idle'] = 100 - self.stats['idle']
174
            self.stats['total'] = 100 - self.stats['idle']
175
176
        else:
177
            # Default behavor
178
            try:
179
                self.stats = self.get_stats_snmp(
180
                    snmp_oid=snmp_oid[self.short_system_name])
181
            except KeyError:
182
                self.stats = self.get_stats_snmp(
183
                    snmp_oid=snmp_oid['default'])
184
185
            if self.stats['idle'] == '':
186
                self.reset()
187
                return self.stats
188
189
            # Convert SNMP stats to float
190
            for key in iterkeys(self.stats):
191
                self.stats[key] = float(self.stats[key])
192
            self.stats['total'] = 100 - self.stats['idle']
193 View Code Duplication
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
194
    def update_views(self):
195
        """Update stats views."""
196
        # Call the father's method
197
        super(Plugin, self).update_views()
198
199
        # Add specifics informations
200
        # Alert and log
201
        for key in ['user', 'system', 'iowait']:
202
            if key in self.stats:
203
                self.views[key]['decoration'] = self.get_alert_log(self.stats[key], header=key)
204
        # Alert only
205
        for key in ['steal', 'total']:
206
            if key in self.stats:
207
                self.views[key]['decoration'] = self.get_alert(self.stats[key], header=key)
208
        # Alert only but depend on Core number
209
        for key in ['ctx_switches']:
210
            if key in self.stats:
211
                self.views[key]['decoration'] = self.get_alert(self.stats[key], maximum=100 * self.stats['cpucore'], header=key)
212
        # Optional
213 View Code Duplication
        for key in ['nice', 'irq', 'iowait', 'steal', 'ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls']:
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
214
            if key in self.stats:
215
                self.views[key]['optional'] = True
216
217
    def msg_curse(self, args=None):
218
        """Return the list to display in the UI."""
219
        # Init the return message
220
        ret = []
221
222
        # Only process if stats exist and plugin not disable
223
        if not self.stats or self.is_disable():
224
            return ret
225
226
        # Build the string message
227
        # If user stat is not here, display only idle / total CPU usage (for
228
        # exemple on Windows OS)
229
        idle_tag = 'user' not in self.stats
230
231
        # Header
232
        msg = '{:8}'.format('CPU')
233
        ret.append(self.curse_add_line(msg, "TITLE"))
234
        # Total CPU usage
235
        msg = '{:>5}%'.format(self.stats['total'])
236
        if idle_tag:
237
            ret.append(self.curse_add_line(
238
                msg, self.get_views(key='total', option='decoration')))
239
        else:
240
            ret.append(self.curse_add_line(msg))
241
        # Nice CPU
242
        if 'nice' in self.stats:
243
            msg = '  {:8}'.format('nice:')
244
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional')))
245
            msg = '{:>5}%'.format(self.stats['nice'])
246
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional')))
247
        # ctx_switches
248
        if 'ctx_switches' in self.stats:
249
            msg = '  {:8}'.format('ctx_sw:')
250
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='ctx_switches', option='optional')))
251 View Code Duplication
            msg = '{:>5}'.format(int(self.stats['ctx_switches'] // self.stats['time_since_update']))
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
252
            ret.append(self.curse_add_line(
253
                msg, self.get_views(key='ctx_switches', option='decoration'),
254
                optional=self.get_views(key='ctx_switches', option='optional')))
255
256
        # New line
257
        ret.append(self.curse_new_line())
258
        # User CPU
259
        if 'user' in self.stats:
260
            msg = '{:8}'.format('user:')
261
            ret.append(self.curse_add_line(msg))
262
            msg = '{:>5}%'.format(self.stats['user'])
263
            ret.append(self.curse_add_line(
264
                msg, self.get_views(key='user', option='decoration')))
265
        elif 'idle' in self.stats:
266
            msg = '{:8}'.format('idle:')
267
            ret.append(self.curse_add_line(msg))
268
            msg = '{:>5}%'.format(self.stats['idle'])
269
            ret.append(self.curse_add_line(msg))
270
        # IRQ CPU
271
        if 'irq' in self.stats:
272
            msg = '  {:8}'.format('irq:')
273
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional')))
274
            msg = '{:>5}%'.format(self.stats['irq'])
275
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional')))
276
        # interrupts
277
        if 'interrupts' in self.stats:
278
            msg = '  {:8}'.format('inter:')
279
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='interrupts', option='optional')))
280
            msg = '{:>5}'.format(int(self.stats['interrupts'] // self.stats['time_since_update']))
281
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='interrupts', option='optional')))
282
283
        # New line
284
        ret.append(self.curse_new_line())
285
        # System CPU
286
        if 'system' in self.stats and not idle_tag:
287
            msg = '{:8}'.format('system:')
288
            ret.append(self.curse_add_line(msg))
289
            msg = '{:>5}%'.format(self.stats['system'])
290
            ret.append(self.curse_add_line(
291
                msg, self.get_views(key='system', option='decoration')))
292
        else:
293
            msg = '{:8}'.format('core:')
294
            ret.append(self.curse_add_line(msg))
295
            msg = '{:>6}'.format(self.stats['nb_log_core'])
296
            ret.append(self.curse_add_line(msg))
297
        # IOWait CPU
298
        if 'iowait' in self.stats:
299
            msg = '  {:8}'.format('iowait:')
300
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='iowait', option='optional')))
301
            msg = '{:>5}%'.format(self.stats['iowait'])
302
            ret.append(self.curse_add_line(
303
                msg, self.get_views(key='iowait', option='decoration'),
304
                optional=self.get_views(key='iowait', option='optional')))
305
        # soft_interrupts
306
        if 'soft_interrupts' in self.stats:
307
            msg = '  {:8}'.format('sw_int:')
308
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='soft_interrupts', option='optional')))
309 View Code Duplication
            msg = '{:>5}'.format(int(self.stats['soft_interrupts'] // self.stats['time_since_update']))
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
310
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='soft_interrupts', option='optional')))
311
312
        # New line
313
        ret.append(self.curse_new_line())
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))
318
            msg = '{:>5}%'.format(self.stats['idle'])
319
            ret.append(self.curse_add_line(msg))
320
        # Steal CPU usage
321
        if 'steal' in self.stats:
322
            msg = '  {:8}'.format('steal:')
323
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='steal', option='optional')))
324 View Code Duplication
            msg = '{:>5}%'.format(self.stats['steal'])
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
325
            ret.append(self.curse_add_line(
326
                msg, self.get_views(key='steal', option='decoration'),
327
                optional=self.get_views(key='steal', option='optional')))
328
        # syscalls
329
        # syscalls: number of system calls since boot. Always set to 0 on Linux. (do not display)
330
        if 'syscalls' in self.stats and not LINUX:
331
            msg = '  {:8}'.format('syscal:')
332
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='syscalls', option='optional')))
333
            msg = '{:>5}'.format(int(self.stats['syscalls'] // self.stats['time_since_update']))
334
            ret.append(self.curse_add_line(msg, optional=self.get_views(key='syscalls', option='optional')))
335
336
        # Return the message with decoration
337
        return ret
338