Test Failed
Push — master ( 05aaee...10b5c2 )
by Nicolas
04:12 queued 14s
created

GlancesStdoutIssue.print_issue()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nop 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# SPDX-FileCopyrightText: 2023 Nicolas Hennion <[email protected]>
6
#
7
# SPDX-License-Identifier: LGPL-3.0-only
8
#
9
10
"""Issue interface class."""
11
12
import os
13
import sys
14
import platform
15
import time
16
import pprint
17
18
from glances.timer import Counter
19
from glances import __version__, psutil_version
20
21
import psutil
22
import glances
23
24
TERMINAL_WIDTH = 79
25
26
27
class colors:
28
    RED = '\033[91m'
29
    GREEN = '\033[92m'
30
    ORANGE = '\033[93m'
31
    BLUE = '\033[94m'
32
    NO = '\033[0m'
33
34
    def disable(self):
35
        self.RED = ''
36
        self.GREEN = ''
37
        self.BLUE = ''
38
        self.ORANGE = ''
39
        self.NO = ''
40
41
42
class GlancesStdoutIssue(object):
43
44
    """This class manages the Issue display."""
45
46
    def __init__(self, config=None, args=None):
47
        # Init
48
        self.config = config
49
        self.args = args
50
51
    def end(self):
52
        pass
53
54
    def print_version(self):
55
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
56
        sys.stdout.write(
57
            'Glances {} ({})\n'.format(colors.BLUE + __version__ + colors.NO, os.path.realpath(glances.__file__))
58
        )
59
        sys.stdout.write('Python {} ({})\n'.format(colors.BLUE + platform.python_version() + colors.NO, sys.executable))
60
        sys.stdout.write(
61
            'PsUtil {} ({})\n'.format(colors.BLUE + psutil_version + colors.NO, os.path.realpath(psutil.__file__))
62
        )
63
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
64
        sys.stdout.flush()
65
66
    def print_issue(self, plugin, result, message):
67
        sys.stdout.write('{}{}{}'.format(colors.BLUE + plugin, result, message))
68
        sys.stdout.write(colors.NO + '\n')
69
        sys.stdout.flush()
70
71
    def update(self, stats, duration=3):
72
        """Display issue"""
73
        self.print_version()
74
75
        for plugin in sorted(stats._plugins):
76
            if stats._plugins[plugin].is_disabled():
77
                continue
78
            try:
79
                # Update the stats
80
                stats._plugins[plugin].update()
81
            except Exception:
82
                pass
83
84
        time.sleep(2)
85
86
        counter_total = Counter()
87
        for plugin in sorted(stats._plugins):
88
            if stats._plugins[plugin].is_disabled():
89
                # If current plugin is disable
90
                # then continue to next plugin
91
                result = colors.NO + '[NA]'.rjust(18 - len(plugin))
92
                message = colors.NO
93
                self.print_issue(plugin, result, message)
94
                continue
95
            # Start the counter
96
            counter = Counter()
97
            counter.reset()
98
            stat = None
99
            stat_error = None
100
            try:
101
                # Update the stats
102
                stats._plugins[plugin].update()
103
                # Get the stats
104
                stat = stats.get_plugin(plugin).get_export()
105
                # Hide private information
106
                if plugin == 'ip':
107
                    for key in stat.keys():
108
                        stat[key] = '***'
109
            except Exception as e:
110
                stat_error = e
111
            if stat_error is None:
112
                result = (colors.GREEN + '[OK]   ' + colors.BLUE + ' {:.5f}s '.format(counter.get())).rjust(
113
                    41 - len(plugin)
114
                )
115
                if isinstance(stat, list) and len(stat) > 0 and 'key' in stat[0]:
116
                    key = 'key={} '.format(stat[0]['key'])
117
                    stat_output = pprint.pformat([stat[0]], compact=True, width=120, depth=3)
118
                    message = colors.ORANGE + key + colors.NO + '\n' + stat_output[0:-1] + ', ...' + stat_output[-1]
119
                else:
120
                    message = '\n' + colors.NO + pprint.pformat(stat, compact=True, width=120, depth=2)
121
            else:
122
                result = (colors.RED + '[ERROR]' + colors.BLUE + ' {:.5f}s '.format(counter.get())).rjust(
123
                    41 - len(plugin)
124
                )
125
                message = colors.NO + str(stat_error)[0 : TERMINAL_WIDTH - 41]
126
127
            # Display the result
128
            self.print_issue(plugin, result, message)
129
130
        # Display total time need to update all plugins
131
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
132
        print("Total time to update all stats: {}{:.5f}s{}".format(colors.BLUE, counter_total.get(), colors.NO))
133
        sys.stdout.write('=' * TERMINAL_WIDTH + '\n')
134
135
        # Return True to exit directly (no refresh)
136
        return True
137