Test Failed
Push — master ( 4c6c3d...040528 )
by Nicolas
04:27
created

glances/plugins/glances_network.py (1 issue)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 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
"""Network plugin."""
21
from __future__ import unicode_literals
22
23
import base64
24
import operator
25
26
from glances.timer import getTimeSinceLastUpdate
27
from glances.plugins.glances_plugin import GlancesPlugin
28
from glances.compat import n, u, b, nativestr
29
from glances.logger import logger
30
31
import psutil
32
33
# SNMP OID
34
# http://www.net-snmp.org/docs/mibs/interfaces.html
35
# Dict key = interface_name
36
snmp_oid = {'default': {'interface_name': '1.3.6.1.2.1.2.2.1.2',
37
                        'cumulative_rx': '1.3.6.1.2.1.2.2.1.10',
38
                        'cumulative_tx': '1.3.6.1.2.1.2.2.1.16'}}
39
40
# Define the history items list
41
items_history_list = [{'name': 'rx',
42
                       'description': 'Download rate per second',
43
                       'y_unit': 'bit/s'},
44
                      {'name': 'tx',
45
                       'description': 'Upload rate per second',
46
                       'y_unit': 'bit/s'}]
47
48
49
class Plugin(GlancesPlugin):
50
    """Glances network plugin.
51
52
    stats is a list
53
    """
54
55 View Code Duplication
    def __init__(self, args=None, config=None):
0 ignored issues
show
This code seems to be duplicated in your project.
Loading history...
56
        """Init the plugin."""
57
        super(Plugin, self).__init__(args=args,
58
                                     config=config,
59
                                     items_history_list=items_history_list,
60
                                     stats_init_value=[])
61
62
        # We want to display the stat in the curse interface
63
        self.display_curse = True
64
        # Hide stats if it has never been != 0
65
        self.hide_zero = config.get_bool_value(
66
            self.plugin_name, 'hide_zero', default=False)
67
        self.hide_zero_fields = ['rx', 'tx']
68
69
    def get_key(self):
70
        """Return the key of the list."""
71
        return 'interface_name'
72
73
    @GlancesPlugin._check_decorator
74
    @GlancesPlugin._log_result_decorator
75
    def update(self):
76
        """Update network stats using the input method.
77
78
        Stats is a list of dict (one dict per interface)
79
        """
80
        # Init new stats
81
        stats = self.get_init_value()
82
83
        if self.input_method == 'local':
84
            # Update stats using the standard system lib
85
86
            # Grab network interface stat using the psutil net_io_counter method
87
            try:
88
                netiocounters = psutil.net_io_counters(pernic=True)
89
            except UnicodeDecodeError as e:
90
                logger.debug('Can not get network interface counters ({})'.format(e))
91
                return self.stats
92
93
            # Grab interface's status (issue #765)
94
            # Grab interface's speed (issue #718)
95
            netstatus = {}
96
            try:
97
                netstatus = psutil.net_if_stats()
98
            except OSError as e:
99
                # see psutil #797/glances #1106
100
                logger.debug('Can not get network interface status ({})'.format(e))
101
102
            # Previous network interface stats are stored in the network_old variable
103
            if not hasattr(self, 'network_old'):
104
                # First call, we init the network_old var
105
                try:
106
                    self.network_old = netiocounters
107
                except (IOError, UnboundLocalError):
108
                    pass
109
                return self.stats
110
111
            # By storing time data we enable Rx/s and Tx/s calculations in the
112
            # XML/RPC API, which would otherwise be overly difficult work
113
            # for users of the API
114
            time_since_update = getTimeSinceLastUpdate('net')
115
116
            # Loop over interfaces
117
            network_new = netiocounters
118
            for net in network_new:
119
                # Do not take hidden interface into account
120
                # or KeyError: 'eth0' when interface is not connected #1348
121
                if self.is_hide(net) or net not in netstatus:
122
                    continue
123
                try:
124
                    cumulative_rx = network_new[net].bytes_recv
125
                    cumulative_tx = network_new[net].bytes_sent
126
                    cumulative_cx = cumulative_rx + cumulative_tx
127
                    rx = cumulative_rx - self.network_old[net].bytes_recv
128
                    tx = cumulative_tx - self.network_old[net].bytes_sent
129
                    cx = rx + tx
130
                    netstat = {'interface_name': n(net),
131
                               'time_since_update': time_since_update,
132
                               'cumulative_rx': cumulative_rx,
133
                               'rx': rx,
134
                               'cumulative_tx': cumulative_tx,
135
                               'tx': tx,
136
                               'cumulative_cx': cumulative_cx,
137
                               'cx': cx,
138
                               # Interface status
139
                               'is_up': netstatus[net].isup,
140
                               # Interface speed in Mbps, convert it to bps
141
                               # Can be always 0 on some OSes
142
                               'speed': netstatus[net].speed * 1048576,
143
                               # Set the key for the dict
144
                               'key': self.get_key()
145
                               }
146
                except KeyError:
147
                    continue
148
                else:
149
                    # Append the interface stats to the list
150
                    stats.append(netstat)
151
152
            # Save stats to compute next bitrate
153
            self.network_old = network_new
154
155
        elif self.input_method == 'snmp':
156
            # Update stats using SNMP
157
158
            # SNMP bulk command to get all network interface in one shot
159
            try:
160
                netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
161
                                                    bulk=True)
162
            except KeyError:
163
                netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid['default'],
164
                                                    bulk=True)
165
166
            # Previous network interface stats are stored in the network_old variable
167
            if not hasattr(self, 'network_old'):
168
                # First call, we init the network_old var
169
                try:
170
                    self.network_old = netiocounters
171
                except (IOError, UnboundLocalError):
172
                    pass
173
            else:
174
                # See description in the 'local' block
175
                time_since_update = getTimeSinceLastUpdate('net')
176
177
                # Loop over interfaces
178
                network_new = netiocounters
179
180
                for net in network_new:
181
                    # Do not take hidden interface into account
182
                    if self.is_hide(net):
183
                        continue
184
185
                    try:
186
                        # Windows: a tips is needed to convert HEX to TXT
187
                        # http://blogs.technet.com/b/networking/archive/2009/12/18/how-to-query-the-list-of-network-interfaces-using-snmp-via-the-ifdescr-counter.aspx
188
                        if self.short_system_name == 'windows':
189
                            try:
190
                                interface_name = str(base64.b16decode(net[2:-2].upper()))
191
                            except TypeError:
192
                                interface_name = net
193
                        else:
194
                            interface_name = net
195
196
                        cumulative_rx = float(network_new[net]['cumulative_rx'])
197
                        cumulative_tx = float(network_new[net]['cumulative_tx'])
198
                        cumulative_cx = cumulative_rx + cumulative_tx
199
                        rx = cumulative_rx - float(self.network_old[net]['cumulative_rx'])
200
                        tx = cumulative_tx - float(self.network_old[net]['cumulative_tx'])
201
                        cx = rx + tx
202
                        netstat = {
203
                            'interface_name': interface_name,
204
                            'time_since_update': time_since_update,
205
                            'cumulative_rx': cumulative_rx,
206
                            'rx': rx,
207
                            'cumulative_tx': cumulative_tx,
208
                            'tx': tx,
209
                            'cumulative_cx': cumulative_cx,
210
                            'cx': cx}
211
                    except KeyError:
212
                        continue
213
                    else:
214
                        netstat['key'] = self.get_key()
215
                        stats.append(netstat)
216
217
                # Save stats to compute next bitrate
218
                self.network_old = network_new
219
220
        # Update the stats
221
        self.stats = stats
222
223
        return self.stats
224
225
    def update_views(self):
226
        """Update stats views."""
227
        # Call the father's method
228
        super(Plugin, self).update_views()
229
230
        # Check if the stats should be hidden
231
        self.update_views_hidden()
232
233
        # Add specifics informations
234
        # Alert
235
        for i in self.get_raw():
236
            ifrealname = i['interface_name'].split(':')[0]
237
            # Convert rate in bps (to be able to compare to interface speed)
238
            bps_rx = int(i['rx'] // i['time_since_update'] * 8)
239
            bps_tx = int(i['tx'] // i['time_since_update'] * 8)
240
241
            # Decorate the bitrate with the configuration file thresolds
242
            alert_rx = self.get_alert(bps_rx, header=ifrealname + '_rx')
243
            alert_tx = self.get_alert(bps_tx, header=ifrealname + '_tx')
244
            # If nothing is define in the configuration file...
245
            # ... then use the interface speed (not available on all systems)
246
            if alert_rx == 'DEFAULT' and 'speed' in i and i['speed'] != 0:
247
                alert_rx = self.get_alert(current=bps_rx,
248
                                          maximum=i['speed'],
249
                                          header='rx')
250
            if alert_tx == 'DEFAULT' and 'speed' in i and i['speed'] != 0:
251
                alert_tx = self.get_alert(current=bps_tx,
252
                                          maximum=i['speed'],
253
                                          header='tx')
254
            # then decorates
255
            self.views[i[self.get_key()]]['rx']['decoration'] = alert_rx
256
            self.views[i[self.get_key()]]['tx']['decoration'] = alert_tx
257
258
    def msg_curse(self, args=None, max_width=None):
259
        """Return the dict to display in the curse interface."""
260
        # Init the return message
261
        ret = []
262
263
        # Only process if stats exist and display plugin enable...
264
        if not self.stats or self.is_disable():
265
            return ret
266
267
        # Max size for the interface name
268
        name_max_width = max_width - 12
269
270
        # Header
271
        msg = '{:{width}}'.format('NETWORK', width=name_max_width)
272
        ret.append(self.curse_add_line(msg, "TITLE"))
273
        if args.network_cumul:
274
            # Cumulative stats
275
            if args.network_sum:
276
                # Sum stats
277
                msg = '{:>14}'.format('Rx+Tx')
278
                ret.append(self.curse_add_line(msg))
279
            else:
280
                # Rx/Tx stats
281
                msg = '{:>7}'.format('Rx')
282
                ret.append(self.curse_add_line(msg))
283
                msg = '{:>7}'.format('Tx')
284
                ret.append(self.curse_add_line(msg))
285
        else:
286
            # Bitrate stats
287
            if args.network_sum:
288
                # Sum stats
289
                msg = '{:>14}'.format('Rx+Tx/s')
290
                ret.append(self.curse_add_line(msg))
291
            else:
292
                msg = '{:>7}'.format('Rx/s')
293
                ret.append(self.curse_add_line(msg))
294
                msg = '{:>7}'.format('Tx/s')
295
                ret.append(self.curse_add_line(msg))
296
        # Interface list (sorted by name)
297
        for i in self.sorted_stats():
298
            # Do not display interface in down state (issue #765)
299
            if ('is_up' in i) and (i['is_up'] is False):
300
                continue
301
            # Hide stats if never be different from 0 (issue #1787)
302
            if all([self.get_views(item=i[self.get_key()], key=f, option='hidden') for f in self.hide_zero_fields]):
303
                continue
304
            # Format stats
305
            # Is there an alias for the interface name ?
306
            ifrealname = i['interface_name'].split(':')[0]
307
            ifname = self.has_alias(i['interface_name'])
308
            if ifname is None:
309
                ifname = ifrealname
310
            if len(ifname) > name_max_width:
311
                # Cut interface name if it is too long
312
                ifname = '_' + ifname[-name_max_width + 1:]
313
314
            if args.byte:
315
                # Bytes per second (for dummy)
316
                to_bit = 1
317
                unit = ''
318
            else:
319
                # Bits per second (for real network administrator | Default)
320
                to_bit = 8
321
                unit = 'b'
322
323
            if args.network_cumul:
324
                rx = self.auto_unit(int(i['cumulative_rx'] * to_bit)) + unit
325
                tx = self.auto_unit(int(i['cumulative_tx'] * to_bit)) + unit
326
                sx = self.auto_unit(int(i['cumulative_rx'] * to_bit) +
327
                                    int(i['cumulative_tx'] * to_bit)) + unit
328
            else:
329
                rx = self.auto_unit(int(i['rx'] // i['time_since_update'] * to_bit)) + unit
330
                tx = self.auto_unit(int(i['tx'] // i['time_since_update'] * to_bit)) + unit
331
                sx = self.auto_unit(int(i['rx'] // i['time_since_update'] * to_bit) +
332
                                    int(i['tx'] // i['time_since_update'] * to_bit)) + unit
333
334
            # New line
335
            ret.append(self.curse_new_line())
336
            msg = '{:{width}}'.format(ifname, width=name_max_width)
337
            ret.append(self.curse_add_line(msg))
338
            if args.network_sum:
339
                msg = '{:>14}'.format(sx)
340
                ret.append(self.curse_add_line(msg))
341
            else:
342
                msg = '{:>7}'.format(rx)
343
                ret.append(self.curse_add_line(
344
                    msg, self.get_views(item=i[self.get_key()], key='rx', option='decoration')))
345
                msg = '{:>7}'.format(tx)
346
                ret.append(self.curse_add_line(
347
                    msg, self.get_views(item=i[self.get_key()], key='tx', option='decoration')))
348
349
        return ret
350