Test Failed
Push — master ( ee826a...d9056e )
by Nicolas
03:09
created

glances.plugins.fs.PluginModel.update()   F

Complexity

Conditions 25

Size

Total Lines 126
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 78
nop 1
dl 0
loc 126
rs 0
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.fs.PluginModel.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
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""File system plugin."""
11
from __future__ import unicode_literals
12
13
import operator
14
15
from glances.globals import u, nativestr, PermissionError
16
from glances.logger import logger
17
from glances.plugins.plugin.model import GlancesPluginModel
18
19
import psutil
20
21
# Fields description
22
# description: human readable description
23
# short_name: shortname to use un UI
24
# unit: unit type
25
# rate: is it a rate ? If yes, // by time_since_update when displayed,
26
# min_symbol: Auto unit should be used if value > than 1 'X' (K, M, G)...
27
fields_description = {
28
    'device_name': {'description': 'Device name.'},
29
    'fs_type': {'description': 'File system type.'},
30
    'mnt_point': {'description': 'Mount point.'},
31
    'size': {
32
        'description': 'Total size.',
33
        'unit': 'byte',
34
    },
35
    'used': {
36
        'description': 'Used size.',
37
        'unit': 'byte',
38
    },
39
    'free': {
40
        'description': 'Free size.',
41
        'unit': 'byte',
42
    },
43
    'percent': {
44
        'description': 'File system usage in percent.',
45
        'unit': 'percent',
46
    },
47
}
48
49
# SNMP OID
50
# The snmpd.conf needs to be edited.
51
# Add the following to enable it on all disk
52
# ...
53
# includeAllDisks 10%
54
# ...
55
# The OIDs are as follows (for the first disk)
56
# Path where the disk is mounted: .1.3.6.1.4.1.2021.9.1.2.1
57
# Path of the device for the partition: .1.3.6.1.4.1.2021.9.1.3.1
58
# Total size of the disk/partition (kBytes): .1.3.6.1.4.1.2021.9.1.6.1
59
# Available space on the disk: .1.3.6.1.4.1.2021.9.1.7.1
60
# Used space on the disk: .1.3.6.1.4.1.2021.9.1.8.1
61
# Percentage of space used on disk: .1.3.6.1.4.1.2021.9.1.9.1
62
# Percentage of inodes used on disk: .1.3.6.1.4.1.2021.9.1.10.1
63
snmp_oid = {
64
    'default': {
65
        'mnt_point': '1.3.6.1.4.1.2021.9.1.2',
66
        'device_name': '1.3.6.1.4.1.2021.9.1.3',
67
        'size': '1.3.6.1.4.1.2021.9.1.6',
68
        'used': '1.3.6.1.4.1.2021.9.1.8',
69
        'percent': '1.3.6.1.4.1.2021.9.1.9',
70
    },
71
    'windows': {
72
        'mnt_point': '1.3.6.1.2.1.25.2.3.1.3',
73
        'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4',
74
        'size': '1.3.6.1.2.1.25.2.3.1.5',
75
        'used': '1.3.6.1.2.1.25.2.3.1.6',
76
    },
77
    'netapp': {
78
        'mnt_point': '1.3.6.1.4.1.789.1.5.4.1.2',
79
        'device_name': '1.3.6.1.4.1.789.1.5.4.1.10',
80
        'size': '1.3.6.1.4.1.789.1.5.4.1.3',
81
        'used': '1.3.6.1.4.1.789.1.5.4.1.4',
82
        'percent': '1.3.6.1.4.1.789.1.5.4.1.6',
83
    },
84
}
85
snmp_oid['esxi'] = snmp_oid['windows']
86
87
# Define the history items list
88
# All items in this list will be historised if the --enable-history tag is set
89
items_history_list = [{'name': 'percent', 'description': 'File system usage in percent', 'y_unit': '%'}]
90
91
92
class PluginModel(GlancesPluginModel):
93
    """Glances file system plugin.
94
95
    stats is a list
96
    """
97
98
    def __init__(self, args=None, config=None):
99
        """Init the plugin."""
100
        super(PluginModel, self).__init__(
101
            args=args,
102
            config=config,
103
            items_history_list=items_history_list,
104
            stats_init_value=[],
105
            fields_description=fields_description,
106
        )
107
108
        # We want to display the stat in the curse interface
109
        self.display_curse = True
110
111
    def get_key(self):
112
        """Return the key of the list."""
113
        return 'mnt_point'
114
115
    @GlancesPluginModel._check_decorator
116
    @GlancesPluginModel._log_result_decorator
117
    def update(self):
118
        """Update the FS stats using the input method."""
119
        # Init new stats
120
        stats = self.get_init_value()
121
122
        if self.input_method == 'local':
123
            # Update stats using the standard system lib
124
125
            # Grab the stats using the psutil disk_partitions
126
            # If 'all'=False return physical devices only (e.g. hard disks, cd-rom drives, USB keys)
127
            # and ignore all others (e.g. memory partitions such as /dev/shm)
128
            try:
129
                fs_stat = psutil.disk_partitions(all=False)
130
            except (UnicodeDecodeError, PermissionError):
131
                logger.debug("Plugin - fs: PsUtil fetch failed")
132
                return self.stats
133
134
            # Optional hack to allow logical mounts points (issue #448)
135
            allowed_fs_types = self.get_conf_value('allow')
136
            if allowed_fs_types:
137
                # Avoid Psutil call unless mounts need to be allowed
138
                try:
139
                    all_mounted_fs = psutil.disk_partitions(all=True)
140
                except (UnicodeDecodeError, PermissionError):
141
                    logger.debug("Plugin - fs: PsUtil extended fetch failed")
142
                else:
143
                    # Discard duplicates (#2299) and add entries matching allowed fs types
144
                    tracked_mnt_points = set(f.mountpoint for f in fs_stat)
145
                    for f in all_mounted_fs:
146
                        if (
147
                            any(f.fstype.find(fs_type) >= 0 for fs_type in allowed_fs_types)
148
                            and f.mountpoint not in tracked_mnt_points
149
                        ):
150
                            fs_stat.append(f)
151
152
            # Loop over fs
153
            for fs in fs_stat:
154
                # Hide the stats if the mount point is in the exclude list
155
                if not self.is_display(fs.mountpoint):
156
                    continue
157
158
                # Grab the disk usage
159
                try:
160
                    fs_usage = psutil.disk_usage(fs.mountpoint)
161
                except OSError:
162
                    # Correct issue #346
163
                    # Disk is ejected during the command
164
                    continue
165
                fs_current = {
166
                    'device_name': fs.device,
167
                    'fs_type': fs.fstype,
168
                    # Manage non breaking space (see issue #1065)
169
                    'mnt_point': u(fs.mountpoint).replace(u'\u00A0', ' '),
170
                    'size': fs_usage.total,
171
                    'used': fs_usage.used,
172
                    'free': fs_usage.free,
173
                    'percent': fs_usage.percent,
174
                    'key': self.get_key(),
175
                }
176
177
                # Hide the stats if the device name is in the exclude list
178
                # Correct issue: glances.conf FS hide not applying #1666
179
                if not self.is_display(fs_current['device_name']):
180
                    continue
181
182
                # Add alias if exist (define in the configuration file)
183
                if self.has_alias(fs_current['mnt_point']) is not None:
184
                    fs_current['alias'] = self.has_alias(fs_current['mnt_point'])
185
186
                stats.append(fs_current)
187
188
        elif self.input_method == 'snmp':
189
            # Update stats using SNMP
190
191
            # SNMP bulk command to get all file system in one shot
192
            try:
193
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], bulk=True)
194
            except KeyError:
195
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid['default'], bulk=True)
196
197
            # Loop over fs
198
            if self.short_system_name in ('windows', 'esxi'):
199
                # Windows or ESXi tips
200
                for fs in fs_stat:
201
                    # Memory stats are grabbed in the same OID table (ignore it)
202
                    if fs == 'Virtual Memory' or fs == 'Physical Memory' or fs == 'Real Memory':
203
                        continue
204
                    size = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
205
                    used = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
206
                    percent = float(used * 100 / size)
207
                    fs_current = {
208
                        'device_name': '',
209
                        'mnt_point': fs.partition(' ')[0],
210
                        'size': size,
211
                        'used': used,
212
                        'percent': percent,
213
                        'key': self.get_key(),
214
                    }
215
                    # Do not take hidden file system into account
216
                    if self.is_hide(fs_current['mnt_point']):
217
                        continue
218
                    else:
219
                        stats.append(fs_current)
220
            else:
221
                # Default behavior
222
                for fs in fs_stat:
223
                    fs_current = {
224
                        'device_name': fs_stat[fs]['device_name'],
225
                        'mnt_point': fs,
226
                        'size': int(fs_stat[fs]['size']) * 1024,
227
                        'used': int(fs_stat[fs]['used']) * 1024,
228
                        'percent': float(fs_stat[fs]['percent']),
229
                        'key': self.get_key(),
230
                    }
231
                    # Do not take hidden file system into account
232
                    if self.is_hide(fs_current['mnt_point']) or self.is_hide(fs_current['device_name']):
233
                        continue
234
                    else:
235
                        stats.append(fs_current)
236
237
        # Update the stats
238
        self.stats = stats
239
240
        return self.stats
241
242
    def update_views(self):
243
        """Update stats views."""
244
        # Call the father's method
245
        super(PluginModel, self).update_views()
246
247
        # Add specifics information
248
        # Alert
249
        for i in self.stats:
250
            self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert(
251
                current=i['size'] - i['free'], maximum=i['size'], header=i['mnt_point']
252
            )
253
254
    def msg_curse(self, args=None, max_width=None):
255
        """Return the dict to display in the curse interface."""
256
        # Init the return message
257
        ret = []
258
259
        # Only process if stats exist and display plugin enable...
260
        if not self.stats or self.is_disabled():
261
            return ret
262
263
        # Max size for the interface name
264
        if max_width:
265
            name_max_width = max_width - 13
266
        else:
267
            # No max_width defined, return an emptu curse message
268
            logger.debug("No max_width defined for the {} plugin, it will not be displayed.".format(self.plugin_name))
269
            return ret
270
271
        # Build the string message
272
        # Header
273
        msg = '{:{width}}'.format('FILE SYS', width=name_max_width)
274
        ret.append(self.curse_add_line(msg, "TITLE"))
275
        if args.fs_free_space:
276
            msg = '{:>8}'.format('Free')
277
        else:
278
            msg = '{:>8}'.format('Used')
279
        ret.append(self.curse_add_line(msg))
280
        msg = '{:>7}'.format('Total')
281
        ret.append(self.curse_add_line(msg))
282
283
        # Filesystem list (sorted by name)
284
        for i in sorted(self.stats, key=operator.itemgetter(self.get_key())):
285
            # New line
286
            ret.append(self.curse_new_line())
287
            mnt_point = i['alias'] if 'alias' in i else i['mnt_point']
288
            if len(mnt_point) + len(i['device_name'].split('/')[-1]) <= name_max_width - 3:
289
                # If possible concatenate mode info... Glances touch inside :)
290
                mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
291
            elif len(mnt_point) > name_max_width:
292
                mnt_point = mnt_point[:name_max_width] + '_'
293
            msg = '{:{width}}'.format(nativestr(mnt_point), width=name_max_width + 1)
294
            ret.append(self.curse_add_line(msg))
295
            if args.fs_free_space:
296
                msg = '{:>7}'.format(self.auto_unit(i['free']))
297
            else:
298
                msg = '{:>7}'.format(self.auto_unit(i['used']))
299
            ret.append(
300
                self.curse_add_line(msg, self.get_views(item=i[self.get_key()], key='used', option='decoration'))
301
            )
302
            msg = '{:>7}'.format(self.auto_unit(i['size']))
303
            ret.append(self.curse_add_line(msg))
304
305
        return ret
306