-
Notifications
You must be signed in to change notification settings - Fork 9
/
systemctl.py
3223 lines (3192 loc) · 137 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
__copyright__ = "(C) 2016-2017 Guido U. Draheim, licensed under the EUPL"
__version__ = "1.0.1423"
import logging
logg = logging.getLogger("systemctl")
import re
import fnmatch
import shlex
import collections
import ConfigParser
import errno
import os
import sys
import subprocess
import signal
import time
import socket
import tempfile
DEBUG_AFTER = False
_root = ""
_sysd_default = "multi-user.target"
_sysd_folder1 = "/etc/systemd/system"
_sysd_folder2 = "/var/run/systemd/system"
_sysd_folder3 = "/usr/lib/systemd/system"
_sysd_folder4 = "/lib/systemd/system"
_sysv_folder1 = "/etc/init.d"
_sysv_folder2 = "/var/run/init.d"
_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"
_waitprocfile = 100
_waitkillproc = 10
_force = False
_quiet = False
_full = False
_now = False
_show_all = False
_unit_type = None
_unit_property = None
_no_legend = False
_no_block = False
_no_wall = False
_no_ask_password = False
_preset_mode = "all"
MinimumSleep = 2
MinimumWaitProcFile = 9
MinimumWaitKillProc = 3
DefaultWaitProcFile = 100
DefaultWaitKillProc = 9
DefaultTimeoutStartSec = 9 # officially 90
DefaultTimeoutStopSec = 9 # officially 90
DefaultMaximumTimeout = 200
_notify_socket_folder = "/var/run/systemd" # alias /run/systemd
_notify_socket_name = "notify" # NOTIFY_SOCKET="/var/run/systemd/notify"
_pid_file_folder = "/var/run"
_journal_log_folder = "/var/log/journal"
_runlevel_targets = [ "runlevel0.target", "runlevel1.target", "runlevel2.target", "runlevel3.target", "runlevel4.target", "runlevel5.target", "runlevel6.target" ]
_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 + _runlevel_targets + _feature_targets
# inside a docker we pretend the following
_all_common_enabled = [ "default.target", "runlevel3.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["$network"] = "network.target"
_sysv_mappings["$remote_fs"] = "remote-fs.target"
_sysv_mappings["$local_fs"] = "local-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 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 shutil_chown(filename, user = None, group = None):
""" in python 3.3. there is shutil.chown """
uid = -1
gid = -1
if group:
import grp
gid = grp.getgrnam(group).gr_gid
if user:
import pwd
uid = pwd.getpwnam(user).pw_uid
if os.path.exists(filename):
os.chown(filename, uid, gid)
def shutil_setuid(user = None, group = None):
""" set fork-child uid/gid """
if group: # pragma: no cover
# no cover: actually tested but in a forked child only
import grp
gid = grp.getgrnam(group).gr_gid
os.setgid(gid)
logg.debug("setgid %s '%s'", gid, group)
if user: # pragma: no cover
# no cover: actually tested but in a forked child only
import pwd
uid = pwd.getpwnam(user).pw_uid
os.setuid(uid)
logg.debug("setuid %s '%s'", uid, user)
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, e:
if e.errno == errno.ENOENT:
return False
raise
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 UnitConfigParser:
""" 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._dict = self._dict_type()
self._files = []
def defaults(self):
return self._defaults
def sections(self):
return self._dict.keys()
def add_section(self, section):
if section not in self._dict:
self._dict[section] = self._dict_type()
def has_section(self, section):
return section in self._dict
def has_option(self, section, option):
if section not in self._dict:
return False
return option in self._dict[section]
def set(self, section, option, value):
if section not in self._dict:
self._dict[section] = self._dict_type()
if option not in self._dict[section]:
self._dict[section][option] = [ value ]
else:
self._dict[section][option].append(value)
if value is None:
self._dict[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._dict:
if default is not None:
return default
if allow_no_value:
return None
logg.error("section {} does not exist".format(section))
logg.error(" have {}".format(self.sections()))
raise AttributeError("section {} does not exist".format(section))
if option not in self._dict[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._dict[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._dict[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._dict:
if default is not None:
return default
if allow_no_value:
return []
logg.error("section {} does not exist".format(section))
logg.error(" have {}".format(self.sections()))
raise AttributeError("section {} does not exist".format(section))
if option not in self._dict[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._dict[section][option] # returns a list, possibly empty
def loaded(self):
return len(self._files)
def name(self):
name = ""
filename = self.filename()
if filename:
name = os.path.basename(filename)
return self.get("Unit", "Id", name)
def filename(self):
""" returns the last filename that was parsed """
if self._files:
return self._files[-1]
return None
def read(self, filename):
return self.read_sysd(filename)
def read_sysd(self, filename):
initscript = False
initinfo = False
section = None
if os.path.isfile(filename):
self._files.append(filename)
nextline = False
name, text = "", ""
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("["):
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:
self.set(section, name, text)
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:
self.set(section, m.group(1), m.group(2).strip())
continue
description = self.get("init.d", "Description", "")
self.set("Unit", "Description", description)
check = self.get("init.d", "Required-Start","")
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","")
for item in runlevels.split(" "):
if item.strip() in _runlevel_mappings:
self.set("Install", "WantedBy", _runlevel_mappings[item.strip()])
self.set("Service", "Type", "sysv")
UnitParser = ConfigParser.RawConfigParser
UnitParser = UnitConfigParser
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
def subprocess_wait(cmd, env=None, check = False, shell=False):
# logg.warning("running = %s", cmd)
run = subprocess.Popen(cmd, shell=shell, env=env)
run.wait()
if check and run.returncode:
logg.error("returncode %i\n %s", run.returncode, cmd)
raise Exception("command failed")
return run
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: no cover
if item.endswith("min"):
try: value += 60 * int(item[:-3])
except: pass # pragma: no cover
elif item.endswith("ms"):
try: value += int(item[:-2]) / 1000.
except: pass # pragma: no cover
elif item.endswith("s"):
try: value += int(item[:-1])
except: pass # pragma: no cover
elif item:
try: value += int(item)
except: pass # pragma: no cover
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: no cover
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: no cover
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: no cover
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: no cover
logg.debug(".. %s", conf.name())
for item in sortlist:
if DEBUG_AFTER: # pragma: no cover
logg.info("(%s) %s", item.rank, item.conf.name())
sortedlist = sorted(sortlist, cmp = lambda x, y: y.rank - x.rank)
for item in sortedlist:
if DEBUG_AFTER: # pragma: no cover
logg.info("[%s] %s", item.rank, item.conf.name())
return [ item.conf for item in sortedlist ]
class Systemctl:
def __init__(self):
self._root = _root
self._sysd_folder1 = _sysd_folder1
self._sysd_folder2 = _sysd_folder2
self._sysd_folder3 = _sysd_folder3
self._sysd_folder4 = _sysd_folder4
self._sysv_folder1 = _sysv_folder1
self._sysv_folder2 = _sysv_folder2
self._preset_folder1 = _preset_folder1
self._preset_folder2 = _preset_folder2
self._preset_folder3 = _preset_folder3
self._preset_folder4 = _preset_folder4
self._notify_socket_folder = _notify_socket_folder
self._notify_socket_name = _notify_socket_name
self._pid_file_folder = _pid_file_folder
self._journal_log_folder = _journal_log_folder
self._WaitProcFile = DefaultWaitProcFile
self._WaitKillProc = DefaultWaitKillProc
self._force = _force
self._quiet = _quiet
self._full = _full
self._now = _now
self._show_all = _show_all
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
def unit_file(self, module = None): # -> filename?
""" file path for the given module (sysv or systemd) """
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 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_folder1, self._sysd_folder2, self._sysd_folder3, self._sysd_folder4):
if self._root:
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 = name
if service_name not in self._file_for_unit_sysd:
self._file_for_unit_sysd[service_name] = path
logg.debug("found %s sysd files", len(self._file_for_unit_sysd))
return self._file_for_unit_sysd.keys()
def unit_sysd_file(self, module = None): # -> filename?
""" file path for the given module (systemd) """
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 module+".service" in self._file_for_unit_sysd:
return self._file_for_unit_sysd[module+".service"]
return None
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._sysv_folder1, self._sysv_folder2):
if self._root:
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 = name+".service"
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 self._file_for_unit_sysv.keys()
def unit_sysv_file(self, module = None): # -> filename?
""" file path for the given module (sysv) """
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 module+".service" in self._file_for_unit_sysv:
return self._file_for_unit_sysv[module+".service"]
return None
def is_sysv_file(self, filename):
""" for routines that have a special treatment for init.d services """
self.unit_file() # 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 load_unit_conf(self, module): # -> conf | None(not-found)
""" read the unit file with a UnitParser (sysv or systemd) """
try:
data = self.load_sysd_unit_conf(module)
if data is not None:
return data
data = self.load_sysv_unit_conf(module)
if data is not None:
return data
except Exception, e:
logg.error("%s: %s", module, e)
return None
def load_sysd_unit_conf(self, module): # -> conf?
""" read the unit file with a UnitParser (systemd) """
path = self.unit_sysd_file(module)
if not path: return None
if path in self._loaded_file_sysd:
return self._loaded_file_sysd[path]
unit = UnitParser()
unit.read_sysd(path)
override_d = path + ".d"
if os.path.isdir(override_d):
for name in os.listdir(override_d):
path = os.path.join(override_d, name)
if os.path.isdir(path):
continue
if name.endswith(".conf"):
unit.read_sysd(path)
self._loaded_file_sysd[path] = unit
return unit
def load_sysv_unit_conf(self, module): # -> conf?
""" read the unit file with a UnitParser (sysv) """
path = self.unit_sysv_file(module)
if not path: return None
if path in self._loaded_file_sysv:
return self._loaded_file_sysv[path]
unit = UnitParser()
unit.read_sysv(path)
self._loaded_file_sysv[path] = unit
return unit
def default_unit_conf(self, module): # -> conf
""" a unit conf that can be printed to the user where
attributes are empty and loaded() is False """
conf = UnitParser()
conf.set("Unit","Id", module)
conf.set("Unit", "Names", module)
conf.set("Unit", "Description", "NOT-FOUND "+module)
return conf
def get_unit_conf(self, module): # -> conf (conf | default-conf)
""" accept that a unit does not exist
and return a unit conf that says 'not-loaded' """
conf = self.load_unit_conf(module)
if conf is not None:
return conf
return self.default_unit_conf(module)
def match_units(self, modules = None, suffix=".service"): # -> [ units,.. ]
""" Helper for about any command with multiple units which can
actually be glob patterns on their respective unit name.
It returns all modules if no modules pattern were given.
Also a single string as one module pattern may be given. """
found = []
for unit in self.match_sysd_units(modules, suffix):
if unit not in found:
found.append(unit)
for unit in self.match_sysv_units(modules, suffix):
if unit not in found:
found.append(unit)
return found
def match_sysd_units(self, modules = None, suffix=".service"): # -> generate[ unit ]
""" make a file glob on all known units (systemd areas).
It returns all modules if no modules pattern were given.
Also a single string as one module pattern may be given. """
if isinstance(modules, basestring):
modules = [ modules ]
self.scan_unit_sysd_files()
for item in sorted(self._file_for_unit_sysd.keys()):
if not modules:
yield item
elif [ module for module in modules if fnmatch.fnmatchcase(item, module) ]:
yield item
elif [ module for module in modules if module+suffix == item ]:
yield item
def match_sysv_units(self, modules = None, suffix=".service"): # -> generate[ unit ]
""" make a file glob on all known units (sysv areas).
It returns all modules if no modules pattern were given.
Also a single string as one module pattern may be given. """
if isinstance(modules, basestring):
modules = [ modules ]
self.scan_unit_sysv_files()
for item in sorted(self._file_for_unit_sysv.keys()):
if not modules:
yield item
elif [ module for module in modules if fnmatch.fnmatchcase(item, module) ]:
yield item
elif [ module for module in modules if module+suffix == item ]:
yield item
def list_service_unit_basics(self):
""" show all the basic loading state of services """
filename = self.unit_file() # scan all
result = []
for name, value in self._file_for_unit_sysd.items():
result += [ (name, "SysD", value) ]
for name, value in self._file_for_unit_sysv.items():
result += [ (name, "SysV", value) ]
return result
def list_service_units(self, *modules): # -> [ (unit,loaded+active+substate,description) ]
""" show all the service units """
result = {}
active = {}
substate = {}
description = {}
for unit in self.match_units(modules):
result[unit] = "not-found"
active[unit] = "inactive"
substate[unit] = "dead"
description[unit] = ""
try:
conf = self.get_unit_conf(unit)
result[unit] = "loaded"
description[unit] = self.get_description_from(conf)
active[unit] = self.get_active_from(conf)
substate[unit] = self.get_substate_from(conf)
except Exception, e:
logg.warning("list-units: %s", e)
return [ (unit, result[unit] + " " + active[unit] + " " + substate[unit], description[unit]) for unit in sorted(result) ]
def show_list_units(self, *modules): # -> [ (unit,loaded,description) ]
""" [PATTERN]... -- List loaded units.
If one or more PATTERNs are specified, only units matching one of
them are shown. NOTE: This is the default command."""
hint = "To show all installed unit files use 'systemctl list-unit-files'."
result = self.list_service_units(*modules)
if _no_legend:
return result
found = "%s loaded units listed." % len(result)
return result + [ "", found, hint ]
def list_service_unit_files(self, *modules): # -> [ (unit,enabled) ]
""" show all the service units and the enabled status"""
result = {}
enabled = {}
for unit in self.match_units(modules):
result[unit] = None
enabled[unit] = ""
try:
conf = self.get_unit_conf(unit)
result[unit] = conf
enabled[unit] = self.enabled_from(conf)
except Exception, e:
logg.warning("list-units: %s", e)
return [ (unit, enabled[unit]) for unit in sorted(result) ]
def list_target_unit_files(self, *modules): # -> [ (unit,enabled) ]
""" show all the target units and the enabled status"""
result = {}
enabled = {}
for unit in _all_common_targets:
result[unit] = None
enabled[unit] = "static"
if unit in _all_common_enabled:
enabled[unit] = "enabled"
if unit in _all_common_disabled:
enabled[unit] = "enabled"
return [ (unit, enabled[unit]) for unit in sorted(result) ]
def show_list_unit_files(self, *modules): # -> [ (unit,enabled) ]
"""[PATTERN]... -- List installed unit files
List installed unit files and their enablement state (as reported
by is-enabled). If one or more PATTERNs are specified, only units
whose filename (just the last component of the path) matches one of
them are shown. This command reacts to limitations of --type being
--type=service or --type=target (and --now for some basics)."""
if self._now:
result = self.list_service_unit_basics()
elif _unit_type == "target":
result = self.list_target_unit_files()
elif _unit_type == "service":
result = self.list_service_unit_files()
elif _unit_type:
logg.error("unsupported unit --type=%s", _unit_type)
result = []
else:
result = self.list_target_unit_files()
result += self.list_service_unit_files(*modules)
if _no_legend:
return result
found = "%s unit files listed." % len(result)
return [ ("UNIT FILE", "STATE") ] + result + [ "", found ]
##
##
def get_description(self, unit, default = None):
return self.get_description_from(self.load_unit_conf(unit))
def get_description_from(self, conf, default = None): # -> text
""" Unit.Description could be empty sometimes """
if not conf: return default or ""
return conf.get("Unit", "Description", default or "")
def write_pid_file(self, pid_file, pid): # -> bool(written)
""" if a pid_file is known then path is created and the
give pid is written as the only content. """
if not pid_file:
logg.debug("pid %s but no pid_file", pid)
return False
dirpath = os.path.dirname(os.path.abspath(pid_file))
if not os.path.isdir(dirpath):
os.makedirs(dirpath)
try:
with open(pid_file, "w") as f:
f.write("{}\n".format(pid))
except IOError, e:
logg.error("PID %s -- %s", pid, e)
return True
def read_pid_file(self, pid_file, default = None):
pid = default
if not pid_file:
return default
if not os.path.isfile(pid_file):
return default
try:
for line in open(pid_file):
if line.strip():
pid = to_int(line.strip())
break
except:
logg.warning("bad read of pid file '%s'", pid_file)
return pid
def wait_pid_file(self, pid_file, timeout = None): # -> pid?
""" wait some seconds for the pid file to appear and return the pid """
timeout = int(timeout or self._WaitProcFile)
timeout = max(timeout, MinimumWaitProcFile)
dirpath = os.path.dirname(os.path.abspath(pid_file))
for x in xrange(timeout):
if not os.path.isdir(dirpath):
self.sleep(1)
continue
pid = self.read_pid_file(pid_file)
if not pid:
self.sleep(1)
continue
if not pid_exists(pid):
self.sleep(1)
continue
return pid
return None
def default_pid_file(self, unit): # -> text
""" default file pattern where to store a pid """
folder = self._pid_file_folder
if self._root:
folder = os_path(self._root, folder)
name = "%s.pid" % unit
return os.path.join(folder, name)
def get_pid_file(self, unit):
""" get the specified or default pid file path """
conf = self.load_unit_conf(unit)
if conf is None:
logg.error("no such unit: '%s'", unit)
return None
return self.get_pid_file_from(conf)
def get_pid_file_from(self, conf, default = None):
""" get the specified or default pid file path """
if not conf: return default
if not conf.filename(): return default
unit = os.path.basename(conf.filename())
if default is None:
default = self.default_pid_file(unit)
return self.pid_file_from(conf, default)
def pid_file_from(self, conf, default = ""):
""" get the specified pid file path (not a computed default) """
return conf.get("Service", "PIDFile", default)
def default_status_file(self, unit): # -> text
""" default file pattern where to store a status mark """
folder = self._pid_file_folder
if self._root:
folder = os_path(self._root, folder)
name = "%s.status" % unit
return os.path.join(folder, name)
def get_status_file(self, unit):
conf = self.load_unit_conf(unit)
if conf is None:
logg.error("no such unit: '%s'", unit)
return None
return self.get_status_file_from(conf)
def get_status_file_from(self, conf, default = None):
if not conf: return default
if not conf.filename(): return default
unit = os.path.basename(conf.filename())
if default is None:
default = self.default_status_file(unit)
return self.status_file_from(conf, default)
def status_file_from(self, conf, default = ""):
return conf.get("Service", "StatusFile", default)
# this not a real setting.
def write_status_file(self, status_file, **status): # -> bool(written)
""" if a status_file is known then path is created and the
give status is written as the only content. """
if not status_file:
logg.debug("status %s but no status_file", pid)
return False
dirpath = os.path.dirname(os.path.abspath(status_file))
if not os.path.isdir(dirpath):
os.makedirs(dirpath)
try:
with open(status_file, "w") as f:
for key in sorted(status.keys()):
value = status[key]
if value is None: value = ""
if key.upper() == "AS": key = "ACTIVESTATE"
if key.upper() == "PID": key = "MAINPID"
if key.upper() == "EXIT": key = "EXIT_STATUS"
f.write("{}={}\n".format(key.upper(), str(value)))
except IOError, e:
logg.error("STATUS %s -- %s", status, e)
return True
def read_status_file(self, status_file, defaults = None):
status = {}
if hasattr(defaults, "keys"):
for key in defaults.keys():
status[key] = defaults[key]
elif isinstance(defaults, basestring):
status["ACTIVESTATE"] = defaults
if not status_file:
return status
if not os.path.isfile(status_file):
return status
try:
for line in open(status_file):
if line.strip():
m = re.match(r"^(\w+)[:=](.*)", line)
if m:
key, value = m.group(1), m.group(2)
if key.strip():
status[key.strip()] = value.strip()
elif line in [ "active", "inactive", "failed"]:
status["ACTIVESTATE"] = line
else:
logg.warning("ignored %s", line.strip())
except:
logg.warning("bad read of status file '%s'", status_file)
return status
#
def sleep(self, seconds = None):
""" just sleep """
seconds = seconds or MinimumSleep
time.sleep(seconds)
def read_env_file(self, env_file): # -> generate[ (name,value) ]
""" EnvironmentFile=<name> is being scanned """
if env_file.startswith("-"):
env_file = env_file[1:]
if not os.path.isfile(os_path(self._root, env_file)):
return
try:
for real_line in open(os_path(self._root, env_file)):
line = real_line.strip()
if not line or line.startswith("#"):
continue