Test Failed
Push — master ( ce0fc3...e09530 )
by Nicolas
03:36
created

glances.plugins.ip.PluginModel.get_public_ip()   B

Complexity

Conditions 7

Size

Total Lines 17
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nop 3
dl 0
loc 17
rs 8
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 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
        # Public IP address
162
        if not stop:
163
            stop, stats = self.get_public_ip(stats)
164
165
        return stats
166
167
    def __hide_ip(self, ip):
168
        """Hide last to digit of the given IP address"""
169
        return '.'.join(ip.split('.')[0:2]) + '.*.*'
170
171
    def msg_curse(self, args=None, max_width=None):
172
        """Return the dict to display in the curse interface."""
173
        # Init the return message
174
        ret = []
175
176
        # Only process if stats exist and display plugin enable...
177
        if not self.stats or self.is_disabled() or import_error_tag:
178
            return ret
179
180
        # Build the string message
181
        msg = ' - '
182
        ret.append(self.curse_add_line(msg, optional=True))
183
184
        # Start with the private IP information
185
        msg = 'IP '
186
        ret.append(self.curse_add_line(msg, 'TITLE', optional=True))
187
        if 'address' in self.stats:
188
            msg = '{}'.format(self.stats['address'])
189
            ret.append(self.curse_add_line(msg, optional=True))
190
        if 'mask_cidr' in self.stats:
191
            # VPN with no internet access (issue #842)
192
            msg = '/{}'.format(self.stats['mask_cidr'])
193
            ret.append(self.curse_add_line(msg, optional=True))
194
195
        # Then with the public IP information
196
        try:
197
            msg_pub = '{}'.format(self.stats['public_address'])
198
        except (UnicodeEncodeError, KeyError):
199
            # Add KeyError exception (see https://github.com/nicolargo/glances/issues/1469)
200
            pass
201
        else:
202
            if self.stats['public_address']:
203
                msg = ' Pub '
204
                ret.append(self.curse_add_line(msg, 'TITLE', optional=True))
205
                ret.append(self.curse_add_line(msg_pub, optional=True))
206
207
            if self.stats['public_info_human']:
208
                ret.append(self.curse_add_line(' {}'.format(self.stats['public_info_human']), optional=True))
209
210
        return ret
211
212
    def public_info_for_human(self, public_info):
213
        """Return the data to pack to the client."""
214
        if not public_info:
215
            return ''
216
217
        return self.public_template.format(**public_info)
218
219
    @staticmethod
220
    def ip_to_cidr(ip):
221
        """Convert IP address to CIDR.
222
223
        Example: '255.255.255.0' will return 24
224
        """
225
        # Thanks to @Atticfire
226
        # See https://github.com/nicolargo/glances/issues/1417#issuecomment-469894399
227
        if ip is None:
228
            # Correct issue #1528
229
            return 0
230
        return sum(bin(int(x)).count('1') for x in ip.split('.'))
231
232
233
class PublicIpInfo:
234
    """Get public IP information from online service."""
235
236
    def __init__(self, url, username, password, timeout=2):
237
        """Init the class."""
238
        self.url = url
239
        self.username = username
240
        self.password = password
241
        self.timeout = timeout
242
243
    def get(self):
244
        """Return the public IP information returned by one of the online service."""
245
        q = queue.Queue()
246
247
        t = threading.Thread(target=self._get_ip_public_info, args=(q, self.url, self.username, self.password))
248
        t.daemon = True
249
        t.start()
250
251
        timer = Timer(self.timeout)
252
        info = None
253
        while not timer.finished() and info is None:
254
            if q.qsize() > 0:
255
                info = q.get()
256
257
        return info
258
259
    def _get_ip_public_info(self, queue_target, url, username, password):
260
        """Request the url service and put the result in the queue_target."""
261
        try:
262
            response = urlopen_auth(url, username, password).read()
263
        except Exception as e:
264
            logger.debug(f"IP plugin - Cannot get public IP information from {url} ({e})")
265
            queue_target.put(None)
266
        else:
267
            try:
268
                queue_target.put(json_loads(response))
269
            except (ValueError, KeyError) as e:
270
                logger.debug(f"IP plugin - Cannot load public IP information from {url} ({e})")
271
                queue_target.put(None)
272