Test Failed
Push — master ( d0fde6...8e443d )
by Nicolas
03:51 queued 15s
created

glances.standalone   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 196
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 29
eloc 106
dl 0
loc 196
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A GlancesStandalone.display_modules_list() 0 4 1
A GlancesStandalone.serve_forever() 0 9 5
A GlancesStandalone.end() 0 16 3
A GlancesStandalone.__serve_once() 0 34 3
A GlancesStandalone.serve_n() 0 5 3
A GlancesStandalone.serve_issue() 0 8 1
A GlancesStandalone.quiet() 0 3 1
D GlancesStandalone.__init__() 0 74 12
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
"""Manage the Glances standalone session."""
11
12
import sys
13
import time
14
15
from glances.globals import WINDOWS
16
from glances.logger import logger
17
from glances.outputs.glances_stdout_json import GlancesStdoutJson
18
from glances.processes import glances_processes
19
from glances.stats import GlancesStats
20
from glances.outputs.glances_curses import GlancesCursesStandalone
21
from glances.outputs.glances_stdout import GlancesStdout
22
from glances.outputs.glances_stdout_json import GlancesStdoutJson
23
from glances.outputs.glances_stdout_csv import GlancesStdoutCsv
24
from glances.outputs.glances_stdout_issue import GlancesStdoutIssue
25
from glances.outputs.glances_stdout_apidoc import GlancesStdoutApiDoc
26
from glances.outdated import Outdated
27
from glances.timer import Counter
28
29
30
class GlancesStandalone(object):
31
32
    """This class creates and manages the Glances standalone session."""
33
34
    def __init__(self, config=None, args=None):
35
        self.config = config
36
        self.args = args
37
38
        # Quiet mode
39
        self._quiet = args.quiet
40
        self.refresh_time = args.time
41
42
        # Init stats
43
        start_duration = Counter()
44
        start_duration.reset()
45
        self.stats = GlancesStats(config=config, args=args)
46
        logger.debug("Plugins initialisation duration: {} seconds".format(start_duration.get()))
47
48
        # Modules (plugins and exporters) are loaded at this point
49
        # Glances can display the list if asked...
50
        if args.modules_list:
51
            self.display_modules_list()
52
            sys.exit(0)
53
54
        # If process extended stats is disabled by user
55
        if not args.enable_process_extended:
56
            logger.debug("Extended stats for top process are disabled")
57
            glances_processes.disable_extended()
58
        else:
59
            logger.debug("Extended stats for top process are enabled")
60
            glances_processes.enable_extended()
61
62
        # Manage optional process filter
63
        if args.process_filter is not None:
64
            glances_processes.process_filter = args.process_filter
65
66
        if (not WINDOWS) and args.no_kernel_threads:
67
            # Ignore kernel threads in process list
68
            glances_processes.disable_kernel_threads()
69
70
        # Initial system information update
71
        start_duration.reset()
72
        self.stats.update()
73
        logger.debug("First stats update duration: {} seconds".format(start_duration.get()))
74
75
        if self.quiet:
76
            logger.info("Quiet mode is ON, nothing will be displayed")
77
            # In quiet mode, nothing is displayed
78
            glances_processes.max_processes = 0
79
        elif args.stdout_issue:
80
            logger.info("Issue mode is ON")
81
            # Init screen
82
            self.screen = GlancesStdoutIssue(config=config, args=args)
83
        elif args.stdout_apidoc:
84
            logger.info("Fields descriptions mode is ON")
85
            # Init screen
86
            self.screen = GlancesStdoutApiDoc(config=config, args=args)
87
        elif args.stdout:
88
            logger.info("Stdout mode is ON, following stats will be displayed: {}".format(args.stdout))
89
            # Init screen
90
            self.screen = GlancesStdout(config=config, args=args)
91
        elif args.stdout_json:
92
            logger.info("Stdout JSON mode is ON, following stats will be displayed: {}".format(args.stdout_json))
93
            # Init screen
94
            self.screen = GlancesStdoutJson(config=config, args=args)
95
        elif args.stdout_csv:
96
            logger.info("Stdout CSV mode is ON, following stats will be displayed: {}".format(args.stdout_csv))
97
            # Init screen
98
            self.screen = GlancesStdoutCsv(config=config, args=args)
99
        else:
100
            # Default number of processes to displayed is set to 50
101
            glances_processes.max_processes = 50
102
103
            # Init screen
104
            self.screen = GlancesCursesStandalone(config=config, args=args)
105
106
        # Check the latest Glances version
107
        self.outdated = Outdated(config=config, args=args)
108
109
    @property
110
    def quiet(self):
111
        return self._quiet
112
113
    def display_modules_list(self):
114
        """Display modules list"""
115
        print("Plugins list: {}".format(', '.join(sorted(self.stats.getPluginsList(enable=False)))))
116
        print("Exporters list: {}".format(', '.join(sorted(self.stats.getExportsList(enable=False)))))
117
118
    def serve_issue(self):
119
        """Special mode for the --issue option
120
121
        Update is done in the screen.update function
122
        """
123
        ret = not self.screen.update(self.stats)
124
        self.end()
125
        return ret
126
127
    def __serve_once(self):
128
        """Main loop for the CLI.
129
130
        :return: True if we should continue (no exit key has been pressed)
131
        """
132
        # Update stats
133
        # Start a counter used to compute the time needed
134
        counter = Counter()
135
        self.stats.update()
136
        logger.debug('Stats updated duration: {} seconds'.format(counter.get()))
137
138
        # Export stats
139
        # Start a counter used to compute the time needed
140
        counter_export = Counter()
141
        self.stats.export(self.stats)
142
        logger.debug('Stats exported duration: {} seconds'.format(counter_export.get()))
143
144
        # Patch for issue1326 to avoid < 0 refresh
145
        adapted_refresh = self.refresh_time - counter.get()
146
        adapted_refresh = adapted_refresh if adapted_refresh > 0 else 0
147
148
        # Display stats
149
        # and wait refresh_time - counter
150
        if not self.quiet:
151
            # The update function return True if an exit key 'q' or 'ESC'
152
            # has been pressed.
153
            ret = not self.screen.update(self.stats, duration=adapted_refresh)
154
        else:
155
            # Nothing is displayed
156
            # Break should be done via a signal (CTRL-C)
157
            time.sleep(adapted_refresh)
158
            ret = True
159
160
        return ret
161
162
    def serve_forever(self):
163
        """Wrapper to the serve_forever function."""
164
        if self.args.stop_after:
165
            for _ in range(self.args.stop_after):
166
                if not self.__serve_once():
167
                    break
168
        else:
169
            while self.__serve_once():
170
                pass
171
        # self.end()
172
173
    def serve_n(self, n=1):
174
        """Serve n time."""
175
        for _ in range(n):
176
            if not self.__serve_once():
177
                break
178
        # self.end()
179
180
    def end(self):
181
        """End of the standalone CLI."""
182
        if not self.quiet:
183
            self.screen.end()
184
185
        # Exit from export modules
186
        self.stats.end()
187
188
        # Check Glances version versus PyPI one
189
        if self.outdated.is_outdated():
190
            print(
191
                "You are using Glances version {}, however version {} is available.".format(
192
                    self.outdated.installed_version(), self.outdated.latest_version()
193
                )
194
            )
195
            print("You should consider upgrading using: pip install --upgrade glances")
196