glances_network.py 13.7 KB
Newer Older
A
Alessio Sergi 已提交
1 2
# -*- coding: utf-8 -*-
#
3
# This file is part of Glances.
A
Alessio Sergi 已提交
4
#
A
Alessio Sergi 已提交
5
# Copyright (C) 2017 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."""
A
Alessio Sergi 已提交
21

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

25
from glances.timer import getTimeSinceLastUpdate
A
Alessio Sergi 已提交
26
from glances.plugins.glances_plugin import GlancesPlugin
A
Alessio Sergi 已提交
27

A
flake8  
Alessio Sergi 已提交
28 29
import psutil

30
# SNMP OID
31
# http://www.net-snmp.org/docs/mibs/interfaces.html
32
# Dict key = interface_name
N
Nicolargo 已提交
33 34 35
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'}}
36

37 38
# Define the history items list
# All items in this list will be historised if the --enable-history tag is set
39 40 41 42 43 44
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'}]
45

A
Alessio Sergi 已提交
46 47

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

    stats is a list
    """

53
    def __init__(self, args=None):
A
PEP 257  
Alessio Sergi 已提交
54
        """Init the plugin."""
A
Alessio Sergi 已提交
55
        super(Plugin, self).__init__(args=args, items_history_list=items_history_list)
A
Alessio Sergi 已提交
56 57 58 59

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

60 61
        # Init the stats
        self.reset()
N
Nicolas Hennion 已提交
62

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

67
    def reset(self):
A
PEP 257  
Alessio Sergi 已提交
68
        """Reset/init the stats."""
69 70
        self.stats = []

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

N
Nicolas Hennion 已提交
76
        Stats is a list of dict (one dict per interface)
A
Alessio Sergi 已提交
77
        """
78 79
        # Reset stats
        self.reset()
A
Alessio Sergi 已提交
80

81
        if self.input_method == 'local':
82 83 84
            # Update stats using the standard system lib

            # Grab network interface stat using the PsUtil net_io_counter method
A
Alessio Sergi 已提交
85
            try:
86 87 88
                netiocounters = psutil.net_io_counters(pernic=True)
            except UnicodeDecodeError:
                return self.stats
A
Alessio Sergi 已提交
89

A
Alessio Sergi 已提交
90
            # New in psutil 3.0.0
91 92
            # - import the interface's status (issue #765)
            # - import the interface's speed (issue #718)
93 94 95
            netstatus = {}
            try:
                netstatus = psutil.net_if_stats()
A
Alessio Sergi 已提交
96 97
            except OSError:
                # see psutil #797/glances #1106
98 99
                pass

100
            # Previous network interface stats are stored in the network_old variable
101
            if not hasattr(self, 'network_old'):
102 103 104 105 106 107 108 109 110 111 112 113 114 115
                # First call, we init the network_old var
                try:
                    self.network_old = netiocounters
                except (IOError, UnboundLocalError):
                    pass
            else:
                # 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:
116 117 118
                    # Do not take hidden interface into account
                    if self.is_hide(net):
                        continue
119
                    try:
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
                        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
                        netstat = {
                            'interface_name': net,
                            'time_since_update': time_since_update,
                            'cumulative_rx': cumulative_rx,
                            'rx': rx,
                            'cumulative_tx': cumulative_tx,
                            'tx': tx,
                            'cumulative_cx': cumulative_cx,
                            'cx': cx}
135 136 137
                    except KeyError:
                        continue
                    else:
138
                        # Interface status
A
Alessio Sergi 已提交
139
                        netstat['is_up'] = netstatus[net].isup
140
                        # Interface speed in Mbps, convert it to bps
A
Alessio Sergi 已提交
141 142
                        # Can be always 0 on some OSes
                        netstat['speed'] = netstatus[net].speed * 1048576
143 144

                        # Finaly, set the key
145
                        netstat['key'] = self.get_key()
146
                        self.stats.append(netstat)
A
Alessio Sergi 已提交
147

148
                # Save stats to compute next bitrate
149
                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
                        self.stats.append(netstat)
A
Alessio Sergi 已提交
212

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

N
Nicolas Hennion 已提交
216 217
        return self.stats

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

        # Add specifics informations
        # Alert
225
        for i in self.stats:
226
            ifrealname = i['interface_name'].split(':')[0]
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            # 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
246

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

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

N
Nicolargo 已提交
256
        # Max size for the interface name
257
        name_max_width = max_width - 12
N
Nicolargo 已提交
258

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

300
            if args.byte:
301
                # Bytes per second (for dummy)
302 303
                to_bit = 1
                unit = ''
A
Alessio Sergi 已提交
304
            else:
A
Alessio Sergi 已提交
305
                # Bits per second (for real network administrator | Default)
306 307 308 309 310 311 312 313 314 315 316 317 318 319
                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 已提交
320 321
            # New line
            ret.append(self.curse_new_line())
322
            msg = '{:{width}}'.format(ifname, width=name_max_width)
A
Alessio Sergi 已提交
323
            ret.append(self.curse_add_line(msg))
324
            if args.network_sum:
325
                msg = '{:>14}'.format(sx)
326 327
                ret.append(self.curse_add_line(msg))
            else:
328
                msg = '{:>7}'.format(rx)
A
Alessio Sergi 已提交
329
                ret.append(self.curse_add_line(
330
                    msg, self.get_views(item=i[self.get_key()], key='rx', option='decoration')))
331
                msg = '{:>7}'.format(tx)
A
Alessio Sergi 已提交
332
                ret.append(self.curse_add_line(
333
                    msg, self.get_views(item=i[self.get_key()], key='tx', option='decoration')))
A
Alessio Sergi 已提交
334 335

        return ret