glances.plugins.glances_fs.Plugin.update()   F
last analyzed

Complexity

Conditions 16

Size

Total Lines 96
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 64
nop 1
dl 0
loc 96
rs 2.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.plugins.glances_fs.Plugin.update() 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
"""File system plugin."""
21
from __future__ import unicode_literals
22
23
import operator
0 ignored issues
show
introduced by desbma
import missing from __future__ import absolute_import
Loading history...
24
25
from glances.compat import u, nativestr, n
0 ignored issues
show
introduced by Nicolas Hennion
import missing from __future__ import absolute_import
Loading history...
Unused Code introduced by Nicolas Hennion
Unused n imported from glances.compat
Loading history...
26
from glances.plugins.glances_plugin import GlancesPlugin
0 ignored issues
show
introduced by Alessio Sergi
import missing from __future__ import absolute_import
Loading history...
27
28
import psutil
0 ignored issues
show
introduced by Alessio Sergi
import missing from __future__ import absolute_import
Loading history...
introduced by Alessio Sergi
Unable to import 'psutil'
Loading history...
29
30
# SNMP OID
31
# The snmpd.conf needs to be edited.
32
# Add the following to enable it on all disk
33
# ...
34
# includeAllDisks 10%
35
# ...
36
# The OIDs are as follows (for the first disk)
37
# Path where the disk is mounted: .1.3.6.1.4.1.2021.9.1.2.1
38
# Path of the device for the partition: .1.3.6.1.4.1.2021.9.1.3.1
39
# Total size of the disk/partion (kBytes): .1.3.6.1.4.1.2021.9.1.6.1
40
# Available space on the disk: .1.3.6.1.4.1.2021.9.1.7.1
41
# Used space on the disk: .1.3.6.1.4.1.2021.9.1.8.1
42
# Percentage of space used on disk: .1.3.6.1.4.1.2021.9.1.9.1
43
# Percentage of inodes used on disk: .1.3.6.1.4.1.2021.9.1.10.1
44
snmp_oid = {'default': {'mnt_point': '1.3.6.1.4.1.2021.9.1.2',
0 ignored issues
show
Coding Style Naming introduced by Nicolas Hennion
The name snmp_oid does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
45
                        'device_name': '1.3.6.1.4.1.2021.9.1.3',
46
                        'size': '1.3.6.1.4.1.2021.9.1.6',
47
                        'used': '1.3.6.1.4.1.2021.9.1.8',
48
                        'percent': '1.3.6.1.4.1.2021.9.1.9'},
49
            'windows': {'mnt_point': '1.3.6.1.2.1.25.2.3.1.3',
50
                        'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4',
51
                        'size': '1.3.6.1.2.1.25.2.3.1.5',
52
                        'used': '1.3.6.1.2.1.25.2.3.1.6'},
53
            'netapp': {'mnt_point': '1.3.6.1.4.1.789.1.5.4.1.2',
54
                       'device_name': '1.3.6.1.4.1.789.1.5.4.1.10',
55
                       'size': '1.3.6.1.4.1.789.1.5.4.1.3',
56
                       'used': '1.3.6.1.4.1.789.1.5.4.1.4',
57
                       'percent': '1.3.6.1.4.1.789.1.5.4.1.6'}}
58
snmp_oid['esxi'] = snmp_oid['windows']
59
60
# Define the history items list
61
# All items in this list will be historised if the --enable-history tag is set
62
items_history_list = [{'name': 'percent',
0 ignored issues
show
Coding Style Naming introduced by Nicolas Hennion
The name items_history_list does not conform to the constant naming conventions ((([A-Z_][A-Z0-9_]*)|(__.*__))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
63
                       'description': 'File system usage in percent',
64
                       'y_unit': '%'}]
65
66
67
class Plugin(GlancesPlugin):
68
    """Glances file system plugin.
69
70
    stats is a list
71
    """
72
73
    def __init__(self, args=None, config=None):
74
        """Init the plugin."""
75
        super(Plugin, self).__init__(args=args,
76
                                     config=config,
77
                                     items_history_list=items_history_list,
78
                                     stats_init_value=[])
79
80
        # We want to display the stat in the curse interface
81
        self.display_curse = True
82
83
    def get_key(self):
84
        """Return the key of the list."""
85
        return 'mnt_point'
86
87
    @GlancesPlugin._check_decorator
88
    @GlancesPlugin._log_result_decorator
89
    def update(self):
90
        """Update the FS stats using the input method."""
91
        # Init new stats
92
        stats = self.get_init_value()
93
94
        if self.input_method == 'local':
95
            # Update stats using the standard system lib
96
97
            # Grab the stats using the psutil disk_partitions
98
            # If 'all'=False return physical devices only (e.g. hard disks, cd-rom drives, USB keys)
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
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...
99
            # and ignore all others (e.g. memory partitions such as /dev/shm)
100
            try:
101
                fs_stat = psutil.disk_partitions(all=False)
102
            except (UnicodeDecodeError, PermissionError):
0 ignored issues
show
Comprehensibility Best Practice introduced by Nicolas Hennion
Undefined variable 'PermissionError'
Loading history...
103
                return self.stats
104
105
            # Optionnal hack to allow logicals mounts points (issue #448)
106
            # Ex: Had to put 'allow=zfs' in the [fs] section of the conf file
107
            #     to allow zfs monitoring
108
            for fstype in self.get_conf_value('allow'):
109
                try:
110
                    fs_stat += [f for f in psutil.disk_partitions(all=True) if f.fstype.find(fstype) >= 0]
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
This line is too long as per the coding-style (106/80).

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

Loading history...
111
                except UnicodeDecodeError:
112
                    return self.stats
113
114
            # Loop over fs
115
            for fs in fs_stat:
0 ignored issues
show
Coding Style Naming introduced by Alessio Sergi
The name fs does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
116
                # Do not take hidden file system into account
117
                if self.is_hide(fs.mountpoint):
118
                    continue
119
                # Grab the disk usage
120
                try:
121
                    fs_usage = psutil.disk_usage(fs.mountpoint)
122
                except OSError:
123
                    # Correct issue #346
124
                    # Disk is ejected during the command
125
                    continue
126
                fs_current = {
127
                    'device_name': fs.device,
128
                    'fs_type': fs.fstype,
129
                    # Manage non breaking space (see issue #1065)
130
                    'mnt_point': u(fs.mountpoint).replace(u'\u00A0', ' '),
131
                    'size': fs_usage.total,
132
                    'used': fs_usage.used,
133
                    'free': fs_usage.free,
134
                    'percent': fs_usage.percent,
135
                    'key': self.get_key()}
136
                stats.append(fs_current)
137
138
        elif self.input_method == 'snmp':
139
            # Update stats using SNMP
140
141
            # SNMP bulk command to get all file system in one shot
142
            try:
143
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
0 ignored issues
show
Coding Style introduced by Alessio Sergi
This line is too long as per the coding-style (88/80).

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

Loading history...
144
                                              bulk=True)
145
            except KeyError:
146
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid['default'],
147
                                              bulk=True)
148
149
            # Loop over fs
150
            if self.short_system_name in ('windows', 'esxi'):
151
                # Windows or ESXi tips
152
                for fs in fs_stat:
0 ignored issues
show
Coding Style Naming introduced by Nicolas Hennion
The name fs does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
153
                    # Memory stats are grabbed in the same OID table (ignore it)
154
                    if fs == 'Virtual Memory' or fs == 'Physical Memory' or fs == 'Real Memory':
0 ignored issues
show
Coding Style introduced by nicolargo
This line is too long as per the coding-style (96/80).

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

Loading history...
155
                        continue
156
                    size = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
0 ignored issues
show
Coding Style introduced by Alessio Sergi
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...
157
                    used = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
0 ignored issues
show
Coding Style introduced by Alessio Sergi
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...
158
                    percent = float(used * 100 / size)
0 ignored issues
show
introduced by Alessio Sergi
division w/o __future__ statement
Loading history...
159
                    fs_current = {
160
                        'device_name': '',
161
                        'mnt_point': fs.partition(' ')[0],
162
                        'size': size,
163
                        'used': used,
164
                        'percent': percent,
165
                        'key': self.get_key()}
166
                    stats.append(fs_current)
167
            else:
168
                # Default behavior
169
                for fs in fs_stat:
0 ignored issues
show
Coding Style Naming introduced by Nicolas Hennion
The name fs does not conform to the variable naming conventions ((([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$).

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
170
                    fs_current = {
171
                        'device_name': fs_stat[fs]['device_name'],
172
                        'mnt_point': fs,
173
                        'size': int(fs_stat[fs]['size']) * 1024,
174
                        'used': int(fs_stat[fs]['used']) * 1024,
175
                        'percent': float(fs_stat[fs]['percent']),
176
                        'key': self.get_key()}
177
                    stats.append(fs_current)
178
179
        # Update the stats
180
        self.stats = stats
181
182
        return self.stats
183
184
    def update_views(self):
185
        """Update stats views."""
186
        # Call the father's method
187
        super(Plugin, self).update_views()
188
189
        # Add specifics informations
190
        # Alert
191
        for i in self.stats:
192
            self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert(
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
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...
193
                i['used'], maximum=i['size'], header=i['mnt_point'])
194
195
    def msg_curse(self, args=None, max_width=None):
196
        """Return the dict to display in the curse interface."""
197
        # Init the return message
198
        ret = []
199
200
        # Only process if stats exist and display plugin enable...
201
        if not self.stats or self.is_disable():
202
            return ret
203
204
        # Max size for the interface name
205
        name_max_width = max_width - 12
206
207
        # Build the string message
208
        # Header
209
        msg = '{:{width}}'.format('FILE SYS', width=name_max_width)
210
        ret.append(self.curse_add_line(msg, "TITLE"))
211
        if args.fs_free_space:
212
            msg = '{:>7}'.format('Free')
213
        else:
214
            msg = '{:>7}'.format('Used')
215
        ret.append(self.curse_add_line(msg))
216
        msg = '{:>7}'.format('Total')
217
        ret.append(self.curse_add_line(msg))
218
219
        # Filesystem list (sorted by name)
220
        for i in sorted(self.stats, key=operator.itemgetter(self.get_key())):
221
            # New line
222
            ret.append(self.curse_new_line())
223
            if i['device_name'] == '' or i['device_name'] == 'none':
224
                mnt_point = i['mnt_point'][-name_max_width + 1:]
225
            elif len(i['mnt_point']) + len(i['device_name'].split('/')[-1]) <= name_max_width - 3:
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
This line is too long as per the coding-style (98/80).

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

Loading history...
226
                # If possible concatenate mode info... Glances touch inside :)
227
                mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
0 ignored issues
show
Coding Style introduced by Alessio Sergi
This line is too long as per the coding-style (89/80).

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

Loading history...
228
            elif len(i['mnt_point']) > name_max_width:
229
                # Cut mount point name if it is too long
230
                mnt_point = '_' + i['mnt_point'][-name_max_width + 1:]
231
            else:
232
                mnt_point = i['mnt_point']
233
            msg = '{:{width}}'.format(nativestr(mnt_point),
234
                                      width=name_max_width)
235
            ret.append(self.curse_add_line(msg))
236
            if args.fs_free_space:
237
                msg = '{:>7}'.format(self.auto_unit(i['free']))
238
            else:
239
                msg = '{:>7}'.format(self.auto_unit(i['used']))
240
            ret.append(self.curse_add_line(msg, self.get_views(item=i[self.get_key()],
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
This line is too long as per the coding-style (86/80).

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

Loading history...
241
                                                               key='used',
242
                                                               option='decoration')))
0 ignored issues
show
Coding Style introduced by Nicolas Hennion
This line is too long as per the coding-style (85/80).

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

Loading history...
243
            msg = '{:>7}'.format(self.auto_unit(i['size']))
244
            ret.append(self.curse_add_line(msg))
245
246
        return ret
247