-
Notifications
You must be signed in to change notification settings - Fork 0
/
systemctl3.py
executable file
·6808 lines (6731 loc) · 295 KB
/
systemctl3.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
# type hints are provided in 'types/systemctl3.pyi'
from __future__ import print_function
import threading
import grp
import pwd
import hashlib
import select
import fcntl
import string
import datetime
import socket
import time
import signal
import sys
import os
import errno
import collections
import shlex
import fnmatch
import re
from types import GeneratorType
__copyright__ = "(C) 2016-2023 Guido U. Draheim, licensed under the EUPL"
__version__ = "1.5.7113"
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
# |
import logging
logg = logging.getLogger("systemctl")
if sys.version[0] == '3':
basestring = str
xrange = range
DEBUG_AFTER = False
DEBUG_STATUS = False
DEBUG_BOOTTIME = False
DEBUG_INITLOOP = False
DEBUG_KILLALL = False
DEBUG_FLOCK = False
DebugPrintResult = False
TestListen = False
TestAccept = False
HINT = (logging.DEBUG + logging.INFO) // 2
NOTE = (logging.WARNING + logging.INFO) // 2
DONE = (logging.WARNING + logging.ERROR) // 2
logging.addLevelName(HINT, "HINT")
logging.addLevelName(NOTE, "NOTE")
logging.addLevelName(DONE, "DONE")
def logg_debug_flock(format, *args):
if DEBUG_FLOCK:
logg.debug(format, *args) # pragma: no cover
def logg_debug_after(format, *args):
if DEBUG_AFTER:
logg.debug(format, *args) # pragma: no cover
NOT_A_PROBLEM = 0 # FOUND_OK
NOT_OK = 1 # FOUND_ERROR
NOT_ACTIVE = 2 # FOUND_INACTIVE
NOT_FOUND = 4 # FOUND_UNKNOWN
# defaults for options
_extra_vars = []
_force = False
_full = False
_log_lines = 0
_no_pager = False
_now = False
_no_reload = False
_no_legend = False
_no_ask_password = False
_preset_mode = "all"
_quiet = False
_root = ""
_unit_type = None
_unit_state = None
_unit_property = None
_what_kind = ""
_show_all = False
_user_mode = False
# common default paths
_system_folder1 = "/etc/systemd/system"
_system_folder2 = "/run/systemd/system"
_system_folder3 = "/var/run/systemd/system"
_system_folder4 = "/usr/local/lib/systemd/system"
_system_folder5 = "/usr/lib/systemd/system"
_system_folder6 = "/lib/systemd/system"
_system_folderX = None
_user_folder1 = "{XDG_CONFIG_HOME}/systemd/user"
_user_folder2 = "/etc/systemd/user"
_user_folder3 = "{XDG_RUNTIME_DIR}/systemd/user"
_user_folder4 = "/run/systemd/user"
_user_folder5 = "/var/run/systemd/user"
_user_folder6 = "{XDG_DATA_HOME}/systemd/user"
_user_folder7 = "/usr/local/lib/systemd/user"
_user_folder8 = "/usr/lib/systemd/user"
_user_folder9 = "/lib/systemd/user"
_user_folderX = None
_init_folder1 = "/etc/init.d"
_init_folder2 = "/run/init.d"
_init_folder3 = "/var/run/init.d"
_init_folderX = None
_preset_folder1 = "/etc/systemd/system-preset"
_preset_folder2 = "/run/systemd/system-preset"
_preset_folder3 = "/var/run/systemd/system-preset"
_preset_folder4 = "/usr/local/lib/systemd/system-preset"
_preset_folder5 = "/usr/lib/systemd/system-preset"
_preset_folder6 = "/lib/systemd/system-preset"
_preset_folderX = None
# standard paths
_dev_null = "/dev/null"
_dev_zero = "/dev/zero"
_etc_hosts = "/etc/hosts"
_rc3_boot_folder = "/etc/rc3.d"
_rc3_init_folder = "/etc/init.d/rc3.d"
_rc5_boot_folder = "/etc/rc5.d"
_rc5_init_folder = "/etc/init.d/rc5.d"
_proc_pid_stat = "/proc/{pid}/stat"
_proc_pid_status = "/proc/{pid}/status"
_proc_pid_cmdline= "/proc/{pid}/cmdline"
_proc_pid_dir = "/proc"
_proc_sys_uptime = "/proc/uptime"
_proc_sys_stat = "/proc/stat"
# default values
SystemCompatibilityVersion = 219
SysInitTarget = "sysinit.target"
SysInitWait = 5 # max for target
MinimumYield = 0.5
MinimumTimeoutStartSec = 4
MinimumTimeoutStopSec = 4
DefaultTimeoutStartSec = 90 # official value
DefaultTimeoutStopSec = 90 # official value
DefaultTimeoutAbortSec = 3600 # officially it none (usually larget than StopSec)
DefaultMaximumTimeout = 200 # overrides all other
DefaultRestartSec = 0.1 # official value of 100ms
DefaultStartLimitIntervalSec = 10 # official value
DefaultStartLimitBurst = 5 # official value
InitLoopSleep = 5
MaxLockWait = 0 # equals DefaultMaximumTimeout
DefaultPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
ResetLocale = ["LANG", "LANGUAGE", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY",
"LC_MESSAGES", "LC_PAPER", "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT",
"LC_IDENTIFICATION", "LC_ALL"]
LocaleConf="/etc/locale.conf"
DefaultListenBacklog=2
ExitWhenNoMoreServices = False
ExitWhenNoMoreProcs = False
DefaultUnit = os.environ.get("SYSTEMD_DEFAULT_UNIT", "default.target") # systemd.exe --unit=default.target
DefaultTarget = os.environ.get("SYSTEMD_DEFAULT_TARGET", "multi-user.target") # DefaultUnit fallback
# LogLevel = os.environ.get("SYSTEMD_LOG_LEVEL", "info") # systemd.exe --log-level
# LogTarget = os.environ.get("SYSTEMD_LOG_TARGET", "journal-or-kmsg") # systemd.exe --log-target
# LogLocation = os.environ.get("SYSTEMD_LOG_LOCATION", "no") # systemd.exe --log-location
# ShowStatus = os.environ.get("SYSTEMD_SHOW_STATUS", "auto") # systemd.exe --show-status
DefaultStandardInput=os.environ.get("SYSTEMD_STANDARD_INPUT", "null")
DefaultStandardOutput=os.environ.get("SYSTEMD_STANDARD_OUTPUT", "journal") # systemd.exe --default-standard-output
DefaultStandardError=os.environ.get("SYSTEMD_STANDARD_ERROR", "inherit") # systemd.exe --default-standard-error
EXEC_SPAWN = False
EXEC_DUP2 = True
REMOVE_LOCK_FILE = False
BOOT_PID_MIN = 0
BOOT_PID_MAX = -9
PROC_MAX_DEPTH = 100
EXPAND_VARS_MAXDEPTH = 20
EXPAND_KEEP_VARS = True
RESTART_FAILED_UNITS = True
ACTIVE_IF_ENABLED=False
TAIL_CMD = "/usr/bin/tail"
LESS_CMD = "/usr/bin/less"
CAT_CMD = "/usr/bin/cat"
# The systemd default was NOTIFY_SOCKET="/var/run/systemd/notify"
_notify_socket_folder = "{RUN}/systemd" # alias /run/systemd
_journal_log_folder = "{LOG}/journal"
SYSTEMCTL_DEBUG_LOG = "{LOG}/systemctl.debug.log"
SYSTEMCTL_EXTRA_LOG = "{LOG}/systemctl.log"
_default_targets = ["poweroff.target", "rescue.target", "sysinit.target", "basic.target", "multi-user.target", "graphical.target", "reboot.target"]
_feature_targets = ["network.target", "remote-fs.target", "local-fs.target", "timers.target", "nfs-client.target"]
_all_common_targets = ["default.target"] + _default_targets + _feature_targets
# inside a docker we pretend the following
_all_common_enabled = ["default.target", "multi-user.target", "remote-fs.target"]
_all_common_disabled = ["graphical.target", "resue.target", "nfs-client.target"]
target_requires = {"graphical.target": "multi-user.target", "multi-user.target": "basic.target", "basic.target": "sockets.target"}
_runlevel_mappings = {} # the official list
_runlevel_mappings["0"] = "poweroff.target"
_runlevel_mappings["1"] = "rescue.target"
_runlevel_mappings["2"] = "multi-user.target"
_runlevel_mappings["3"] = "multi-user.target"
_runlevel_mappings["4"] = "multi-user.target"
_runlevel_mappings["5"] = "graphical.target"
_runlevel_mappings["6"] = "reboot.target"
_sysv_mappings = {} # by rule of thumb
_sysv_mappings["$local_fs"] = "local-fs.target"
_sysv_mappings["$network"] = "network.target"
_sysv_mappings["$remote_fs"] = "remote-fs.target"
_sysv_mappings["$timer"] = "timers.target"
# sections from conf
Unit = "Unit"
Service = "Service"
Socket = "Socket"
Install = "Install"
# https://tldp.org/LDP/abs/html/exitcodes.html
# https://freedesktop.org/software/systemd/man/systemd.exec.html#id-1.20.8
EXIT_SUCCESS = 0
EXIT_FAILURE = 1
def strINET(value):
if value == socket.SOCK_DGRAM:
return "UDP"
if value == socket.SOCK_STREAM:
return "TCP"
if value == socket.SOCK_RAW: # pragma: no cover
return "RAW"
if value == socket.SOCK_RDM: # pragma: no cover
return "RDM"
if value == socket.SOCK_SEQPACKET: # pragma: no cover
return "SEQ"
return "<?>" # pragma: no cover
def strYes(value):
if value is True:
return "yes"
if not value:
return "no"
return str(value)
def strE(part):
if not part:
return ""
return str(part)
def strQ(part):
if part is None:
return ""
if isinstance(part, int):
return str(part)
return "'%s'" % part
def shell_cmd(cmd):
return " ".join([strQ(part) for part in cmd])
def to_intN(value, default = None):
if not value:
return default
try:
return int(value)
except:
return default
def to_int(value, default = 0):
try:
return int(value)
except:
return default
def to_list(value):
if not value:
return []
if isinstance(value, list):
return value
if isinstance(value, tuple):
return list(value)
return str(value or "").split(",")
def int_mode(value):
try: return int(value, 8)
except: return None # pragma: no cover
def unit_of(module):
if "." not in module:
return module + ".service"
return module
def o22(part):
if isinstance(part, basestring):
if len(part) <= 22:
return part
return part[:5] + "..." + part[-14:]
return part # pragma: no cover (is always str)
def o44(part):
if isinstance(part, basestring):
if len(part) <= 44:
return part
return part[:10] + "..." + part[-31:]
return part # pragma: no cover (is always str)
def o77(part):
if isinstance(part, basestring):
if len(part) <= 77:
return part
return part[:20] + "..." + part[-54:]
return part # pragma: no cover (is always str)
def path44(filename):
if not filename:
return "<none>"
x = filename.find("/", 8)
if len(filename) <= 40:
if "/" not in filename:
return ".../" + filename
elif len(filename) <= 44:
return filename
if 0 < x and x < 14:
out = filename[:x+1]
out += "..."
else:
out = filename[:10]
out += "..."
remain = len(filename) - len(out)
y = filename.find("/", remain)
if 0 < y and y < remain+5:
out += filename[y:]
else:
out += filename[remain:]
return out
def unit_name_escape(text):
# https://www.freedesktop.org/software/systemd/man/systemd.unit.html#id-1.6
esc = re.sub("([^a-z-AZ.-/])", lambda m: "\\x%02x" % ord(m.group(1)[0]), text)
return esc.replace("/", "-")
def unit_name_unescape(text):
esc = text.replace("-", "/")
return re.sub("\\\\x(..)", lambda m: "%c" % chr(int(m.group(1), 16)), esc)
def is_good_root(root):
if not root:
return True
return root.strip(os.path.sep).count(os.path.sep) > 1
def os_path(root, path):
if not root:
return path
if not path:
return path
if is_good_root(root) and path.startswith(root):
return path
while path.startswith(os.path.sep):
path = path[1:]
return os.path.join(root, path)
def path_replace_extension(path, old, new):
if path.endswith(old):
path = path[:-len(old)]
return path + new
def get_PAGER():
PAGER = os.environ.get("PAGER", "less")
pager = os.environ.get("SYSTEMD_PAGER", "{PAGER}").format(**locals())
options = os.environ.get("SYSTEMD_LESS", "FRSXMK") # see 'man timedatectl'
if not pager: pager = "cat"
if "less" in pager and options:
return [pager, "-" + options]
return [pager]
def os_getlogin():
""" NOT using os.getlogin() """
return pwd.getpwuid(os.geteuid()).pw_name
def get_runtime_dir():
explicit = os.environ.get("XDG_RUNTIME_DIR", "")
if explicit: return explicit
user = os_getlogin()
return "/tmp/run-"+user
def get_RUN(root = False):
tmp_var = get_TMP(root)
if _root:
tmp_var = _root
if root:
for p in ("/run", "/var/run", "{tmp_var}/run"):
path = p.format(**locals())
if os.path.isdir(path) and os.access(path, os.W_OK):
return path
os.makedirs(path) # "/tmp/run"
return path
else:
uid = get_USER_ID(root)
for p in ("/run/user/{uid}", "/var/run/user/{uid}", "{tmp_var}/run-{uid}"):
path = p.format(**locals())
if os.path.isdir(path) and os.access(path, os.W_OK):
return path
os.makedirs(path, 0o700) # "/tmp/run/user/{uid}"
return path
def get_PID_DIR(root = False):
if root:
return get_RUN(root)
else:
return os.path.join(get_RUN(root), "run") # compat with older systemctl.py
def get_home():
if False: # pragma: no cover
explicit = os.environ.get("HOME", "") # >> On Unix, an initial ~ (tilde) is replaced by the
if explicit: return explicit # environment variable HOME if it is set; otherwise
uid = os.geteuid() # the current users home directory is looked up in the
# # password directory through the built-in module pwd.
return pwd.getpwuid(uid).pw_name # An initial ~user i looked up directly in the
return os.path.expanduser("~") # password directory. << from docs(os.path.expanduser)
def get_HOME(root = False):
if root: return "/root"
return get_home()
def get_USER_ID(root = False):
ID = 0
if root: return ID
return os.geteuid()
def get_USER(root = False):
if root: return "root"
uid = os.geteuid()
return pwd.getpwuid(uid).pw_name
def get_GROUP_ID(root = False):
ID = 0
if root: return ID
return os.getegid()
def get_GROUP(root = False):
if root: return "root"
gid = os.getegid()
return grp.getgrgid(gid).gr_name
def get_TMP(root = False):
TMP = "/tmp"
if root: return TMP
return os.environ.get("TMPDIR", os.environ.get("TEMP", os.environ.get("TMP", TMP)))
def get_VARTMP(root = False):
VARTMP = "/var/tmp"
if root: return VARTMP
return os.environ.get("TMPDIR", os.environ.get("TEMP", os.environ.get("TMP", VARTMP)))
def get_SHELL(root = False):
SHELL = "/bin/sh"
if root: return SHELL
return os.environ.get("SHELL", SHELL)
def get_RUNTIME_DIR(root = False):
RUN = "/run"
if root: return RUN
return os.environ.get("XDG_RUNTIME_DIR", get_runtime_dir())
def get_CONFIG_HOME(root = False):
CONFIG = "/etc"
if root: return CONFIG
HOME = get_HOME(root)
return os.environ.get("XDG_CONFIG_HOME", HOME + "/.config")
def get_CACHE_HOME(root = False):
CACHE = "/var/cache"
if root: return CACHE
HOME = get_HOME(root)
return os.environ.get("XDG_CACHE_HOME", HOME + "/.cache")
def get_DATA_HOME(root = False):
SHARE = "/usr/share"
if root: return SHARE
HOME = get_HOME(root)
return os.environ.get("XDG_DATA_HOME", HOME + "/.local/share")
def get_LOG_DIR(root = False):
LOGDIR = "/var/log"
if root: return LOGDIR
CONFIG = get_CONFIG_HOME(root)
return os.path.join(CONFIG, "log")
def get_VARLIB_HOME(root = False):
VARLIB = "/var/lib"
if root: return VARLIB
CONFIG = get_CONFIG_HOME(root)
return CONFIG
def expand_path(path, root = False):
HOME = get_HOME(root)
RUN = get_RUN(root)
LOG = get_LOG_DIR(root)
XDG_DATA_HOME=get_DATA_HOME(root)
XDG_CONFIG_HOME=get_CONFIG_HOME(root)
XDG_RUNTIME_DIR=get_RUNTIME_DIR(root)
return os.path.expanduser(path.replace("${", "{").format(**locals()))
def shutil_chown(path, user, group):
if user or group:
uid, gid = -1, -1
if user:
uid = pwd.getpwnam(user).pw_uid
gid = pwd.getpwnam(user).pw_gid
if group:
gid = grp.getgrnam(group).gr_gid
os.chown(path, uid, gid)
def shutil_fchown(fileno, user, group):
if user or group:
uid, gid = -1, -1
if user:
uid = pwd.getpwnam(user).pw_uid
gid = pwd.getpwnam(user).pw_gid
if group:
gid = grp.getgrnam(group).gr_gid
os.fchown(fileno, uid, gid)
def shutil_setuid(user = None, group = None, xgroups = None):
""" set fork-child uid/gid (returns pw-info env-settings)"""
if group:
gid = grp.getgrnam(group).gr_gid
os.setgid(gid)
logg.debug("setgid %s for %s", gid, strQ(group))
groups = [gid]
try:
os.setgroups(groups)
logg.debug("setgroups %s < (%s)", groups, group)
except OSError as e: # pragma: no cover (it will occur in non-root mode anyway)
logg.debug("setgroups %s < (%s) : %s", groups, group, e)
if user:
pw = pwd.getpwnam(user)
gid = pw.pw_gid
gname = grp.getgrgid(gid).gr_name
if not group:
os.setgid(gid)
logg.debug("setgid %s for user %s", gid, strQ(user))
groupnames = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
if xgroups:
groups += [g.gr_gid for g in grp.getgrall() if g.gr_name in xgroups and g.gr_gid not in groups]
if not groups:
if group:
gid = grp.getgrnam(group).gr_gid
groups = [gid]
try:
os.setgroups(groups)
logg.debug("setgroups %s > %s ", groups, groupnames)
except OSError as e: # pragma: no cover (it will occur in non-root mode anyway)
logg.debug("setgroups %s > %s : %s", groups, groupnames, e)
uid = pw.pw_uid
os.setuid(uid)
logg.debug("setuid %s for user %s", uid, strQ(user))
home = pw.pw_dir
shell = pw.pw_shell
logname = pw.pw_name
return {"USER": user, "LOGNAME": logname, "HOME": home, "SHELL": shell}
return {}
def shutil_truncate(filename):
""" truncates the file (or creates a new empty file)"""
filedir = os.path.dirname(filename)
if not os.path.isdir(filedir):
os.makedirs(filedir)
f = open(filename, "w")
f.write("")
f.close()
# http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid is None: # pragma: no cover (is never null)
return False
return _pid_exists(int(pid))
def _pid_exists(pid):
"""Check whether pid exists in the current process table.
UNIX only.
"""
if pid < 0:
return False
if pid == 0:
# According to "man 2 kill" PID 0 refers to every process
# in the process group of the calling process.
# On certain systems 0 is a valid PID but we have no way
# to know that in a portable fashion.
raise ValueError('invalid PID 0')
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH)
raise
else:
return True
def pid_zombie(pid):
""" may be a pid exists but it is only a zombie """
if pid is None:
return False
return _pid_zombie(int(pid))
def _pid_zombie(pid):
""" may be a pid exists but it is only a zombie """
if pid < 0:
return False
if pid == 0:
# According to "man 2 kill" PID 0 refers to every process
# in the process group of the calling process.
# On certain systems 0 is a valid PID but we have no way
# to know that in a portable fashion.
raise ValueError('invalid PID 0')
check = _proc_pid_status.format(**locals())
try:
for line in open(check):
if line.startswith("State:"):
return "Z" in line
except IOError as e:
if e.errno != errno.ENOENT:
logg.error("%s (%s): %s", check, e.errno, e)
return False
return False
def checkprefix(cmd):
prefix = ""
for i, c in enumerate(cmd):
if c in "-+!@:":
prefix = prefix + c
else:
newcmd = cmd[i:]
return prefix, newcmd
return prefix, ""
ExecMode = collections.namedtuple("ExecMode", ["mode", "check", "nouser", "noexpand", "argv0"])
def exec_path(cmd):
""" Hint: exec_path values are usually not moved by --root (while load_path are)"""
prefix, newcmd = checkprefix(cmd)
check = "-" not in prefix
nouser = "+" in prefix or "!" in prefix
noexpand = ":" in prefix
argv0 = "@" in prefix
mode = ExecMode(prefix, check, nouser, noexpand, argv0)
return mode, newcmd
LoadMode = collections.namedtuple("LoadMode", ["mode", "check"])
def load_path(ref):
""" Hint: load_path values are usually moved by --root (while exec_path are not)"""
prefix, filename = "", ref
while filename.startswith("-"):
prefix = prefix + filename[0]
filename = filename[1:]
check = "-" not in prefix
mode = LoadMode(prefix, check)
return mode, filename
# https://github.com/phusion/baseimage-docker/blob/rel-0.9.16/image/bin/my_init
def ignore_signals_and_raise_keyboard_interrupt(signame):
signal.signal(signal.SIGTERM, signal.SIG_IGN)
signal.signal(signal.SIGINT, signal.SIG_IGN)
raise KeyboardInterrupt(signame)
_default_dict_type = collections.OrderedDict
_default_conf_type = collections.OrderedDict
class SystemctlConfData:
""" A *.service files has a structure similar to an *.ini file so
that data is structured in sections and values. Actually the
values are lists - the raw data is in .getlist(). Otherwise
.get() will return the first line that was encountered. """
# |
# |
# |
# |
# |
# |
def __init__(self, defaults=None, dict_type=None, conf_type=None, allow_no_value=False):
self._defaults = defaults or {}
self._conf_type = conf_type or _default_conf_type
self._dict_type = dict_type or _default_dict_type
self._allow_no_value = allow_no_value
self._conf = self._conf_type()
self._files = []
def defaults(self):
return self._defaults
def sections(self):
return list(self._conf.keys())
def add_section(self, section):
if section not in self._conf:
self._conf[section] = self._dict_type()
def has_section(self, section):
return section in self._conf
def has_option(self, section, option):
if section not in self._conf:
return False
return option in self._conf[section]
def set(self, section, option, value):
if section not in self._conf:
self._conf[section] = self._dict_type()
if value is None:
self._conf[section][option] = []
elif option not in self._conf[section]:
self._conf[section][option] = [value]
else:
self._conf[section][option].append(value)
def getstr(self, section, option, default = None, allow_no_value = False):
done = self.get(section, option, strE(default), allow_no_value)
if done is None: return strE(default)
return done
def get(self, section, option, default = None, allow_no_value = False):
allow_no_value = allow_no_value or self._allow_no_value
if section not in self._conf:
if default is not None:
return default
if allow_no_value:
return None
logg.warning("section {} does not exist".format(section))
logg.warning(" have {}".format(self.sections()))
raise AttributeError("section {} does not exist".format(section))
if option not in self._conf[section]:
if default is not None:
return default
if allow_no_value:
return None
raise AttributeError("option {} in {} does not exist".format(option, section))
if not self._conf[section][option]: # i.e. an empty list
if default is not None:
return default
if allow_no_value:
return None
raise AttributeError("option {} in {} is None".format(option, section))
return self._conf[section][option][0] # the first line in the list of configs
def getlist(self, section, option, default = None, allow_no_value = False):
allow_no_value = allow_no_value or self._allow_no_value
if section not in self._conf:
if default is not None:
return default
if allow_no_value:
return []
logg.warning("section {} does not exist".format(section))
logg.warning(" have {}".format(self.sections()))
raise AttributeError("section {} does not exist".format(section))
if option not in self._conf[section]:
if default is not None:
return default
if allow_no_value:
return []
raise AttributeError("option {} in {} does not exist".format(option, section))
return self._conf[section][option] # returns a list, possibly empty
def filenames(self):
return self._files
class SystemctlConfigParser(SystemctlConfData):
""" A *.service files has a structure similar to an *.ini file but it is
actually not like it. Settings may occur multiple times in each section
and they create an implicit list. In reality all the settings are
globally uniqute, so that an 'environment' can be printed without
adding prefixes. Settings are continued with a backslash at the end
of the line. """
# def __init__(self, defaults=None, dict_type=None, allow_no_value=False):
# SystemctlConfData.__init__(self, defaults, dict_type, allow_no_value)
def read(self, filename):
return self.read_sysd(filename)
def read_sysd(self, filename):
initscript = False
initinfo = False
section = "GLOBAL"
nextline = False
name, text = "", ""
if os.path.isfile(filename):
self._files.append(filename)
for orig_line in open(filename):
if nextline:
text += orig_line
if text.rstrip().endswith("\\") or text.rstrip().endswith("\\\n"):
text = text.rstrip() + "\n"
else:
self.set(section, name, text)
nextline = False
continue
line = orig_line.strip()
if not line:
continue
if line.startswith("#"):
continue
if line.startswith(";"):
continue
if line.startswith(".include"):
logg.error("the '.include' syntax is deprecated. Use x.service.d/ drop-in files!")
includefile = re.sub(r'^\.include[ ]*', '', line).rstrip()
if not os.path.isfile(includefile):
raise Exception("tried to include file that doesn't exist: %s" % includefile)
self.read_sysd(includefile)
continue
if line.startswith("["):
x = line.find("]")
if x > 0:
section = line[1:x]
self.add_section(section)
continue
m = re.match(r"(\w+) *=(.*)", line)
if not m:
logg.warning("bad ini line: %s", line)
raise Exception("bad ini line")
name, text = m.group(1), m.group(2).strip()
if text.endswith("\\") or text.endswith("\\\n"):
nextline = True
text = text + "\n"
else:
# hint: an empty line shall reset the value-list
self.set(section, name, text and text or None)
return self
def read_sysv(self, filename):
""" an LSB header is scanned and converted to (almost)
equivalent settings of a SystemD ini-style input """
initscript = False
initinfo = False
section = "GLOBAL"
if os.path.isfile(filename):
self._files.append(filename)
for orig_line in open(filename):
line = orig_line.strip()
if line.startswith("#"):
if " BEGIN INIT INFO" in line:
initinfo = True
section = "init.d"
if " END INIT INFO" in line:
initinfo = False
if initinfo:
m = re.match(r"\S+\s*(\w[\w_-]*):(.*)", line)
if m:
key, val = m.group(1), m.group(2).strip()
self.set(section, key, val)
continue
self.systemd_sysv_generator(filename)
return self
def systemd_sysv_generator(self, filename):
""" see systemd-sysv-generator(8) """
self.set(Unit, "SourcePath", filename)
description = self.get("init.d", "Description", "")
if description:
self.set(Unit, "Description", description)
check = self.get("init.d", "Required-Start", "")
if check:
for item in check.split(" "):
if item.strip() in _sysv_mappings:
self.set(Unit, "Requires", _sysv_mappings[item.strip()])
provides = self.get("init.d", "Provides", "")
if provides:
self.set(Install, "Alias", provides)
# if already in multi-user.target then start it there.
runlevels = self.getstr("init.d", "Default-Start", "3 5")
for item in runlevels.split(" "):
if item.strip() in _runlevel_mappings:
self.set(Install, "WantedBy", _runlevel_mappings[item.strip()])
self.set(Service, "Restart", "no")
self.set(Service, "TimeoutSec", strE(DefaultMaximumTimeout))
self.set(Service, "KillMode", "process")
self.set(Service, "GuessMainPID", "no")
# self.set(Service, "RemainAfterExit", "yes")
# self.set(Service, "SuccessExitStatus", "5 6")
self.set(Service, "ExecStart", filename + " start")
self.set(Service, "ExecStop", filename + " stop")
if description: # LSB style initscript
self.set(Service, "ExecReload", filename + " reload")
self.set(Service, "Type", "forking") # not "sysv" anymore
# UnitConfParser = ConfigParser.RawConfigParser
UnitConfParser = SystemctlConfigParser
class SystemctlSocket:
def __init__(self, conf, sock, skip = False):
self.conf = conf
self.sock = sock
self.skip = skip
def fileno(self):
return self.sock.fileno()
def listen(self, backlog = None):
if backlog is None:
backlog = DefaultListenBacklog
dgram = (self.sock.type == socket.SOCK_DGRAM)
if not dgram and not self.skip:
self.sock.listen(backlog)
def name(self):
return self.conf.name()
def addr(self):
stream = self.conf.get(Socket, "ListenStream", "")
dgram = self.conf.get(Socket, "ListenDatagram", "")
return stream or dgram
def close(self):
self.sock.close()
class SystemctlConf:
# |
# |
# |
# |
# |
# |
# |
# |
# |
def __init__(self, data, module = None):
self.data = data # UnitConfParser
self.env = {}
self.status = None
self.masked = None
self.module = module
self.nonloaded_path = ""
self.drop_in_files = {}
self._root = _root
self._user_mode = _user_mode
def root_mode(self):
return not self._user_mode
def loaded(self):
files = self.data.filenames()
if self.masked:
return "masked"
if len(files):
return "loaded"
return ""
def filename(self):
""" returns the last filename that was parsed """
files = self.data.filenames()
if files:
return files[0]
return None
def overrides(self):
""" drop-in files are loaded alphabetically by name, not by full path """
return [self.drop_in_files[name] for name in sorted(self.drop_in_files)]
def name(self):
""" the unit id or defaults to the file name """
name = self.module or ""
filename = self.filename()
if filename:
name = os.path.basename(filename)
return self.module or name
def set(self, section, name, value):
return self.data.set(section, name, value)
def get(self, section, name, default, allow_no_value = False):
return self.data.getstr(section, name, default, allow_no_value)
def getlist(self, section, name, default = None, allow_no_value = False):
return self.data.getlist(section, name, default or [], allow_no_value)
def getbool(self, section, name, default = None):
value = self.data.get(section, name, default or "no")
if value:
if value[0] in "TtYy123456789":
return True
return False
class PresetFile:
# |
# |
def __init__(self):
self._files = []
self._lines = []
def filename(self):
""" returns the last filename that was parsed """
if self._files:
return self._files[-1]
return None
def read(self, filename):
self._files.append(filename)
for line in open(filename):
self._lines.append(line.strip())
return self
def get_preset(self, unit):
for line in self._lines:
m = re.match(r"(enable|disable)\s+(\S+)", line)
if m:
status, pattern = m.group(1), m.group(2)
if fnmatch.fnmatchcase(unit, pattern):
logg.debug("%s %s => %s %s", status, pattern, unit, strQ(self.filename()))
return status
return None
## with waitlock(conf): self.start()
class waitlock:
# |
# |
# |
def __init__(self, conf):
self.conf = conf # currently unused
self.opened = -1
self.lockfolder = expand_path(_notify_socket_folder, conf.root_mode())
try:
folder = self.lockfolder
if not os.path.isdir(folder):
os.makedirs(folder)
except Exception as e:
logg.warning("oops, %s", e)
def lockfile(self):
unit = ""
if self.conf:
unit = self.conf.name()
return os.path.join(self.lockfolder, str(unit or "global") + ".lock")
def __enter__(self):
try:
lockfile = self.lockfile()
lockname = os.path.basename(lockfile)
self.opened = os.open(lockfile, os.O_RDWR | os.O_CREAT, 0o600)
for attempt in xrange(int(MaxLockWait or DefaultMaximumTimeout)):
try:
logg_debug_flock("[%s] %s. trying %s _______ ", os.getpid(), attempt, lockname)
fcntl.flock(self.opened, fcntl.LOCK_EX | fcntl.LOCK_NB)
st = os.fstat(self.opened)
if not st.st_nlink:
logg_debug_flock("[%s] %s. %s got deleted, trying again", os.getpid(), attempt, lockname)
os.close(self.opened)
self.opened = os.open(lockfile, os.O_RDWR | os.O_CREAT, 0o600)
continue
content = "{ 'systemctl': %s, 'lock': '%s' }\n" % (os.getpid(), lockname)
os.write(self.opened, content.encode("utf-8"))
logg_debug_flock("[%s] %s. holding lock on %s", os.getpid(), attempt, lockname)
return True
except IOError as e: