Test Failed
Push — develop ( 66c9ff...e21229 )
by Nicolas
05:06
created

glances.web_list.GlancesWebList.load()   C

Complexity

Conditions 10

Size

Total Lines 85
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 52
nop 2
dl 0
loc 85
rs 5.7709
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.web_list.GlancesWebList.load() 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
# 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 web/url list (Ports plugin)."""
21
22
from glances.compat import range, urlparse
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...
introduced by
import missing from __future__ import absolute_import
Loading history...
23
from glances.logger import logger
0 ignored issues
show
introduced by
import missing from __future__ import absolute_import
Loading history...
24
25
26
class GlancesWebList(object):
27
28
    """Manage the Web/Url list for the ports plugin."""
29
30
    _section = "ports"
31
    _default_refresh = 60
32
    _default_timeout = 3
33
34
    def __init__(self, config=None, args=None):
0 ignored issues
show
Unused Code introduced by
The argument args seems to be unused.
Loading history...
35
        # web_list is a list of dict (JSON compliant)
36
        # [ {'url': 'http://blog.nicolargo.com',
37
        #    'refresh': 30,
38
        #    'description': 'My blog',
39
        #    'status': 404} ... ]
40
        # Load the configuration file
41
        self._web_list = self.load(config)
42
43
    def load(self, config):
44
        """Load the web list from the configuration file."""
45
        web_list = []
46
47
        if config is None:
48
            logger.debug("No configuration file available. Cannot load ports list.")
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (84/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
49
        elif not config.has_section(self._section):
50
            logger.debug("No [%s] section in the configuration file. Cannot load ports list." % self._section)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (110/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
51
        else:
52
            logger.debug("Start reading the [%s] section in the configuration file" % self._section)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (100/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
53
54
            refresh = int(config.get_value(self._section, 'refresh', default=self._default_refresh))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (100/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
55
            timeout = int(config.get_value(self._section, 'timeout', default=self._default_timeout))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (100/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
56
57
            # Read the web/url list
58
            for i in range(1, 256):
59
                new_web = {}
60
                postfix = 'web_%s_' % str(i)
61
62
                # Read mandatories configuration key: host
63
                new_web['url'] = config.get_value(self._section, '%s%s' % (postfix, 'url'))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (91/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
64
                if new_web['url'] is None:
65
                    continue
66
                url_parse = urlparse(new_web['url'])
67
                if not bool(url_parse.scheme) or not bool(url_parse.netloc):
68
                    logger.error('Bad URL (%s) in the [%s] section of configuration file.' % (new_web['url'],
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (109/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
69
                                                                                              self._section))
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (109/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
70
                    continue
71
72
                # Read optionals configuration keys
73
                # Default description is the URL without the http://
74
                new_web['description'] = config.get_value(self._section,
75
                                                          '%sdescription' % postfix,
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (84/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
76
                                                          default="%s" % url_parse.netloc)
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (90/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
77
78
                # Default status
79
                new_web['status'] = None
80
                new_web['elapsed'] = 0
81
82
                # Refresh rate in second
83
                new_web['refresh'] = refresh
84
85
                # Timeout in second
86
                new_web['timeout'] = int(config.get_value(self._section,
87
                                                          '%stimeout' % postfix,
88
                                                          default=timeout))
89
90
                # RTT warning
91
                new_web['rtt_warning'] = config.get_value(self._section,
92
                                                          '%srtt_warning' % postfix,
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (84/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
93
                                                          default=None)
94
                if new_web['rtt_warning'] is not None:
95
                    # Convert to second
96
                    new_web['rtt_warning'] = int(new_web['rtt_warning']) / 1000.0
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (81/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
97
98
                # Indice
99
                new_web['indice'] = 'web_' + str(i)
100
                
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
101
                # ssl_verify
102
                new_web['ssl_verify'] = config.get_value(self._section, 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
103
                                                        '%sssl_verify' % postfix,
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (add 1 space).
Loading history...
Coding Style introduced by
This line is too long as per the coding-style (81/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
104
                                                         default=True)
105
                # Proxy
106
                http_proxy = config.get_value(self._section, 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
107
                                                '%shttp_proxy' % postfix,
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 2 spaces).
Loading history...
108
                                                default=None)
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 2 spaces).
Loading history...
109
                
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
110
                https_proxy = config.get_value(self._section, 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
111
                                                '%shttps_proxy' % postfix,
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 1 space).
Loading history...
112
                                                default=None)
0 ignored issues
show
Coding Style introduced by
Wrong continued indentation (remove 1 space).
Loading history...
113
114
                if https_proxy is None and http_proxy is None:
115
                    new_web['proxies'] = None
116
                else:
117
                    new_web['proxies'] = {'http' : http_proxy,
118
                                          'https' : https_proxy }
0 ignored issues
show
Coding Style introduced by
No space allowed before bracket
Loading history...
119
120
                # Add the server to the list
121
                logger.debug("Add Web URL %s to the static list" % new_web['url'])
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (82/80).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
122
                web_list.append(new_web)
123
124
            # Ports list loaded
125
            logger.debug("Web list loaded: %s" % web_list)
0 ignored issues
show
Coding Style Best Practice introduced by
Specify string format arguments as logging function parameters
Loading history...
126
127
        return web_list
128
129
    def get_web_list(self):
130
        """Return the current server list (dict of dict)."""
131
        return self._web_list
132
133
    def set_server(self, pos, key, value):
134
        """Set the key to the value for the pos (position in the list)."""
135
        self._web_list[pos][key] = value
136