Total Complexity | 48 |
Total Lines | 390 |
Duplicated Lines | 5.9 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like glances.plugins.network 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 | # -*- coding: utf-8 -*- |
||
2 | # |
||
3 | # This file is part of Glances. |
||
4 | # |
||
5 | # SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]> |
||
6 | # |
||
7 | # SPDX-License-Identifier: LGPL-3.0-only |
||
8 | # |
||
9 | |||
10 | """Network plugin.""" |
||
11 | from __future__ import unicode_literals |
||
12 | |||
13 | import base64 |
||
14 | |||
15 | from glances.timer import getTimeSinceLastUpdate |
||
16 | from glances.plugins.plugin.model import GlancesPluginModel |
||
17 | from glances.logger import logger |
||
18 | |||
19 | import psutil |
||
20 | |||
21 | # {'interface_name': 'mpqemubr0-dummy', |
||
22 | # 'alias': None, |
||
23 | # 'time_since_update': 2.081636428833008, |
||
24 | # 'cumulative_rx': 0, |
||
25 | # 'rx': 0, 'cumulative_tx': 0, 'tx': 0, 'cumulative_cx': 0, 'cx': 0, |
||
26 | # 'is_up': False, |
||
27 | # 'speed': 0, |
||
28 | # 'key': 'interface_name'} |
||
29 | # Fields description |
||
30 | fields_description = { |
||
31 | 'interface_name': {'description': 'Interface name.', 'unit': 'string'}, |
||
32 | 'alias': {'description': 'Interface alias name (optional).', 'unit': 'string'}, |
||
33 | 'rx': {'description': 'The received/input rate (in bit per second).', 'unit': 'bps'}, |
||
34 | 'tx': {'description': 'The sent/output rate (in bit per second).', 'unit': 'bps'}, |
||
35 | 'cx': {'description': 'The cumulative received+sent rate (in bit per second).', 'unit': 'bps'}, |
||
36 | 'cumulative_rx': { |
||
37 | 'description': 'The number of bytes received through the interface (cumulative).', |
||
38 | 'unit': 'bytes', |
||
39 | }, |
||
40 | 'cumulative_tx': {'description': 'The number of bytes sent through the interface (cumulative).', 'unit': 'bytes'}, |
||
41 | 'cumulative_cx': { |
||
42 | 'description': 'The cumulative number of bytes reveived and sent through the interface (cumulative).', |
||
43 | 'unit': 'bytes', |
||
44 | }, |
||
45 | 'speed': { |
||
46 | 'description': 'Maximum interface speed (in bit per second). Can return 0 on some operating-system.', |
||
47 | 'unit': 'bps', |
||
48 | }, |
||
49 | 'is_up': {'description': 'Is the interface up ?', 'unit': 'bool'}, |
||
50 | 'time_since_update': {'description': 'Number of seconds since last update.', 'unit': 'seconds'}, |
||
51 | } |
||
52 | |||
53 | # SNMP OID |
||
54 | # http://www.net-snmp.org/docs/mibs/interfaces.html |
||
55 | # Dict key = interface_name |
||
56 | snmp_oid = { |
||
57 | 'default': { |
||
58 | 'interface_name': '1.3.6.1.2.1.2.2.1.2', |
||
59 | 'cumulative_rx': '1.3.6.1.2.1.2.2.1.10', |
||
60 | 'cumulative_tx': '1.3.6.1.2.1.2.2.1.16', |
||
61 | } |
||
62 | } |
||
63 | |||
64 | # Define the history items list |
||
65 | items_history_list = [ |
||
66 | {'name': 'rx', 'description': 'Download rate per second', 'y_unit': 'bit/s'}, |
||
67 | {'name': 'tx', 'description': 'Upload rate per second', 'y_unit': 'bit/s'}, |
||
68 | ] |
||
69 | |||
70 | |||
71 | class PluginModel(GlancesPluginModel): |
||
72 | """Glances network plugin. |
||
73 | |||
74 | stats is a list |
||
75 | """ |
||
76 | |||
77 | View Code Duplication | def __init__(self, args=None, config=None): |
|
|
|||
78 | """Init the plugin.""" |
||
79 | super(PluginModel, self).__init__( |
||
80 | args=args, |
||
81 | config=config, |
||
82 | items_history_list=items_history_list, |
||
83 | fields_description=fields_description, |
||
84 | stats_init_value=[], |
||
85 | ) |
||
86 | |||
87 | # We want to display the stat in the curse interface |
||
88 | self.display_curse = True |
||
89 | |||
90 | # Hide stats if it has never been != 0 |
||
91 | if config is not None: |
||
92 | self.hide_zero = config.get_bool_value(self.plugin_name, 'hide_zero', default=False) |
||
93 | else: |
||
94 | self.hide_zero = False |
||
95 | self.hide_zero_fields = ['rx', 'tx'] |
||
96 | |||
97 | # Force a first update because we need two update to have the first stat |
||
98 | self.update() |
||
99 | self.refresh_timer.set(0) |
||
100 | |||
101 | def get_key(self): |
||
102 | """Return the key of the list.""" |
||
103 | return 'interface_name' |
||
104 | |||
105 | # @GlancesPluginModel._check_decorator |
||
106 | @GlancesPluginModel._log_result_decorator |
||
107 | def update(self): |
||
108 | """Update network stats using the input method. |
||
109 | |||
110 | :return: list of stats dict (one dict per interface) |
||
111 | """ |
||
112 | # Init new stats |
||
113 | stats = self.get_init_value() |
||
114 | |||
115 | if self.input_method == 'local': |
||
116 | # Update stats using the standard system lib |
||
117 | |||
118 | # Grab network interface stat using the psutil net_io_counter method |
||
119 | try: |
||
120 | net_io_counters = psutil.net_io_counters(pernic=True) |
||
121 | except UnicodeDecodeError as e: |
||
122 | logger.debug('Can not get network interface counters ({})'.format(e)) |
||
123 | return self.stats |
||
124 | |||
125 | # Grab interface's status (issue #765) |
||
126 | # Grab interface's speed (issue #718) |
||
127 | net_status = {} |
||
128 | try: |
||
129 | net_status = psutil.net_if_stats() |
||
130 | except OSError as e: |
||
131 | # see psutil #797/glances #1106 |
||
132 | logger.debug('Can not get network interface status ({})'.format(e)) |
||
133 | |||
134 | # Previous network interface stats are stored in the network_old variable |
||
135 | if not hasattr(self, 'network_old'): |
||
136 | # First call, we init the network_old var |
||
137 | try: |
||
138 | self.network_old = net_io_counters |
||
139 | except (IOError, UnboundLocalError): |
||
140 | pass |
||
141 | return self.stats |
||
142 | |||
143 | # By storing time data we enable Rx/s and Tx/s calculations in the |
||
144 | # XML/RPC API, which would otherwise be overly difficult work |
||
145 | # for users of the API |
||
146 | time_since_update = getTimeSinceLastUpdate('net') |
||
147 | |||
148 | # Loop over interfaces |
||
149 | network_new = net_io_counters |
||
150 | for net in network_new: |
||
151 | # Do not take hidden interface into account |
||
152 | # or KeyError: 'eth0' when interface is not connected #1348 |
||
153 | if not self.is_display(net) or net not in net_status: |
||
154 | continue |
||
155 | try: |
||
156 | cumulative_rx = network_new[net].bytes_recv |
||
157 | cumulative_tx = network_new[net].bytes_sent |
||
158 | cumulative_cx = cumulative_rx + cumulative_tx |
||
159 | rx = cumulative_rx - self.network_old[net].bytes_recv |
||
160 | tx = cumulative_tx - self.network_old[net].bytes_sent |
||
161 | cx = rx + tx |
||
162 | netstat = { |
||
163 | 'interface_name': net, |
||
164 | 'alias': self.has_alias(net), |
||
165 | 'time_since_update': time_since_update, |
||
166 | 'cumulative_rx': cumulative_rx, |
||
167 | 'rx': rx, |
||
168 | 'cumulative_tx': cumulative_tx, |
||
169 | 'tx': tx, |
||
170 | 'cumulative_cx': cumulative_cx, |
||
171 | 'cx': cx, |
||
172 | # Interface status |
||
173 | 'is_up': net_status[net].isup, |
||
174 | # Interface speed in Mbps, convert it to bps |
||
175 | # Can be always 0 on some OSes |
||
176 | 'speed': net_status[net].speed * 1048576, |
||
177 | # Set the key for the dict |
||
178 | 'key': self.get_key(), |
||
179 | } |
||
180 | except KeyError: |
||
181 | continue |
||
182 | else: |
||
183 | # Append the interface stats to the list |
||
184 | stats.append(netstat) |
||
185 | |||
186 | # Save stats to compute next bitrate |
||
187 | self.network_old = network_new |
||
188 | |||
189 | elif self.input_method == 'snmp': |
||
190 | # Update stats using SNMP |
||
191 | |||
192 | # SNMP bulk command to get all network interface in one shot |
||
193 | try: |
||
194 | net_io_counters = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], bulk=True) |
||
195 | except KeyError: |
||
196 | net_io_counters = self.get_stats_snmp(snmp_oid=snmp_oid['default'], bulk=True) |
||
197 | |||
198 | # Previous network interface stats are stored in the network_old variable |
||
199 | if not hasattr(self, 'network_old'): |
||
200 | # First call, we init the network_old var |
||
201 | try: |
||
202 | self.network_old = net_io_counters |
||
203 | except (IOError, UnboundLocalError): |
||
204 | pass |
||
205 | else: |
||
206 | # See description in the 'local' block |
||
207 | time_since_update = getTimeSinceLastUpdate('net') |
||
208 | |||
209 | # Loop over interfaces |
||
210 | network_new = net_io_counters |
||
211 | |||
212 | for net in network_new: |
||
213 | # Do not take hidden interface into account |
||
214 | if not self.is_display(net): |
||
215 | continue |
||
216 | |||
217 | try: |
||
218 | # Windows: a tips is needed to convert HEX to TXT |
||
219 | # 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 |
||
220 | if self.short_system_name == 'windows': |
||
221 | try: |
||
222 | interface_name = str(base64.b16decode(net[2:-2].upper())) |
||
223 | except TypeError: |
||
224 | interface_name = net |
||
225 | else: |
||
226 | interface_name = net |
||
227 | |||
228 | cumulative_rx = float(network_new[net]['cumulative_rx']) |
||
229 | cumulative_tx = float(network_new[net]['cumulative_tx']) |
||
230 | cumulative_cx = cumulative_rx + cumulative_tx |
||
231 | rx = cumulative_rx - float(self.network_old[net]['cumulative_rx']) |
||
232 | tx = cumulative_tx - float(self.network_old[net]['cumulative_tx']) |
||
233 | cx = rx + tx |
||
234 | netstat = { |
||
235 | 'interface_name': interface_name, |
||
236 | 'alias': self.has_alias(interface_name), |
||
237 | 'time_since_update': time_since_update, |
||
238 | 'cumulative_rx': cumulative_rx, |
||
239 | 'rx': rx, |
||
240 | 'cumulative_tx': cumulative_tx, |
||
241 | 'tx': tx, |
||
242 | 'cumulative_cx': cumulative_cx, |
||
243 | 'cx': cx, |
||
244 | } |
||
245 | except KeyError: |
||
246 | continue |
||
247 | else: |
||
248 | netstat['key'] = self.get_key() |
||
249 | stats.append(netstat) |
||
250 | |||
251 | # Save stats to compute next bitrate |
||
252 | self.network_old = network_new |
||
253 | |||
254 | # Update the stats |
||
255 | self.stats = stats |
||
256 | |||
257 | return self.stats |
||
258 | |||
259 | def update_views(self): |
||
260 | """Update stats views.""" |
||
261 | # Call the father's method |
||
262 | super(PluginModel, self).update_views() |
||
263 | |||
264 | # Check if the stats should be hidden |
||
265 | self.update_views_hidden() |
||
266 | |||
267 | # Add specifics information |
||
268 | # Alert |
||
269 | for i in self.get_raw(): |
||
270 | if i['time_since_update'] == 0: |
||
271 | # Skip alert if no timespan to measure |
||
272 | continue |
||
273 | |||
274 | if_real_name = i['interface_name'].split(':')[0] |
||
275 | # Convert rate in bps (to be able to compare to interface speed) |
||
276 | bps_rx = int(i['rx'] // i['time_since_update'] * 8) |
||
277 | bps_tx = int(i['tx'] // i['time_since_update'] * 8) |
||
278 | |||
279 | # Decorate the bitrate with the configuration file thresholds |
||
280 | alert_rx = self.get_alert(bps_rx, header=if_real_name + '_rx') |
||
281 | alert_tx = self.get_alert(bps_tx, header=if_real_name + '_tx') |
||
282 | # If nothing is define in the configuration file... |
||
283 | # ... then use the interface speed (not available on all systems) |
||
284 | if alert_rx == 'DEFAULT' and 'speed' in i and i['speed'] != 0: |
||
285 | alert_rx = self.get_alert(current=bps_rx, maximum=i['speed'], header='rx') |
||
286 | if alert_tx == 'DEFAULT' and 'speed' in i and i['speed'] != 0: |
||
287 | alert_tx = self.get_alert(current=bps_tx, maximum=i['speed'], header='tx') |
||
288 | # then decorates |
||
289 | self.views[i[self.get_key()]]['rx']['decoration'] = alert_rx |
||
290 | self.views[i[self.get_key()]]['tx']['decoration'] = alert_tx |
||
291 | |||
292 | def msg_curse(self, args=None, max_width=None): |
||
293 | """Return the dict to display in the curse interface.""" |
||
294 | # Init the return message |
||
295 | ret = [] |
||
296 | |||
297 | # Only process if stats exist and display plugin enable... |
||
298 | if not self.stats or self.is_disabled(): |
||
299 | return ret |
||
300 | |||
301 | # Max size for the interface name |
||
302 | name_max_width = max_width - 12 |
||
303 | |||
304 | # Header |
||
305 | msg = '{:{width}}'.format('NETWORK', width=name_max_width) |
||
306 | ret.append(self.curse_add_line(msg, "TITLE")) |
||
307 | if args.network_cumul: |
||
308 | # Cumulative stats |
||
309 | if args.network_sum: |
||
310 | # Sum stats |
||
311 | msg = '{:>14}'.format('Rx+Tx') |
||
312 | ret.append(self.curse_add_line(msg)) |
||
313 | else: |
||
314 | # Rx/Tx stats |
||
315 | msg = '{:>7}'.format('Rx') |
||
316 | ret.append(self.curse_add_line(msg)) |
||
317 | msg = '{:>7}'.format('Tx') |
||
318 | ret.append(self.curse_add_line(msg)) |
||
319 | else: |
||
320 | # Bitrate stats |
||
321 | if args.network_sum: |
||
322 | # Sum stats |
||
323 | msg = '{:>14}'.format('Rx+Tx/s') |
||
324 | ret.append(self.curse_add_line(msg)) |
||
325 | else: |
||
326 | msg = '{:>7}'.format('Rx/s') |
||
327 | ret.append(self.curse_add_line(msg)) |
||
328 | msg = '{:>7}'.format('Tx/s') |
||
329 | ret.append(self.curse_add_line(msg)) |
||
330 | # Interface list (sorted by name) |
||
331 | for i in self.sorted_stats(): |
||
332 | # Do not display interface in down state (issue #765) |
||
333 | if ('is_up' in i) and (i['is_up'] is False): |
||
334 | continue |
||
335 | # Hide stats if never be different from 0 (issue #1787) |
||
336 | if all([self.get_views(item=i[self.get_key()], key=f, option='hidden') for f in self.hide_zero_fields]): |
||
337 | continue |
||
338 | # Format stats |
||
339 | # Is there an alias for the interface name ? |
||
340 | if i['alias'] is None: |
||
341 | if_name = i['interface_name'].split(':')[0] |
||
342 | else: |
||
343 | if_name = i['alias'] |
||
344 | if len(if_name) > name_max_width: |
||
345 | # Cut interface name if it is too long |
||
346 | if_name = '_' + if_name[-name_max_width + 1 :] |
||
347 | |||
348 | if args.byte: |
||
349 | # Bytes per second (for dummy) |
||
350 | to_bit = 1 |
||
351 | unit = '' |
||
352 | else: |
||
353 | # Bits per second (for real network administrator | Default) |
||
354 | to_bit = 8 |
||
355 | unit = 'b' |
||
356 | |||
357 | if args.network_cumul: |
||
358 | rx = self.auto_unit(int(i['cumulative_rx'] * to_bit)) + unit |
||
359 | tx = self.auto_unit(int(i['cumulative_tx'] * to_bit)) + unit |
||
360 | sx = self.auto_unit(int(i['cumulative_rx'] * to_bit) + int(i['cumulative_tx'] * to_bit)) + unit |
||
361 | else: |
||
362 | rx = self.auto_unit(int(i['rx'] // i['time_since_update'] * to_bit)) + unit |
||
363 | tx = self.auto_unit(int(i['tx'] // i['time_since_update'] * to_bit)) + unit |
||
364 | sx = ( |
||
365 | self.auto_unit( |
||
366 | int(i['rx'] // i['time_since_update'] * to_bit) |
||
367 | + int(i['tx'] // i['time_since_update'] * to_bit) |
||
368 | ) |
||
369 | + unit |
||
370 | ) |
||
371 | |||
372 | # New line |
||
373 | ret.append(self.curse_new_line()) |
||
374 | msg = '{:{width}}'.format(if_name, width=name_max_width) |
||
375 | ret.append(self.curse_add_line(msg)) |
||
376 | if args.network_sum: |
||
377 | msg = '{:>14}'.format(sx) |
||
378 | ret.append(self.curse_add_line(msg)) |
||
379 | else: |
||
380 | msg = '{:>7}'.format(rx) |
||
381 | ret.append( |
||
382 | self.curse_add_line(msg, self.get_views(item=i[self.get_key()], key='rx', option='decoration')) |
||
383 | ) |
||
384 | msg = '{:>7}'.format(tx) |
||
385 | ret.append( |
||
386 | self.curse_add_line(msg, self.get_views(item=i[self.get_key()], key='tx', option='decoration')) |
||
387 | ) |
||
388 | |||
389 | return ret |
||
390 |