-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocno.py
2698 lines (2288 loc) · 111 KB
/
procno.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""
Procno: Process monitor and notifications forwarder
===================================================
A GUI procfs stat viewer with Freedesktop-Notifications forwarding. Kind of like ``top``, but not as we know it.
Usage:
======
procno [-h]
[--about] [--detailed-help]
[--install] [--uninstall]
Optional arguments:
-------------------
-h, --help show this help message and exit
--detailed-help full help in markdown format
--about about procno
--install installs the procno in the current user's path and desktop application menu.
--uninstall uninstalls the procno application menu file and script for the current user.
Description
===========
``Procno`` is a GUI ``procfs`` process stat monitoring tool. Procno can can warn of processes consuming
excessive CPU or memory by raising *Freedesktop DBUS Notifications* (most linux desktop environments present
DBUS Notifications as popup messages). Procno's UI functions as follows:
* All the processes on the system are represented by dots.
* The static dot coloring is specific to the process owner (all the light grey processes belong to root).
* If a process consumes a little CPU (<10%) its dot will briefly light up in blue.
* If a process consumes a lot of CPU its dot will vary from lighter pinkish-red to full-red depending on how much
CPU it is consuming.
* If a dot briefly enlarges or decreases in size, the process's resident set size has gone up or down.
* Each process dot is augmented with a dashed-ring that indicates the processes resident set size as proportion of RAM.
* If text is entered in the search field (for example nmb), any process with matching text is circled in red
(this happens dynamically, so new matching processes will be circled when they start). Text search becomes
incremental once more than three characters have been entered.
* Hovering over a dot brings up a tooltip containing process details.
* Clicking on a dot brings up a small dialog with process details that update dynamically. The dialog
includes an arming switch (a checkbox) that arms a signal dropdown which can be used to signal/terminate
the process.
* If a process consumes too much CPU or RSS for too long, a desktop notification will be raised. The notification
will continue to update as long as the process continues to offend. If the notification is closed, no
no further notifications will be raised while the process continues to offend. When a processed ceases
to offend its notification status is reset, any subsequent offending will result in fresh notifications.
* Procno can optionally run out of the system tray. Geometry and configuration is preserved
across restarts. Procno dynamically adjusts to light and dark desktop themes.
* The mouse wheel zooms the view.
Procno is designed to increase awareness of background activity. Possibilities for it use include:
* Detecting runaway processes, either CPU or RAM.
* Getting a quick overview of where resources are going.
* Looking for patterns in resource consumption.
* Identifying unnecessary services that are present and idle.
* Entertaining the cat.
Optional metrics
----------------
Procno can optionally report some other process metrics:
* USS: unique set size, this should more accurately reflect memory consumption, but it appears to be
very expensive to collect, procno's CPU consumption jumps from around 8% to 50% if USS stats
are enabled. In respect to my own desktop, RSS is pretty similar to USS for the applications
that consume the bulk of most memory. Another issue with USS is that access to USS is limited,
USS will only be shown for your own processes.
* Shared memory: this is inexpensive to report but is not confined to RSS or USS, so may not be
a good indicator of pressure on the system.
* I/O: this is a basic indicator of whether read/write occurred in the last period. Most processes
are continually doing some amount of I/O, so perhaps this is not that useful, although a
continuous-on indicator may be an indication of pressure in some circumstances. Access to
I/O read/write counts is restricted, I/O indicators will only be shown for your own processes.
Experimentation notification options
------------------------------------
The follow options excercise facilities defined in the
[Desktop Notifications Specification](https://specifications.freedesktop.org/notification-spec/latest/)
(https://specifications.freedesktop.org/notification-spec/latest/)
Some Linux desktops claim to support many of these features, but quite often the implementations are
buggy or divergent from behaviour specified in the standard.
If the following two options fail to work as expected, it is almost certainly a defect in your
desktop's support of the standard. Any bugs raised should be directed to the desktop project concerned
and not the procno application.
* notification_updates_enabled: if a desktop supports updatable notifications, notifications
will be updated as the incident continues. On some desktops this can be buggy, for example
on KDE/Plasma the desktop sometimes loses track of existing notifications leading to multiple
notifications appearing instead of one (a logout may correct the problem).
* notification_actions_enabled: an Info button will be added to notifications, when pressed it
should callback the application to popup info on the incident's subject process. On some
desktops this too is buggy, and causes even more problems when combined with notification
updates.
Despite the results being buggy, I've left the options available, partly as a reference-implementation,
and partly in the hope that desktops support of these features may improve in time.
Config files
------------
All settings made in the *Configuration* panel are saved to a config file. There is no need to manually
edit the config file, but if it is externally edited the application will automatically reload the changes.
The config file is in INI-format divided into a number of sections as outlined below::
```
# The options section controls notice timeouts, burst treatment
[options]
# Polling interval, how often to wait for journal entries between checking for config changes
poll_seconds = 2
# Run out of the system tray
system_tray_enabled = yes
# Start the application with notifications enabled (disable notifications from start up).
start_with_notifications_enabled = yes
# For debugging the application
debug_enabled = yes
```
The config file is normally save to a standard desktop location:
$HOME/.config/procno/procno.conf
In addition to the application config file, window geometry and state is saved to:
$HOME/.config/procno.qt.state/procno.conf
Prerequisites
=============
All the following runtime dependencies are likely to be available pre-packaged on any modern Linux distribution
(``procno`` was originally developed on OpenSUSE Tumbleweed).
* python 3.8: ``procno`` is written in python and may depend on some features present only in 3.8 onward.
* python 3.8 QtPy: the python GUI library used by ``procno``.
* python 3.8 psutils: the library used to gather the data (often preinstalled in many Linux systems)
* python 3.8 dbus: python module for dbus used for issuing notifications
Dependency installation on ``OpenSUSE``:
zypper install python38-QtPy python38-dbus
Optional Accessories
====================
A suggested accessory is [KDE Connect](https://kdeconnect.kde.org/). If you enabled the appropriate permissions on
your phone, KDE Connect can forward desktop notifications to the phone. Use procno to forward Systemd-Journal
messages to Desktop-Notifications, and use KDE Connect to forward them to your phone.
Debugging Tools
===============
* dbus-monitor --session interface=org.freedesktop.Notifications
* d-feet
* gdbus monitor --session --dest org.freedesktop.Notifications
Procno Copyright (C) 2021 Michael Hamilton
===========================================
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, version 3.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along
with this program. If not, see <https://www.gnu.org/licenses/>.
**Contact:** m i c h a e l @ a c t r i x . g e n . n z
----------
"""
# TODO IO
# TODO vsize ring?
# TODO random color suggestion button
# TODO make the random color picker pick colors distant from the last pick - maybe feed it an invert of the last pick.
# TODO input validation (more)
# TODO zoom in should do more than just enlarge - annotate?
# TODO Help
# TODO night palette option?
# TODO try a brighter less-pastel palette
#
import argparse
import configparser
import math
import os
import pwd
import random
import re
import signal
import stat
import sys
import textwrap
import time
import traceback
from datetime import timedelta
from html import escape
from io import StringIO
from pathlib import Path
from typing import Mapping, List, Type, Callable, Tuple
import dbus
import psutil
from PyQt5.QtCore import QCoreApplication, QProcess, Qt, pyqtSignal, QThread, QSize, \
QEvent, QSettings, QObject, QRegExp, QRect
from PyQt5.QtGui import QPixmap, QIcon, QImage, QPainter, QIntValidator, \
QFontDatabase, QCloseEvent, QPalette, QColor, QPen, QMouseEvent, QWheelEvent, QResizeEvent, \
QRegExpValidator, QGuiApplication
from PyQt5.QtSvg import QSvgRenderer
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QMessageBox, QLineEdit, QLabel, \
QPushButton, QSystemTrayIcon, QMenu, QTextEdit, QDialog, QCheckBox, QGridLayout, QMainWindow, QSizePolicy, QToolBar, \
QHBoxLayout, QStyleFactory, QToolButton, QScrollArea, QLayout, QStatusBar, QToolTip, QComboBox, QTabWidget, \
QColorDialog
from dbus.mainloop.glib import DBusGMainLoop
PROGRAM_VERSION = '1.2.9'
# On Plasma Wayland the system tray may not be immediately available at login - so keep trying for...
SYSTEM_TRAY_WAIT_SECONDS = 20
def get_program_name() -> str:
return Path(sys.argv[0]).stem
ABOUT_TEXT = f"""
<b>Procno version {PROGRAM_VERSION}</b>
<p>
A Systemd-process viewer with Freedesktop-Notifications forwarding.
<p>
Visit <a href="https://github.com/digitaltrails/{get_program_name()}">https://github.com/digitaltrails/{get_program_name()}</a> for
more details.
<p><p>
<b>Procno Copyright (C) 2021 Michael Hamilton</b>
<p>
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, version 3.
<p>
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
<p>
You should have received a copy of the GNU General Public License along
with this program. If not, see <a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>.
"""
DEFAULT_CONFIG = '''
[options]
poll_seconds = 1
debug_enabled = yes
system_tray_enabled = no
notification_seconds = 30
start_with_notifications_enabled = yes
notify_cpu_use_percent = 100
notify_cpu_use_seconds = 30
notify_rss_exceeded_mbytes = 1000
notify_rss_growing_seconds = 5
io_indicators_enabled = no
uss_enabled = no
shared_enabled = no
tree_enabled = no
[colors]
cpu_activity_color = 0x3491e1
new_process_color = 0xf8b540
search_match_color = 0x00aa00
root_user_color = 0xd2d2d2
'''
ERROR_DBUS_NOTIFICATIONS_UNAVAILABLE = "DBUS notification service unavailable"
ERROR_DBUS_NOTIFICATION_FAILED = "DBUS notification failed"
ICON_HELP_ABOUT = "help-about"
ICON_HELP_CONTENTS = "help-contents"
ICON_APPLICATION_EXIT = "application-exit"
ICON_CONTEXT_MENU_LISTENING_ENABLE = "view-refresh"
ICON_CONTEXT_MENU_LISTENING_DISABLE = "process-stop"
SVG_TRAY_LISTENING_DISABLED = ICON_CONTEXT_MENU_LISTENING_DISABLE
ICON_COPY_TO_CLIPBOARD = "edit-copy"
ICON_UNDOCK = "window-new"
ICON_DOCK = "view-restore"
ICON_GO_NEXT = "go-down"
ICON_GO_PREVIOUS = "go-up"
ICON_CLEAR_RECENTS = "edit-clear-all"
ICON_DEFAULTS = 'edit-reset'
ICON_REVERT = 'edit-undo'
# This might only be KDE/Linux icons - not in Freedesktop Standard.
ICON_APPLY = "dialog-ok-apply"
ICON_VIEW_PROCESS_ENTRY = 'view-fullscreen'
ICON_CLEAR_SELECTION = 'edit-undo'
ICON_COPY_SELECTED = 'edit-copy'
ICON_PLAIN_TEXT_SEARCH = 'insert-text'
ICON_REGEXP_SEARCH = 'list-add'
ICON_SETTINGS_CONFIGURE = 'settings-configure'
ICON_SEARCH_PROCESSES = "system-search"
SVG_LIGHT_THEME_COLOR = b"#232629"
SVG_DARK_THEME_COLOR = b"#f3f3f3"
SVG_PROGRAM_ICON = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<circle cx="5" cy="5" r="2" fill="#3491e1"/>
<circle cx="10" cy="5" r="2" fill="#3491e1"/>
<circle cx="15" cy="5" r="2" fill="#da4453"/>
<circle cx="5" cy="10" r="2" fill="#3491e1"/>
<circle cx="10" cy="10" r="2" fill="#3491e1"/>
<circle cx="15" cy="10" r="2" fill="#3491e1"/>
<circle cx="5" cy="15" r="2" fill="#3491e1"/>
<circle cx="10" cy="15" r="2" fill="#3491e1"/>
<circle cx="15" cy="15" r="2" fill="#3491e1"/>
</svg>"""
SVG_PROGRAM_ICON_LIGHT = SVG_PROGRAM_ICON.replace(SVG_LIGHT_THEME_COLOR, b'#bbbbbb')
SVG_TOOLBAR_RUN_DISABLED = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#232629;
}
</style>
<path d="m3 3v16l16-8z" class="ColorScheme-Text" fill="currentColor"/>
</svg>
"""
SVG_TOOLBAR_RUN_ENABLED = SVG_TOOLBAR_RUN_DISABLED.replace(b"#232629;", b"#3daee9;")
SVG_TOOLBAR_STOP = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#da4453;
}
</style>
<path d="m3 3h16v16h-16z" class="ColorScheme-Text" fill="currentColor"/>
</svg>
"""
SVG_TRAY_LISTENING_DISABLED = SVG_PROGRAM_ICON.replace(b'3491e1', b'ff0000')
SVG_TOOLBAR_HAMBURGER_MENU = b"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#232629;
}
</style>
</defs>
<path
style="fill:currentColor;fill-opacity:1;stroke:none"
d="m3 5v2h16v-2h-16m0 5v2h16v-2h-16m0 5v2h16v-2h-16" class="ColorScheme-Text" />
</svg>
"""
SVG_TOOLBAR_NOTIFIER_ENABLED = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#379fd3;
}
</style>
</defs>
<path style="fill:currentColor;fill-opacity:1;stroke:none"
d="M 3 4 L 3 16 L 6 20 L 6 17 L 6 16 L 19 16 L 19 4 L 3 4 z M 4 5 L 18 5 L 18 15 L 4 15 L 4 5 z M 16 6 L 9.5 12.25 L 7 10 L 6 11 L 9.5 14 L 17 7 L 16 6 z "
class="ColorScheme-Text"
/>
</svg>
"""
SVG_TOOLBAR_NOTIFIER_DISABLED = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<defs id="defs3051">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#da4453;
}
</style>
</defs>
<path style="fill:currentColor;fill-opacity:1;stroke:none"
d="M 3 4 L 3 16 L 6 20 L 6 17 L 6 16 L 19 16 L 19 4 L 3 4 z M 4 5 L 18 5 L 18 15 L 4 15 L 4 5 z M 8 6 L 7 7 L 10 10 L 7 13 L 8 14 L 11 11 L 14 14 L 15 13 L 12 10 L 15 7 L 14 6 L 11 9 L 8 6 z "
class="ColorScheme-Text"
/>
</svg>
"""
SVG_COLOR_SWATCH = b"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 22">
<style type="text/css" id="current-color-scheme">
.ColorScheme-Text {
color:#000000;
}
</style>
<path d="m3 3h16v16h-16z" class="ColorScheme-Text" fill="currentColor"/>
</svg>
"""
system_boot_time = psutil.boot_time()
system_vm_bytes = psutil.virtual_memory().total
system_ticks_per_second = os.sysconf(os.sysconf_names['SC_CLK_TCK'])
def tr(source_text: str):
"""For future internationalization - recommended way to do this at this time."""
return QCoreApplication.translate('procno', source_text)
class ConfigOption:
def __init__(self, option_id: str, tooltip: str, int_range: Tuple[int, int] = None):
self.option_id = option_id
self.int_range = int_range
self._tooltip = tooltip
def label(self):
return tr(self.option_id).replace('_', ' ').capitalize()
def tooltip(self):
fmt = tr(self._tooltip)
return fmt.format(self.int_range[0], self.int_range[1]) if self.int_range is not None else fmt
CONFIG_OPTIONS_LIST: List[ConfigOption] = [
ConfigOption('poll_seconds', tr('How often to poll for new messages ({}..{} seconds).'), (1, 30)),
ConfigOption('notification_seconds',
tr('How long should a desktop notification remain visible, zero for no timeout ({}..{} seconds)'),
(0, 60)),
ConfigOption('notify_cpu_use_percent',
tr('Processes CPU consumption threshold ({}..{} percent)'),
(0, 900)),
ConfigOption('notify_cpu_use_seconds',
tr('Notify if a process stays above the CPU threshold for this amount of time ({}..{} seconds)'),
(0, 300)),
ConfigOption('notify_rss_exceeded_mbytes',
tr('Process rss consumption threshold (1..100000 Mbytes)'),
(1, 100_000)),
ConfigOption('notify_rss_growing_seconds',
tr('Notify if a process rss continues to grow above the threshold for this amount of time ({}..{} '
'seconds)'),
(0, 60)),
ConfigOption('system_tray_enabled', tr('procno should start minimised in the system-tray.')),
ConfigOption('start_with_notifications_enabled', tr('procno should start with desktop notifications enabled.')),
ConfigOption('io_indicators_enabled',
tr("Show read/write indicators\n(not available for other user's processes).")),
ConfigOption('uss_enabled', tr("Show USS - Unique SS - obtaining USS is expensive CPU wise\n"
"(not available for other user's processes).")),
ConfigOption('shared_enabled', tr("Show potentially shared.")),
ConfigOption('notification_updates_enabled',
tr("Update existing notifications with new info (if supported by desktop, buggy on some desktops).")),
ConfigOption('notification_actions_enabled',
tr("Info button on notifications (if supported by desktop, buggy on some desktops, buggy on some "
"desktops when combined with update notifications).")),
ConfigOption('tree_enabled', tr("Festive layout.")),
ConfigOption('debug_enabled', tr('Enable extra debugging output to standard-out.')),
]
io_indicators_enabled = False
uss_enabled = False
shared_enabled = False
debugging = True
def debug(*arg):
if debugging:
print('DEBUG:', *arg)
def info(*arg):
print('INFO:', *arg)
def warning(*arg):
print('WARNING:', *arg)
def error(*arg):
print('ERROR:', *arg)
def random_color(mix, seed: int = None):
if seed:
random.seed(seed)
# https://newbedev.com/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette
# Changed 127 to 168 to make the colors lighter
red = random.randint(168, 256)
green = random.randint(168, 256)
blue = random.randint(168, 256)
# mix the color
if mix is not None:
red = (red + mix[0]) // 2
green = (green + mix[1]) // 2
blue = (blue + mix[2]) // 2
return red, green, blue
def exception_handler(e_type, e_value, e_traceback):
"""Overarching error handler in case something unexpected happens."""
error("\n", ''.join(traceback.format_exception(e_type, e_value, e_traceback)))
alert = QMessageBox()
alert.setText(tr('Error: {}').format(''.join(traceback.format_exception_only(e_type, e_value))))
alert.setInformativeText(tr('Unexpected error'))
alert.setDetailedText(
tr('Details: {}').format(''.join(traceback.format_exception(e_type, e_value, e_traceback))))
alert.setIcon(QMessageBox.Critical)
alert.exec()
QApplication.quit()
def install_as_desktop_application(uninstall: bool = False):
"""Self install this script in the current Linux user's bin directory and desktop applications->settings menu."""
desktop_dir = Path.home().joinpath('.local', 'share', 'applications')
icon_dir = Path.home().joinpath('.local', 'share', 'icons')
if not desktop_dir.exists():
warning("creating:{desktop_dir.as_posix()}")
os.mkdir(desktop_dir)
bin_dir = Path.home().joinpath('bin')
if not bin_dir.is_dir():
warning("creating:{bin_dir.as_posix()}")
os.mkdir(bin_dir)
if not icon_dir.is_dir():
warning("creating:{icon_dir.as_posix()}")
os.mkdir(icon_dir)
installed_script_path = bin_dir.joinpath("procno")
desktop_definition_path = desktop_dir.joinpath("procno.desktop")
icon_path = icon_dir.joinpath("procno.png")
if uninstall:
os.remove(installed_script_path)
info(f'removed {installed_script_path.as_posix()}')
os.remove(desktop_definition_path)
info(f'removed {desktop_definition_path.as_posix()}')
os.remove(icon_path)
info(f'removed {icon_path.as_posix()}')
return
if installed_script_path.exists():
warning(f"skipping installation of {installed_script_path.as_posix()}, it is already present.")
else:
source = open(__file__).read()
source = source.replace("#!/usr/bin/python3", '#!' + sys.executable)
info(f'creating {installed_script_path.as_posix()}')
open(installed_script_path, 'w').write(source)
info(f'chmod u+rwx {installed_script_path.as_posix()}')
os.chmod(installed_script_path, stat.S_IRWXU)
if desktop_definition_path.exists():
warning(f"skipping installation of {desktop_definition_path.as_posix()}, it is already present.")
else:
info(f'creating {desktop_definition_path.as_posix()}')
desktop_definition = textwrap.dedent(f"""
[Desktop Entry]
Type=Application
Exec={installed_script_path.as_posix()}
Name=procno
GenericName=procno
Comment=A process monitor with DBUS Freedesktop-Notifications. Like top, but not as we know it.
Icon={icon_path.as_posix()}
Categories=Qt;System;Monitor;System;
""")
open(desktop_definition_path, 'w').write(desktop_definition)
if icon_path.exists():
warning(f"skipping installation of {icon_path.as_posix()}, it is already present.")
else:
info(f'creating {icon_path.as_posix()}')
create_pixmap_from_svg_bytes(SVG_PROGRAM_ICON).save(icon_path.as_posix())
info('installation complete. Your desktop->applications->system should now contain procno')
def parse_args():
args = sys.argv[1:]
parser = argparse.ArgumentParser(
description="A process monitor.",
formatter_class=argparse.RawTextHelpFormatter)
parser.epilog = textwrap.dedent(f"""
""")
parser.add_argument('--detailed-help', default=False, action='store_true',
help='Detailed help (in markdown format).')
parser.add_argument('--debug', default=False, action='store_true', help='enable debug output to stdout')
parser.add_argument('--install', action='store_true',
help="installs the procno application in the current user's path and desktop application menu.")
parser.add_argument('--uninstall', action='store_true',
help='uninstalls the procno application menu file and script for the current user.')
parsed_args = parser.parse_args(args=args)
if parsed_args.install:
install_as_desktop_application()
sys.exit()
if parsed_args.uninstall:
install_as_desktop_application(uninstall=True)
sys.exit()
if parsed_args.detailed_help:
print(__doc__)
sys.exit()
def get_config_path() -> Path:
program_name = get_program_name()
config_dir_path = Path.home().joinpath('.config').joinpath(program_name)
if not config_dir_path.parent.is_dir() or not config_dir_path.is_dir():
os.makedirs(config_dir_path)
path = config_dir_path.joinpath(program_name + '.conf')
return path
class Config(configparser.ConfigParser):
def __init__(self):
super().__init__()
self.path = get_config_path()
debug("config=", self.path) if debugging else None
self.modified_time = 0.0
self.read_string(DEFAULT_CONFIG)
def save(self):
if self.path.exists():
self.path.rename(self.path.with_suffix('.bak'))
with self.path.open('w') as config_file:
self.write(config_file)
def refresh(self) -> bool:
if self.path.is_file():
modified_time = self.path.lstat().st_mtime
if self.modified_time == modified_time:
return False
self.modified_time = modified_time
info(f"Config: reading {self.path}")
config_text = self.path.read_text()
for section in ['colors', ]:
self.remove_section(section)
self.read_string(config_text)
for section in ['options', 'colors', ]:
if section not in self:
self[section] = {}
global_colors.copy_from_config(self['colors'])
return True
if self.modified_time > 0.0:
info(f"Config file has been deleted: {self.path}")
self.modified_time = 0.0
return False
def is_different(self, other: 'Config'):
try:
io1 = StringIO()
self.write(io1)
io2 = StringIO()
other.write(io2)
return io1.getvalue() != io2.getvalue()
finally:
io1.close()
io2.close()
def is_dark_theme():
# Heuristic for checking for a dark theme.
# Is the sample text lighter than the background?
label = QLabel("am I in the dark?")
text_hsv_value = label.palette().color(QPalette.WindowText).value()
bg_hsv_value = label.palette().color(QPalette.Background).value()
dark_theme_found = text_hsv_value > bg_hsv_value
# debug(f"is_dark_them text={text_hsv_value} bg={bg_hsv_value} is_dark={dark_theme_found}") if debugging else None
return dark_theme_found
def create_image_from_svg_bytes(svg_str: bytes) -> QImage:
"""There is no QIcon option for loading QImage from a string, only from a SVG file, so roll our own."""
if is_dark_theme():
svg_str = svg_str.replace(SVG_LIGHT_THEME_COLOR, SVG_DARK_THEME_COLOR)
renderer = QSvgRenderer(svg_str)
image = QImage(64, 64, QImage.Format_ARGB32)
image.fill(0x0)
painter = QPainter(image)
renderer.render(painter)
painter.end()
return image
def create_pixmap_from_svg_bytes(svg_str: bytes) -> QPixmap:
"""There is no QIcon option for loading SVG from a string, only from a SVG file, so roll our own."""
image = create_image_from_svg_bytes(svg_str)
return QPixmap.fromImage(image)
def create_icon_from_svg_bytes(default_svg: bytes = None,
on_svg: bytes = None, off_svg: bytes = None,
disabled_svg: bytes = None) -> QIcon:
"""There is no QIcon option for loading SVG from a string, only from a SVG file, so roll our own."""
if default_svg is not None:
icon = QIcon(create_pixmap_from_svg_bytes(default_svg))
else:
icon = QIcon()
if on_svg is not None:
icon.addPixmap(create_pixmap_from_svg_bytes(on_svg), state=QIcon.On)
if off_svg is not None:
icon.addPixmap(create_pixmap_from_svg_bytes(off_svg), state=QIcon.Off)
if disabled_svg:
icon = QIcon(create_pixmap_from_svg_bytes(on_svg), mode=QIcon.Disabled)
return icon
def get_icon(source) -> QIcon:
# Consider caching icon loading - but icons are mutable and subject to theme changes,
# so perhaps that's asking for trouble.
if isinstance(source, str):
return QIcon.fromTheme(source)
if isinstance(source, bytes):
return create_icon_from_svg_bytes(source)
raise ValueError(f"get_icon parameter has unsupported type {type(source)} = {str(source)}")
class NotifyFreeDesktop:
NO_MORE_NOTIFICATIONS = -1
def __init__(self, action_request_handler: callable):
self.notify_interface = dbus.Interface(
object=dbus.SessionBus(mainloop=DBusGMainLoop(set_as_default=True)).get_object(
"org.freedesktop.Notifications",
"/org/freedesktop/Notifications"),
dbus_interface="org.freedesktop.Notifications")
self.message_id_map: Mapping[int, object] = {}
self.capabilities = [str(cap) for cap in self.notify_interface.GetCapabilities()]
self.supports_persistence = 'persistence' in self.capabilities
# Persistence and actions together don't seem to always play well - can corrupt the DBUS notifications service.
self.supports_actions = not self.supports_persistence and 'actions' in self.capabilities
self.supports_actions = 'actions' in self.capabilities
debug('notify_interface.GetCapabilities', self.capabilities)
def notification_closed_handler(*args, **kwargs):
message_id = args[0]
debug('notification_closed_handler', message_id)
if message_id in self.message_id_map:
debug("close for message_id", message_id)
del self.message_id_map[message_id]
def notification_action_invoked_handler(*args, **kwargs):
message_id = args[0]
debug('notification_action_invoked_handler', message_id)
if message_id in self.message_id_map:
action_id = args[1]
debug("action for message_id", message_id, action_id)
action_request_handler(action_id, self.message_id_map[message_id])
self.notify_interface.connect_to_signal("NotificationClosed", notification_closed_handler)
self.notify_interface.connect_to_signal("ActionInvoked", notification_action_invoked_handler)
def notify_desktop(self, app_name: str, summary: str, message: str,
timeout: int, replace_id: int = 0, action_requests=[], context: object = None) -> int:
if self.notify_interface is None:
return -1
# https://specifications.freedesktop.org/notification-spec/notification-spec-latest.html
notification_icon = 'dialog-error'
# extra_hints = {"urgency": 1, "sound-name": "dialog-warning", }
# Urgency of 2 cannot time out.
extra_hints = {"urgency": '2'}
if replace_id != 0:
if not self.supports_persistence:
# No persistence, do not update the existing message (it will probably just generate a duplicate)
return NotifyFreeDesktop.NO_MORE_NOTIFICATIONS
if replace_id not in self.message_id_map:
# user has dismissed this message, do not update a message which no longer exists
return NotifyFreeDesktop.NO_MORE_NOTIFICATIONS
if len(action_requests) > 0 and not self.supports_actions:
action_requests = []
message_id = self.notify_interface.Notify(app_name,
replace_id,
notification_icon,
escape(summary).encode('UTF-8'),
escape(message).encode('UTF-8'),
action_requests,
extra_hints,
timeout)
debug("notification_id ", message_id, "replace_id", replace_id)
self.message_id_map[message_id] = context
return message_id
class ProcessInfo:
def __init__(self, process: psutil.Process, new_process: bool):
self.last_update = time.time()
self.pid = process.pid
self.real_uid, self.effective_uid, _ = process.uids()
try:
self.cmdline = process.cmdline()
except psutil.ZombieProcess:
self.cmdline = "(zombie)"
self.comm = process.name()
cpu_times = process.cpu_times()
self.utime = cpu_times.user
self.stime = cpu_times.system
self.rss = process.memory_info().rss
self.start_time = time.localtime(process.create_time())
self.start_time_text = time.strftime("%Y-%m-%d %H:%M:%S", self.start_time)
self.end_time_text = None
self.cpu_diff = 0
self.rss_diff = 0
self.current_cpu_percent = 0.0
self.read_count = 0
self.write_count = 0
self.read_diff = 0
self.write_diff = 0
self.uss = 0
self.shared = 0
self.io_accessible = True
if io_indicators_enabled:
self.read_count, self.write_count = self.access_io_counters(process)
self.uss_accessible = True
if uss_enabled:
self.uss = self.access_uss(process)
self.new_process = new_process
self.cpu_burn_seconds = 0
self.rss_growing_seconds = 0
self.incidents = {}
self.rss_current_percent_of_system_vm = 100.0 * self.rss / system_vm_bytes
try:
self.username = pwd.getpwuid(int(self.real_uid)).pw_name
if self.effective_uid != self.real_uid:
self.effective_username = pwd.getpwuid(int(self.effective_uid)).pw_name
else:
self.effective_username = None
except KeyError:
self.username = '<no name>'
self.effective_username = None
self.user_color = None
self.alive = True
self.psutil_process = process
def updated(self, process: psutil.Process, cpu_burn_ratio, rss_exceeded_mbytes):
# Trying to be frugal, not copying to a new ProcInfo, might mean the GUI sees the object as it's
# being updated - no great sin?
self.new_process = False
now = time.time()
elapsed_seconds = now - self.last_update
self.last_update = now
cpu_times = process.cpu_times()
utime = cpu_times.user
stime = cpu_times.system
cpu_diff = (utime + stime) - (self.utime + self.stime)
rss = process.memory_info().rss
rss_diff = rss - self.rss
self.utime = utime
self.stime = stime
self.rss = rss
self.cpu_diff = cpu_diff
self.read_diff = 0
self.write_diff = 0
if shared_enabled:
self.shared = process.memory_info().shared
if uss_enabled and self.uss_accessible:
self.uss = self.access_uss(process)
if io_indicators_enabled and self.io_accessible:
read_count, write_count = self.access_io_counters(process)
self.read_diff = read_count - self.read_count
self.write_diff = write_count - self.write_count
self.read_count = read_count
self.write_count = write_count
# Don't do unnecessary expensive math - this is called a lot.
self.current_cpu_percent = 0.0 if cpu_diff == 0 else math.ceil(100.0 * cpu_diff / elapsed_seconds)
# if self.current_cpu_percent > 95:
# print(self.pid, self.current_cpu_percent, cpu_diff / system_ticks_per_second, elapsed_seconds)
if self.current_cpu_percent >= cpu_burn_ratio:
self.cpu_burn_seconds += elapsed_seconds
else:
self.cpu_burn_seconds = 0
self.rss_diff = rss_diff
# Don't do unnecessary expensive math - this is called a lot.
if self.rss_diff != 0:
self.rss_current_percent_of_system_vm = 100.0 * self.rss / system_vm_bytes
if rss_diff > 0 and rss > rss_exceeded_mbytes * 1_000_000:
self.rss_growing_seconds += elapsed_seconds
else:
self.rss_growing_seconds = 0
return self
def access_io_counters(self, process):
try:
io_counters = process.io_counters()
return io_counters.read_count, io_counters.write_count
except psutil.AccessDenied:
self.io_accessible = False
return 0, 0
def access_uss(self, process):
try:
return process.memory_full_info().uss
except psutil.AccessDenied:
self.uss_accessible = False
return 0
def text(self, compact: bool = False):
cmdline_text = str(self.cmdline)
if compact and len(cmdline_text) > 30:
cmdline_text = cmdline_text[0:30] + '..'
report_io = io_indicators_enabled and (self.read_count > 0 or self.write_count > 0)
finished = ' \u25b7Finished\u25c1' if not self.alive else ''
return \
f"PID: {self.pid}{finished}\ncomm: {self.comm}\n" \
f"cmdline: {cmdline_text}\n" + \
f"CPU: {self.current_cpu_percent:2.0f}% utime: {self.utime} stime: {self.stime}\n" + \
f"RSS/MEM: {self.rss_current_percent_of_system_vm:5.2f}% rss: {self.rss / 1_000_000:.3f} Mbytes\n" + \
(f"USS: {self.uss}\n" if uss_enabled else '') + \
(f"Shared: {self.shared}\n" if shared_enabled else '') + \
(f"Reads: {self.read_count} Writes: {self.write_count}\n" if report_io else '') + \
f"Started: {self.start_time_text}\n" + \
(f"Finished {self.end_time_text}\n" if not self.alive else '') + \
f"Real_UID: {self.real_uid} User={self.username}" + \
('' if self.effective_uid == self.real_uid else f"\nEffective_UID: {self.effective_uid}") + \
('' if self.effective_username is None else f" Effective_User={self.effective_username}")
def __str__(self):
return self.text()
class GenericIncident:
def __init__(self, watcher: "ProcessWatcher", proc_info: ProcessInfo):
self.proc_info = proc_info
self.short_name = self.proc_info.comm if self.proc_info.comm != '' else self.proc_info.cmdline
if len(self.short_name) > 20:
self.short_name = self.short_name[0:18] + '..'
self.duration_seconds = 0.0
self.watcher = watcher
self.incident_notification_suppressed = False
self.start_time = time.strftime('%Y-%m-%d %H:%M:%S')
self.ceased = False
self.notify_id = 0
self.title_cause = None
self.summary_cause = None
self.message_cause = None
def incident_type(self):
pass
def format_state(self):
return tr("finished") if not self.proc_info.alive else (tr("ongoing") if not self.ceased else tr("ceased"))
def format_notification(self) -> (str, str, str):
pass
def update(self, duration_seconds: int):
self.duration_seconds = duration_seconds
class CpuBurnIncident(GenericIncident):
def __init__(self, watcher: "ProcessWatcher", proc_info: ProcessInfo):
super().__init__(watcher, proc_info)
def format_notification(self) -> (str, str, str):
app_name = "\u25b3 CPU consumption [{}]".format(self.short_name)
summary = tr("\u25b6PID={} [{}] High CPU consumption.").format(self.proc_info.pid, self.short_name)
message = tr(
"CPU > {:.0f}% for {:.0f} seconds ({}).\npid={}\ncomm={}\ncmdline={}\nIncident started at {}").format(
self.watcher.notify_cpu_use_percent,
self.duration_seconds,
self.format_state(),
self.proc_info.pid,
self.proc_info.comm,
' '.join(self.proc_info.cmdline),
self.start_time)
return app_name, summary, message
class RssGrowingIncident(GenericIncident):
def __init__(self, watcher: "ProcessWatcher", proc_info: ProcessInfo):
super().__init__(watcher, proc_info)
def format_notification(self) -> (str, str, str):
app_name = "\u25b3 rss growth [{}]".format(self.short_name)
# \U0001F4C8
summary = tr("\u25b6PID={} [{}] High rss growth.").format(self.proc_info.pid, self.short_name)
message = tr(
"rss has been growing for {:.0f} seconds ({})\nRSS={:.0f} Mbytes. {:0.1f}% of memory\n"
"pid={}\ncomm={}\ncmdline={}\nIncident started at {}").format(
self.duration_seconds,
self.format_state(),
self.proc_info.rss / 1_000_000.0,