Issues (49)

glances/ports_list.py (1 issue)

1
#
2
# This file is part of Glances.
3
#
4
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]>
5
#
6
# SPDX-License-Identifier: LGPL-3.0-only
7
#
8
9
"""Manage the Glances ports list (Ports plugin)."""
10
11
from glances.globals import BSD
12
from glances.logger import logger
13
14
# XXX *BSDs: Segmentation fault (core dumped)
15
# -- https://bitbucket.org/al45tair/netifaces/issues/15
16
# Also used in the glances_ip plugin
17
if not BSD:
18
    try:
19
        import netifaces
20
21
        netifaces_tag = True
22
    except ImportError:
23
        netifaces_tag = False
24
else:
25
    netifaces_tag = False
26
27
28
class GlancesPortsList:
29
    """Manage the ports list for the ports plugin."""
30
31
    _section = "ports"
32
    _default_refresh = 60
33
    _default_timeout = 3
34
35
    def __init__(self, config=None, args=None):
36
        # ports_list is a list of dict (JSON compliant)
37
        # [ {'host': 'www.google.fr', 'port': 443, 'refresh': 30, 'description': Internet, 'status': True} ... ]
38
        # Load the configuration file
39
        self._ports_list = self.load(config)
40
41
    def load(self, config):
42
        """Load the ports list from the configuration file."""
43
        ports_list = []
44
45
        if config is None:
46
            logger.debug("No configuration file available. Cannot load ports list.")
47
        elif not config.has_section(self._section):
48
            logger.debug(f"No [{self._section}] section in the configuration file. Cannot load ports list.")
49
        else:
50
            logger.debug(f"Start reading the [{self._section}] section in the configuration file")
51
52
            refresh = int(config.get_value(self._section, 'refresh', default=self._default_refresh))
53
            timeout = int(config.get_value(self._section, 'timeout', default=self._default_timeout))
54
55
            # Add default gateway on top of the ports_list lists
56
            default_gateway = config.get_value(self._section, 'port_default_gateway', default='False')
57
            if default_gateway.lower().startswith('true') and netifaces_tag:
58
                new_port = {}
59
                try:
60
                    new_port['host'] = netifaces.gateways()['default'][netifaces.AF_INET][0]
0 ignored issues
show
The variable netifaces does not seem to be defined for all execution paths.
Loading history...
61
                except KeyError:
62
                    new_port['host'] = None
63
                # ICMP
64
                new_port['port'] = 0
65
                new_port['description'] = 'DefaultGateway'
66
                new_port['refresh'] = refresh
67
                new_port['timeout'] = timeout
68
                new_port['status'] = None
69
                new_port['rtt_warning'] = None
70
                new_port['indice'] = 'port_0'
71
                logger.debug("Add default gateway {} to the static list".format(new_port['host']))
72
                ports_list.append(new_port)
73
74
            # Read the scan list
75
            for i in range(1, 256):
76
                new_port = {}
77
                postfix = f'port_{str(i)}_'
78
79
                # Read mandatory configuration key: host
80
                new_port['host'] = config.get_value(self._section, '{}{}'.format(postfix, 'host'))
81
82
                if new_port['host'] is None:
83
                    continue
84
85
                # Read optionals configuration keys
86
                # Port is set to 0 by default. 0 mean ICMP check instead of TCP check
87
                new_port['port'] = config.get_value(self._section, '{}{}'.format(postfix, 'port'), 0)
88
                new_port['description'] = config.get_value(
89
                    self._section, f'{postfix}description', default="{}:{}".format(new_port['host'], new_port['port'])
90
                )
91
92
                # Default status
93
                new_port['status'] = None
94
95
                # Refresh rate in second
96
                new_port['refresh'] = refresh
97
98
                # Timeout in second
99
                new_port['timeout'] = int(config.get_value(self._section, f'{postfix}timeout', default=timeout))
100
101
                # RTT warning
102
                new_port['rtt_warning'] = config.get_value(self._section, f'{postfix}rtt_warning', default=None)
103
                if new_port['rtt_warning'] is not None:
104
                    # Convert to second
105
                    new_port['rtt_warning'] = int(new_port['rtt_warning']) / 1000.0
106
107
                # Indice
108
                new_port['indice'] = 'port_' + str(i)
109
110
                # Add the server to the list
111
                logger.debug("Add port {}:{} to the static list".format(new_port['host'], new_port['port']))
112
                ports_list.append(new_port)
113
114
            # Ports list loaded
115
            logger.debug(f"Ports list loaded: {ports_list}")
116
117
        return ports_list
118
119
    def get_ports_list(self):
120
        """Return the current server list (dict of dict)."""
121
        return self._ports_list
122
123
    def set_server(self, pos, key, value):
124
        """Set the key to the value for the pos (position in the list)."""
125
        self._ports_list[pos][key] = value
126