glances_network.py 14.0 KB
Newer Older
A
Alessio Sergi 已提交
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
A
Alessio Sergi 已提交
4
#
N
nicolargo 已提交
5
# Copyright (C) 2019 Nicolargo <nicolas@nicolargo.com>
A
Alessio Sergi 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18
#
# Glances is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Glances is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
A
PEP 257  
Alessio Sergi 已提交
19 20

"""Network plugin."""
N
nicolargo 已提交
21
from __future__ import unicode_literals
A
Alessio Sergi 已提交
22

N
Nicolargo 已提交
23
import base64
24
import operator
N
Nicolargo 已提交
25

26
from glances.timer import getTimeSinceLastUpdate
A
Alessio Sergi 已提交
27
from glances.plugins.glances_plugin import GlancesPlugin
N
nicolargo 已提交
28
from glances.compat import n, u, b, nativestr
29
from glances.logger import logger
A
Alessio Sergi 已提交
30

A
flake8  
Alessio Sergi 已提交
31 32
import psutil

33
# SNMP OID
34
# http://www.net-snmp.org/docs/mibs/interfaces.html
35
# Dict key = interface_name
N
Nicolargo 已提交
36 37 38
snmp_oid = {'default': {'interface_name': '1.3.6.1.2.1.2.2.1.2',
                        'cumulative_rx': '1.3.6.1.2.1.2.2.1.10',
                        'cumulative_tx': '1.3.6.1.2.1.2.2.1.16'}}
39

40
# Define the history items list
41 42 43 44 45 46
items_history_list = [{'name': 'rx',
                       'description': 'Download rate per second',
                       'y_unit': 'bit/s'},
                      {'name': 'tx',
                       'description': 'Upload rate per second',
                       'y_unit': 'bit/s'}]
47

A
Alessio Sergi 已提交
48 49

class Plugin(GlancesPlugin):
A
PEP 257  
Alessio Sergi 已提交
50
    """Glances network plugin.
A
Alessio Sergi 已提交
51 52 53 54

    stats is a list
    """

55
    def __init__(self, args=None, config=None):
A
PEP 257  
Alessio Sergi 已提交
56
        """Init the plugin."""
57
        super(Plugin, self).__init__(args=args,
58
                                     config=config,
59 60
                                     items_history_list=items_history_list,
                                     stats_init_value=[])
A
Alessio Sergi 已提交
61 62 63 64

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

65
    def get_key(self):
A
PEP 257  
Alessio Sergi 已提交
66
        """Return the key of the list."""
67 68
        return 'interface_name'

69
    @GlancesPlugin._check_decorator
70
    @GlancesPlugin._log_result_decorator
71
    def update(self):
A
PEP 257  
Alessio Sergi 已提交
72 73
        """Update network stats using the input method.

N
Nicolas Hennion 已提交
74
        Stats is a list of dict (one dict per interface)
A
Alessio Sergi 已提交
75
        """
76 77
        # Init new stats
        stats = self.get_init_value()
A
Alessio Sergi 已提交
78

79
        if self.input_method == 'local':
80 81
            # Update stats using the standard system lib

A
Alessio Sergi 已提交
82
            # Grab network interface stat using the psutil net_io_counter method
A
Alessio Sergi 已提交
83
            try:
84
                netiocounters = psutil.net_io_counters(pernic=True)
85 86
            except UnicodeDecodeError as e:
                logger.debug('Can not get network interface counters ({})'.format(e))
87
                return self.stats
A
Alessio Sergi 已提交
88

89 90
            # Grab interface's status (issue #765)
            # Grab interface's speed (issue #718)
91 92 93
            netstatus = {}
            try:
                netstatus = psutil.net_if_stats()
94
            except OSError as e:
A
Alessio Sergi 已提交
95
                # see psutil #797/glances #1106
96
                logger.debug('Can not get network interface status ({})'.format(e))
97

98
            # Previous network interface stats are stored in the network_old variable
99
            if not hasattr(self, 'network_old'):
100 101 102 103 104
                # First call, we init the network_old var
                try:
                    self.network_old = netiocounters
                except (IOError, UnboundLocalError):
                    pass
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
                return self.stats

            # By storing time data we enable Rx/s and Tx/s calculations in the
            # XML/RPC API, which would otherwise be overly difficult work
            # for users of the API
            time_since_update = getTimeSinceLastUpdate('net')

            # Loop over interfaces
            network_new = netiocounters
            for net in network_new:
                # Do not take hidden interface into account
                # or KeyError: 'eth0' when interface is not connected #1348
                if self.is_hide(net) or net not in netstatus:
                    continue
                try:
                    cumulative_rx = network_new[net].bytes_recv
                    cumulative_tx = network_new[net].bytes_sent
                    cumulative_cx = cumulative_rx + cumulative_tx
                    rx = cumulative_rx - self.network_old[net].bytes_recv
                    tx = cumulative_tx - self.network_old[net].bytes_sent
                    cx = rx + tx
N
nicolargo 已提交
126
                    netstat = {'interface_name': n(net),
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
                               'time_since_update': time_since_update,
                               'cumulative_rx': cumulative_rx,
                               'rx': rx,
                               'cumulative_tx': cumulative_tx,
                               'tx': tx,
                               'cumulative_cx': cumulative_cx,
                               'cx': cx,
                               # Interface status
                               'is_up': netstatus[net].isup,
                               # Interface speed in Mbps, convert it to bps
                               # Can be always 0 on some OSes
                               'speed': netstatus[net].speed * 1048576,
                               # Set the key for the dict
                               'key': self.get_key()
                               }
                except KeyError:
                    continue
                else:
                    # Append the interface stats to the list
                    stats.append(netstat)

            # Save stats to compute next bitrate
            self.network_old = network_new
N
Nicolargo 已提交
150

151
        elif self.input_method == 'snmp':
152
            # Update stats using SNMP
153

154
            # SNMP bulk command to get all network interface in one shot
N
Nicolargo 已提交
155
            try:
156
                netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
N
Nicolargo 已提交
157 158
                                                    bulk=True)
            except KeyError:
159
                netiocounters = self.get_stats_snmp(snmp_oid=snmp_oid['default'],
N
Nicolargo 已提交
160
                                                    bulk=True)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

            # Previous network interface stats are stored in the network_old variable
            if not hasattr(self, 'network_old'):
                # First call, we init the network_old var
                try:
                    self.network_old = netiocounters
                except (IOError, UnboundLocalError):
                    pass
            else:
                # See description in the 'local' block
                time_since_update = getTimeSinceLastUpdate('net')

                # Loop over interfaces
                network_new = netiocounters

                for net in network_new:
177 178 179 180
                    # Do not take hidden interface into account
                    if self.is_hide(net):
                        continue

181
                    try:
N
Nicolargo 已提交
182 183
                        # Windows: a tips is needed to convert HEX to TXT
                        # 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
184
                        if self.short_system_name == 'windows':
N
Nicolargo 已提交
185
                            try:
186
                                interface_name = str(base64.b16decode(net[2:-2].upper()))
N
Nicolargo 已提交
187
                            except TypeError:
188
                                interface_name = net
N
Nicolargo 已提交
189
                        else:
190
                            interface_name = net
191

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
                        cumulative_rx = float(network_new[net]['cumulative_rx'])
                        cumulative_tx = float(network_new[net]['cumulative_tx'])
                        cumulative_cx = cumulative_rx + cumulative_tx
                        rx = cumulative_rx - float(self.network_old[net]['cumulative_rx'])
                        tx = cumulative_tx - float(self.network_old[net]['cumulative_tx'])
                        cx = rx + tx
                        netstat = {
                            'interface_name': interface_name,
                            'time_since_update': time_since_update,
                            'cumulative_rx': cumulative_rx,
                            'rx': rx,
                            'cumulative_tx': cumulative_tx,
                            'tx': tx,
                            'cumulative_cx': cumulative_cx,
                            'cx': cx}
207 208 209
                    except KeyError:
                        continue
                    else:
210
                        netstat['key'] = self.get_key()
211
                        stats.append(netstat)
A
Alessio Sergi 已提交
212

213 214
                # Save stats to compute next bitrate
                self.network_old = network_new
215

216 217 218
        # Update the stats
        self.stats = stats

N
Nicolas Hennion 已提交
219 220
        return self.stats

221
    def update_views(self):
A
PEP 257  
Alessio Sergi 已提交
222
        """Update stats views."""
223
        # Call the father's method
A
Alessio Sergi 已提交
224
        super(Plugin, self).update_views()
225 226 227

        # Add specifics informations
        # Alert
228
        for i in self.stats:
229
            ifrealname = i['interface_name'].split(':')[0]
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
            # Convert rate in bps ( to be able to compare to interface speed)
            bps_rx = int(i['rx'] // i['time_since_update'] * 8)
            bps_tx = int(i['tx'] // i['time_since_update'] * 8)
            # Decorate the bitrate with the configuration file thresolds
            alert_rx = self.get_alert(bps_rx, header=ifrealname + '_rx')
            alert_tx = self.get_alert(bps_tx, header=ifrealname + '_tx')
            # If nothing is define in the configuration file...
            # ... then use the interface speed (not available on all systems)
            if alert_rx == 'DEFAULT' and 'speed' in i and i['speed'] != 0:
                alert_rx = self.get_alert(current=bps_rx,
                                          maximum=i['speed'],
                                          header='rx')
            if alert_tx == 'DEFAULT' and 'speed' in i and i['speed'] != 0:
                alert_tx = self.get_alert(current=bps_tx,
                                          maximum=i['speed'],
                                          header='tx')
            # then decorates
            self.views[i[self.get_key()]]['rx']['decoration'] = alert_rx
            self.views[i[self.get_key()]]['tx']['decoration'] = alert_tx
249

N
Nicolargo 已提交
250
    def msg_curse(self, args=None, max_width=None):
A
PEP 257  
Alessio Sergi 已提交
251
        """Return the dict to display in the curse interface."""
A
Alessio Sergi 已提交
252 253 254
        # Init the return message
        ret = []

255
        # Only process if stats exist and display plugin enable...
N
nicolargo 已提交
256
        if not self.stats or self.is_disable():
257 258
            return ret

N
Nicolargo 已提交
259
        # Max size for the interface name
260
        name_max_width = max_width - 12
N
Nicolargo 已提交
261

A
Alessio Sergi 已提交
262
        # Header
263
        msg = '{:{width}}'.format('NETWORK', width=name_max_width)
A
Alessio Sergi 已提交
264
        ret.append(self.curse_add_line(msg, "TITLE"))
265
        if args.network_cumul:
N
Nicolas Hennion 已提交
266
            # Cumulative stats
267
            if args.network_sum:
268
                # Sum stats
269
                msg = '{:>14}'.format('Rx+Tx')
270 271 272
                ret.append(self.curse_add_line(msg))
            else:
                # Rx/Tx stats
273
                msg = '{:>7}'.format('Rx')
274
                ret.append(self.curse_add_line(msg))
275
                msg = '{:>7}'.format('Tx')
276
                ret.append(self.curse_add_line(msg))
N
Nicolas Hennion 已提交
277 278
        else:
            # Bitrate stats
279
            if args.network_sum:
280
                # Sum stats
281
                msg = '{:>14}'.format('Rx+Tx/s')
282 283
                ret.append(self.curse_add_line(msg))
            else:
284
                msg = '{:>7}'.format('Rx/s')
285
                ret.append(self.curse_add_line(msg))
286
                msg = '{:>7}'.format('Tx/s')
A
Alessio Sergi 已提交
287
                ret.append(self.curse_add_line(msg))
A
Alessio Sergi 已提交
288
        # Interface list (sorted by name)
289
        for i in self.sorted_stats():
290 291 292
            # Do not display interface in down state (issue #765)
            if ('is_up' in i) and (i['is_up'] is False):
                continue
A
Alessio Sergi 已提交
293
            # Format stats
294
            # Is there an alias for the interface name ?
N
Nicolargo 已提交
295
            ifrealname = i['interface_name'].split(':')[0]
296 297
            ifname = self.has_alias(i['interface_name'])
            if ifname is None:
N
Nicolargo 已提交
298
                ifname = ifrealname
299
            if len(ifname) > name_max_width:
300
                # Cut interface name if it is too long
301
                ifname = '_' + ifname[-name_max_width + 1:]
302

303
            if args.byte:
304
                # Bytes per second (for dummy)
305 306
                to_bit = 1
                unit = ''
A
Alessio Sergi 已提交
307
            else:
A
Alessio Sergi 已提交
308
                # Bits per second (for real network administrator | Default)
309 310 311 312 313 314 315 316 317 318 319 320 321 322
                to_bit = 8
                unit = 'b'

            if args.network_cumul:
                rx = self.auto_unit(int(i['cumulative_rx'] * to_bit)) + unit
                tx = self.auto_unit(int(i['cumulative_tx'] * to_bit)) + unit
                sx = self.auto_unit(int(i['cumulative_rx'] * to_bit) +
                                    int(i['cumulative_tx'] * to_bit)) + unit
            else:
                rx = self.auto_unit(int(i['rx'] // i['time_since_update'] * to_bit)) + unit
                tx = self.auto_unit(int(i['tx'] // i['time_since_update'] * to_bit)) + unit
                sx = self.auto_unit(int(i['rx'] // i['time_since_update'] * to_bit) +
                                    int(i['tx'] // i['time_since_update'] * to_bit)) + unit

A
Alessio Sergi 已提交
323 324
            # New line
            ret.append(self.curse_new_line())
325
            msg = '{:{width}}'.format(ifname, width=name_max_width)
A
Alessio Sergi 已提交
326
            ret.append(self.curse_add_line(msg))
327
            if args.network_sum:
328
                msg = '{:>14}'.format(sx)
329 330
                ret.append(self.curse_add_line(msg))
            else:
331
                msg = '{:>7}'.format(rx)
A
Alessio Sergi 已提交
332
                ret.append(self.curse_add_line(
333
                    msg, self.get_views(item=i[self.get_key()], key='rx', option='decoration')))
334
                msg = '{:>7}'.format(tx)
A
Alessio Sergi 已提交
335
                ret.append(self.curse_add_line(
336
                    msg, self.get_views(item=i[self.get_key()], key='tx', option='decoration')))
A
Alessio Sergi 已提交
337 338

        return ret