Completed
Push — master ( bcff18...adb900 )
by Nicolas
01:15
created

glances.plugins.Plugin.update()   C

Complexity

Conditions 7

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 7
dl 0
loc 31
rs 5.5
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2015 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
"""IP plugin."""
21
22
from glances.compat import iterkeys
23
from glances.globals import BSD
24
from glances.logger import logger
25
from glances.plugins.glances_plugin import GlancesPlugin
26
27
# XXX *BSDs: Segmentation fault (core dumped)
28
# -- https://bitbucket.org/al45tair/netifaces/issues/15
29
if not BSD:
30
    try:
31
        import netifaces
32
        netifaces_tag = True
33
    except ImportError:
34
        netifaces_tag = False
35
else:
36
    netifaces_tag = False
37
38
39
class Plugin(GlancesPlugin):
40
41
    """Glances IP Plugin.
42
43
    stats is a dict
44
    """
45
46
    def __init__(self, args=None):
47
        """Init the plugin."""
48
        super(Plugin, self).__init__(args=args)
49
50
        # We want to display the stat in the curse interface
51
        self.display_curse = True
52
53
        # Init the stats
54
        self.reset()
55
56
    def reset(self):
57
        """Reset/init the stats."""
58
        self.stats = {}
59
60
    @GlancesPlugin._log_result_decorator
61
    def update(self):
62
        """Update IP stats using the input method.
63
64
        Stats is dict
65
        """
66
        # Reset stats
67
        self.reset()
68
69
        if self.input_method == 'local' and netifaces_tag:
70
            # Update stats using the netifaces lib
71
            try:
72
                default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
73
            except (KeyError, AttributeError) as e:
74
                logger.debug("Cannot grab the default gateway ({0})".format(e))
75
            else:
76
                try:
77
                    self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
78
                    self.stats['mask'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
79
                    self.stats['mask_cidr'] = self.ip_to_cidr(self.stats['mask'])
80
                    self.stats['gateway'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
81
                except (KeyError, AttributeError) as e:
82
                    logger.debug("Cannot grab IP information: {0}".format(e))
83
        elif self.input_method == 'snmp':
84
            # Not implemented yet
85
            pass
86
87
        # Update the view
88
        self.update_views()
89
90
        return self.stats
91
92
    def update_views(self):
93
        """Update stats views."""
94
        # Call the father's method
95
        super(Plugin, self).update_views()
96
97
        # Add specifics informations
98
        # Optional
99
        for key in iterkeys(self.stats):
100
            self.views[key]['optional'] = True
101
102
    def msg_curse(self, args=None):
103
        """Return the dict to display in the curse interface."""
104
        # Init the return message
105
        ret = []
106
107
        # Only process if stats exist and display plugin enable...
108
        if not self.stats or args.disable_ip:
109
            return ret
110
111
        # Build the string message
112
        msg = ' - '
113
        ret.append(self.curse_add_line(msg))
114
        msg = 'IP '
115
        ret.append(self.curse_add_line(msg, 'TITLE'))
116
        msg = '{0:}/{1}'.format(self.stats['address'], self.stats['mask_cidr'])
117
        ret.append(self.curse_add_line(msg))
118
119
        return ret
120
121
    @staticmethod
122
    def ip_to_cidr(ip):
123
        """Convert IP address to CIDR.
124
125
        Example: '255.255.255.0' will return 24
126
        """
127
        return sum([int(x) << 8 for x in ip.split('.')]) // 8128
128