glances.plugins.glances_mem   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 283
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 146
dl 0
loc 283
rs 10
c 0
b 0
f 0
wmc 22

4 Methods

Rating   Name   Duplication   Size   Complexity  
F Plugin.update() 0 99 15
A Plugin.update_views() 0 12 3
A Plugin.__init__() 0 8 1
A Plugin.msg_curse() 0 46 3
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""Virtual memory plugin."""
11
12
from glances.compat import iterkeys
13
from glances.plugins.glances_plugin import GlancesPlugin
14
15
import psutil
16
17
# Fields description
18
fields_description = {
19
    'total': {'description': 'Total physical memory available.', 'unit': 'bytes', 'min_symbol': 'K'},
20
    'available': {
21
        'description': 'The actual amount of available memory that can be given instantly \
22
to processes that request more memory in bytes; this is calculated by summing \
23
different memory values depending on the platform (e.g. free + buffers + cached on Linux) \
24
and it is supposed to be used to monitor actual memory usage in a cross platform fashion.',
25
        'unit': 'bytes',
26
        'min_symbol': 'K',
27
    },
28
    'percent': {
29
        'description': 'The percentage usage calculated as (total - available) / total * 100.',
30
        'unit': 'percent',
31
    },
32
    'used': {
33
        'description': 'Memory used, calculated differently depending on the platform and \
34
designed for informational purposes only.',
35
        'unit': 'bytes',
36
        'min_symbol': 'K',
37
    },
38
    'free': {
39
        'description': 'Memory not being used at all (zeroed) that is readily available; \
40
note that this doesn\'t reflect the actual memory available (use \'available\' instead).',
41
        'unit': 'bytes',
42
        'min_symbol': 'K',
43
    },
44
    'active': {
45
        'description': '*(UNIX)*: memory currently in use or very recently used, and so it is in RAM.',
46
        'unit': 'bytes',
47
        'min_symbol': 'K',
48
    },
49
    'inactive': {
50
        'description': '*(UNIX)*: memory that is marked as not used.',
51
        'unit': 'bytes',
52
        'min_symbol': 'K',
53
        'short_name': 'inacti',
54
    },
55
    'buffers': {
56
        'description': '*(Linux, BSD)*: cache for things like file system metadata.',
57
        'unit': 'bytes',
58
        'min_symbol': 'K',
59
        'short_name': 'buffer',
60
    },
61
    'cached': {'description': '*(Linux, BSD)*: cache for various things.', 'unit': 'bytes', 'min_symbol': 'K'},
62
    'wired': {
63
        'description': '*(BSD, macOS)*: memory that is marked to always stay in RAM. It is never moved to disk.',
64
        'unit': 'bytes',
65
        'min_symbol': 'K',
66
    },
67
    'shared': {
68
        'description': '*(BSD)*: memory that may be simultaneously accessed by multiple processes.',
69
        'unit': 'bytes',
70
        'min_symbol': 'K',
71
    },
72
}
73
74
# SNMP OID
75
# Total RAM in machine: .1.3.6.1.4.1.2021.4.5.0
76
# Total RAM used: .1.3.6.1.4.1.2021.4.6.0
77
# Total RAM Free: .1.3.6.1.4.1.2021.4.11.0
78
# Total RAM Shared: .1.3.6.1.4.1.2021.4.13.0
79
# Total RAM Buffered: .1.3.6.1.4.1.2021.4.14.0
80
# Total Cached Memory: .1.3.6.1.4.1.2021.4.15.0
81
# Note: For Windows, stats are in the FS table
82
snmp_oid = {
83
    'default': {
84
        'total': '1.3.6.1.4.1.2021.4.5.0',
85
        'free': '1.3.6.1.4.1.2021.4.11.0',
86
        'shared': '1.3.6.1.4.1.2021.4.13.0',
87
        'buffers': '1.3.6.1.4.1.2021.4.14.0',
88
        'cached': '1.3.6.1.4.1.2021.4.15.0',
89
    },
90
    'windows': {
91
        'mnt_point': '1.3.6.1.2.1.25.2.3.1.3',
92
        'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4',
93
        'size': '1.3.6.1.2.1.25.2.3.1.5',
94
        'used': '1.3.6.1.2.1.25.2.3.1.6',
95
    },
96
    'esxi': {
97
        'mnt_point': '1.3.6.1.2.1.25.2.3.1.3',
98
        'alloc_unit': '1.3.6.1.2.1.25.2.3.1.4',
99
        'size': '1.3.6.1.2.1.25.2.3.1.5',
100
        'used': '1.3.6.1.2.1.25.2.3.1.6',
101
    },
102
}
103
104
# Define the history items list
105
# All items in this list will be historised if the --enable-history tag is set
106
items_history_list = [{'name': 'percent', 'description': 'RAM memory usage', 'y_unit': '%'}]
107
108
109
class Plugin(GlancesPlugin):
110
    """Glances' memory plugin.
111
112
    stats is a dict
113
    """
114
115
    def __init__(self, args=None, config=None):
116
        """Init the plugin."""
117
        super(Plugin, self).__init__(
118
            args=args, config=config, items_history_list=items_history_list, fields_description=fields_description
119
        )
120
121
        # We want to display the stat in the curse interface
122
        self.display_curse = True
123
124
    @GlancesPlugin._check_decorator
125
    @GlancesPlugin._log_result_decorator
126
    def update(self):
127
        """Update RAM memory stats using the input method."""
128
        # Init new stats
129
        stats = self.get_init_value()
130
131
        if self.input_method == 'local':
132
            # Update stats using the standard system lib
133
            # Grab MEM using the psutil virtual_memory method
134
            vm_stats = psutil.virtual_memory()
135
136
            # Get all the memory stats (copy/paste of the psutil documentation)
137
            # total: total physical memory available.
138
            # available: the actual amount of available memory that can be given instantly
139
            # to processes that request more memory in bytes; this is calculated by summing
140
            # different memory values depending on the platform (e.g. free + buffers + cached on Linux)
141
            # and it is supposed to be used to monitor actual memory usage in a cross platform fashion.
142
            # percent: the percentage usage calculated as (total - available) / total * 100.
143
            # used: memory used, calculated differently depending on the platform and designed for informational
144
            # purposes only.
145
            # free: memory not being used at all (zeroed) that is readily available; note that this doesn't
146
            # reflect the actual memory available (use ‘available’ instead).
147
            # Platform-specific fields:
148
            # active: (UNIX): memory currently in use or very recently used, and so it is in RAM.
149
            # inactive: (UNIX): memory that is marked as not used.
150
            # buffers: (Linux, BSD): cache for things like file system metadata.
151
            # cached: (Linux, BSD): cache for various things.
152
            # wired: (BSD, macOS): memory that is marked to always stay in RAM. It is never moved to disk.
153
            # shared: (BSD): memory that may be simultaneously accessed by multiple processes.
154
            self.reset()
155
            for mem in [
156
                'total',
157
                'available',
158
                'percent',
159
                'used',
160
                'free',
161
                'active',
162
                'inactive',
163
                'buffers',
164
                'cached',
165
                'wired',
166
                'shared',
167
            ]:
168
                if hasattr(vm_stats, mem):
169
                    stats[mem] = getattr(vm_stats, mem)
170
171
            # Use the 'free'/htop calculation
172
            # free=available+buffer+cached
173
            stats['free'] = stats['available']
174
            if hasattr(stats, 'buffers'):
175
                stats['free'] += stats['buffers']
176
            if hasattr(stats, 'cached'):
177
                stats['free'] += stats['cached']
178
            # used=total-free
179
            stats['used'] = stats['total'] - stats['free']
180
        elif self.input_method == 'snmp':
181
            # Update stats using SNMP
182
            if self.short_system_name in ('windows', 'esxi'):
183
                # Mem stats for Windows|Vmware Esxi are stored in the FS table
184
                try:
185
                    fs_stat = self.get_stats_snmp(snmp_oid=snmp_oid[self.short_system_name], bulk=True)
186
                except KeyError:
187
                    self.reset()
188
                else:
189
                    for fs in fs_stat:
190
                        # The Physical Memory (Windows) or Real Memory (VMware)
191
                        # gives statistics on RAM usage and availability.
192
                        if fs in ('Physical Memory', 'Real Memory'):
193
                            stats['total'] = int(fs_stat[fs]['size']) * int(fs_stat[fs]['alloc_unit'])
194
                            stats['used'] = int(fs_stat[fs]['used']) * int(fs_stat[fs]['alloc_unit'])
195
                            stats['percent'] = float(stats['used'] * 100 / stats['total'])
196
                            stats['free'] = stats['total'] - stats['used']
197
                            break
198
            else:
199
                # Default behavior for others OS
200
                stats = self.get_stats_snmp(snmp_oid=snmp_oid['default'])
201
202
                if stats['total'] == '':
203
                    self.reset()
204
                    return self.stats
205
206
                for key in iterkeys(stats):
207
                    if stats[key] != '':
208
                        stats[key] = float(stats[key]) * 1024
209
210
                # Use the 'free'/htop calculation
211
                stats['free'] = stats['free'] - stats['total'] + (stats['buffers'] + stats['cached'])
212
213
                # used=total-free
214
                stats['used'] = stats['total'] - stats['free']
215
216
                # percent: the percentage usage calculated as (total - available) / total * 100.
217
                stats['percent'] = float((stats['total'] - stats['free']) / stats['total'] * 100)
218
219
        # Update the stats
220
        self.stats = stats
221
222
        return self.stats
223
224
    def update_views(self):
225
        """Update stats views."""
226
        # Call the father's method
227
        super(Plugin, self).update_views()
228
229
        # Add specifics information
230
        # Alert and log
231
        self.views['percent']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats['total'])
232
        # Optional
233
        for key in ['active', 'inactive', 'buffers', 'cached']:
234
            if key in self.stats:
235
                self.views[key]['optional'] = True
236
237
    def msg_curse(self, args=None, max_width=None):
238
        """Return the dict to display in the curse interface."""
239
        # Init the return message
240
        ret = []
241
242
        # Only process if stats exist and plugin not disabled
243
        if not self.stats or self.is_disabled():
244
            return ret
245
246
        # First line
247
        # total% + active
248
        msg = '{}'.format('MEM')
249
        ret.append(self.curse_add_line(msg, "TITLE"))
250
        msg = ' {:2}'.format(self.trend_msg(self.get_trend('percent')))
251
        ret.append(self.curse_add_line(msg))
252
        # Percent memory usage
253
        msg = '{:>7.1%}'.format(self.stats['percent'] / 100)
254
        ret.append(self.curse_add_line(msg, self.get_views(key='percent', option='decoration')))
255
        # Active memory usage
256
        ret.extend(self.curse_add_stat('active', width=16, header='  '))
257
258
        # Second line
259
        # total + inactive
260
        ret.append(self.curse_new_line())
261
        # Total memory usage
262
        ret.extend(self.curse_add_stat('total', width=15))
263
        # Inactive memory usage
264
        ret.extend(self.curse_add_stat('inactive', width=16, header='  '))
265
266
        # Third line
267
        # used + buffers
268
        ret.append(self.curse_new_line())
269
        # Used memory usage
270
        ret.extend(self.curse_add_stat('used', width=15))
271
        # Buffers memory usage
272
        ret.extend(self.curse_add_stat('buffers', width=16, header='  '))
273
274
        # Fourth line
275
        # free + cached
276
        ret.append(self.curse_new_line())
277
        # Free memory usage
278
        ret.extend(self.curse_add_stat('free', width=15))
279
        # Cached memory usage
280
        ret.extend(self.curse_add_stat('cached', width=16, header='  '))
281
282
        return ret
283