Issues (46)

glances/ports_list.py (1 issue)

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