This repository has been archived by the owner on Sep 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
systemctl.py
executable file
·4617 lines (4571 loc) · 199 KB
/
systemctl.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/python
from __future__ import print_function
__copyright__ = "(C) 2016-2019 Guido U. Draheim, licensed under the EUPL"
__version__ = "1.4.3326"
import logging
logg = logging.getLogger("systemctl")
import re
import fnmatch
import shlex
import collections
import errno
import os
import sys
import signal
import time
import socket
import datetime
import fcntl
import glob
if sys.version[0] == '2':
string_types = basestring
BlockingIOError = IOError
else:
string_types = str
xrange = range
# --coverage=removelockfile,oldest,spawn,sleep,quick,initializing
COVERAGE = os.environ.get("SYSTEMCTL_COVERAGE", "")
DEBUG_AFTER = os.environ.get("SYSTEMCTL_DEBUG_AFTER", "") or False
EXIT_WHEN_NO_MORE_PROCS = os.environ.get("SYSTEMCTL_EXIT_WHEN_NO_MORE_PROCS", "") or False
EXIT_WHEN_NO_MORE_SERVICES = os.environ.get("SYSTEMCTL_EXIT_WHEN_NO_MORE_SERVICES", "") or False
FOUND_OK = 0
FOUND_INACTIVE = 2
FOUND_UNKNOWN = 4
# defaults for options
_extra_vars = []
_force = False
_full = False
_now = False
_no_legend = False
_no_ask_password = False
_preset_mode = "all"
_quiet = False
_wait = False
_root = ""
_unit_type = None
_unit_state = None
_unit_property = None
_show_all = False
_user_mode = False
_user_global = False
# common default paths
_default_target = "multi-user.target"
_system_global = "/etc/systemd"
_system_folder1 = "/etc/systemd/system"
_system_folder2 = "/var/run/systemd/system"
_system_folder3 = "/usr/lib/systemd/system"
_system_folder4 = "/lib/systemd/system"
_system_folder9 = None
_user_folder1 = "~/.config/systemd/user"
_user_folder2 = "/etc/systemd/user"
_user_folder3 = "~.local/share/systemd/user"
_user_folder4 = "/usr/lib/systemd/user"
_user_folder9 = None
_init_folder1 = "/etc/init.d"
_init_folder2 = "/var/run/init.d"
_init_folder9 = None
_preset_folder1 = "/etc/systemd/system-preset"
_preset_folder2 = "/var/run/systemd/system-preset"
_preset_folder3 = "/usr/lib/systemd/system-preset"
_preset_folder4 = "/lib/systemd/system-preset"
_preset_folder9 = None
SystemCompatibilityVersion = 219
SysInitTarget = "sysinit.target"
SysInitWait = 5 # max for target
EpsilonTime = 0.1
MinimumYield = 0.5
MinimumTimeoutStartSec = 4
MinimumTimeoutStopSec = 4
DefaultTimeoutStartSec = int(os.environ.get("SYSTEMCTL_TIMEOUT_START_SEC", 90)) # official value
DefaultTimeoutStopSec = int(os.environ.get("SYSTEMCTL_TIMEOUT_STOP_SEC", 90)) # official value
DefaultMaximumTimeout = int(os.environ.get("SYSTEMCTL_MAXIMUM_TIMEOUT", 200)) # overrides all other
InitLoopSleep = int(os.environ.get("SYSTEMCTL_INITLOOP", 5))
ProcMaxDepth = 100
MaxLockWait = None # 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"]
# The systemd default is NOTIFY_SOCKET="/var/run/systemd/notify"
_notify_socket_folder = "/var/run/systemd" # alias /run/systemd
_pid_file_folder = "/var/run"
_journal_log_folder = "/var/log/journal"
_systemctl_debug_log = "/var/log/systemctl.debug.log"
_systemctl_extra_log = "/var/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" ]
_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"
def shell_cmd(cmd):
return " ".join(["'%s'" % part for part in cmd])
def to_int(value, default = 0):
try:
return int(value)
except:
return default
def to_list(value):
if isinstance(value, string_types):
return [ value ]
return value
def unit_of(module):
if "." not in module:
return module + ".service"
return module
def systemd_normpath(path):
# we skip hexlify of the characters '@', '.', '/', '-' as they are special in parse_unit.
# we skip hexlify of the characters '*', '?', '!', '[', ']' being used during fnmatchcase.
# the fnmatch characters are assumed to not exist in instance objects just as the backslash.
# this function one is idempotent when no backslash is ever used in the unescaped unit name.
return re.sub("([^a-zA-Z0-9_/@.\\\\*?!\\[\\]-])", lambda m: "\\x%02x" % ord(m.group(1)), path)
def systemd_unescape(text):
try:
base_text = bytearray(text, sys.getfilesystemencoding()) # python3
hexx_text = base_text.replace(b"-", b"/")
core_text = re.sub(b"\\\\x([0-9A-Fa-f]{2})", lambda m: bytes(chr(int(m.group(1), 16)), "utf-8"), hexx_text)
return core_text.decode("utf-8")
except:
base_text = bytearray(text.decode(sys.getfilesystemencoding()), "utf-8")
hexx_text = base_text.replace(b"-", b"/")
core_text = re.sub(b"\\\\x([0-9A-Fa-f]{2})", lambda m: chr(int(str(m.group(1)), 16)), hexx_text)
return core_text.decode("utf-8")
def os_path(root, path):
if not root:
return path
if not path:
return path
while path.startswith(os.path.sep):
path = path[1:]
return os.path.join(root, path)
def os_getlogin():
""" NOT using os.getlogin() """
import pwd
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_home():
explicit = os.environ.get("HOME", "")
if explicit: return explicit
return os.path.expanduser("~")
def _var_path(path):
""" assumes that the path starts with /var - when in
user mode it shall be moved to /run/user/1001/run/
or as a fallback path to /tmp/run-{user}/ so that
you may find /var/log in /tmp/run-{user}/log .."""
if path.startswith("/var"):
runtime = get_runtime_dir() # $XDG_RUNTIME_DIR
if not os.path.isdir(runtime):
os.makedirs(runtime)
os.chmod(runtime, 0o700)
return re.sub("^(/var)?", get_runtime_dir(), path)
return path
def shutil_setuid(user = None, group = None):
""" set fork-child uid/gid (returns pw-info env-settings)"""
if group:
import grp
gid = grp.getgrnam(group).gr_gid
os.setgid(gid)
logg.debug("setgid %s '%s'", gid, group)
if user:
import pwd
pw = pwd.getpwnam(user)
if not group:
gid = pw.pw_gid
os.setgid(gid)
logg.debug("setgid %s", gid)
uid = pw.pw_uid
os.setuid(uid)
logg.debug("setuid %s '%s'", uid, 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:
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/%s/status" % pid
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 checkstatus(cmd):
if cmd.startswith("-"):
return False, cmd[1:]
else:
return True, cmd
# 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)
class SystemctlConfigParser:
""" 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):
self._defaults = defaults or {}
self._dict_type = dict_type or collections.OrderedDict
self._allow_no_value = allow_no_value
self._conf = self._dict_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 option not in self._conf[section]:
self._conf[section][option] = [ value ]
else:
self._conf[section][option].append(value)
if value is None:
self._conf[section][option] = []
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 read(self, filename):
return self.read_sysd(filename)
def read_sysd(self, filename):
initscript = False
initinfo = False
section = None
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)
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 = None
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
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.get("init.d", "Default-Start","")
if runlevels:
for item in runlevels.split(" "):
if item.strip() in _runlevel_mappings:
self.set("Install", "WantedBy", _runlevel_mappings[item.strip()])
self.set("Service", "Type", "sysv")
def filenames(self):
return self._files
# UnitConfParser = ConfigParser.RawConfigParser
UnitConfParser = SystemctlConfigParser
class SystemctlConf:
def __init__(self, data, module = None):
self.data = data # UnitConfParser
self.env = {}
self.status = None
self.masked = None
self.module = module
self.drop_in_files = {}
self._root = _root
self._user_mode = _user_mode
self._user_global = _user_global
def os_path(self, path):
return os_path(self._root, path)
def os_path_var(self, path):
if self._user_mode: # not _user_global
return os_path(self._root, _var_path(path))
return os_path(self._root, path)
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 """
if self.module:
return self.module
filename = self.filename()
if filename:
return systemd_normpath(os.path.basename(filename))
return self.get("Unit", "Id", "")
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.get(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, self.filename())
return status
return None
## with waitlock(conf): self.start()
class waitlock:
def __init__(self, conf):
self.conf = conf # currently unused
self.opened = None
self.lockfolder = conf.os_path_var(_notify_socket_folder)
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("[%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("[%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("[%s] %s. holding lock on %s", os.getpid(), attempt, lockname)
return True
except BlockingIOError as e:
whom = os.read(self.opened, 4096)
os.lseek(self.opened, 0, os.SEEK_SET)
logg.info("[%s] %s. systemctl locked by %s", os.getpid(), attempt, whom.rstrip())
time.sleep(1) # until MaxLockWait
continue
logg.error("[%s] not able to get the lock to %s", os.getpid(), lockname)
except Exception as e:
logg.warning("[%s] oops %s, %s", os.getpid(), str(type(e)), e)
#TODO# raise Exception("no lock for %s", self.unit or "global")
return False
def __exit__(self, type, value, traceback):
try:
os.lseek(self.opened, 0, os.SEEK_SET)
os.ftruncate(self.opened, 0)
if "removelockfile" in COVERAGE: # actually an optional implementation
lockfile = self.lockfile()
lockname = os.path.basename(lockfile)
os.unlink(lockfile) # ino is kept allocated because opened by this process
logg.debug("[%s] lockfile removed for %s", os.getpid(), lockname)
fcntl.flock(self.opened, fcntl.LOCK_UN)
os.close(self.opened) # implies an unlock but that has happend like 6 seconds later
self.opened = None
except Exception as e:
logg.warning("oops, %s", e)
def must_have_failed(waitpid, cmd):
# found to be needed on ubuntu:16.04 to match test result from ubuntu:18.04 and other distros
# .... I have tracked it down that python's os.waitpid() returns an exitcode==0 even when the
# .... underlying process has actually failed with an exitcode<>0. It is unknown where that
# .... bug comes from but it seems a bit serious to trash some very basic unix functionality.
# .... Essentially a parent process does not get the correct exitcode from its own children.
if cmd and cmd[0] == "/bin/kill":
pid = None
for arg in cmd[1:]:
if not arg.startswith("-"):
pid = arg
if pid is None: # unknown $MAINPID
if not waitpid.returncode:
logg.error("waitpid %s did return %s => correcting as 11", cmd, waitpid.returncode)
waitpidNEW = collections.namedtuple("waitpidNEW", ["pid", "returncode", "signal" ])
waitpid = waitpidNEW(waitpid.pid, 11, waitpid.signal)
return waitpid
def subprocess_waitpid(pid):
waitpid = collections.namedtuple("waitpid", ["pid", "returncode", "signal" ])
run_pid, run_stat = os.waitpid(pid, 0)
return waitpid(run_pid, os.WEXITSTATUS(run_stat), os.WTERMSIG(run_stat))
def subprocess_testpid(pid):
testpid = collections.namedtuple("testpid", ["pid", "returncode", "signal" ])
run_pid, run_stat = os.waitpid(pid, os.WNOHANG)
if run_pid:
return testpid(run_pid, os.WEXITSTATUS(run_stat), os.WTERMSIG(run_stat))
else:
return testpid(pid, None, 0)
def parse_unit(fullname): # -> object(prefix, instance, suffix, ...., name, component)
# "full unit name": %N is the same as "%n", but with the type suffix removed.
name, suffix = fullname, ""
has_suffix = fullname.rfind(".")
if has_suffix > 0:
name = fullname[:has_suffix]
suffix = fullname[has_suffix+1:]
# "prefix name": %p refers to the string before the first "@" character of the unit name. For non-instantiated units, same as "%N".
# "instance name": %i is the string between the first "@" character and the type suffix. Empty for non-instantiated units.
prefix, instance = name, ""
has_instance = name.find("@")
if has_instance > 0:
prefix = name[:has_instance]
instance = name[has_instance+1:]
# "Final component of the prefix":
# %j is the string between the last "-" and the end of the prefix name. If there is no "-", this is the same as "%p".
componentof, component = "", prefix
has_component = prefix.rfind("-")
if has_component > 0:
component = prefix[has_component+1:]
componentof = prefix[:has_component+1] # including the dash as it refers to include ./name-.d/
UnitName = collections.namedtuple(
"UnitName", ["fullname", "name", "suffix", "componentof", "component", "prefix", "instance" ])
return UnitName(fullname, name, suffix, componentof, component, prefix, instance)
def time_to_seconds(text, maximum = None):
if maximum is None:
maximum = DefaultMaximumTimeout
value = 0
for part in str(text).split(" "):
item = part.strip()
if item == "infinity":
return maximum
if item.endswith("m"):
try: value += 60 * int(item[:-1])
except: pass # pragma: nocover
if item.endswith("min"):
try: value += 60 * int(item[:-3])
except: pass # pragma: nocover
elif item.endswith("ms"):
try: value += int(item[:-2]) / 1000.
except: pass # pragma: nocover
elif item.endswith("s"):
try: value += int(item[:-1])
except: pass # pragma: nocover
elif item:
try: value += int(item)
except: pass # pragma: nocover
if value > maximum:
return maximum
if not value:
return 1
return value
def seconds_to_time(seconds):
seconds = float(seconds)
mins = int(int(seconds) / 60)
secs = int(int(seconds) - (mins * 60))
msecs = int(int(seconds * 1000) - (secs * 1000 + mins * 60000))
if mins and secs and msecs:
return "%smin %ss %sms" % (mins, secs, msecs)
elif mins and secs:
return "%smin %ss" % (mins, secs)
elif secs and msecs:
return "%ss %sms" % (secs, msecs)
elif mins and msecs:
return "%smin %sms" % (mins, msecs)
elif mins:
return "%smin" % (mins)
else:
return "%ss" % (secs)
def getBefore(conf):
result = []
beforelist = conf.getlist("Unit", "Before", [])
for befores in beforelist:
for before in befores.split(" "):
name = before.strip()
if name and name not in result:
result.append(name)
return result
def getAfter(conf):
result = []
afterlist = conf.getlist("Unit", "After", [])
for afters in afterlist:
for after in afters.split(" "):
name = after.strip()
if name and name not in result:
result.append(name)
return result
def compareAfter(confA, confB):
idA = confA.name()
idB = confB.name()
for after in getAfter(confA):
if after == idB:
logg.debug("%s After %s", idA, idB)
return -1
for after in getAfter(confB):
if after == idA:
logg.debug("%s After %s", idB, idA)
return 1
for before in getBefore(confA):
if before == idB:
logg.debug("%s Before %s", idA, idB)
return 1
for before in getBefore(confB):
if before == idA:
logg.debug("%s Before %s", idB, idA)
return -1
return 0
def sortedAfter(conflist, cmp = compareAfter):
# the normal sorted() does only look at two items
# so if "A after C" and a list [A, B, C] then
# it will see "A = B" and "B = C" assuming that
# "A = C" and the list is already sorted.
#
# To make a totalsorted we have to create a marker
# that informs sorted() that also B has a relation.
# It only works when 'after' has a direction, so
# anything without 'before' is a 'after'. In that
# case we find that "B after C".
class SortTuple:
def __init__(self, rank, conf):
self.rank = rank
self.conf = conf
sortlist = [ SortTuple(0, conf) for conf in conflist]
for check in xrange(len(sortlist)): # maxrank = len(sortlist)
changed = 0
for A in xrange(len(sortlist)):
for B in xrange(len(sortlist)):
if A != B:
itemA = sortlist[A]
itemB = sortlist[B]
before = compareAfter(itemA.conf, itemB.conf)
if before > 0 and itemA.rank <= itemB.rank:
if DEBUG_AFTER: # pragma: nocover
logg.info(" %-30s before %s", itemA.conf.name(), itemB.conf.name())
itemA.rank = itemB.rank + 1
changed += 1
if before < 0 and itemB.rank <= itemA.rank:
if DEBUG_AFTER: # pragma: nocover
logg.info(" %-30s before %s", itemB.conf.name(), itemA.conf.name())
itemB.rank = itemA.rank + 1
changed += 1
if not changed:
if DEBUG_AFTER: # pragma: nocover
logg.info("done in check %s of %s", check, len(sortlist))
break
# because Requires is almost always the same as the After clauses
# we are mostly done in round 1 as the list is in required order
for conf in conflist:
if DEBUG_AFTER: # pragma: nocover
logg.debug(".. %s", conf.name())
for item in sortlist:
if DEBUG_AFTER: # pragma: nocover
logg.info("(%s) %s", item.rank, item.conf.name())
sortedlist = sorted(sortlist, key = lambda item: -item.rank)
for item in sortedlist:
if DEBUG_AFTER: # pragma: nocover
logg.info("[%s] %s", item.rank, item.conf.name())
return [ item.conf for item in sortedlist ]
class Systemctl:
def __init__(self):
# from command line options or the defaults
self._extra_vars = _extra_vars
self._force = _force
self._full = _full
self._init = _init
self._no_ask_password = _no_ask_password
self._no_legend = _no_legend
self._now = _now
self._preset_mode = _preset_mode
self._quiet = _quiet
self._root = _root
self._show_all = _show_all
self._unit_property = _unit_property
self._unit_state = _unit_state
self._unit_type = _unit_type
# some common constants that may be changed
self._systemd_version = SystemCompatibilityVersion
self._pid_file_folder = _pid_file_folder
self._journal_log_folder = _journal_log_folder
# and the actual internal runtime state
self._loaded_file_sysv = {} # /etc/init.d/name => config data
self._loaded_file_sysd = {} # /etc/systemd/system/name.service => config data
self._file_for_unit_sysv = None # name.service => /etc/init.d/name
self._file_for_unit_sysd = None # name.service => /etc/systemd/system/name.service
self._preset_file_list = None # /etc/systemd/system-preset/* => file content
self._default_target = _default_target
self._sysinit_target = None
self.exit_when_no_more_procs = EXIT_WHEN_NO_MORE_PROCS or False
self.exit_when_no_more_services = EXIT_WHEN_NO_MORE_SERVICES or False
self._user_mode = _user_mode
self._user_global = _user_global
self._user_getlogin = os_getlogin()
self._log_file = {} # init-loop
self._log_hold = {} # init-loop
def user(self):
return self._user_getlogin
def user_mode(self):
return self._user_mode or self._user_global
def user_global(self):
return self._user_global
def init_folders(self):
if _init_folder1: yield _init_folder1
if _init_folder2: yield _init_folder2
if _init_folder9: yield _init_folder9
def preset_folders(self):
if _preset_folder1: yield _preset_folder1
if _preset_folder2: yield _preset_folder2
if _preset_folder3: yield _preset_folder3
if _preset_folder4: yield _preset_folder4
if _preset_folder9: yield _preset_folder9
def user_folders(self):
if _user_folder1: yield os.path.expanduser(_user_folder1)
if _user_folder2: yield os.path.expanduser(_user_folder2)
if _user_folder3: yield os.path.expanduser(_user_folder3)
if _user_folder4: yield os.path.expanduser(_user_folder4)
if _user_folder9: yield os.path.expanduser(_user_folder9)
def system_folders(self):
if _system_folder1: yield _system_folder1
if _system_folder2: yield _system_folder2
if _system_folder3: yield _system_folder3
if _system_folder4: yield _system_folder4
if _system_folder9: yield _system_folder9
def sysd_folders(self):
""" if --user then these folders are preferred """
if self.user_mode():
for folder in self.user_folders():
yield folder
if True:
for folder in self.system_folders():
yield folder
def scan_unit_sysd_files(self, module = None): # -> [ unit-names,... ]
""" reads all unit files, returns the first filename for the unit given """
if self._file_for_unit_sysd is None:
self._file_for_unit_sysd = {}
for folder in self.sysd_folders():
if not folder:
continue
folder = os_path(self._root, folder)
if not os.path.isdir(folder):
continue
for name in os.listdir(folder):
path = os.path.join(folder, name)
if os.path.isdir(path):
continue
service_name = systemd_normpath(name)
if service_name not in self._file_for_unit_sysd:
self._file_for_unit_sysd[service_name] = path
unit = parse_unit(service_name)
logg.debug("found %s sysd files", len(self._file_for_unit_sysd))
return list(self._file_for_unit_sysd.keys())
def scan_unit_sysv_files(self, module = None): # -> [ unit-names,... ]
""" reads all init.d files, returns the first filename when unit is a '.service' """
if self._file_for_unit_sysv is None:
self._file_for_unit_sysv = {}
for folder in self.init_folders():
if not folder:
continue
folder = os_path(self._root, folder)
if not os.path.isdir(folder):
continue
for name in os.listdir(folder):
path = os.path.join(folder, name)
if os.path.isdir(path):
continue
service_name = systemd_normpath(name) + ".service" # simulate systemd
if service_name not in self._file_for_unit_sysv:
self._file_for_unit_sysv[service_name] = path
logg.debug("found %s sysv files", len(self._file_for_unit_sysv))
return list(self._file_for_unit_sysv.keys())
def unit_sysd_file(self, module): # -> filename?
""" file path for the given module (systemd) """
if not module: return module
self.scan_unit_sysd_files()
if module and module in self._file_for_unit_sysd:
return self._file_for_unit_sysd[module]
if module and unit_of(module) in self._file_for_unit_sysd:
return self._file_for_unit_sysd[unit_of(module)]
if "@" in module:
unit_args = parse_unit(module)
unit_name = "%s@.%s" % (unit_args.prefix, unit_args.suffix)
if unit_name in self._file_for_unit_sysd:
return self._file_for_unit_sysd[unit_name]
return None
def unit_sysv_file(self, module): # -> filename?
""" file path for the given module (sysv) """
if not module: return None
self.scan_unit_sysv_files()
if module and module in self._file_for_unit_sysv:
return self._file_for_unit_sysv[module]
if module and unit_of(module) in self._file_for_unit_sysv:
return self._file_for_unit_sysv[unit_of(module)]
return None
def unit_file(self, module): # -> filename?
""" file path for the given module (sysv or systemd) """
if not module: return module
path = self.unit_sysd_file(module)
if path is not None: return path
path = self.unit_sysv_file(module)
if path is not None: return path
return None
def is_sysv_file(self, filename):
""" for routines that have a special treatment for init.d services """
self.match_all_units() # scan all
if not filename: return None
if filename in self._file_for_unit_sysd.values(): return False
if filename in self._file_for_unit_sysv.values(): return True
return None # not True
def is_user_conf(self, conf):
if not conf:
return False # no such conf >> ignored
filename = conf.filename()
if filename and "/user/" in filename:
return True
return False
def not_user_conf(self, conf):
""" conf can not be started as user service (when --user)"""
if not conf:
return True # no such conf >> ignored
if not self.user_mode():
logg.debug("%s no --user mode >> accept", conf.filename())
return False
if self.is_user_conf(conf):
logg.debug("%s is /user/ conf >> accept", conf.filename())
return False
# to allow for 'docker run -u user' with system services
user = self.expand_special(conf.get("Service", "User", ""), conf)
if user and user == self.user():
logg.debug("%s with User=%s >> accept", conf.filename(), user)
return False
return True
def find_drop_in_files(self, unit):
""" search for some.service.d/extra.conf files """
result = {}
basename_d = unit + ".d"
for folder in self.sysd_folders():
if not folder:
continue
folder = os_path(self._root, folder)
override_d = os_path(folder, basename_d)
if not os.path.isdir(override_d):
continue
for name in os.listdir(override_d):
path = os.path.join(override_d, name)
if os.path.isdir(path):
continue
if not path.endswith(".conf"):
continue
if name not in result: