Issues (49)

glances/outputs/glances_curses.py (1 issue)

1
#
2
# This file is part of Glances.
3
#
4
# SPDX-FileCopyrightText: 2024 Nicolas Hennion <[email protected]>
5
#
6
# SPDX-License-Identifier: LGPL-3.0-only
7
#
8
9
"""Curses interface class."""
10
11
import getpass
12
import sys
13
14
from glances.events_list import glances_events
15
from glances.globals import MACOS, WINDOWS, disable, enable, itervalues, nativestr, u
16
from glances.logger import logger
17
from glances.outputs.glances_unicode import unicode_message
18
from glances.processes import glances_processes, sort_processes_key_list
19
from glances.timer import Timer
20
21
# Import curses library for "normal" operating system
22
try:
23
    import curses
24
    import curses.panel
25
    from curses.textpad import Textbox
26
except ImportError:
27
    logger.critical("Curses module not found. Glances cannot start in standalone mode.")
28
    if WINDOWS:
29
        logger.critical("For Windows you can try installing windows-curses with pip install.")
30
    sys.exit(1)
31
32
33
class _GlancesCurses:
34
    """This class manages the curses display (and key pressed).
35
36
    Note: It is a private class, use GlancesCursesClient or GlancesCursesBrowser.
37
    """
38
39
    _hotkeys = {
40
        '\n': {'handler': '_handle_enter'},
41
        '0': {'switch': 'disable_irix'},
42
        '1': {'switch': 'percpu'},
43
        '2': {'switch': 'disable_left_sidebar'},
44
        '3': {'switch': 'disable_quicklook'},
45
        '4': {'handler': '_handle_quicklook'},
46
        '5': {'handler': '_handle_top_menu'},
47
        '6': {'switch': 'meangpu'},
48
        '/': {'switch': 'process_short_name'},
49
        'a': {'sort_key': 'auto'},
50
        'A': {'switch': 'disable_amps'},
51
        'b': {'switch': 'byte'},
52
        'B': {'switch': 'diskio_iops'},
53
        'c': {'sort_key': 'cpu_percent'},
54
        'C': {'switch': 'disable_cloud'},
55
        'd': {'switch': 'disable_diskio'},
56
        'D': {'switch': 'disable_containers'},
57
        # 'e' > Enable/Disable process extended
58
        'E': {'handler': '_handle_erase_filter'},
59
        'f': {'handler': '_handle_fs_stats'},
60
        'F': {'switch': 'fs_free_space'},
61
        'g': {'switch': 'generate_graph'},
62
        'G': {'switch': 'disable_gpu'},
63
        'h': {'switch': 'help_tag'},
64
        'i': {'sort_key': 'io_counters'},
65
        'I': {'switch': 'disable_ip'},
66
        'j': {'switch': 'programs'},
67
        # 'k' > Kill selected process
68
        'K': {'switch': 'disable_connections'},
69
        'l': {'switch': 'disable_alert'},
70
        'm': {'sort_key': 'memory_percent'},
71
        'M': {'switch': 'reset_minmax_tag'},
72
        'n': {'switch': 'disable_network'},
73
        'N': {'switch': 'disable_now'},
74
        'p': {'sort_key': 'name'},
75
        'P': {'switch': 'disable_ports'},
76
        # 'q' or ESCAPE > Quit
77
        'Q': {'switch': 'enable_irq'},
78
        'r': {'switch': 'disable_smart'},
79
        'R': {'switch': 'disable_raid'},
80
        's': {'switch': 'disable_sensors'},
81
        'S': {'switch': 'sparkline'},
82
        't': {'sort_key': 'cpu_times'},
83
        'T': {'switch': 'network_sum'},
84
        'u': {'sort_key': 'username'},
85
        'U': {'switch': 'network_cumul'},
86
        'w': {'handler': '_handle_clean_logs'},
87
        'W': {'switch': 'disable_wifi'},
88
        'x': {'handler': '_handle_clean_critical_logs'},
89
        'z': {'handler': '_handle_disable_process'},
90
        '+': {'handler': '_handle_increase_nice'},
91
        '-': {'handler': '_handle_decrease_nice'},
92
        # "<" (left arrow) navigation through process sort
93
        # ">" (right arrow) navigation through process sort
94
        # 'UP' > Up in the server list
95
        # 'DOWN' > Down in the server list
96
    }
97
98
    _sort_loop = sort_processes_key_list
99
100
    # Define top menu
101
    _top = ['quicklook', 'cpu', 'percpu', 'gpu', 'mem', 'memswap', 'load']
102
    _quicklook_max_width = 58
103
104
    # Define left sidebar
105
    # This default list is also defined in the glances/outputs/static/js/uiconfig.json
106
    # file for the web interface
107
    # Both can be overwritten by the configuration file ([outputs] left_menu option)
108
    _left_sidebar = [
109
        'network',
110
        'ports',
111
        'wifi',
112
        'connections',
113
        'diskio',
114
        'fs',
115
        'irq',
116
        'folders',
117
        'raid',
118
        'smart',
119
        'sensors',
120
        'now',
121
    ]
122
    _left_sidebar_min_width = 23
123
    _left_sidebar_max_width = 34
124
125
    # Define right sidebar
126
    _right_sidebar = ['containers', 'processcount', 'amps', 'processlist', 'alert']
127
128
    def __init__(self, config=None, args=None):
129
        # Init
130
        self.config = config
131
        self.args = args
132
133
        # Init windows positions
134
        self.term_w = 80
135
        self.term_h = 24
136
137
        # Space between stats
138
        self.space_between_column = 3
139
        self.space_between_line = 2
140
141
        # Init the curses screen
142
        try:
143
            self.screen = curses.initscr()
144
            if not self.screen:
145
                logger.critical("Cannot init the curses library.\n")
146
                sys.exit(1)
147
            else:
148
                logger.debug(f"Curses library initialized with term: {curses.longname()}")
149
        except Exception as e:
150
            if args.export:
151
                logger.info("Cannot init the curses library, quiet mode on and export.")
152
                args.quiet = True
153
                return
154
155
            logger.critical(f"Cannot init the curses library ({e})")
156
            sys.exit(1)
157
158
        # Load configuration file
159
        self.load_config(config)
160
161
        # Init cursor
162
        self._init_cursor()
163
164
        # Init the colors
165
        self._init_colors()
166
167
        # Init main window
168
        self.term_window = self.screen.subwin(0, 0)
169
170
        # Init edit filter tag
171
        self.edit_filter = False
172
173
        # Init nice increase/decrease tag
174
        self.increase_nice_process = False
175
        self.decrease_nice_process = False
176
177
        # Init kill process tag
178
        self.kill_process = False
179
180
        # Init the process min/max reset
181
        self.args.reset_minmax_tag = False
182
183
        # Init cursor
184
        self.args.cursor_position = 0
185
186
        # Catch key pressed with non blocking mode
187
        self.term_window.keypad(1)
188
        self.term_window.nodelay(1)
189
        self.pressedkey = -1
190
191
        # History tag
192
        self._init_history()
193
194
    def load_config(self, config):
195
        """Load the outputs section of the configuration file."""
196
        if config is not None and config.has_section('outputs'):
197
            logger.debug('Read the outputs section in the configuration file')
198
            # Separator ?
199
            self.args.enable_separator = config.get_bool_value('outputs', 'separator', default=True)
200
            # Set the left sidebar list
201
            self._left_sidebar = config.get_list_value('outputs', 'left_menu', default=self._left_sidebar)
202
203
    def _init_history(self):
204
        """Init the history option."""
205
206
        self.reset_history_tag = False
207
208
    def _init_cursor(self):
209
        """Init cursors."""
210
211
        if hasattr(curses, 'noecho'):
212
            curses.noecho()
213
        if hasattr(curses, 'cbreak'):
214
            curses.cbreak()
215
        self.set_cursor(0)
216
217
    def _init_colors(self):
218
        """Init the Curses color layout."""
219
220
        # Set curses options
221
        try:
222
            if hasattr(curses, 'start_color'):
223
                curses.start_color()
224
                logger.debug(f'Curses interface compatible with {curses.COLORS} colors')
225
            if hasattr(curses, 'use_default_colors'):
226
                curses.use_default_colors()
227
        except Exception as e:
228
            logger.warning(f'Error initializing terminal color ({e})')
229
230
        # Init colors
231
        if self.args.disable_bold:
232
            A_BOLD = 0
233
            self.args.disable_bg = True
234
        else:
235
            A_BOLD = curses.A_BOLD
236
237
        self.title_color = A_BOLD
238
        self.title_underline_color = A_BOLD | curses.A_UNDERLINE
239
        self.help_color = A_BOLD
240
241
        if curses.has_colors():
242
            # The screen is compatible with a colored design
243
            # ex: export TERM=xterm-256color
244
            #     export TERM=xterm-color
245
246
            curses.init_pair(1, -1, -1)
247
            if self.args.disable_bg:
248
                curses.init_pair(2, curses.COLOR_RED, -1)
249
                curses.init_pair(3, curses.COLOR_GREEN, -1)
250
                curses.init_pair(5, curses.COLOR_MAGENTA, -1)
251
            else:
252
                curses.init_pair(2, -1, curses.COLOR_RED)
253
                curses.init_pair(3, -1, curses.COLOR_GREEN)
254
                curses.init_pair(5, -1, curses.COLOR_MAGENTA)
255
            curses.init_pair(4, curses.COLOR_BLUE, -1)
256
            curses.init_pair(6, curses.COLOR_RED, -1)
257
            curses.init_pair(7, curses.COLOR_GREEN, -1)
258
            curses.init_pair(8, curses.COLOR_MAGENTA, -1)
259
260
            # Colors text styles
261
            self.no_color = curses.color_pair(1)
262
            self.default_color = curses.color_pair(3) | A_BOLD
263
            self.nice_color = curses.color_pair(8)
264
            self.cpu_time_color = curses.color_pair(8)
265
            self.ifCAREFUL_color = curses.color_pair(4) | A_BOLD
266
            self.ifWARNING_color = curses.color_pair(5) | A_BOLD
267
            self.ifCRITICAL_color = curses.color_pair(2) | A_BOLD
268
            self.default_color2 = curses.color_pair(7)
269
            self.ifCAREFUL_color2 = curses.color_pair(4)
270
            self.ifWARNING_color2 = curses.color_pair(8) | A_BOLD
271
            self.ifCRITICAL_color2 = curses.color_pair(6) | A_BOLD
272
            self.ifINFO_color = curses.color_pair(4)
273
            self.filter_color = A_BOLD
274
            self.selected_color = A_BOLD
275
            self.separator = curses.color_pair(1)
276
277
            if curses.COLORS > 8:
278
                # ex: export TERM=xterm-256color
279
                colors_list = [curses.COLOR_CYAN, curses.COLOR_YELLOW]
280
                for i in range(0, 3):
281
                    try:
282
                        curses.init_pair(i + 9, colors_list[i], -1)
283
                    except Exception:
284
                        curses.init_pair(i + 9, -1, -1)
285
                self.filter_color = curses.color_pair(9) | A_BOLD
286
                self.selected_color = curses.color_pair(10) | A_BOLD
287
                # Define separator line style
288
                try:
289
                    curses.init_color(11, 500, 500, 500)
290
                    curses.init_pair(11, curses.COLOR_BLACK, -1)
291
                    self.separator = curses.color_pair(11)
292
                except Exception:
293
                    # Catch exception in TMUX
294
                    pass
295
        else:
296
            # The screen is NOT compatible with a colored design
297
            # switch to B&W text styles
298
            # ex: export TERM=xterm-mono
299
            self.no_color = -1
300
            self.default_color = -1
301
            self.nice_color = A_BOLD
302
            self.cpu_time_color = A_BOLD
303
            self.ifCAREFUL_color = A_BOLD
304
            self.ifWARNING_color = curses.A_UNDERLINE
305
            self.ifCRITICAL_color = curses.A_REVERSE
306
            self.default_color2 = -1
307
            self.ifCAREFUL_color2 = A_BOLD
308
            self.ifWARNING_color2 = curses.A_UNDERLINE
309
            self.ifCRITICAL_color2 = curses.A_REVERSE
310
            self.ifINFO_color = A_BOLD
311
            self.filter_color = A_BOLD
312
            self.selected_color = A_BOLD
313
            self.separator = -1
314
315
        # Define the colors list (hash table) for stats
316
        self.colors_list = {
317
            'DEFAULT': self.no_color,
318
            'UNDERLINE': curses.A_UNDERLINE,
319
            'BOLD': A_BOLD,
320
            'SORT': curses.A_UNDERLINE | A_BOLD,
321
            'OK': self.default_color2,
322
            'MAX': self.default_color2 | A_BOLD,
323
            'FILTER': self.filter_color,
324
            'TITLE': self.title_color,
325
            'PROCESS': self.default_color2,
326
            'PROCESS_SELECTED': self.default_color2 | curses.A_UNDERLINE,
327
            'STATUS': self.default_color2,
328
            'NICE': self.nice_color,
329
            'CPU_TIME': self.cpu_time_color,
330
            'CAREFUL': self.ifCAREFUL_color2,
331
            'WARNING': self.ifWARNING_color2,
332
            'CRITICAL': self.ifCRITICAL_color2,
333
            'OK_LOG': self.default_color,
334
            'CAREFUL_LOG': self.ifCAREFUL_color,
335
            'WARNING_LOG': self.ifWARNING_color,
336
            'CRITICAL_LOG': self.ifCRITICAL_color,
337
            'PASSWORD': curses.A_PROTECT,
338
            'SELECTED': self.selected_color,
339
            'INFO': self.ifINFO_color,
340
            'ERROR': self.selected_color,
341
            'SEPARATOR': self.separator,
342
        }
343
344
    def set_cursor(self, value):
345
        """Configure the curse cursor appearance.
346
347
        0: invisible
348
        1: visible
349
        2: very visible
350
        """
351
        if hasattr(curses, 'curs_set'):
352
            try:
353
                curses.curs_set(value)
354
            except Exception:
355
                pass
356
357
    def get_key(self, window):
358
        # TODO: Check issue #163
359
        return window.getch()
360
361
    def __catch_key(self, return_to_browser=False):
362
        # Catch the pressed key
363
        self.pressedkey = self.get_key(self.term_window)
364
        if self.pressedkey == -1:
365
            return -1
366
367
        # Actions (available in the global hotkey dict)...
368
        logger.debug(f"Keypressed (code: {self.pressedkey})")
369
        for hotkey in self._hotkeys:
370
            if self.pressedkey == ord(hotkey) and 'switch' in self._hotkeys[hotkey]:
371
                self._handle_switch(hotkey)
372
            elif self.pressedkey == ord(hotkey) and 'sort_key' in self._hotkeys[hotkey]:
373
                self._handle_sort_key(hotkey)
374
            if self.pressedkey == ord(hotkey) and 'handler' in self._hotkeys[hotkey]:
375
                action = getattr(self, self._hotkeys[hotkey]['handler'])
376
                action()
377
378
        # Other actions with key > 255 (ord will not work) and/or additional test...
379
        if self.pressedkey == ord('e') and not self.args.programs:
380
            self._handle_process_extended()
381
        elif self.pressedkey == ord('k') and not self.args.disable_cursor:
382
            self._handle_kill_process()
383
        elif self.pressedkey == curses.KEY_LEFT:
384
            self._handle_sort_left()
385
        elif self.pressedkey == curses.KEY_RIGHT:
386
            self._handle_sort_right()
387
        elif self.pressedkey == curses.KEY_UP or self.pressedkey == 65 and not self.args.disable_cursor:
388
            self._handle_cursor_up()
389
        elif self.pressedkey == curses.KEY_DOWN or self.pressedkey == 66 and not self.args.disable_cursor:
390
            self._handle_cursor_down()
391
        elif self.pressedkey == ord('\x1b') or self.pressedkey == ord('q'):
392
            self._handle_quit(return_to_browser)
393
        elif self.pressedkey == curses.KEY_F5 or self.pressedkey == 18:
394
            self._handle_refresh()
395
396
        # Return the key code
397
        return self.pressedkey
398
399
    def _handle_switch(self, hotkey):
400
        option = '_'.join(self._hotkeys[hotkey]['switch'].split('_')[1:])
401
        if self._hotkeys[hotkey]['switch'].startswith('disable_'):
402
            if getattr(self.args, self._hotkeys[hotkey]['switch']):
403
                enable(self.args, option)
404
            else:
405
                disable(self.args, option)
406
        elif self._hotkeys[hotkey]['switch'].startswith('enable_'):
407
            if getattr(self.args, self._hotkeys[hotkey]['switch']):
408
                disable(self.args, option)
409
            else:
410
                enable(self.args, option)
411
        else:
412
            setattr(
413
                self.args,
414
                self._hotkeys[hotkey]['switch'],
415
                not getattr(self.args, self._hotkeys[hotkey]['switch']),
416
            )
417
418
    def _handle_sort_key(self, hotkey):
419
        glances_processes.set_sort_key(self._hotkeys[hotkey]['sort_key'], self._hotkeys[hotkey]['sort_key'] == 'auto')
420
421
    def _handle_enter(self):
422
        self.edit_filter = not self.edit_filter
423
424
    def _handle_quicklook(self):
425
        self.args.full_quicklook = not self.args.full_quicklook
426
        if self.args.full_quicklook:
427
            self.enable_fullquicklook()
428
        else:
429
            self.disable_fullquicklook()
430
431
    def _handle_top_menu(self):
432
        self.args.disable_top = not self.args.disable_top
433
        if self.args.disable_top:
434
            self.disable_top()
435
        else:
436
            self.enable_top()
437
438
    def _handle_process_extended(self):
439
        self.args.enable_process_extended = not self.args.enable_process_extended
440
        if not self.args.enable_process_extended:
441
            glances_processes.disable_extended()
442
        else:
443
            glances_processes.enable_extended()
444
        self.args.disable_cursor = self.args.enable_process_extended and self.args.is_standalone
445
446
    def _handle_erase_filter(self):
447
        glances_processes.process_filter = None
448
449
    def _handle_fs_stats(self):
450
        self.args.disable_fs = not self.args.disable_fs
451
        self.args.disable_folders = not self.args.disable_folders
452
453
    def _handle_increase_nice(self):
454
        self.increase_nice_process = not self.increase_nice_process
455
456
    def _handle_decrease_nice(self):
457
        self.decrease_nice_process = not self.decrease_nice_process
458
459
    def _handle_kill_process(self):
460
        self.kill_process = not self.kill_process
461
462
    def _handle_clean_logs(self):
463
        glances_events.clean()
464
465
    def _handle_clean_critical_logs(self):
466
        glances_events.clean(critical=True)
467
468
    def _handle_disable_process(self):
469
        self.args.disable_process = not self.args.disable_process
470
        if self.args.disable_process:
471
            glances_processes.disable()
472
        else:
473
            glances_processes.enable()
474
475
    def _handle_sort_left(self):
476
        next_sort = (self.loop_position() - 1) % len(self._sort_loop)
477
        glances_processes.set_sort_key(self._sort_loop[next_sort], False)
478
479
    def _handle_sort_right(self):
480
        next_sort = (self.loop_position() + 1) % len(self._sort_loop)
481
        glances_processes.set_sort_key(self._sort_loop[next_sort], False)
482
483
    def _handle_cursor_up(self):
484
        if self.args.cursor_position > 0:
485
            self.args.cursor_position -= 1
486
487
    def _handle_cursor_down(self):
488
        if self.args.cursor_position < glances_processes.processes_count:
489
            self.args.cursor_position += 1
490
491
    def _handle_quit(self, return_to_browser):
492
        if return_to_browser:
493
            logger.info("Stop Glances client and return to the browser")
494
        else:
495
            logger.info(f"Stop Glances (keypressed: {self.pressedkey})")
496
497
    def _handle_refresh(self):
498
        pass
499
500
    def loop_position(self):
501
        """Return the current sort in the loop"""
502
        for i, v in enumerate(self._sort_loop):
503
            if v == glances_processes.sort_key:
504
                return i
505
        return 0
506
507
    def disable_top(self):
508
        """Disable the top panel"""
509
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap', 'load']:
510
            setattr(self.args, 'disable_' + p, True)
511
512
    def enable_top(self):
513
        """Enable the top panel"""
514
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap', 'load']:
515
            setattr(self.args, 'disable_' + p, False)
516
517
    def disable_fullquicklook(self):
518
        """Disable the full quicklook mode"""
519
        for p in ['quicklook', 'cpu', 'gpu', 'mem', 'memswap']:
520
            setattr(self.args, 'disable_' + p, False)
521
522
    def enable_fullquicklook(self):
523
        """Disable the full quicklook mode"""
524
        self.args.disable_quicklook = False
525
        for p in ['cpu', 'gpu', 'mem', 'memswap']:
526
            setattr(self.args, 'disable_' + p, True)
527
528
    def end(self):
529
        """Shutdown the curses window."""
530
        if hasattr(curses, 'echo'):
531
            curses.echo()
532
        if hasattr(curses, 'nocbreak'):
533
            curses.nocbreak()
534
        try:
535
            curses.curs_set(1)
536
        except Exception:
537
            pass
538
        try:
539
            curses.endwin()
540
        except Exception:
541
            pass
542
543
    def init_line_column(self):
544
        """Init the line and column position for the curses interface."""
545
        self.init_line()
546
        self.init_column()
547
548
    def init_line(self):
549
        """Init the line position for the curses interface."""
550
        self.line = 0
551
        self.next_line = 0
552
553
    def init_column(self):
554
        """Init the column position for the curses interface."""
555
        self.column = 0
556
        self.next_column = 0
557
558
    def new_line(self, separator=False):
559
        """New line in the curses interface."""
560
        self.line = self.next_line
561
562
    def new_column(self):
563
        """New column in the curses interface."""
564
        self.column = self.next_column
565
566
    def separator_line(self, color='SEPARATOR'):
567
        """Add a separator line in the curses interface."""
568
        if not self.args.enable_separator:
569
            return
570
        self.new_line()
571
        self.line -= 1
572
        line_width = self.term_window.getmaxyx()[1] - self.column
573
        self.term_window.addnstr(
574
            self.line,
575
            self.column,
576
            unicode_message('MEDIUM_LINE', self.args) * line_width,
577
            line_width,
578
            self.colors_list[color],
579
        )
580
581
    def __get_stat_display(self, stats, layer):
582
        """Return a dict of dict with all the stats display.
583
        # TODO: Drop extra parameter
584
585
        :param stats: Global stats dict
586
        :param layer: ~ cs_status
587
            "None": standalone or server mode
588
            "Connected": Client is connected to a Glances server
589
            "SNMP": Client is connected to a SNMP server
590
            "Disconnected": Client is disconnected from the server
591
592
        :returns: dict of dict
593
            * key: plugin name
594
            * value: dict returned by the get_stats_display Plugin method
595
        """
596
        ret = {}
597
598
        for p in stats.getPluginsList(enable=False):
599
            # Ignore Quicklook because it is compute later in __display_top
600
            if p == 'quicklook':
601
                continue
602
603
            # Compute the plugin max size for the left sidebar
604
            plugin_max_width = None
605
            if p in self._left_sidebar:
606
                plugin_max_width = min(
607
                    self._left_sidebar_max_width,
608
                    max(self._left_sidebar_min_width, self.term_window.getmaxyx()[1] - 105),
609
                )
610
611
            # Get the view
612
            ret[p] = stats.get_plugin(p).get_stats_display(args=self.args, max_width=plugin_max_width)
613
614
        return ret
615
616
    def display(self, stats, cs_status=None):
617
        """Display stats on the screen.
618
619
        :param stats: Stats database to display
620
        :param cs_status:
621
            "None": standalone or server mode
622
            "Connected": Client is connected to a Glances server
623
            "SNMP": Client is connected to a SNMP server
624
            "Disconnected": Client is disconnected from the server
625
626
        :return: True if the stats have been displayed else False if the help have been displayed
627
        """
628
        # Init the internal line/column for Glances Curses
629
        self.init_line_column()
630
631
        # Update the stats messages
632
        ###########################
633
634
        # Get all the plugins view
635
        self.args.cs_status = cs_status
636
        __stat_display = self.__get_stat_display(stats, layer=cs_status)
637
638
        # Display the stats on the curses interface
639
        ###########################################
640
641
        # Help screen (on top of the other stats)
642
        if self.args.help_tag:
643
            # Display the stats...
644
            self.display_plugin(stats.get_plugin('help').get_stats_display(args=self.args))
645
            # ... and exit
646
            return False
647
648
        # =======================================
649
        # Display first line (system+ip+uptime)
650
        # Optionally: Cloud is on the second line
651
        # =======================================
652
        self.__display_header(__stat_display)
653
        self.separator_line()
654
655
        # ==============================================================
656
        # Display second line (<SUMMARY>+CPU|PERCPU+<GPU>+LOAD+MEM+SWAP)
657
        # ==============================================================
658
        self.__display_top(__stat_display, stats)
659
        self.init_column()
660
        self.separator_line()
661
662
        # ==================================================================
663
        # Display left sidebar (NETWORK+PORTS+DISKIO+FS+SENSORS+Current time)
664
        # ==================================================================
665
        self.__display_left(__stat_display)
666
667
        # ====================================
668
        # Display right stats (process and co)
669
        # ====================================
670
        self.__display_right(__stat_display)
671
672
        # =====================
673
        # Others popup messages
674
        # =====================
675
676
        # Display edit filter popup
677
        # Only in standalone mode (cs_status is None)
678
        if self.edit_filter and cs_status is None:
679
            new_filter = self.display_popup(
680
                'Process filter pattern: \n\n'
681
                + 'Examples:\n'
682
                + '- .*python.*\n'
683
                + '- /usr/lib.*\n'
684
                + '- name:.*nautilus.*\n'
685
                + '- cmdline:.*glances.*\n'
686
                + '- username:nicolargo\n'
687
                + '- username:^root        ',
688
                popup_type='input',
689
                input_value=glances_processes.process_filter_input,
690
            )
691
            glances_processes.process_filter = new_filter
692
        elif self.edit_filter and cs_status is not None:
693
            self.display_popup('Process filter only available in standalone mode')
694
        self.edit_filter = False
695
696
        # Manage increase/decrease nice level of the selected process
697
        # Only in standalone mode (cs_status is None)
698
        if self.increase_nice_process and cs_status is None:
699
            self.nice_increase(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
700
        self.increase_nice_process = False
701
        if self.decrease_nice_process and cs_status is None:
702
            self.nice_decrease(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
703
        self.decrease_nice_process = False
704
705
        # Display kill process confirmation popup
706
        # Only in standalone mode (cs_status is None)
707
        if self.kill_process and cs_status is None:
708
            self.kill(stats.get_plugin('processlist').get_raw()[self.args.cursor_position])
709
        elif self.kill_process and cs_status is not None:
710
            self.display_popup('Kill process only available for local processes')
711
        self.kill_process = False
712
713
        # Display graph generation popup
714
        if self.args.generate_graph:
715
            if 'graph' in stats.getExportsList():
716
                self.display_popup(f'Generate graph in {self.args.export_graph_path}')
717
            else:
718
                logger.warning('Graph export module is disable. Run Glances with --export graph to enable it.')
719
                self.args.generate_graph = False
720
721
        return True
722
723
    def nice_increase(self, process):
724
        glances_processes.nice_increase(process['pid'])
725
726
    def nice_decrease(self, process):
727
        glances_processes.nice_decrease(process['pid'])
728
729
    def kill(self, process):
730
        """Kill a process, or a list of process if the process has a childrens field.
731
732
        :param process
733
        :return: None
734
        """
735
        logger.debug(f"Selected process to kill: {process}")
736
737
        if 'childrens' in process:
738
            pid_to_kill = process['childrens']
739
        else:
740
            pid_to_kill = [process['pid']]
741
742
        confirm = self.display_popup(
743
            'Kill process: {} (pid: {}) ?\n\nConfirm ([y]es/[n]o): '.format(
744
                process['name'],
745
                ', '.join(map(str, pid_to_kill)),
746
            ),
747
            popup_type='yesno',
748
        )
749
750
        if confirm.lower().startswith('y'):
751
            for pid in pid_to_kill:
752
                try:
753
                    ret_kill = glances_processes.kill(pid)
754
                except Exception as e:
755
                    logger.error(f'Can not kill process {pid} ({e})')
756
                else:
757
                    logger.info(f'Kill signal has been sent to process {pid} (return code: {ret_kill})')
758
759
    def __display_header(self, stat_display):
760
        """Display the firsts lines (header) in the Curses interface.
761
762
        system + ip + uptime
763
        (cloud)
764
        """
765
        # First line
766
        self.new_line()
767
        self.space_between_column = 0
768
        l_uptime = 1
769
        for i in ['system', 'ip', 'uptime']:
770
            if i in stat_display:
771
                l_uptime += self.get_stats_display_width(stat_display[i])
772
        self.display_plugin(stat_display["system"], display_optional=(self.term_window.getmaxyx()[1] >= l_uptime))
773
        self.space_between_column = 3
774
        if 'ip' in stat_display:
775
            self.new_column()
776
            self.display_plugin(stat_display["ip"], display_optional=(self.term_window.getmaxyx()[1] >= 100))
777
        self.new_column()
778
        self.display_plugin(
779
            stat_display["uptime"], add_space=-(self.get_stats_display_width(stat_display["cloud"]) != 0)
780
        )
781
        self.init_column()
782
        if self.get_stats_display_width(stat_display["cloud"]) != 0:
783
            # Second line (optional)
784
            self.new_line()
785
            self.display_plugin(stat_display["cloud"])
786
787
    def __display_top(self, stat_display, stats):
788
        """Display the second line in the Curses interface.
789
790
        <QUICKLOOK> + CPU|PERCPU + <GPU> + MEM + SWAP + LOAD
791
        """
792
        self.init_column()
793
        self.new_line()
794
795
        # Init quicklook
796
        stat_display['quicklook'] = {'msgdict': []}
797
798
        # Dict for plugins width
799
        plugin_widths = {}
800
        for p in self._top:
801
            plugin_widths[p] = (
802
                self.get_stats_display_width(stat_display.get(p, 0)) if hasattr(self.args, 'disable_' + p) else 0
803
            )
804
805
        # Width of all plugins
806
        stats_width = sum(itervalues(plugin_widths))
807
808
        # Number of plugin but quicklook
809
        stats_number = sum(
810
            [int(stat_display[p]['msgdict'] != []) for p in self._top if not getattr(self.args, 'disable_' + p)]
811
        )
812
813
        if not self.args.disable_quicklook:
814
            # Quick look is in the place !
815
            if self.args.full_quicklook:
816
                quicklook_width = self.term_window.getmaxyx()[1] - (
817
                    stats_width + 8 + stats_number * self.space_between_column
818
                )
819
            else:
820
                quicklook_width = min(
821
                    self.term_window.getmaxyx()[1] - (stats_width + 8 + stats_number * self.space_between_column),
822
                    self._quicklook_max_width - 5,
823
                )
824
            try:
825
                stat_display["quicklook"] = stats.get_plugin('quicklook').get_stats_display(
826
                    max_width=quicklook_width, args=self.args
827
                )
828
            except AttributeError as e:
829
                logger.debug(f"Quicklook plugin not available ({e})")
830
            else:
831
                plugin_widths['quicklook'] = self.get_stats_display_width(stat_display["quicklook"])
832
                stats_width = sum(itervalues(plugin_widths)) + 1
833
            self.space_between_column = 1
834
            self.display_plugin(stat_display["quicklook"])
835
            self.new_column()
836
837
        # Compute spaces between plugins
838
        # Note: Only one space between Quicklook and others
839
        plugin_display_optional = {}
840
        for p in self._top:
841
            plugin_display_optional[p] = True
842
        if stats_number > 1:
843
            self.space_between_column = max(1, int((self.term_window.getmaxyx()[1] - stats_width) / (stats_number - 1)))
844
            for p in ['mem', 'cpu']:
845
                # No space ? Remove optional stats
846
                if self.space_between_column < 3:
847
                    plugin_display_optional[p] = False
848
                    plugin_widths[p] = (
849
                        self.get_stats_display_width(stat_display[p], without_option=True)
850
                        if hasattr(self.args, 'disable_' + p)
851
                        else 0
852
                    )
853
                    stats_width = sum(itervalues(plugin_widths)) + 1
854
                    self.space_between_column = max(
855
                        1, int((self.term_window.getmaxyx()[1] - stats_width) / (stats_number - 1))
856
                    )
857
        else:
858
            self.space_between_column = 0
859
860
        # Display CPU, MEM, SWAP and LOAD
861
        for p in self._top:
862
            if p == 'quicklook':
863
                continue
864
            if p in stat_display:
865
                self.display_plugin(stat_display[p], display_optional=plugin_display_optional[p])
866
            if p != 'load':
867
                # Skip last column
868
                self.new_column()
869
870
        # Space between column
871
        self.space_between_column = 3
872
873
        # Backup line position
874
        self.saved_line = self.next_line
875
876
    def __display_left(self, stat_display):
877
        """Display the left sidebar in the Curses interface."""
878
        self.init_column()
879
880
        if self.args.disable_left_sidebar:
881
            return
882
883
        for p in self._left_sidebar:
884
            if (hasattr(self.args, 'enable_' + p) or hasattr(self.args, 'disable_' + p)) and p in stat_display:
885
                self.new_line()
886
                if p == 'sensors':
887
                    self.display_plugin(
888
                        stat_display['sensors'],
889
                        max_y=(self.term_window.getmaxyx()[0] - self.get_stats_display_height(stat_display['now']) - 2),
890
                    )
891
                else:
892
                    self.display_plugin(stat_display[p])
893
894
    def __display_right(self, stat_display):
895
        """Display the right sidebar in the Curses interface.
896
897
        docker + processcount + amps + processlist + alert
898
        """
899
        # Do not display anything if space is not available...
900
        if self.term_window.getmaxyx()[1] < self._left_sidebar_min_width:
901
            return
902
903
        # Restore line position
904
        self.next_line = self.saved_line
905
906
        # Display right sidebar
907
        self.new_column()
908
        for p in self._right_sidebar:
909
            if (hasattr(self.args, 'enable_' + p) or hasattr(self.args, 'disable_' + p)) and p in stat_display:
910
                self.new_line()
911
                if p == 'processlist':
912
                    self.display_plugin(
913
                        stat_display['processlist'],
914
                        display_optional=(self.term_window.getmaxyx()[1] > 102),
915
                        display_additional=(not MACOS),
916
                        max_y=(
917
                            self.term_window.getmaxyx()[0] - self.get_stats_display_height(stat_display['alert']) - 2
918
                        ),
919
                    )
920
                else:
921
                    self.display_plugin(stat_display[p])
922
923
    def display_popup(
924
        self,
925
        message,
926
        size_x=None,
927
        size_y=None,
928
        duration=3,
929
        popup_type='info',
930
        input_size=30,
931
        input_value=None,
932
        is_password=False,
933
    ):
934
        """
935
        Display a centered popup.
936
937
        popup_type: ='info'
938
         Just an information popup, no user interaction
939
         Display a centered popup with the given message during duration seconds
940
         If size_x and size_y: set the popup size
941
         else set it automatically
942
         Return True if the popup could be displayed
943
944
        popup_type='input'
945
         Display a centered popup with the given message and a input field
946
         If size_x and size_y: set the popup size
947
         else set it automatically
948
         Return the input string or None if the field is empty
949
950
        popup_type='yesno'
951
         Display a centered popup with the given message
952
         If size_x and size_y: set the popup size
953
         else set it automatically
954
         Return True (yes) or False (no)
955
        """
956
        # Center the popup
957
        sentence_list = message.split('\n')
958
        if size_x is None:
959
            size_x = len(max(sentence_list, key=len)) + 4
960
            # Add space for the input field
961
            if popup_type == 'input':
962
                size_x += input_size
963
        if size_y is None:
964
            size_y = len(sentence_list) + 4
965
        screen_x = self.term_window.getmaxyx()[1]
966
        screen_y = self.term_window.getmaxyx()[0]
967
        if size_x > screen_x or size_y > screen_y:
968
            # No size to display the popup => abord
969
            return False
970
        pos_x = int((screen_x - size_x) / 2)
971
        pos_y = int((screen_y - size_y) / 2)
972
973
        # Create the popup
974
        popup = curses.newwin(size_y, size_x, pos_y, pos_x)
975
976
        # Fill the popup
977
        popup.border()
978
979
        # Add the message
980
        for y, m in enumerate(sentence_list):
981
            if len(m) > 0:
982
                popup.addnstr(2 + y, 2, m, len(m))
983
984
        if popup_type == 'info':
985
            # Display the popup
986
            popup.refresh()
987
            self.wait(duration * 1000)
988
            return True
989
990
        if popup_type == 'input':
991
            logger.info(popup_type)
992
            logger.info(is_password)
993
            # Create a sub-window for the text field
994
            sub_pop = popup.derwin(1, input_size, 2, 2 + len(m))
0 ignored issues
show
The variable m does not seem to be defined in case the for loop on line 980 is not entered. Are you sure this can never be the case?
Loading history...
995
            sub_pop.attron(self.colors_list['FILTER'])
996
            # Init the field with the current value
997
            if input_value is not None:
998
                sub_pop.addnstr(0, 0, input_value, len(input_value))
999
            # Display the popup
1000
            popup.refresh()
1001
            sub_pop.refresh()
1002
            # Create the textbox inside the sub-windows
1003
            self.set_cursor(2)
1004
            self.term_window.keypad(1)
1005
            if is_password:
1006
                textbox = getpass.getpass('')
1007
                self.set_cursor(0)
1008
                if textbox != '':
1009
                    return textbox
1010
                return None
1011
1012
            # No password
1013
            textbox = GlancesTextbox(sub_pop, insert_mode=True)
1014
            textbox.edit()
1015
            self.set_cursor(0)
1016
            if textbox.gather() != '':
1017
                return textbox.gather()[:-1]
1018
            return None
1019
1020
        if popup_type == 'yesno':
1021
            # # Create a sub-window for the text field
1022
            sub_pop = popup.derwin(1, 2, len(sentence_list) + 1, len(m) + 2)
1023
            sub_pop.attron(self.colors_list['FILTER'])
1024
            # Init the field with the current value
1025
            sub_pop.addnstr(0, 0, '', 0)
1026
            # Display the popup
1027
            popup.refresh()
1028
            sub_pop.refresh()
1029
            # Create the textbox inside the sub-windows
1030
            self.set_cursor(2)
1031
            self.term_window.keypad(1)
1032
            textbox = GlancesTextboxYesNo(sub_pop, insert_mode=False)
1033
            textbox.edit()
1034
            self.set_cursor(0)
1035
            # self.term_window.keypad(0)
1036
            return textbox.gather()
1037
1038
        return None
1039
1040
    def display_plugin(self, plugin_stats, display_optional=True, display_additional=True, max_y=65535, add_space=0):
1041
        """Display the plugin_stats on the screen.
1042
1043
        :param plugin_stats:
1044
        :param display_optional: display the optional stats if True
1045
        :param display_additional: display additional stats if True
1046
        :param max_y: do not display line > max_y
1047
        :param add_space: add x space (line) after the plugin
1048
        """
1049
        # Exit if:
1050
        # - the plugin_stats message is empty
1051
        # - the display tag = False
1052
        if plugin_stats is None or not plugin_stats['msgdict'] or not plugin_stats['display']:
1053
            # Exit
1054
            return 0
1055
1056
        # Get the screen size
1057
        screen_x = self.term_window.getmaxyx()[1]
1058
        screen_y = self.term_window.getmaxyx()[0]
1059
1060
        # Set the upper/left position of the message
1061
        if plugin_stats['align'] == 'right':
1062
            # Right align (last column)
1063
            display_x = screen_x - self.get_stats_display_width(plugin_stats)
1064
        else:
1065
            display_x = self.column
1066
        if plugin_stats['align'] == 'bottom':
1067
            # Bottom (last line)
1068
            display_y = screen_y - self.get_stats_display_height(plugin_stats)
1069
        else:
1070
            display_y = self.line
1071
1072
        # Display
1073
        x = display_x
1074
        x_max = x
1075
        y = display_y
1076
        for m in plugin_stats['msgdict']:
1077
            # New line
1078
            try:
1079
                if m['msg'].startswith('\n'):
1080
                    # Go to the next line
1081
                    y += 1
1082
                    # Return to the first column
1083
                    x = display_x
1084
                    continue
1085
            except Exception:
1086
                # Avoid exception (see issue #1692)
1087
                pass
1088
            # Do not display outside the screen
1089
            if x < 0:
1090
                continue
1091
            if not m['splittable'] and (x + len(m['msg']) > screen_x):
1092
                continue
1093
            if y < 0 or (y + 1 > screen_y) or (y > max_y):
1094
                break
1095
            # If display_optional = False do not display optional stats
1096
            if not display_optional and m['optional']:
1097
                continue
1098
            # If display_additional = False do not display additional stats
1099
            if not display_additional and m['additional']:
1100
                continue
1101
            # Is it possible to display the stat with the current screen size
1102
            # !!! Crash if not try/except... Why ???
1103
            try:
1104
                self.term_window.addnstr(
1105
                    y,
1106
                    x,
1107
                    m['msg'],
1108
                    # Do not display outside the screen
1109
                    screen_x - x,
1110
                    self.colors_list[m['decoration']],
1111
                )
1112
            except Exception:
1113
                pass
1114
            else:
1115
                # New column
1116
                # Python 2: we need to decode to get real screen size because
1117
                # UTF-8 special tree chars occupy several bytes.
1118
                # Python 3: strings are strings and bytes are bytes, all is
1119
                # good.
1120
                try:
1121
                    x += len(u(m['msg']))
1122
                except UnicodeDecodeError:
1123
                    # Quick and dirty hack for issue #745
1124
                    pass
1125
                if x > x_max:
1126
                    x_max = x
1127
1128
        # Compute the next Glances column/line position
1129
        self.next_column = max(self.next_column, x_max + self.space_between_column)
1130
        self.next_line = max(self.next_line, y + self.space_between_line)
1131
1132
        # Have empty lines after the plugins
1133
        self.next_line += add_space
1134
        return None
1135
1136
    def clear(self):
1137
        """Erase the content of the screen.
1138
        The difference is that clear() also calls clearok(). clearok()
1139
        basically tells ncurses to forget whatever it knows about the current
1140
        terminal contents, so that when refresh() is called, it will actually
1141
        begin by clearing the entire terminal screen before redrawing any of it."""
1142
        self.term_window.clear()
1143
1144
    def erase(self):
1145
        """Erase the content of the screen.
1146
        erase() on the other hand, just clears the screen (the internal
1147
        object, not the terminal screen). When refresh() is later called,
1148
        ncurses will still compute the minimum number of characters to send to
1149
        update the terminal."""
1150
        self.term_window.erase()
1151
1152
    def refresh(self):
1153
        """Refresh the windows"""
1154
        self.term_window.refresh()
1155
1156
    def flush(self, stats, cs_status=None):
1157
        """Erase and update the screen.
1158
1159
        :param stats: Stats database to display
1160
        :param cs_status:
1161
            "None": standalone or server mode
1162
            "Connected": Client is connected to the server
1163
            "Disconnected": Client is disconnected from the server
1164
        """
1165
        # See https://stackoverflow.com/a/43486979/1919431
1166
        self.erase()
1167
        self.display(stats, cs_status=cs_status)
1168
        self.refresh()
1169
1170
    def update(self, stats, duration=3, cs_status=None, return_to_browser=False):
1171
        """Update the screen.
1172
1173
        :param stats: Stats database to display
1174
        :param duration: duration of the loop
1175
        :param cs_status:
1176
            "None": standalone or server mode
1177
            "Connected": Client is connected to the server
1178
            "Disconnected": Client is disconnected from the server
1179
        :param return_to_browser:
1180
            True: Do not exist, return to the browser list
1181
            False: Exit and return to the shell
1182
1183
        :return: True if exit key has been pressed else False
1184
        """
1185
        # Flush display
1186
        self.flush(stats, cs_status=cs_status)
1187
1188
        # If the duration is < 0 (update + export time > refresh_time)
1189
        # Then display the interface and log a message
1190
        if duration <= 0:
1191
            logger.warning('Update and export time higher than refresh_time.')
1192
            duration = 0.1
1193
1194
        # Wait duration (in s) time
1195
        isexitkey = False
1196
        countdown = Timer(duration)
1197
        # Set the default timeout (in ms) between two getch
1198
        self.term_window.timeout(100)
1199
        while not countdown.finished() and not isexitkey:
1200
            # Getkey
1201
            pressedkey = self.__catch_key(return_to_browser=return_to_browser)
1202
            isexitkey = pressedkey == ord('\x1b') or pressedkey == ord('q')
1203
1204
            if pressedkey == curses.KEY_F5 or self.pressedkey == 18:
1205
                # Were asked to refresh (F5 or Ctrl-R)
1206
                self.clear()
1207
                return isexitkey
1208
1209
            if pressedkey in (curses.KEY_UP, 65, curses.KEY_DOWN, 66):
1210
                # Up of won key pressed, reset the countdown
1211
                # Better for user experience
1212
                countdown.reset()
1213
1214
            if isexitkey and self.args.help_tag:
1215
                # Quit from help should return to main screen, not exit #1874
1216
                self.args.help_tag = not self.args.help_tag
1217
                return False
1218
1219
            if not isexitkey and pressedkey > -1:
1220
                # Redraw display
1221
                self.flush(stats, cs_status=cs_status)
1222
                # Overwrite the timeout with the countdown
1223
                self.wait(delay=int(countdown.get() * 1000))
1224
1225
        return isexitkey
1226
1227
    def wait(self, delay=100):
1228
        """Wait delay in ms"""
1229
        curses.napms(delay)
1230
1231
    def get_stats_display_width(self, curse_msg, without_option=False):
1232
        """Return the width of the formatted curses message."""
1233
        try:
1234
            if without_option:
1235
                # Size without options
1236
                c = len(
1237
                    max(
1238
                        ''.join(
1239
                            [
1240
                                (u(u(nativestr(i['msg'])).encode('ascii', 'replace')) if not i['optional'] else "")
1241
                                for i in curse_msg['msgdict']
1242
                            ]
1243
                        ).split('\n'),
1244
                        key=len,
1245
                    )
1246
                )
1247
            else:
1248
                # Size with all options
1249
                c = len(
1250
                    max(
1251
                        ''.join(
1252
                            [u(u(nativestr(i['msg'])).encode('ascii', 'replace')) for i in curse_msg['msgdict']]
1253
                        ).split('\n'),
1254
                        key=len,
1255
                    )
1256
                )
1257
        except Exception as e:
1258
            logger.debug(f'ERROR: Can not compute plugin width ({e})')
1259
            return 0
1260
        else:
1261
            return c
1262
1263
    def get_stats_display_height(self, curse_msg):
1264
        """Return the height of the formatted curses message.
1265
1266
        The height is defined by the number of '\n' (new line).
1267
        """
1268
        try:
1269
            c = [i['msg'] for i in curse_msg['msgdict']].count('\n')
1270
        except Exception as e:
1271
            logger.debug(f'ERROR: Can not compute plugin height ({e})')
1272
            return 0
1273
        else:
1274
            return c + 1
1275
1276
1277
class GlancesCursesStandalone(_GlancesCurses):
1278
    """Class for the Glances curse standalone."""
1279
1280
1281
class GlancesCursesClient(_GlancesCurses):
1282
    """Class for the Glances curse client."""
1283
1284
1285
class GlancesTextbox(Textbox):
1286
    def __init__(self, *args, **kwargs):
1287
        super().__init__(*args, **kwargs)
1288
1289
    def do_command(self, ch):
1290
        if ch == 10:  # Enter
1291
            return 0
1292
        if ch == 127:  # Back
1293
            return 8
1294
        return super().do_command(ch)
1295
1296
1297
class GlancesTextboxYesNo(Textbox):
1298
    def __init__(self, *args, **kwargs):
1299
        super().__init__(*args, **kwargs)
1300
1301
    def do_command(self, ch):
1302
        return super().do_command(ch)
1303