Test Failed
Pull Request — develop (#2998)
by
unknown
03:05
created

glances.plugins.ip.PluginModel.get_private_ipv4()   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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