Test Failed
Push — develop ( d7cf39...faa4bd )
by Nicolas
04:34 queued 10s
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
            # 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]
111
                except UnicodeDecodeError:
112
                    return self.stats
113
114
            # Loop over fs
115
            for fs in fs_stat:
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],
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:
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':
155
                        continue
156
                    size = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
157
                    used = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
158
                    percent = float(used * 100 / size)
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:
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(
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:
226
                # If possible concatenate mode info... Glances touch inside :)
227
                mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
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()],
241
                                                               key='used',
242
                                                               option='decoration')))
243
            msg = '{:>7}'.format(self.auto_unit(i['size']))
244
            ret.append(self.curse_add_line(msg))
245
246
        return ret
247