Test Failed
Push — master ( 4c6c3d...040528 )
by Nicolas
04:27
created

glances/plugins/glances_fs.py (1 issue)

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
import missing from __future__ import absolute_import
Loading history...
24
25
from glances.compat import u, nativestr, n
26
from glances.plugins.glances_plugin import GlancesPlugin
27
28
import psutil
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',
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',
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)
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):
103
                return self.stats
104
105
            # Optionnal hack to allow logicals mounts points (issue #448)
106
            for fstype in self.get_conf_value('allow'):
107
                try:
108
                    fs_stat += [f for f in psutil.disk_partitions(all=True) if f.fstype.find(fstype) >= 0]
109
                except UnicodeDecodeError:
110
                    return self.stats
111
112
            # Loop over fs
113
            for fs in fs_stat:
114
                # Do not take hidden file system into account
115
                # Also check device name (see issue #1606)
116
                if self.is_hide(fs.mountpoint) or self.is_hide(fs.device):
117
                    continue
118
                # Grab the disk usage
119
                try:
120
                    fs_usage = psutil.disk_usage(fs.mountpoint)
121
                except OSError:
122
                    # Correct issue #346
123
                    # Disk is ejected during the command
124
                    continue
125
                fs_current = {
126
                    'device_name': fs.device,
127
                    'fs_type': fs.fstype,
128
                    # Manage non breaking space (see issue #1065)
129
                    'mnt_point': u(fs.mountpoint).replace(u'\u00A0', ' '),
130
                    'size': fs_usage.total,
131
                    'used': fs_usage.used,
132
                    'free': fs_usage.free,
133
                    'percent': fs_usage.percent,
134
                    'key': self.get_key()}
135
                stats.append(fs_current)
136
137
        elif self.input_method == 'snmp':
138
            # Update stats using SNMP
139
140
            # SNMP bulk command to get all file system in one shot
141
            try:
142
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name],
143
                                              bulk=True)
144
            except KeyError:
145
                fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid['default'],
146
                                              bulk=True)
147
148
            # Loop over fs
149
            if self.short_system_name in ('windows', 'esxi'):
150
                # Windows or ESXi tips
151
                for fs in fs_stat:
152
                    # Memory stats are grabbed in the same OID table (ignore it)
153
                    if fs == 'Virtual Memory' or fs == 'Physical Memory' or fs == 'Real Memory':
154
                        continue
155
                    size = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
156
                    used = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
157
                    percent = float(used * 100 / size)
158
                    fs_current = {
159
                        'device_name': '',
160
                        'mnt_point': fs.partition(' ')[0],
161
                        'size': size,
162
                        'used': used,
163
                        'percent': percent,
164
                        'key': self.get_key()}
165
                    # Do not take hidden file system into account
166
                    if self.is_hide(fs_current['mnt_point']):
167
                        continue
168
                    else:
169
                        stats.append(fs_current)
170
            else:
171
                # Default behavior
172
                for fs in fs_stat:
173
                    fs_current = {
174
                        'device_name': fs_stat[fs]['device_name'],
175
                        'mnt_point': fs,
176
                        'size': int(fs_stat[fs]['size']) * 1024,
177
                        'used': int(fs_stat[fs]['used']) * 1024,
178
                        'percent': float(fs_stat[fs]['percent']),
179
                        'key': self.get_key()}
180
                    # Do not take hidden file system into account
181
                    if self.is_hide(fs_current['mnt_point']) or self.is_hide(fs_current['device_name']):
182
                        continue
183
                    else:
184
                        stats.append(fs_current)
185
186
        # Update the stats
187
        self.stats = stats
188
189
        return self.stats
190
191
    def update_views(self):
192
        """Update stats views."""
193
        # Call the father's method
194
        super(Plugin, self).update_views()
195
196
        # Add specifics informations
197
        # Alert
198
        for i in self.stats:
199
            self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert(
200
                current=i['size'] - i['free'], maximum=i['size'], header=i['mnt_point'])
201
202
    def msg_curse(self, args=None, max_width=None):
203
        """Return the dict to display in the curse interface."""
204
        # Init the return message
205
        ret = []
206
207
        # Only process if stats exist and display plugin enable...
208
        if not self.stats or self.is_disable():
209
            return ret
210
211
        # Max size for the interface name
212
        name_max_width = max_width - 12
213
214
        # Build the string message
215
        # Header
216
        msg = '{:{width}}'.format('FILE SYS', width=name_max_width)
217
        ret.append(self.curse_add_line(msg, "TITLE"))
218
        if args.fs_free_space:
219
            msg = '{:>7}'.format('Free')
220
        else:
221
            msg = '{:>7}'.format('Used')
222
        ret.append(self.curse_add_line(msg))
223
        msg = '{:>7}'.format('Total')
224
        ret.append(self.curse_add_line(msg))
225
226
        # Filesystem list (sorted by name)
227
        for i in sorted(self.stats, key=operator.itemgetter(self.get_key())):
228
            # New line
229
            ret.append(self.curse_new_line())
230
            if i['device_name'] == '' or i['device_name'] == 'none':
231
                mnt_point = i['mnt_point'][-name_max_width + 1:]
232
            elif len(i['mnt_point']) + len(i['device_name'].split('/')[-1]) <= name_max_width - 3:
233
                # If possible concatenate mode info... Glances touch inside :)
234
                mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
235
            elif len(i['mnt_point']) > name_max_width:
236
                # Cut mount point name if it is too long
237
                mnt_point = '_' + i['mnt_point'][-name_max_width + 1:]
238
            else:
239
                mnt_point = i['mnt_point']
240
            msg = '{:{width}}'.format(nativestr(mnt_point),
241
                                      width=name_max_width)
242
            ret.append(self.curse_add_line(msg))
243
            if args.fs_free_space:
244
                msg = '{:>7}'.format(self.auto_unit(i['free']))
245
            else:
246
                msg = '{:>7}'.format(self.auto_unit(i['used']))
247
            ret.append(self.curse_add_line(msg, self.get_views(item=i[self.get_key()],
248
                                                               key='used',
249
                                                               option='decoration')))
250
            msg = '{:>7}'.format(self.auto_unit(i['size']))
251
            ret.append(self.curse_add_line(msg))
252
253
        return ret
254