Test Failed
Push — master ( 73a01d...ef36eb )
by Nicolas
04:43
created

glances.plugins.fs.FsPlugin.update_local()   C

Complexity

Conditions 9

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 32
nop 1
dl 0
loc 53
rs 6.6666
c 0
b 0
f 0

How to fix   Long Method   

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:

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