Test Failed
Pull Request — develop (#2998)
by
unknown
02:57
created

glances.plugins.ip   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 273
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 158
dl 0
loc 273
rs 8.8
c 0
b 0
f 0
wmc 45

13 Methods

Rating   Name   Duplication   Size   Complexity  
A PluginModel.__init__() 0 22 1
A PluginModel.ip_to_cidr() 0 12 2
A PluginModel.get_private_ip() 0 11 3
A PluginModel.__hide_ip() 0 3 1
A PublicIpInfo.__init__() 0 6 1
B PluginModel.get_public_ip() 0 17 7
A PluginModel.public_info_for_human() 0 6 2
A PluginModel.get_first_ip() 0 14 3
A PublicIpInfo._get_ip_public_info() 0 13 4
A PluginModel.update() 0 21 4
A PublicIpInfo.get() 0 15 4
A PluginModel.get_stats_for_local_input() 0 12 3
C PluginModel.msg_curse() 0 40 10

How to fix   Complexity   

Complexity

Complex classes like glances.plugins.ip often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#
2
# This file is part of Glances.
3
#
4
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <[email protected]>
5
#
6
# SPDX-License-Identifier: LGPL-3.0-only
7
#
8
9
"""IP plugin."""
10
11
import threading
12
13
from glances.globals import json_loads, queue, urlopen_auth
14
from glances.logger import logger
15
from glances.plugins.plugin.model import GlancesPluginModel
16
from glances.timer import Timer, getTimeSinceLastUpdate
17
18
# Import plugin specific dependency
19
try:
20
    import netifaces
21
except ImportError as e:
22
    import_error_tag = True
23
    logger.warning(f"Missing Python Lib ({e}), IP plugin is disabled")
24
else:
25
    import_error_tag = False
26
27
# Fields description
28
# description: human readable description
29
# short_name: shortname to use un UI
30
# unit: unit type
31
# rate: is it a rate ? If yes, // by time_since_update when displayed,
32
# min_symbol: Auto unit should be used if value > than 1 'X' (K, M, G)...
33
fields_description = {
34
    'address': {
35
        'description': 'Private IP address',
36
    },
37
    'mask': {
38
        'description': 'Private IP mask',
39
    },
40
    'mask_cidr': {
41
        'description': 'Private IP mask in CIDR format',
42
        'unit': 'number',
43
    },
44
    'gateway': {
45
        'description': 'Private IP gateway',
46
    },
47
    'public_address': {
48
        'description': 'Public IP address',
49
    },
50
    'public_info_human': {
51
        'description': 'Public IP information',
52
    },
53
}
54
55
56
class PluginModel(GlancesPluginModel):
57
    """Glances IP Plugin.
58
59
    stats is a dict
60
    """
61
62
    _default_public_refresh_interval = 300
63
64
    def __init__(self, args=None, config=None):
65
        """Init the plugin."""
66
        super().__init__(args=args, config=config, fields_description=fields_description)
67
68
        # We want to display the stat in the curse interface
69
        self.display_curse = True
70
71
        # Public information (see issue #2732)
72
        self.public_address = ""
73
        self.public_info = ""
74
        self.public_api = self.get_conf_value("public_api", default=[None])[0]
75
        self.public_username = self.get_conf_value("public_username", default=[None])[0]
76
        self.public_password = self.get_conf_value("public_password", default=[None])[0]
77
        self.public_field = self.get_conf_value("public_field", default=[None])
78
        self.public_template = self.get_conf_value("public_template", default=[None])[0]
79
        self.public_disabled = (
80
            self.get_conf_value('public_disabled', default='False')[0].lower() != 'false'
81
            or self.public_api is None
82
            or self.public_field is None
83
        )
84
        self.public_address_refresh_interval = self.get_conf_value(
85
            "public_refresh_interval", default=self._default_public_refresh_interval
86
        )
87
88
    def get_private_ip(self, stats, stop=False):
89
        # Get the default gateway thanks to the netifaces lib
90
        try:
91
            default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
92
        except (KeyError, AttributeError) as e:
93
            logger.debug(f"Cannot grab default gateway IP address ({e})")
94
            stop = True
95
        else:
96
            stats['gateway'] = default_gw[0]
97
98
        return (stop, stats)
99
100
    def get_first_ip(self, stats, stop=False):
101
        try:
102
            default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
103
            address = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
104
            mask = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['netmask']
105
        except (KeyError, AttributeError) as e:
106
            logger.debug(f"Cannot grab private IP address ({e})")
107
            stop = True
108
        else:
109
            stats['address'] = address
110
            stats['mask'] = mask
111
            stats['mask_cidr'] = self.ip_to_cidr(stats['mask'])
112
113
        return (stop, stats)
114
115
    def get_public_ip(self, stats, stop=True):
116
        time_since_update = getTimeSinceLastUpdate('public-ip')
117
        try:
118
            if not self.public_disabled and (
119
                self.public_address == "" or time_since_update > self.public_address_refresh_interval
120
            ):
121
                self.public_info = PublicIpInfo(self.public_api, self.public_username, self.public_password).get()
122
                self.public_address = self.public_info['ip']
123
        except (KeyError, AttributeError, TypeError) as e:
124
            logger.debug(f"Cannot grab public IP information ({e})")
125
        else:
126
            stats['public_address'] = (
127
                self.public_address if not self.args.hide_public_info else self.__hide_ip(self.public_address)
128
            )
129
            stats['public_info_human'] = self.public_info_for_human(self.public_info)
130
131
        return (stop, stats)
132
133
    @GlancesPluginModel._check_decorator
134
    @GlancesPluginModel._log_result_decorator
135
    def update(self):
136
        """Update IP stats using the input method.
137
138
        :return: the stats dict
139
        """
140
        # Init new stats
141
        stats = self.get_init_value()
142
143
        if self.input_method == 'local' and not import_error_tag:
144
            stats = self.get_stats_for_local_input(stats)
145
146
        elif self.input_method == 'snmp':
147
            # Not implemented yet
148
            pass
149
150
        # Update the stats
151
        self.stats = stats
152
153
        return self.stats
154
155
    def get_stats_for_local_input(self, stats):
156
        # Private IP address
157
        stop, stats = self.get_private_ip(stats)
158
        # If multiple IP addresses are available, only the one with the default gateway is returned
159
        if not stop:
160
            stop, stats = self.get_first_ip(stats)
161
162
        # Public IP address
163
        if not stop:
164
            stop, stats = self.get_public_ip(stats)
165
166
        return stats
167
168
    def __hide_ip(self, ip):
169
        """Hide last to digit of the given IP address"""
170
        return '.'.join(ip.split('.')[0:2]) + '.*.*'
171
172
    def msg_curse(self, args=None, max_width=None):
173
        """Return the dict to display in the curse interface."""
174
        # Init the return message
175
        ret = []
176
177
        # Only process if stats exist and display plugin enable...
178
        if not self.stats or self.is_disabled() or import_error_tag:
179
            return ret
180
181
        # Build the string message
182
        msg = ' - '
183
        ret.append(self.curse_add_line(msg, optional=True))
184
185
        # Start with the private IP information
186
        msg = 'IP '
187
        ret.append(self.curse_add_line(msg, 'TITLE', optional=True))
188
        if 'address' in self.stats:
189
            msg = '{}'.format(self.stats['address'])
190
            ret.append(self.curse_add_line(msg, optional=True))
191
        if 'mask_cidr' in self.stats:
192
            # VPN with no internet access (issue #842)
193
            msg = '/{}'.format(self.stats['mask_cidr'])
194
            ret.append(self.curse_add_line(msg, optional=True))
195
196
        # Then with the public IP information
197
        try:
198
            msg_pub = '{}'.format(self.stats['public_address'])
199
        except (UnicodeEncodeError, KeyError):
200
            # Add KeyError exception (see https://github.com/nicolargo/glances/issues/1469)
201
            pass
202
        else:
203
            if self.stats['public_address']:
204
                msg = ' Pub '
205
                ret.append(self.curse_add_line(msg, 'TITLE', optional=True))
206
                ret.append(self.curse_add_line(msg_pub, optional=True))
207
208
            if self.stats['public_info_human']:
209
                ret.append(self.curse_add_line(' {}'.format(self.stats['public_info_human']), optional=True))
210
211
        return ret
212
213
    def public_info_for_human(self, public_info):
214
        """Return the data to pack to the client."""
215
        if not public_info:
216
            return ''
217
218
        return self.public_template.format(**public_info)
219
220
    @staticmethod
221
    def ip_to_cidr(ip):
222
        """Convert IP address to CIDR.
223
224
        Example: '255.255.255.0' will return 24
225
        """
226
        # Thanks to @Atticfire
227
        # See https://github.com/nicolargo/glances/issues/1417#issuecomment-469894399
228
        if ip is None:
229
            # Correct issue #1528
230
            return 0
231
        return sum(bin(int(x)).count('1') for x in ip.split('.'))
232
233
234
class PublicIpInfo:
235
    """Get public IP information from online service."""
236
237
    def __init__(self, url, username, password, timeout=2):
238
        """Init the class."""
239
        self.url = url
240
        self.username = username
241
        self.password = password
242
        self.timeout = timeout
243
244
    def get(self):
245
        """Return the public IP information returned by one of the online service."""
246
        q = queue.Queue()
247
248
        t = threading.Thread(target=self._get_ip_public_info, args=(q, self.url, self.username, self.password))
249
        t.daemon = True
250
        t.start()
251
252
        timer = Timer(self.timeout)
253
        info = None
254
        while not timer.finished() and info is None:
255
            if q.qsize() > 0:
256
                info = q.get()
257
258
        return info
259
260
    def _get_ip_public_info(self, queue_target, url, username, password):
261
        """Request the url service and put the result in the queue_target."""
262
        try:
263
            response = urlopen_auth(url, username, password).read()
264
        except Exception as e:
265
            logger.debug(f"IP plugin - Cannot get public IP information from {url} ({e})")
266
            queue_target.put(None)
267
        else:
268
            try:
269
                queue_target.put(json_loads(response))
270
            except (ValueError, KeyError) as e:
271
                logger.debug(f"IP plugin - Cannot load public IP information from {url} ({e})")
272
                queue_target.put(None)
273