Test Failed
Push — develop ( 8c9822...0ae24b )
by Nicolas
02:37
created

glances.plugins.folders   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 170
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 87
dl 0
loc 170
rs 10
c 0
b 0
f 0
wmc 22

5 Methods

Rating   Name   Duplication   Size   Complexity  
A FoldersPlugin.__init__() 0 12 1
C FoldersPlugin.get_alert() 0 33 10
A FoldersPlugin.update() 0 25 3
A FoldersPlugin.get_key() 0 3 1
B FoldersPlugin.msg_curse() 0 38 7
1
#
2
# This file is part of Glances.
3
#
4
# SPDX-FileCopyrightText: 2022 Nicolas Hennion <[email protected]>
5
#
6
# SPDX-License-Identifier: LGPL-3.0-only
7
#
8
9
"""Folder plugin."""
10
11
from glances.events_list import glances_events
12
from glances.folder_list import FolderList as glancesFolderList
13
from glances.globals import nativestr
14
from glances.logger import logger
15
from glances.plugins.plugin.model import GlancesPluginModel
16
17
# Fields description
18
# description: human readable description
19
# short_name: shortname to use un UI
20
# unit: unit type
21
# rate: is it a rate ? If yes, // by time_since_update when displayed,
22
# min_symbol: Auto unit should be used if value > than 1 'X' (K, M, G)...
23
fields_description = {
24
    'path': {'description': 'Absolute path.'},
25
    'size': {
26
        'description': 'Folder size in bytes.',
27
        'unit': 'byte',
28
    },
29
    'refresh': {
30
        'description': 'Refresh interval in seconds.',
31
        'unit': 'second',
32
    },
33
    'errno': {
34
        'description': 'Return code when retrieving folder size (0 is no error).',
35
        'unit': 'number',
36
    },
37
    'careful': {
38
        'description': 'Careful threshold in MB.',
39
        'unit': 'megabyte',
40
    },
41
    'warning': {
42
        'description': 'Warning threshold in MB.',
43
        'unit': 'megabyte',
44
    },
45
    'critical': {
46
        'description': 'Critical threshold in MB.',
47
        'unit': 'megabyte',
48
    },
49
}
50
51
52
class FoldersPlugin(GlancesPluginModel):
53
    """Glances folder plugin."""
54
55
    def __init__(self, args=None, config=None):
56
        """Init the plugin."""
57
        super().__init__(args=args, config=config, stats_init_value=[], fields_description=fields_description)
58
59
        self.args = args
60
        self.config = config
61
62
        # We want to display the stat in the curse interface
63
        self.display_curse = True
64
65
        # Init stats
66
        self.glances_folders = glancesFolderList(config)
67
68
    def get_key(self):
69
        """Return the key of the list."""
70
        return 'path'
71
72
    @GlancesPluginModel._check_decorator
73
    @GlancesPluginModel._log_result_decorator
74
    def update(self):
75
        """Update the folders list."""
76
        # Init new stats
77
        stats = self.get_init_value()
78
79
        if self.input_method == 'local':
80
            # Folder list only available in a full Glances environment
81
            # Check if the glances_folder instance is init
82
            if self.glances_folders is None:
83
                return self.stats
84
85
            # Update the folders list (result of command)
86
            self.glances_folders.update(key=self.get_key())
87
88
            # Put it on the stats var
89
            stats = self.glances_folders.get()
90
        else:
91
            pass
92
93
        # Update the stats
94
        self.stats = stats
95
96
        return self.stats
97
98
    def get_alert(self, stat, header=None, action_key=None, log=False):
99
        """Manage limits of the folder list."""
100
        if stat['errno'] != 0:
101
            ret = 'ERROR'
102
        else:
103
            ret = 'OK'
104
105
            if stat['critical'] is not None and stat['size'] > int(stat['critical']) * 1000000:
106
                ret = 'CRITICAL'
107
            elif stat['warning'] is not None and stat['size'] > int(stat['warning']) * 1000000:
108
                ret = 'WARNING'
109
            elif stat['careful'] is not None and stat['size'] > int(stat['careful']) * 1000000:
110
                ret = 'CAREFUL'
111
112
        # Get stat name
113
        stat_name = self.get_stat_name(header=header, action_key=action_key)
114
115
        # Manage log
116
        log_str = ""
117
        if self.get_limit_log(stat_name=stat_name, default_action=log) and ret != 'DEFAULT':
118
            # Add _LOG to the return string
119
            # So stats will be highlighted with a specific color
120
            log_str = "_LOG"
121
            # Add the log to the events list
122
            glances_events.add(ret, stat_name.upper(), stat['size'])
123
124
        # Manage threshold
125
        self.manage_threshold(stat_name, ret)
126
127
        # Manage action
128
        self.manage_action(stat_name, ret.lower(), header, action_key)
129
130
        return ret + log_str
131
132
    def msg_curse(self, args=None, max_width=None):
133
        """Return the dict to display in the curse interface."""
134
        # Init the return message
135
        ret = []
136
137
        # Only process if stats exist and display plugin enable...
138
        if not self.stats or self.is_disabled():
139
            return ret
140
141
        # Max size for the interface name
142
        if max_width:
143
            name_max_width = max_width - 7
144
        else:
145
            # No max_width defined, return an empty curse message
146
            logger.debug(f"No max_width defined for the {self.plugin_name} plugin, it will not be displayed.")
147
            return ret
148
149
        # Header
150
        msg = '{:{width}}'.format('FOLDERS', width=name_max_width)
151
        ret.append(self.curse_add_line(msg, "TITLE"))
152
153
        # Data
154
        for i in self.stats:
155
            ret.append(self.curse_new_line())
156
            if len(i['path']) > name_max_width:
157
                # Cut path if it is too long
158
                path = '_' + i['path'][-name_max_width + 1 :]
159
            else:
160
                path = i['path']
161
            msg = '{:{width}}'.format(nativestr(path), width=name_max_width)
162
            ret.append(self.curse_add_line(msg))
163
            if i['errno'] != 0:
164
                msg = '?{:>8}'.format(self.auto_unit(i['size']))
165
            else:
166
                msg = '{:>9}'.format(self.auto_unit(i['size']))
167
            ret.append(self.curse_add_line(msg, self.get_alert(i, header='folder', action_key=i['indice'])))
168
169
        return ret
170