GlancesProcesses.reset_max_values()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
import os
10
11
import psutil
12
13
from glances.filter import GlancesFilter, GlancesFilterList
14
from glances.globals import BSD, LINUX, MACOS, WINDOWS, iterkeys, list_of_namedtuple_to_list_of_dict, namedtuple_to_dict
15
from glances.logger import logger
16
from glances.programs import processes_to_programs
17
from glances.timer import Timer, getTimeSinceLastUpdate
18
19
psutil_version_info = tuple([int(num) for num in psutil.__version__.split('.')])
20
21
# This constant defines the list of available processes sort key
22
sort_processes_key_list = ['cpu_percent', 'memory_percent', 'username', 'cpu_times', 'io_counters', 'name']
23
24
# Sort dictionary for human
25
sort_for_human = {
26
    'io_counters': 'disk IO',
27
    'cpu_percent': 'CPU consumption',
28
    'memory_percent': 'memory consumption',
29
    'cpu_times': 'process time',
30
    'username': 'user name',
31
    'name': 'processs name',
32
    None: 'None',
33
}
34
35
36
class GlancesProcesses:
37
    """Get processed stats using the psutil library."""
38
39
    def __init__(self, cache_timeout=60):
40
        """Init the class to collect stats about processes."""
41
        # Init the args, coming from the GlancesStandalone class
42
        # Should be set by the set_args method
43
        self.args = None
44
45
        # The internals caches will be cleaned each 'cache_timeout' seconds
46
        self.cache_timeout = cache_timeout
47
        # First iteration, no cache
48
        self.cache_timer = Timer(0)
49
50
        # Init the io_old dict used to compute the IO bitrate
51
        # key = pid
52
        # value = [ read_bytes_old, write_bytes_old ]
53
        self.io_old = {}
54
55
        # Init stats
56
        self.auto_sort = None
57
        self._sort_key = None
58
        # Default processes sort key is 'auto'
59
        # Can be overwrite from the configuration file (issue#1536) => See glances_processlist.py init
60
        self.set_sort_key('auto', auto=True)
61
        self.processlist = []
62
        self.reset_processcount()
63
64
        # Cache is a dict with key=pid and value = dict of cached value
65
        self.processlist_cache = {}
66
67
        # List of processes stats to export
68
        # Only process matching one of the filter will be exported
69
        self._filter_export = GlancesFilterList()
70
        self.processlist_export = []
71
72
        # Tag to enable/disable the processes stats (to reduce the Glances CPU consumption)
73
        # Default is to enable the processes stats
74
        self.disable_tag = False
75
76
        # Extended stats for top process is enable by default
77
        self.disable_extended_tag = False
78
        self.extended_process = None
79
80
        # Test if the system can grab io_counters
81
        try:
82
            p = psutil.Process()
83
            p.io_counters()
84
        except Exception as e:
85
            logger.warning(f'PsUtil can not grab processes io_counters ({e})')
86
            self.disable_io_counters = True
87
        else:
88
            logger.debug('PsUtil can grab processes io_counters')
89
            self.disable_io_counters = False
90
91
        # Test if the system can grab gids
92
        try:
93
            p = psutil.Process()
94
            p.gids()
95
        except Exception as e:
96
            logger.warning(f'PsUtil can not grab processes gids ({e})')
97
            self.disable_gids = True
98
        else:
99
            logger.debug('PsUtil can grab processes gids')
100
            self.disable_gids = False
101
102
        # Maximum number of processes showed in the UI (None if no limit)
103
        self._max_processes = None
104
105
        # Process filter
106
        self._filter = GlancesFilter()
107
108
        # Whether or not to hide kernel threads
109
        self.no_kernel_threads = False
110
111
        # Store maximums values in a dict
112
        # Used in the UI to highlight the maximum value
113
        self._max_values_list = ('cpu_percent', 'memory_percent')
114
        # { 'cpu_percent': 0.0, 'memory_percent': 0.0 }
115
        self._max_values = {}
116
        self.reset_max_values()
117
118
    def set_args(self, args):
119
        """Set args."""
120
        self.args = args
121
122
    def reset_processcount(self):
123
        """Reset the global process count"""
124
        self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0, 'pid_max': None}
125
126
    def update_processcount(self, plist):
127
        """Update the global process count from the current processes list"""
128
        # Update the maximum process ID (pid) number
129
        self.processcount['pid_max'] = self.pid_max
130
        # For each key in the processcount dict
131
        # count the number of processes with the same status
132
        for k in iterkeys(self.processcount):
133
            self.processcount[k] = len(list(filter(lambda v: v['status'] is k, plist)))
0 ignored issues
show
introduced by
The variable k does not seem to be defined in case the for loop on line 132 is not entered. Are you sure this can never be the case?
Loading history...
134
        # Compute thread
135
        self.processcount['thread'] = sum(i['num_threads'] for i in plist if i['num_threads'] is not None)
136
        # Compute total
137
        self.processcount['total'] = len(plist)
138
139
    def enable(self):
140
        """Enable process stats."""
141
        self.disable_tag = False
142
        self.update()
143
144
    def disable(self):
145
        """Disable process stats."""
146
        self.disable_tag = True
147
148
    def enable_extended(self):
149
        """Enable extended process stats."""
150
        self.disable_extended_tag = False
151
        self.update()
152
153
    def disable_extended(self):
154
        """Disable extended process stats."""
155
        self.disable_extended_tag = True
156
157
    @property
158
    def pid_max(self):
159
        """
160
        Get the maximum PID value.
161
162
        On Linux, the value is read from the `/proc/sys/kernel/pid_max` file.
163
164
        From `man 5 proc`:
165
        The default value for this file, 32768, results in the same range of
166
        PIDs as on earlier kernels. On 32-bit platforms, 32768 is the maximum
167
        value for pid_max. On 64-bit systems, pid_max can be set to any value
168
        up to 2^22 (PID_MAX_LIMIT, approximately 4 million).
169
170
        If the file is unreadable or not available for whatever reason,
171
        returns None.
172
173
        Some other OSes:
174
        - On FreeBSD and macOS the maximum is 99999.
175
        - On OpenBSD >= 6.0 the maximum is 99999 (was 32766).
176
        - On NetBSD the maximum is 30000.
177
178
        :returns: int or None
179
        """
180
        if LINUX:
181
            # XXX: waiting for https://github.com/giampaolo/psutil/issues/720
182
            try:
183
                with open('/proc/sys/kernel/pid_max', 'rb') as f:
184
                    return int(f.read())
185
            except OSError:
186
                return None
187
        else:
188
            return None
189
190
    @property
191
    def processes_count(self):
192
        """Get the current number of processes showed in the UI."""
193
        return min(self._max_processes - 2, glances_processes.processcount['total'] - 1)
194
195
    @property
196
    def max_processes(self):
197
        """Get the maximum number of processes showed in the UI."""
198
        return self._max_processes
199
200
    @max_processes.setter
201
    def max_processes(self, value):
202
        """Set the maximum number of processes showed in the UI."""
203
        self._max_processes = value
204
205
    # Process filter
206
207
    @property
208
    def process_filter_input(self):
209
        """Get the process filter (given by the user)."""
210
        return self._filter.filter_input
211
212
    @property
213
    def process_filter(self):
214
        """Get the process filter (current apply filter)."""
215
        return self._filter.filter
216
217
    @process_filter.setter
218
    def process_filter(self, value):
219
        """Set the process filter."""
220
        self._filter.filter = value
221
222
    @property
223
    def process_filter_key(self):
224
        """Get the process filter key."""
225
        return self._filter.filter_key
226
227
    @property
228
    def process_filter_re(self):
229
        """Get the process regular expression compiled."""
230
        return self._filter.filter_re
231
232
    # Export filter
233
234
    @property
235
    def export_process_filter(self):
236
        """Get the export process filter (current export process filter list)."""
237
        return self._filter_export.filter
238
239
    @export_process_filter.setter
240
    def export_process_filter(self, value):
241
        """Set the export process filter list."""
242
        self._filter_export.filter = value
243
244
    # Kernel threads
245
246
    def disable_kernel_threads(self):
247
        """Ignore kernel threads in process list."""
248
        self.no_kernel_threads = True
249
250
    @property
251
    def sort_reverse(self):
252
        """Return True to sort processes in reverse 'key' order, False instead."""
253
        if self.sort_key == 'name' or self.sort_key == 'username':
254
            return False
255
256
        return True
257
258
    def max_values(self):
259
        """Return the max values dict."""
260
        return self._max_values
261
262
    def get_max_values(self, key):
263
        """Get the maximum values of the given stat (key)."""
264
        return self._max_values[key]
265
266
    def set_max_values(self, key, value):
267
        """Set the maximum value for a specific stat (key)."""
268
        self._max_values[key] = value
269
270
    def reset_max_values(self):
271
        """Reset the maximum values dict."""
272
        self._max_values = {}
273
        for k in self._max_values_list:
274
            self._max_values[k] = 0.0
275
276
    def get_extended_stats(self, proc):
277
        """Get the extended stats for the given PID."""
278
        # - cpu_affinity (Linux, Windows, FreeBSD)
279
        # - ionice (Linux and Windows > Vista)
280
        # - num_ctx_switches (not available on Illumos/Solaris)
281
        # - num_fds (Unix-like)
282
        # - num_handles (Windows)
283
        # - memory_maps (only swap, Linux)
284
        #   https://www.cyberciti.biz/faq/linux-which-process-is-using-swap/
285
        # - connections (TCP and UDP)
286
        # - CPU min/max/mean
287
288
        # Set the extended stats list (OS dependant)
289
        extended_stats = ['cpu_affinity', 'ionice', 'num_ctx_switches']
290
        if LINUX:
291
            # num_fds only available on Unix system (see issue #1351)
292
            extended_stats += ['num_fds']
293
        if WINDOWS:
294
            extended_stats += ['num_handles']
295
296
        ret = {}
297
        try:
298
            logger.debug('Grab extended stats for process {}'.format(proc['pid']))
299
300
            # Get PID of the selected process
301
            selected_process = psutil.Process(proc['pid'])
302
303
            # Get the extended stats for the selected process
304
            ret = selected_process.as_dict(attrs=extended_stats, ad_value=None)
305
306
            # Get memory swap for the selected process (Linux Only)
307
            ret['memory_swap'] = self.__get_extended_memory_swap(selected_process)
308
309
            # Get number of TCP and UDP network connections for the selected process
310
            ret['tcp'], ret['udp'] = self.__get_extended_connections(selected_process)
311
        except (psutil.NoSuchProcess, ValueError, AttributeError) as e:
312
            logger.error(f'Can not grab extended stats ({e})')
313
            self.extended_process = None
314
            ret['extended_stats'] = False
315
        else:
316
            # Compute CPU and MEM min/max/mean
317
            # Merge the returned dict with the current on
318
            ret.update(self.__get_min_max_mean(proc))
319
            self.extended_process = ret
320
            ret['extended_stats'] = True
321
        return namedtuple_to_dict(ret)
322
323
    def __get_min_max_mean(self, proc, prefix=['cpu', 'memory']):
324
        """Return the min/max/mean for the given process"""
325
        ret = {}
326
        for stat_prefix in prefix:
327
            min_key = stat_prefix + '_min'
328
            max_key = stat_prefix + '_max'
329
            mean_sum_key = stat_prefix + '_mean_sum'
330
            mean_counter_key = stat_prefix + '_mean_counter'
331
            if min_key not in self.extended_process:
332
                ret[min_key] = proc[stat_prefix + '_percent']
333
            else:
334
                ret[min_key] = min(proc[stat_prefix + '_percent'], self.extended_process[min_key])
335
            if max_key not in self.extended_process:
336
                ret[max_key] = proc[stat_prefix + '_percent']
337
            else:
338
                ret[max_key] = max(proc[stat_prefix + '_percent'], self.extended_process[max_key])
339
            if mean_sum_key not in self.extended_process:
340
                ret[mean_sum_key] = proc[stat_prefix + '_percent']
341
            else:
342
                ret[mean_sum_key] = self.extended_process[mean_sum_key] + proc[stat_prefix + '_percent']
343
            if mean_counter_key not in self.extended_process:
344
                ret[mean_counter_key] = 1
345
            else:
346
                ret[mean_counter_key] = self.extended_process[mean_counter_key] + 1
347
            ret[stat_prefix + '_mean'] = ret[mean_sum_key] / ret[mean_counter_key]
348
        return ret
349
350
    def __get_extended_memory_swap(self, process):
351
        """Return the memory swap for the given process"""
352
        if not LINUX:
353
            return None
354
        try:
355
            memory_swap = sum([v.swap for v in process.memory_maps()])
356
        except (psutil.NoSuchProcess, KeyError):
357
            # (KeyError catch for issue #1551)
358
            pass
359
        except (psutil.AccessDenied, NotImplementedError):
360
            # NotImplementedError: /proc/${PID}/smaps file doesn't exist
361
            # on kernel < 2.6.14 or CONFIG_MMU kernel configuration option
362
            # is not enabled (see psutil #533/glances #413).
363
            memory_swap = None
364
        return memory_swap
365
366
    def __get_extended_connections(self, process):
367
        """Return a tuple with (tcp, udp) connections count
368
        The code is compliant with both PsUtil<6 and Psutil>=6
369
        """
370
        try:
371
            # Hack for issue #2754 (PsUtil 6+)
372
            if psutil_version_info[0] >= 6:
373
                tcp = len(process.net_connections(kind="tcp"))
374
                udp = len(process.net_connections(kind="udp"))
375
            else:
376
                tcp = len(process.connections(kind="tcp"))
377
                udp = len(process.connections(kind="udp"))
378
        except (psutil.AccessDenied, psutil.NoSuchProcess):
379
            # Manage issue1283 (psutil.AccessDenied)
380
            tcp = None
381
            udp = None
382
        return tcp, udp
383
384
    def is_selected_extended_process(self, position):
385
        """Return True if the process is the selected one for extended stats."""
386
        return (
387
            hasattr(self.args, 'programs')
388
            and not self.args.programs
389
            and hasattr(self.args, 'enable_process_extended')
390
            and self.args.enable_process_extended
391
            and not self.disable_extended_tag
392
            and hasattr(self.args, 'cursor_position')
393
            and position == self.args.cursor_position
394
            and not self.args.disable_cursor
395
        )
396
397
    def update(self):
398
        """Update the processes stats."""
399
        # Init new processes stats
400
        processlist = []
401
402
        # Do not process if disable tag is set
403
        if self.disable_tag:
404
            return processlist
405
406
        # Time since last update (for disk_io rate computation)
407
        time_since_update = getTimeSinceLastUpdate('process_disk')
408
409
        # Grab standard stats
410
        #####################
411
        sorted_attrs = ['cpu_percent', 'cpu_times', 'memory_percent', 'name', 'status', 'num_threads']
412
        displayed_attr = ['memory_info', 'nice', 'pid']
413
        # The following attributes are cached and only retreive every self.cache_timeout seconds
414
        # Warning: 'name' can not be cached because it is used for filtering
415
        cached_attrs = ['cmdline', 'username']
416
417
        # Some stats are optional
418
        if not self.disable_io_counters:
419
            sorted_attrs.append('io_counters')
420
        if not self.disable_gids:
421
            displayed_attr.append('gids')
422
        # Some stats are not sort key
423
        # An optimisation can be done be only grabbed displayed_attr
424
        # for displayed processes (but only in standalone mode...)
425
        sorted_attrs.extend(displayed_attr)
426
        # Some stats are cached (not necessary to be refreshed every time)
427
        if self.cache_timer.finished():
428
            sorted_attrs += cached_attrs
429
            self.cache_timer.set(self.cache_timeout)
430
            self.cache_timer.reset()
431
            is_cached = False
432
        else:
433
            is_cached = True
434
435
        # Build the processes stats list (it is why we need psutil>=5.3.0)
436
        # This is one of the main bottleneck of Glances (see flame graph)
437
        # It may be optimized with PsUtil 6+ (see issue #2755)
438
        processlist = list(
439
            filter(
440
                lambda p: not (BSD and p.info['name'] == 'idle')
441
                and not (WINDOWS and p.info['name'] == 'System Idle Process')
442
                and not (MACOS and p.info['name'] == 'kernel_task')
443
                and not (self.no_kernel_threads and LINUX and p.info['gids'].real == 0),
444
                psutil.process_iter(attrs=sorted_attrs, ad_value=None),
445
            )
446
        )
447
        # Only get the info key
448
        processlist = [p.info for p in processlist]
449
        # Sort the processes list by the current sort_key
450
        processlist = sort_stats(processlist, sorted_by=self.sort_key, reverse=True)
451
452
        # Update the processcount
453
        self.update_processcount(processlist)
454
455
        # Loop over processes and :
456
        # - add extended stats for selected process
457
        # - add metadata
458
        for position, proc in enumerate(processlist):
459
            # Extended stats
460
            ################
461
462
            # Get the selected process when the 'e' key is pressed
463
            if self.is_selected_extended_process(position):
464
                self.extended_process = proc
465
466
            # Grab extended stats only for the selected process (see issue #2225)
467
            if self.extended_process is not None and proc['pid'] == self.extended_process['pid']:
468
                proc.update(self.get_extended_stats(self.extended_process))
469
                self.extended_process = namedtuple_to_dict(proc)
470
471
            # Meta data
472
            ###########
473
474
            # PID is the key
475
            proc['key'] = 'pid'
476
477
            # Time since last update (for disk_io rate computation)
478
            proc['time_since_update'] = time_since_update
479
480
            # Process status (only keep the first char)
481
            proc['status'] = str(proc['status'])[:1].upper()
482
483
            # Process IO
484
            # procstat['io_counters'] is a list:
485
            # [read_bytes, write_bytes, read_bytes_old, write_bytes_old, io_tag]
486
            # If io_tag = 0 > Access denied or first time (display "?")
487
            # If io_tag = 1 > No access denied (display the IO rate)
488
            if 'io_counters' in proc and proc['io_counters'] is not None:
489
                io_new = [proc['io_counters'][2], proc['io_counters'][3]]
490
                # For IO rate computation
491
                # Append saved IO r/w bytes
492
                try:
493
                    proc['io_counters'] = io_new + self.io_old[proc['pid']]
494
                    io_tag = 1
495
                except KeyError:
496
                    proc['io_counters'] = io_new + [0, 0]
497
                    io_tag = 0
498
                # then save the IO r/w bytes
499
                self.io_old[proc['pid']] = io_new
500
            else:
501
                proc['io_counters'] = [0, 0] + [0, 0]
502
                io_tag = 0
503
            # Append the IO tag (for display)
504
            proc['io_counters'] += [io_tag]
505
506
            # Manage cached information
507
            if is_cached:
508
                # Grab cached values (in case of a new incoming process)
509
                if proc['pid'] not in self.processlist_cache:
510
                    try:
511
                        self.processlist_cache[proc['pid']] = psutil.Process(pid=proc['pid']).as_dict(
512
                            attrs=cached_attrs, ad_value=None
513
                        )
514
                    except psutil.NoSuchProcess:
515
                        pass
516
                # Add cached value to current stat
517
                try:
518
                    proc.update(self.processlist_cache[proc['pid']])
519
                except KeyError:
520
                    pass
521
            else:
522
                # Save values to cache
523
                try:
524
                    self.processlist_cache[proc['pid']] = {cached: proc[cached] for cached in cached_attrs}
525
                except KeyError:
526
                    pass
527
528
        # Filter and transform process export list
529
        self.processlist_export = self.update_export_list(processlist)
530
531
        # Filter and transform process list
532
        processlist = self.update_list(processlist)
533
534
        # Compute the maximum value for keys in self._max_values_list: CPU, MEM
535
        # Useful to highlight the processes with maximum values
536
        for k in self._max_values_list:
537
            values_list = [i[k] for i in processlist if i[k] is not None]
538
            if values_list:
539
                self.set_max_values(k, max(values_list))
540
541
        # Update the stats
542
        self.processlist = processlist
543
544
        return self.processlist
545
546
    def update_list(self, processlist):
547
        """Return the process list after filtering and transformation (namedtuple to dict)."""
548
        if self._filter.filter is None:
549
            return list_of_namedtuple_to_list_of_dict(processlist)
550
        ret = list(filter(lambda p: self._filter.is_filtered(p), processlist))
551
        return list_of_namedtuple_to_list_of_dict(ret)
552
553
    def update_export_list(self, processlist):
554
        """Return the process export list after filtering and transformation (namedtuple to dict)."""
555
        if self._filter_export.filter == []:
556
            return []
557
        ret = list(filter(lambda p: self._filter_export.is_filtered(p), processlist))
558
        return list_of_namedtuple_to_list_of_dict(ret)
559
560
    def get_count(self):
561
        """Get the number of processes."""
562
        return self.processcount
563
564
    def get_list(self, sorted_by=None, as_programs=False):
565
        """Get the processlist.
566
        By default, return the list of threads.
567
        If as_programs is True, return the list of programs."""
568
        if as_programs:
569
            return processes_to_programs(self.processlist)
570
        return self.processlist
571
572
    def get_export(self):
573
        """Return the processlist for export."""
574
        return self.processlist_export
575
576
    @property
577
    def sort_key(self):
578
        """Get the current sort key."""
579
        return self._sort_key
580
581
    def set_sort_key(self, key, auto=True):
582
        """Set the current sort key."""
583
        if key == 'auto':
584
            self.auto_sort = True
585
            self._sort_key = 'cpu_percent'
586
        else:
587
            self.auto_sort = auto
588
            self._sort_key = key
589
590
    def nice_decrease(self, pid):
591
        """Decrease nice level
592
        On UNIX this is a number which usually goes from -20 to 20.
593
        The higher the nice value, the lower the priority of the process."""
594
        p = psutil.Process(pid)
595
        try:
596
            p.nice(p.nice() - 1)
597
            logger.info(f'Set nice level of process {pid} to {p.nice()} (higher the priority)')
598
        except psutil.AccessDenied:
599
            logger.warning(f'Can not decrease (higher the priority) the nice level of process {pid} (access denied)')
600
601
    def nice_increase(self, pid):
602
        """Increase nice level
603
        On UNIX this is a number which usually goes from -20 to 20.
604
        The higher the nice value, the lower the priority of the process."""
605
        p = psutil.Process(pid)
606
        try:
607
            p.nice(p.nice() + 1)
608
            logger.info(f'Set nice level of process {pid} to {p.nice()} (lower the priority)')
609
        except psutil.AccessDenied:
610
            logger.warning(f'Can not increase (lower the priority) the nice level of process {pid} (access denied)')
611
612
    def kill(self, pid, timeout=3):
613
        """Kill process with pid"""
614
        assert pid != os.getpid(), "Glances can kill itself..."
615
        p = psutil.Process(pid)
616
        logger.debug(f'Send kill signal to process: {p}')
617
        p.kill()
618
        return p.wait(timeout)
619
620
621
def weighted(value):
622
    """Manage None value in dict value."""
623
    return -float('inf') if value is None else value
624
625
626
def _sort_io_counters(process, sorted_by='io_counters', sorted_by_secondary='memory_percent'):
627
    """Specific case for io_counters
628
629
    :return: Sum of io_r + io_w
630
    """
631
    return process[sorted_by][0] - process[sorted_by][2] + process[sorted_by][1] - process[sorted_by][3]
632
633
634
def _sort_cpu_times(process, sorted_by='cpu_times', sorted_by_secondary='memory_percent'):
635
    """Specific case for cpu_times
636
637
    Patch for "Sorting by process time works not as expected #1321"
638
    By default PsUtil only takes user time into account
639
    see (https://github.com/giampaolo/psutil/issues/1339)
640
    The following implementation takes user and system time into account
641
    """
642
    return process[sorted_by][0] + process[sorted_by][1]
643
644
645
def _sort_lambda(sorted_by='cpu_percent', sorted_by_secondary='memory_percent'):
646
    """Return a sort lambda function for the sorted_by key"""
647
    ret = None
648
    if sorted_by == 'io_counters':
649
        ret = _sort_io_counters
650
    elif sorted_by == 'cpu_times':
651
        ret = _sort_cpu_times
652
    return ret
653
654
655
def sort_stats(stats, sorted_by='cpu_percent', sorted_by_secondary='memory_percent', reverse=True):
656
    """Return the stats (dict) sorted by (sorted_by).
657
    A secondary sort key should be specified.
658
659
    Reverse the sort if reverse is True.
660
    """
661
    if sorted_by is None and sorted_by_secondary is None:
662
        # No need to sort...
663
        return stats
664
665
    # Check if a specific sort should be done
666
    sort_lambda = _sort_lambda(sorted_by=sorted_by, sorted_by_secondary=sorted_by_secondary)
667
668
    if sort_lambda is not None:
669
        # Specific sort
670
        try:
671
            stats.sort(key=sort_lambda, reverse=reverse)
672
        except Exception:
673
            # If an error is detected, fallback to cpu_percent
674
            stats.sort(
675
                key=lambda process: (weighted(process['cpu_percent']), weighted(process[sorted_by_secondary])),
676
                reverse=reverse,
677
            )
678
    else:
679
        # Standard sort
680
        try:
681
            stats.sort(
682
                key=lambda process: (weighted(process[sorted_by]), weighted(process[sorted_by_secondary])),
683
                reverse=reverse,
684
            )
685
        except (KeyError, TypeError):
686
            # Fallback to name
687
            stats.sort(key=lambda process: process['name'] if process['name'] is not None else '~', reverse=False)
688
689
    return stats
690
691
692
glances_processes = GlancesProcesses()
693