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

Complexity

Conditions 25

Size

Total Lines 124
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Importance

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