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

GlancesStaticServer.load_server_list()   C

Complexity

Conditions 11

Size

Total Lines 58
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 37
nop 2
dl 0
loc 58
rs 5.4
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like glances.servers_list_static.GlancesStaticServer.load_server_list() 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
#
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 server static list."""
10
11
from socket import gaierror, gethostbyname
12
13
from glances.logger import logger
14
15
16
class GlancesStaticServer:
17
    """Manage the static servers list for the client browser."""
18
19
    _section = "serverlist"
20
21
    def __init__(self, config=None, args=None):
22
        # server_list is a list of dict (JSON compliant)
23
        # [ {'key': 'zeroconf name', ip': '172.1.2.3', 'port': 61209, 'protocol': 'rpc', 'cpu': 3, 'mem': 34 ...} ... ]
24
        # Load server list from the Glances configuration file
25
        self._server_list = self.load_server_list(config)
26
27
    def load_server_list(self, config):
28
        """Load the server list from the configuration file."""
29
        server_list = []
30
31
        if config is None:
32
            logger.debug("No configuration file available. Cannot load server list.")
33
        elif not config.has_section(self._section):
34
            logger.warning(f"No [{self._section}] section in the configuration file. Cannot load server list.")
35
        else:
36
            logger.info(f"Start reading the [{self._section}] section in the configuration file")
37
            for i in range(1, 256):
38
                # Read the configuration
39
                new_server = {}
40
                postfix = f'server_{str(i)}_'
41
                for s in ['name', 'port', 'alias', 'protocol']:
42
                    new_server[s] = config.get_value(self._section, f'{postfix}{s}')
43
44
                if new_server['name'] is None:
45
                    continue
46
47
                # Type in order to support both RPC and REST servers (see #1121)
48
                if new_server['protocol'] is None:
49
                    new_server['protocol'] = 'rpc'
50
                new_server['protocol'] = new_server['protocol'].lower()
51
                if new_server['protocol'] not in ('rpc', 'rest'):
52
                    logger.error(f'Unknow protocol for {postfix}, skip it.')
53
                    continue
54
55
                # Default port
56
                if new_server['port'] is None:
57
                    new_server['port'] = '61209' if new_server['type'] == 'rpc' else '61208'
58
59
                # By default, try empty (aka no) password
60
                new_server['username'] = 'glances'
61
                new_server['password'] = ''
62
63
                try:
64
                    new_server['ip'] = gethostbyname(new_server['name'])
65
                except gaierror as e:
66
                    logger.error("Cannot get IP address for server {} ({})".format(new_server['name'], e))
67
                    continue
68
                new_server['key'] = new_server['name'] + ':' + new_server['port']
69
70
                # Default status is 'UNKNOWN'
71
                new_server['status'] = 'UNKNOWN'
72
73
                # Server type is 'STATIC'
74
                new_server['type'] = 'STATIC'
75
76
                # Add the server to the list
77
                logger.debug("Add server {} to the static list".format(new_server['name']))
78
                server_list.append(new_server)
79
80
            # Server list loaded
81
            logger.info(f"{len(server_list)} server(s) loaded from the configuration file")
82
            logger.debug(f"Static server list: {server_list}")
83
84
        return server_list
85
86
    def get_servers_list(self):
87
        """Return the current server list (list of dict)."""
88
        return self._server_list
89
90
    def set_server(self, server_pos, key, value):
91
        """Set the key to the value for the server_pos (position in the list)."""
92
        self._server_list[server_pos][key] = value
93