Test Failed
Push — develop ( d7cf39...faa4bd )
by Nicolas
04:34 queued 10s
created

glances/ports_list.py (6 issues)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""Manage the Glances ports list (Ports plugin)."""
21
22
from glances.compat import range
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in range.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

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