You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6851 lines
296 KiB

  1. #! /usr/bin/python3
  2. # type hints are provided in 'types/systemctl3.pyi'
  3. from __future__ import print_function
  4. import threading
  5. import grp
  6. import pwd
  7. import hashlib
  8. import select
  9. import fcntl
  10. import string
  11. import datetime
  12. import socket
  13. import time
  14. import signal
  15. import sys
  16. import os
  17. import errno
  18. import collections
  19. import shlex
  20. import fnmatch
  21. import re
  22. from types import GeneratorType
  23. __copyright__ = "(C) 2016-2024 Guido U. Draheim, licensed under the EUPL"
  24. __version__ = "1.5.8066"
  25. # |
  26. # |
  27. # |
  28. # |
  29. # |
  30. # |
  31. # |
  32. # |
  33. # |
  34. # |
  35. # |
  36. # |
  37. # |
  38. import logging
  39. logg = logging.getLogger("systemctl")
  40. if sys.version[0] == '3':
  41. basestring = str
  42. xrange = range
  43. DEBUG_AFTER = False
  44. DEBUG_STATUS = False
  45. DEBUG_BOOTTIME = False
  46. DEBUG_INITLOOP = False
  47. DEBUG_KILLALL = False
  48. DEBUG_FLOCK = False
  49. DebugPrintResult = False
  50. TestListen = False
  51. TestAccept = False
  52. HINT = (logging.DEBUG + logging.INFO) // 2
  53. NOTE = (logging.WARNING + logging.INFO) // 2
  54. DONE = (logging.WARNING + logging.ERROR) // 2
  55. logging.addLevelName(HINT, "HINT")
  56. logging.addLevelName(NOTE, "NOTE")
  57. logging.addLevelName(DONE, "DONE")
  58. def logg_debug_flock(format, *args):
  59. if DEBUG_FLOCK:
  60. logg.debug(format, *args) # pragma: no cover
  61. def logg_debug_after(format, *args):
  62. if DEBUG_AFTER:
  63. logg.debug(format, *args) # pragma: no cover
  64. NOT_A_PROBLEM = 0 # FOUND_OK
  65. NOT_OK = 1 # FOUND_ERROR
  66. NOT_ACTIVE = 2 # FOUND_INACTIVE
  67. NOT_FOUND = 4 # FOUND_UNKNOWN
  68. # defaults for options
  69. _extra_vars = []
  70. _force = False
  71. _full = False
  72. _log_lines = 0
  73. _no_pager = False
  74. _now = False
  75. _no_reload = False
  76. _no_legend = False
  77. _no_ask_password = False
  78. _preset_mode = "all"
  79. _quiet = False
  80. _root = ""
  81. _show_all = False
  82. _user_mode = False
  83. _only_what = []
  84. _only_type = []
  85. _only_state = []
  86. _only_property = []
  87. # common default paths
  88. _system_folders = [
  89. "/etc/systemd/system",
  90. "/run/systemd/system",
  91. "/var/run/systemd/system",
  92. "/usr/local/lib/systemd/system",
  93. "/usr/lib/systemd/system",
  94. "/lib/systemd/system",
  95. ]
  96. _user_folders = [
  97. "{XDG_CONFIG_HOME}/systemd/user",
  98. "/etc/systemd/user",
  99. "{XDG_RUNTIME_DIR}/systemd/user",
  100. "/run/systemd/user",
  101. "/var/run/systemd/user",
  102. "{XDG_DATA_HOME}/systemd/user",
  103. "/usr/local/lib/systemd/user",
  104. "/usr/lib/systemd/user",
  105. "/lib/systemd/user",
  106. ]
  107. _init_folders = [
  108. "/etc/init.d",
  109. "/run/init.d",
  110. "/var/run/init.d",
  111. ]
  112. _preset_folders = [
  113. "/etc/systemd/system-preset",
  114. "/run/systemd/system-preset",
  115. "/var/run/systemd/system-preset",
  116. "/usr/local/lib/systemd/system-preset",
  117. "/usr/lib/systemd/system-preset",
  118. "/lib/systemd/system-preset",
  119. ]
  120. # standard paths
  121. _dev_null = "/dev/null"
  122. _dev_zero = "/dev/zero"
  123. _etc_hosts = "/etc/hosts"
  124. _rc3_boot_folder = "/etc/rc3.d"
  125. _rc3_init_folder = "/etc/init.d/rc3.d"
  126. _rc5_boot_folder = "/etc/rc5.d"
  127. _rc5_init_folder = "/etc/init.d/rc5.d"
  128. _proc_pid_stat = "/proc/{pid}/stat"
  129. _proc_pid_status = "/proc/{pid}/status"
  130. _proc_pid_cmdline= "/proc/{pid}/cmdline"
  131. _proc_pid_dir = "/proc"
  132. _proc_sys_uptime = "/proc/uptime"
  133. _proc_sys_stat = "/proc/stat"
  134. # default values
  135. SystemCompatibilityVersion = 219
  136. SysInitTarget = "sysinit.target"
  137. SysInitWait = 5 # max for target
  138. MinimumYield = 0.5
  139. MinimumTimeoutStartSec = 4
  140. MinimumTimeoutStopSec = 4
  141. DefaultTimeoutStartSec = 90 # official value
  142. DefaultTimeoutStopSec = 90 # official value
  143. DefaultTimeoutAbortSec = 3600 # officially it none (usually larget than StopSec)
  144. DefaultMaximumTimeout = 200 # overrides all other
  145. DefaultRestartSec = 0.1 # official value of 100ms
  146. DefaultStartLimitIntervalSec = 10 # official value
  147. DefaultStartLimitBurst = 5 # official value
  148. InitLoopSleep = 5
  149. MaxLockWait = 0 # equals DefaultMaximumTimeout
  150. DefaultPath = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  151. ResetLocale = ["LANG", "LANGUAGE", "LC_CTYPE", "LC_NUMERIC", "LC_TIME", "LC_COLLATE", "LC_MONETARY",
  152. "LC_MESSAGES", "LC_PAPER", "LC_NAME", "LC_ADDRESS", "LC_TELEPHONE", "LC_MEASUREMENT",
  153. "LC_IDENTIFICATION", "LC_ALL"]
  154. LocaleConf="/etc/locale.conf"
  155. DefaultListenBacklog=2
  156. ExitWhenNoMoreServices = False
  157. ExitWhenNoMoreProcs = False
  158. DefaultUnit = os.environ.get("SYSTEMD_DEFAULT_UNIT", "default.target") # systemd.exe --unit=default.target
  159. DefaultTarget = os.environ.get("SYSTEMD_DEFAULT_TARGET", "multi-user.target") # DefaultUnit fallback
  160. # LogLevel = os.environ.get("SYSTEMD_LOG_LEVEL", "info") # systemd.exe --log-level
  161. # LogTarget = os.environ.get("SYSTEMD_LOG_TARGET", "journal-or-kmsg") # systemd.exe --log-target
  162. # LogLocation = os.environ.get("SYSTEMD_LOG_LOCATION", "no") # systemd.exe --log-location
  163. # ShowStatus = os.environ.get("SYSTEMD_SHOW_STATUS", "auto") # systemd.exe --show-status
  164. DefaultStandardInput=os.environ.get("SYSTEMD_STANDARD_INPUT", "null")
  165. DefaultStandardOutput=os.environ.get("SYSTEMD_STANDARD_OUTPUT", "journal") # systemd.exe --default-standard-output
  166. DefaultStandardError=os.environ.get("SYSTEMD_STANDARD_ERROR", "inherit") # systemd.exe --default-standard-error
  167. EXEC_SPAWN = False
  168. EXEC_DUP2 = True
  169. REMOVE_LOCK_FILE = False
  170. BOOT_PID_MIN = 0
  171. BOOT_PID_MAX = -9
  172. PROC_MAX_DEPTH = 100
  173. EXPAND_VARS_MAXDEPTH = 20
  174. EXPAND_KEEP_VARS = True
  175. RESTART_FAILED_UNITS = True
  176. ACTIVE_IF_ENABLED=False
  177. TAIL_CMDS = ["/bin/tail", "/usr/bin/tail", "/usr/local/bin/tail"]
  178. LESS_CMDS = ["/bin/less", "/usr/bin/less", "/usr/local/bin/less"]
  179. CAT_CMDS = ["/bin/cat", "/usr/bin/cat", "/usr/local/bin/cat"]
  180. # The systemd default was NOTIFY_SOCKET="/var/run/systemd/notify"
  181. _notify_socket_folder = "{RUN}/systemd" # alias /run/systemd
  182. _journal_log_folder = "{LOG}/journal"
  183. SYSTEMCTL_DEBUG_LOG = "{LOG}/systemctl.debug.log"
  184. SYSTEMCTL_EXTRA_LOG = "{LOG}/systemctl.log"
  185. _default_targets = ["poweroff.target", "rescue.target", "sysinit.target", "basic.target", "multi-user.target", "graphical.target", "reboot.target"]
  186. _feature_targets = ["network.target", "remote-fs.target", "local-fs.target", "timers.target", "nfs-client.target"]
  187. _all_common_targets = ["default.target"] + _default_targets + _feature_targets
  188. # inside a docker we pretend the following
  189. _all_common_enabled = ["default.target", "multi-user.target", "remote-fs.target"]
  190. _all_common_disabled = ["graphical.target", "resue.target", "nfs-client.target"]
  191. target_requires = {"graphical.target": "multi-user.target", "multi-user.target": "basic.target", "basic.target": "sockets.target"}
  192. _runlevel_mappings = {} # the official list
  193. _runlevel_mappings["0"] = "poweroff.target"
  194. _runlevel_mappings["1"] = "rescue.target"
  195. _runlevel_mappings["2"] = "multi-user.target"
  196. _runlevel_mappings["3"] = "multi-user.target"
  197. _runlevel_mappings["4"] = "multi-user.target"
  198. _runlevel_mappings["5"] = "graphical.target"
  199. _runlevel_mappings["6"] = "reboot.target"
  200. _sysv_mappings = {} # by rule of thumb
  201. _sysv_mappings["$local_fs"] = "local-fs.target"
  202. _sysv_mappings["$network"] = "network.target"
  203. _sysv_mappings["$remote_fs"] = "remote-fs.target"
  204. _sysv_mappings["$timer"] = "timers.target"
  205. # sections from conf
  206. Unit = "Unit"
  207. Service = "Service"
  208. Socket = "Socket"
  209. Install = "Install"
  210. # https://tldp.org/LDP/abs/html/exitcodes.html
  211. # https://freedesktop.org/software/systemd/man/systemd.exec.html#id-1.20.8
  212. EXIT_SUCCESS = 0
  213. EXIT_FAILURE = 1
  214. def strINET(value):
  215. if value == socket.SOCK_DGRAM:
  216. return "UDP"
  217. if value == socket.SOCK_STREAM:
  218. return "TCP"
  219. if value == socket.SOCK_RAW: # pragma: no cover
  220. return "RAW"
  221. if value == socket.SOCK_RDM: # pragma: no cover
  222. return "RDM"
  223. if value == socket.SOCK_SEQPACKET: # pragma: no cover
  224. return "SEQ"
  225. return "<?>" # pragma: no cover
  226. def strYes(value):
  227. if value is True:
  228. return "yes"
  229. if not value:
  230. return "no"
  231. return str(value)
  232. def strE(part):
  233. if not part:
  234. return ""
  235. return str(part)
  236. def strQ(part):
  237. if part is None:
  238. return ""
  239. if isinstance(part, int):
  240. return str(part)
  241. return "'%s'" % part
  242. def shell_cmd(cmd):
  243. return " ".join([strQ(part) for part in cmd])
  244. def to_intN(value, default = None):
  245. if not value:
  246. return default
  247. try:
  248. return int(value)
  249. except:
  250. return default
  251. def to_int(value, default = 0):
  252. try:
  253. return int(value)
  254. except:
  255. return default
  256. def to_list(value):
  257. if not value:
  258. return []
  259. if isinstance(value, list):
  260. return value
  261. if isinstance(value, tuple):
  262. return list(value)
  263. return str(value or "").split(",")
  264. def commalist(value):
  265. return list(_commalist(value))
  266. def _commalist(value):
  267. for val in value:
  268. if not val:
  269. continue
  270. for elem in val.strip().split(","):
  271. yield elem
  272. def int_mode(value):
  273. try: return int(value, 8)
  274. except: return None # pragma: no cover
  275. def unit_of(module):
  276. if "." not in module:
  277. return module + ".service"
  278. return module
  279. def o22(part):
  280. if isinstance(part, basestring):
  281. if len(part) <= 22:
  282. return part
  283. return part[:5] + "..." + part[-14:]
  284. return part # pragma: no cover (is always str)
  285. def o44(part):
  286. if isinstance(part, basestring):
  287. if len(part) <= 44:
  288. return part
  289. return part[:10] + "..." + part[-31:]
  290. return part # pragma: no cover (is always str)
  291. def o77(part):
  292. if isinstance(part, basestring):
  293. if len(part) <= 77:
  294. return part
  295. return part[:20] + "..." + part[-54:]
  296. return part # pragma: no cover (is always str)
  297. def path44(filename):
  298. if not filename:
  299. return "<none>"
  300. x = filename.find("/", 8)
  301. if len(filename) <= 40:
  302. if "/" not in filename:
  303. return ".../" + filename
  304. elif len(filename) <= 44:
  305. return filename
  306. if 0 < x and x < 14:
  307. out = filename[:x+1]
  308. out += "..."
  309. else:
  310. out = filename[:10]
  311. out += "..."
  312. remain = len(filename) - len(out)
  313. y = filename.find("/", remain)
  314. if 0 < y and y < remain+5:
  315. out += filename[y:]
  316. else:
  317. out += filename[remain:]
  318. return out
  319. def unit_name_escape(text):
  320. # https://www.freedesktop.org/software/systemd/man/systemd.unit.html#id-1.6
  321. esc = re.sub("([^a-z-AZ.-/])", lambda m: "\\x%02x" % ord(m.group(1)[0]), text)
  322. return esc.replace("/", "-")
  323. def unit_name_unescape(text):
  324. esc = text.replace("-", "/")
  325. return re.sub("\\\\x(..)", lambda m: "%c" % chr(int(m.group(1), 16)), esc)
  326. def is_good_root(root):
  327. if not root:
  328. return True
  329. return root.strip(os.path.sep).count(os.path.sep) > 1
  330. def os_path(root, path):
  331. if not root:
  332. return path
  333. if not path:
  334. return path
  335. if is_good_root(root) and path.startswith(root):
  336. return path
  337. while path.startswith(os.path.sep):
  338. path = path[1:]
  339. return os.path.join(root, path)
  340. def path_replace_extension(path, old, new):
  341. if path.endswith(old):
  342. path = path[:-len(old)]
  343. return path + new
  344. def get_exist_path(paths):
  345. for p in paths:
  346. if os.path.exists(p):
  347. return p
  348. return None
  349. def get_PAGER():
  350. PAGER = os.environ.get("PAGER", "less")
  351. pager = os.environ.get("SYSTEMD_PAGER", "{PAGER}").format(**locals())
  352. options = os.environ.get("SYSTEMD_LESS", "FRSXMK") # see 'man timedatectl'
  353. if not pager: pager = "cat"
  354. if "less" in pager and options:
  355. return [pager, "-" + options]
  356. return [pager]
  357. def os_getlogin():
  358. """ NOT using os.getlogin() """
  359. return pwd.getpwuid(os.geteuid()).pw_name
  360. def get_runtime_dir():
  361. explicit = os.environ.get("XDG_RUNTIME_DIR", "")
  362. if explicit: return explicit
  363. user = os_getlogin()
  364. return "/tmp/run-"+user
  365. def get_RUN(root = False):
  366. tmp_var = get_TMP(root)
  367. if _root:
  368. tmp_var = _root
  369. if root:
  370. for p in ("/run", "/var/run", "{tmp_var}/run"):
  371. path = p.format(**locals())
  372. if os.path.isdir(path) and os.access(path, os.W_OK):
  373. return path
  374. os.makedirs(path) # "/tmp/run"
  375. return path
  376. else:
  377. uid = get_USER_ID(root)
  378. for p in ("/run/user/{uid}", "/var/run/user/{uid}", "{tmp_var}/run-{uid}"):
  379. path = p.format(**locals())
  380. if os.path.isdir(path) and os.access(path, os.W_OK):
  381. return path
  382. os.makedirs(path, 0o700) # "/tmp/run/user/{uid}"
  383. return path
  384. def get_PID_DIR(root = False):
  385. if root:
  386. return get_RUN(root)
  387. else:
  388. return os.path.join(get_RUN(root), "run") # compat with older systemctl.py
  389. def get_home():
  390. if False: # pragma: no cover
  391. explicit = os.environ.get("HOME", "") # >> On Unix, an initial ~ (tilde) is replaced by the
  392. if explicit: return explicit # environment variable HOME if it is set; otherwise
  393. uid = os.geteuid() # the current users home directory is looked up in the
  394. # # password directory through the built-in module pwd.
  395. return pwd.getpwuid(uid).pw_name # An initial ~user i looked up directly in the
  396. return os.path.expanduser("~") # password directory. << from docs(os.path.expanduser)
  397. def get_HOME(root = False):
  398. if root: return "/root"
  399. return get_home()
  400. def get_USER_ID(root = False):
  401. ID = 0
  402. if root: return ID
  403. return os.geteuid()
  404. def get_USER(root = False):
  405. if root: return "root"
  406. uid = os.geteuid()
  407. return pwd.getpwuid(uid).pw_name
  408. def get_GROUP_ID(root = False):
  409. ID = 0
  410. if root: return ID
  411. return os.getegid()
  412. def get_GROUP(root = False):
  413. if root: return "root"
  414. gid = os.getegid()
  415. return grp.getgrgid(gid).gr_name
  416. def get_TMP(root = False):
  417. TMP = "/tmp"
  418. if root: return TMP
  419. return os.environ.get("TMPDIR", os.environ.get("TEMP", os.environ.get("TMP", TMP)))
  420. def get_VARTMP(root = False):
  421. VARTMP = "/var/tmp"
  422. if root: return VARTMP
  423. return os.environ.get("TMPDIR", os.environ.get("TEMP", os.environ.get("TMP", VARTMP)))
  424. def get_SHELL(root = False):
  425. SHELL = "/bin/sh"
  426. if root: return SHELL
  427. return os.environ.get("SHELL", SHELL)
  428. def get_RUNTIME_DIR(root = False):
  429. RUN = "/run"
  430. if root: return RUN
  431. return os.environ.get("XDG_RUNTIME_DIR", get_runtime_dir())
  432. def get_CONFIG_HOME(root = False):
  433. CONFIG = "/etc"
  434. if root: return CONFIG
  435. HOME = get_HOME(root)
  436. return os.environ.get("XDG_CONFIG_HOME", HOME + "/.config")
  437. def get_CACHE_HOME(root = False):
  438. CACHE = "/var/cache"
  439. if root: return CACHE
  440. HOME = get_HOME(root)
  441. return os.environ.get("XDG_CACHE_HOME", HOME + "/.cache")
  442. def get_DATA_HOME(root = False):
  443. SHARE = "/usr/share"
  444. if root: return SHARE
  445. HOME = get_HOME(root)
  446. return os.environ.get("XDG_DATA_HOME", HOME + "/.local/share")
  447. def get_LOG_DIR(root = False):
  448. LOGDIR = "/var/log"
  449. if root: return LOGDIR
  450. CONFIG = get_CONFIG_HOME(root)
  451. return os.path.join(CONFIG, "log")
  452. def get_VARLIB_HOME(root = False):
  453. VARLIB = "/var/lib"
  454. if root: return VARLIB
  455. CONFIG = get_CONFIG_HOME(root)
  456. return CONFIG
  457. def expand_path(path, root = False):
  458. HOME = get_HOME(root)
  459. RUN = get_RUN(root)
  460. LOG = get_LOG_DIR(root)
  461. XDG_DATA_HOME=get_DATA_HOME(root)
  462. XDG_CONFIG_HOME=get_CONFIG_HOME(root)
  463. XDG_RUNTIME_DIR=get_RUNTIME_DIR(root)
  464. return os.path.expanduser(path.replace("${", "{").format(**locals()))
  465. def shutil_chown(path, user, group):
  466. if user or group:
  467. uid, gid = -1, -1
  468. if user:
  469. uid = pwd.getpwnam(user).pw_uid
  470. gid = pwd.getpwnam(user).pw_gid
  471. if group:
  472. gid = grp.getgrnam(group).gr_gid
  473. os.chown(path, uid, gid)
  474. def shutil_fchown(fileno, user, group):
  475. if user or group:
  476. uid, gid = -1, -1
  477. if user:
  478. uid = pwd.getpwnam(user).pw_uid
  479. gid = pwd.getpwnam(user).pw_gid
  480. if group:
  481. gid = grp.getgrnam(group).gr_gid
  482. os.fchown(fileno, uid, gid)
  483. def shutil_setuid(user = None, group = None, xgroups = None):
  484. """ set fork-child uid/gid (returns pw-info env-settings)"""
  485. if group:
  486. gid = grp.getgrnam(group).gr_gid
  487. os.setgid(gid)
  488. logg.debug("setgid %s for %s", gid, strQ(group))
  489. groups = [gid]
  490. try:
  491. os.setgroups(groups)
  492. logg.debug("setgroups %s < (%s)", groups, group)
  493. except OSError as e: # pragma: no cover (it will occur in non-root mode anyway)
  494. logg.debug("setgroups %s < (%s) : %s", groups, group, e)
  495. if user:
  496. pw = pwd.getpwnam(user)
  497. gid = pw.pw_gid
  498. gname = grp.getgrgid(gid).gr_name
  499. if not group:
  500. os.setgid(gid)
  501. logg.debug("setgid %s for user %s", gid, strQ(user))
  502. groupnames = [g.gr_name for g in grp.getgrall() if user in g.gr_mem]
  503. groups = [g.gr_gid for g in grp.getgrall() if user in g.gr_mem]
  504. if xgroups:
  505. groups += [g.gr_gid for g in grp.getgrall() if g.gr_name in xgroups and g.gr_gid not in groups]
  506. if not groups:
  507. if group:
  508. gid = grp.getgrnam(group).gr_gid
  509. groups = [gid]
  510. try:
  511. os.setgroups(groups)
  512. logg.debug("setgroups %s > %s ", groups, groupnames)
  513. except OSError as e: # pragma: no cover (it will occur in non-root mode anyway)
  514. logg.debug("setgroups %s > %s : %s", groups, groupnames, e)
  515. uid = pw.pw_uid
  516. os.setuid(uid)
  517. logg.debug("setuid %s for user %s", uid, strQ(user))
  518. home = pw.pw_dir
  519. shell = pw.pw_shell
  520. logname = pw.pw_name
  521. return {"USER": user, "LOGNAME": logname, "HOME": home, "SHELL": shell}
  522. return {}
  523. def shutil_truncate(filename):
  524. """ truncates the file (or creates a new empty file)"""
  525. filedir = os.path.dirname(filename)
  526. if not os.path.isdir(filedir):
  527. os.makedirs(filedir)
  528. f = open(filename, "w")
  529. f.write("")
  530. f.close()
  531. # http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid
  532. def pid_exists(pid):
  533. """Check whether pid exists in the current process table."""
  534. if pid is None: # pragma: no cover (is never null)
  535. return False
  536. return _pid_exists(int(pid))
  537. def _pid_exists(pid):
  538. """Check whether pid exists in the current process table.
  539. UNIX only.
  540. """
  541. if pid < 0:
  542. return False
  543. if pid == 0:
  544. # According to "man 2 kill" PID 0 refers to every process
  545. # in the process group of the calling process.
  546. # On certain systems 0 is a valid PID but we have no way
  547. # to know that in a portable fashion.
  548. raise ValueError('invalid PID 0')
  549. try:
  550. os.kill(pid, 0)
  551. except OSError as err:
  552. if err.errno == errno.ESRCH:
  553. # ESRCH == No such process
  554. return False
  555. elif err.errno == errno.EPERM:
  556. # EPERM clearly means there's a process to deny access to
  557. return True
  558. else:
  559. # According to "man 2 kill" possible error values are
  560. # (EINVAL, EPERM, ESRCH)
  561. raise
  562. else:
  563. return True
  564. def pid_zombie(pid):
  565. """ may be a pid exists but it is only a zombie """
  566. if pid is None:
  567. return False
  568. return _pid_zombie(int(pid))
  569. def _pid_zombie(pid):
  570. """ may be a pid exists but it is only a zombie """
  571. if pid < 0:
  572. return False
  573. if pid == 0:
  574. # According to "man 2 kill" PID 0 refers to every process
  575. # in the process group of the calling process.
  576. # On certain systems 0 is a valid PID but we have no way
  577. # to know that in a portable fashion.
  578. raise ValueError('invalid PID 0')
  579. check = _proc_pid_status.format(**locals())
  580. try:
  581. for line in open(check):
  582. if line.startswith("State:"):
  583. return "Z" in line
  584. except IOError as e:
  585. if e.errno != errno.ENOENT:
  586. logg.error("%s (%s): %s", check, e.errno, e)
  587. return False
  588. return False
  589. def checkprefix(cmd):
  590. prefix = ""
  591. for i, c in enumerate(cmd):
  592. if c in "-+!@:":
  593. prefix = prefix + c
  594. else:
  595. newcmd = cmd[i:]
  596. return prefix, newcmd
  597. return prefix, ""
  598. ExecMode = collections.namedtuple("ExecMode", ["mode", "check", "nouser", "noexpand", "argv0"])
  599. def exec_path(cmd):
  600. """ Hint: exec_path values are usually not moved by --root (while load_path are)"""
  601. prefix, newcmd = checkprefix(cmd)
  602. check = "-" not in prefix
  603. nouser = "+" in prefix or "!" in prefix
  604. noexpand = ":" in prefix
  605. argv0 = "@" in prefix
  606. mode = ExecMode(prefix, check, nouser, noexpand, argv0)
  607. return mode, newcmd
  608. LoadMode = collections.namedtuple("LoadMode", ["mode", "check"])
  609. def load_path(ref):
  610. """ Hint: load_path values are usually moved by --root (while exec_path are not)"""
  611. prefix, filename = "", ref
  612. while filename.startswith("-"):
  613. prefix = prefix + filename[0]
  614. filename = filename[1:]
  615. check = "-" not in prefix
  616. mode = LoadMode(prefix, check)
  617. return mode, filename
  618. # https://github.com/phusion/baseimage-docker/blob/rel-0.9.16/image/bin/my_init
  619. def ignore_signals_and_raise_keyboard_interrupt(signame):
  620. signal.signal(signal.SIGTERM, signal.SIG_IGN)
  621. signal.signal(signal.SIGINT, signal.SIG_IGN)
  622. raise KeyboardInterrupt(signame)
  623. _default_dict_type = collections.OrderedDict
  624. _default_conf_type = collections.OrderedDict
  625. class SystemctlConfData:
  626. """ A *.service files has a structure similar to an *.ini file so
  627. that data is structured in sections and values. Actually the
  628. values are lists - the raw data is in .getlist(). Otherwise
  629. .get() will return the first line that was encountered. """
  630. # |
  631. # |
  632. # |
  633. # |
  634. # |
  635. # |
  636. def __init__(self, defaults=None, dict_type=None, conf_type=None, allow_no_value=False):
  637. self._defaults = defaults or {}
  638. self._conf_type = conf_type or _default_conf_type
  639. self._dict_type = dict_type or _default_dict_type
  640. self._allow_no_value = allow_no_value
  641. self._conf = self._conf_type()
  642. self._files = []
  643. def defaults(self):
  644. return self._defaults
  645. def sections(self):
  646. return list(self._conf.keys())
  647. def add_section(self, section):
  648. if section not in self._conf:
  649. self._conf[section] = self._dict_type()
  650. def has_section(self, section):
  651. return section in self._conf
  652. def has_option(self, section, option):
  653. if section not in self._conf:
  654. return False
  655. return option in self._conf[section]
  656. def set(self, section, option, value):
  657. if section not in self._conf:
  658. self._conf[section] = self._dict_type()
  659. if value is None:
  660. self._conf[section][option] = []
  661. elif option not in self._conf[section]:
  662. self._conf[section][option] = [value]
  663. else:
  664. self._conf[section][option].append(value)
  665. def getstr(self, section, option, default = None, allow_no_value = False):
  666. done = self.get(section, option, strE(default), allow_no_value)
  667. if done is None: return strE(default)
  668. return done
  669. def get(self, section, option, default = None, allow_no_value = False):
  670. allow_no_value = allow_no_value or self._allow_no_value
  671. if section not in self._conf:
  672. if default is not None:
  673. return default
  674. if allow_no_value:
  675. return None
  676. logg.warning("section {} does not exist".format(section))
  677. logg.warning(" have {}".format(self.sections()))
  678. raise AttributeError("section {} does not exist".format(section))
  679. if option not in self._conf[section]:
  680. if default is not None:
  681. return default
  682. if allow_no_value:
  683. return None
  684. raise AttributeError("option {} in {} does not exist".format(option, section))
  685. if not self._conf[section][option]: # i.e. an empty list
  686. if default is not None:
  687. return default
  688. if allow_no_value:
  689. return None
  690. raise AttributeError("option {} in {} is None".format(option, section))
  691. return self._conf[section][option][0] # the first line in the list of configs
  692. def getlist(self, section, option, default = None, allow_no_value = False):
  693. allow_no_value = allow_no_value or self._allow_no_value
  694. if section not in self._conf:
  695. if default is not None:
  696. return default
  697. if allow_no_value:
  698. return []
  699. logg.warning("section {} does not exist".format(section))
  700. logg.warning(" have {}".format(self.sections()))
  701. raise AttributeError("section {} does not exist".format(section))
  702. if option not in self._conf[section]:
  703. if default is not None:
  704. return default
  705. if allow_no_value:
  706. return []
  707. raise AttributeError("option {} in {} does not exist".format(option, section))
  708. return self._conf[section][option] # returns a list, possibly empty
  709. def filenames(self):
  710. return self._files
  711. class SystemctlConfigParser(SystemctlConfData):
  712. """ A *.service files has a structure similar to an *.ini file but it is
  713. actually not like it. Settings may occur multiple times in each section
  714. and they create an implicit list. In reality all the settings are
  715. globally uniqute, so that an 'environment' can be printed without
  716. adding prefixes. Settings are continued with a backslash at the end
  717. of the line. """
  718. # def __init__(self, defaults=None, dict_type=None, allow_no_value=False):
  719. # SystemctlConfData.__init__(self, defaults, dict_type, allow_no_value)
  720. def read(self, filename):
  721. return self.read_sysd(filename)
  722. def read_sysd(self, filename):
  723. initscript = False
  724. initinfo = False
  725. section = "GLOBAL"
  726. nextline = False
  727. name, text = "", ""
  728. if os.path.isfile(filename):
  729. self._files.append(filename)
  730. for orig_line in open(filename):
  731. if nextline:
  732. text += orig_line
  733. if text.rstrip().endswith("\\") or text.rstrip().endswith("\\\n"):
  734. text = text.rstrip() + "\n"
  735. else:
  736. self.set(section, name, text)
  737. nextline = False
  738. continue
  739. line = orig_line.strip()
  740. if not line:
  741. continue
  742. if line.startswith("#"):
  743. continue
  744. if line.startswith(";"):
  745. continue
  746. if line.startswith(".include"):
  747. logg.error("the '.include' syntax is deprecated. Use x.service.d/ drop-in files!")
  748. includefile = re.sub(r'^\.include[ ]*', '', line).rstrip()
  749. if not os.path.isfile(includefile):
  750. raise Exception("tried to include file that doesn't exist: %s" % includefile)
  751. self.read_sysd(includefile)
  752. continue
  753. if line.startswith("["):
  754. x = line.find("]")
  755. if x > 0:
  756. section = line[1:x]
  757. self.add_section(section)
  758. continue
  759. m = re.match(r"(\w+) *=(.*)", line)
  760. if not m:
  761. logg.warning("bad ini line: %s", line)
  762. raise Exception("bad ini line")
  763. name, text = m.group(1), m.group(2).strip()
  764. if text.endswith("\\") or text.endswith("\\\n"):
  765. nextline = True
  766. text = text + "\n"
  767. else:
  768. # hint: an empty line shall reset the value-list
  769. self.set(section, name, text and text or None)
  770. return self
  771. def read_sysv(self, filename):
  772. """ an LSB header is scanned and converted to (almost)
  773. equivalent settings of a SystemD ini-style input """
  774. initscript = False
  775. initinfo = False
  776. section = "GLOBAL"
  777. if os.path.isfile(filename):
  778. self._files.append(filename)
  779. for orig_line in open(filename):
  780. line = orig_line.strip()
  781. if line.startswith("#"):
  782. if " BEGIN INIT INFO" in line:
  783. initinfo = True
  784. section = "init.d"
  785. if " END INIT INFO" in line:
  786. initinfo = False
  787. if initinfo:
  788. m = re.match(r"\S+\s*(\w[\w_-]*):(.*)", line)
  789. if m:
  790. key, val = m.group(1), m.group(2).strip()
  791. self.set(section, key, val)
  792. continue
  793. self.systemd_sysv_generator(filename)
  794. return self
  795. def systemd_sysv_generator(self, filename):
  796. """ see systemd-sysv-generator(8) """
  797. self.set(Unit, "SourcePath", filename)
  798. description = self.get("init.d", "Description", "")
  799. if description:
  800. self.set(Unit, "Description", description)
  801. check = self.get("init.d", "Required-Start", "")
  802. if check:
  803. for item in check.split(" "):
  804. if item.strip() in _sysv_mappings:
  805. self.set(Unit, "Requires", _sysv_mappings[item.strip()])
  806. provides = self.get("init.d", "Provides", "")
  807. if provides:
  808. self.set(Install, "Alias", provides)
  809. # if already in multi-user.target then start it there.
  810. runlevels = self.getstr("init.d", "Default-Start", "3 5")
  811. for item in runlevels.split(" "):
  812. if item.strip() in _runlevel_mappings:
  813. self.set(Install, "WantedBy", _runlevel_mappings[item.strip()])
  814. self.set(Service, "Restart", "no")
  815. self.set(Service, "TimeoutSec", strE(DefaultMaximumTimeout))
  816. self.set(Service, "KillMode", "process")
  817. self.set(Service, "GuessMainPID", "no")
  818. # self.set(Service, "RemainAfterExit", "yes")
  819. # self.set(Service, "SuccessExitStatus", "5 6")
  820. self.set(Service, "ExecStart", filename + " start")
  821. self.set(Service, "ExecStop", filename + " stop")
  822. if description: # LSB style initscript
  823. self.set(Service, "ExecReload", filename + " reload")
  824. self.set(Service, "Type", "forking") # not "sysv" anymore
  825. # UnitConfParser = ConfigParser.RawConfigParser
  826. UnitConfParser = SystemctlConfigParser
  827. class SystemctlSocket:
  828. def __init__(self, conf, sock, skip = False):
  829. self.conf = conf
  830. self.sock = sock
  831. self.skip = skip
  832. def fileno(self):
  833. return self.sock.fileno()
  834. def listen(self, backlog = None):
  835. if backlog is None:
  836. backlog = DefaultListenBacklog
  837. dgram = (self.sock.type == socket.SOCK_DGRAM)
  838. if not dgram and not self.skip:
  839. self.sock.listen(backlog)
  840. def name(self):
  841. return self.conf.name()
  842. def addr(self):
  843. stream = self.conf.get(Socket, "ListenStream", "")
  844. dgram = self.conf.get(Socket, "ListenDatagram", "")
  845. return stream or dgram
  846. def close(self):
  847. self.sock.close()
  848. class SystemctlConf:
  849. # |
  850. # |
  851. # |
  852. # |
  853. # |
  854. # |
  855. # |
  856. # |
  857. # |
  858. def __init__(self, data, module = None):
  859. self.data = data # UnitConfParser
  860. self.env = {}
  861. self.status = None
  862. self.masked = None
  863. self.module = module
  864. self.nonloaded_path = ""
  865. self.drop_in_files = {}
  866. self._root = _root
  867. self._user_mode = _user_mode
  868. def root_mode(self):
  869. return not self._user_mode
  870. def loaded(self):
  871. files = self.data.filenames()
  872. if self.masked:
  873. return "masked"
  874. if len(files):
  875. return "loaded"
  876. return ""
  877. def filename(self):
  878. """ returns the last filename that was parsed """
  879. files = self.data.filenames()
  880. if files:
  881. return files[0]
  882. return None
  883. def overrides(self):
  884. """ drop-in files are loaded alphabetically by name, not by full path """
  885. return [self.drop_in_files[name] for name in sorted(self.drop_in_files)]
  886. def name(self):
  887. """ the unit id or defaults to the file name """
  888. name = self.module or ""
  889. filename = self.filename()
  890. if filename:
  891. name = os.path.basename(filename)
  892. return self.module or name
  893. def set(self, section, name, value):
  894. return self.data.set(section, name, value)
  895. def get(self, section, name, default, allow_no_value = False):
  896. return self.data.getstr(section, name, default, allow_no_value)
  897. def getlist(self, section, name, default = None, allow_no_value = False):
  898. return self.data.getlist(section, name, default or [], allow_no_value)
  899. def getbool(self, section, name, default = None):
  900. value = self.data.get(section, name, default or "no")
  901. if value:
  902. if value[0] in "TtYy123456789":
  903. return True
  904. return False
  905. class PresetFile:
  906. # |
  907. # |
  908. def __init__(self):
  909. self._files = []
  910. self._lines = []
  911. def filename(self):
  912. """ returns the last filename that was parsed """
  913. if self._files:
  914. return self._files[-1]
  915. return None
  916. def read(self, filename):
  917. self._files.append(filename)
  918. for line in open(filename):
  919. self._lines.append(line.strip())
  920. return self
  921. def get_preset(self, unit):
  922. for line in self._lines:
  923. m = re.match(r"(enable|disable)\s+(\S+)", line)
  924. if m:
  925. status, pattern = m.group(1), m.group(2)
  926. if fnmatch.fnmatchcase(unit, pattern):
  927. logg.debug("%s %s => %s %s", status, pattern, unit, strQ(self.filename()))
  928. return status
  929. return None
  930. ## with waitlock(conf): self.start()
  931. class waitlock:
  932. # |
  933. # |
  934. # |
  935. def __init__(self, conf):
  936. self.conf = conf # currently unused
  937. self.opened = -1
  938. self.lockfolder = expand_path(_notify_socket_folder, conf.root_mode())
  939. try:
  940. folder = self.lockfolder
  941. if not os.path.isdir(folder):
  942. os.makedirs(folder)
  943. except Exception as e:
  944. logg.warning("oops, %s", e)
  945. def lockfile(self):
  946. unit = ""
  947. if self.conf:
  948. unit = self.conf.name()
  949. return os.path.join(self.lockfolder, str(unit or "global") + ".lock")
  950. def __enter__(self):
  951. try:
  952. lockfile = self.lockfile()
  953. lockname = os.path.basename(lockfile)
  954. self.opened = os.open(lockfile, os.O_RDWR | os.O_CREAT, 0o600)
  955. for attempt in xrange(int(MaxLockWait or DefaultMaximumTimeout)):
  956. try:
  957. logg_debug_flock("[%s] %s. trying %s _______ ", os.getpid(), attempt, lockname)
  958. fcntl.flock(self.opened, fcntl.LOCK_EX | fcntl.LOCK_NB)
  959. st = os.fstat(self.opened)
  960. if not st.st_nlink:
  961. logg_debug_flock("[%s] %s. %s got deleted, trying again", os.getpid(), attempt, lockname)
  962. os.close(self.opened)
  963. self.opened = os.open(lockfile, os.O_RDWR | os.O_CREAT, 0o600)
  964. continue
  965. content = "{ 'systemctl': %s, 'lock': '%s' }\n" % (os.getpid(), lockname)
  966. os.write(self.opened, content.encode("utf-8"))
  967. logg_debug_flock("[%s] %s. holding lock on %s", os.getpid(), attempt, lockname)
  968. return True
  969. except IOError as e:
  970. whom = os.read(self.opened, 4096)
  971. os.lseek(self.opened, 0, os.SEEK_SET)
  972. logg.info("[%s] %s. systemctl locked by %s", os.getpid(), attempt, whom.rstrip())
  973. time.sleep(1) # until MaxLockWait
  974. continue
  975. logg.error("[%s] not able to get the lock to %s", os.getpid(), lockname)
  976. except Exception as e:
  977. logg.warning("[%s] oops %s, %s", os.getpid(), str(type(e)), e)
  978. # TODO# raise Exception("no lock for %s", self.unit or "global")
  979. return False
  980. def __exit__(self, type, value, traceback):
  981. try:
  982. os.lseek(self.opened, 0, os.SEEK_SET)
  983. os.ftruncate(self.opened, 0)
  984. if REMOVE_LOCK_FILE: # an optional implementation
  985. lockfile = self.lockfile()
  986. lockname = os.path.basename(lockfile)
  987. os.unlink(lockfile) # ino is kept allocated because opened by this process
  988. logg.debug("[%s] lockfile removed for %s", os.getpid(), lockname)
  989. fcntl.flock(self.opened, fcntl.LOCK_UN)
  990. os.close(self.opened) # implies an unlock but that has happend like 6 seconds later
  991. self.opened = -1
  992. except Exception as e:
  993. logg.warning("oops, %s", e)
  994. SystemctlWaitPID = collections.namedtuple("SystemctlWaitPID", ["pid", "returncode", "signal"])
  995. def must_have_failed(waitpid, cmd):
  996. # found to be needed on ubuntu:16.04 to match test result from ubuntu:18.04 and other distros
  997. # .... I have tracked it down that python's os.waitpid() returns an exitcode==0 even when the
  998. # .... underlying process has actually failed with an exitcode<>0. It is unknown where that
  999. # .... bug comes from but it seems a bit serious to trash some very basic unix functionality.
  1000. # .... Essentially a parent process does not get the correct exitcode from its own children.
  1001. if cmd and cmd[0] == "/bin/kill":
  1002. pid = None
  1003. for arg in cmd[1:]:
  1004. if not arg.startswith("-"):
  1005. pid = arg
  1006. if pid is None: # unknown $MAINPID
  1007. if not waitpid.returncode:
  1008. logg.error("waitpid %s did return %s => correcting as 11", cmd, waitpid.returncode)
  1009. waitpid = SystemctlWaitPID(waitpid.pid, 11, waitpid.signal)
  1010. return waitpid
  1011. def subprocess_waitpid(pid):
  1012. run_pid, run_stat = os.waitpid(pid, 0)
  1013. return SystemctlWaitPID(run_pid, os.WEXITSTATUS(run_stat), os.WTERMSIG(run_stat))
  1014. def subprocess_testpid(pid):
  1015. run_pid, run_stat = os.waitpid(pid, os.WNOHANG)
  1016. if run_pid:
  1017. return SystemctlWaitPID(run_pid, os.WEXITSTATUS(run_stat), os.WTERMSIG(run_stat))
  1018. else:
  1019. return SystemctlWaitPID(pid, None, 0)
  1020. SystemctlUnitName = collections.namedtuple("SystemctlUnitName", ["fullname", "name", "prefix", "instance", "suffix", "component"])
  1021. def parse_unit(fullname): # -> object(prefix, instance, suffix, ...., name, component)
  1022. name, suffix = fullname, ""
  1023. has_suffix = fullname.rfind(".")
  1024. if has_suffix > 0:
  1025. name = fullname[:has_suffix]
  1026. suffix = fullname[has_suffix+1:]
  1027. prefix, instance = name, ""
  1028. has_instance = name.find("@")
  1029. if has_instance > 0:
  1030. prefix = name[:has_instance]
  1031. instance = name[has_instance+1:]
  1032. component = ""
  1033. has_component = prefix.rfind("-")
  1034. if has_component > 0:
  1035. component = prefix[has_component+1:]
  1036. return SystemctlUnitName(fullname, name, prefix, instance, suffix, component)
  1037. def time_to_seconds(text, maximum):
  1038. value = 0.
  1039. for part in str(text).split(" "):
  1040. item = part.strip()
  1041. if item == "infinity":
  1042. return maximum
  1043. if item.endswith("m"):
  1044. try: value += 60 * int(item[:-1])
  1045. except: pass # pragma: no cover
  1046. if item.endswith("min"):
  1047. try: value += 60 * int(item[:-3])
  1048. except: pass # pragma: no cover
  1049. elif item.endswith("ms"):
  1050. try: value += int(item[:-2]) / 1000.
  1051. except: pass # pragma: no cover
  1052. elif item.endswith("s"):
  1053. try: value += int(item[:-1])
  1054. except: pass # pragma: no cover
  1055. elif item:
  1056. try: value += int(item)
  1057. except: pass # pragma: no cover
  1058. if value > maximum:
  1059. return maximum
  1060. if not value and text.strip() == "0":
  1061. return 0.
  1062. if not value:
  1063. return 1.
  1064. return value
  1065. def seconds_to_time(seconds):
  1066. seconds = float(seconds)
  1067. mins = int(int(seconds) / 60)
  1068. secs = int(int(seconds) - (mins * 60))
  1069. msecs = int(int(seconds * 1000) - (secs * 1000 + mins * 60000))
  1070. if mins and secs and msecs:
  1071. return "%smin %ss %sms" % (mins, secs, msecs)
  1072. elif mins and secs:
  1073. return "%smin %ss" % (mins, secs)
  1074. elif secs and msecs:
  1075. return "%ss %sms" % (secs, msecs)
  1076. elif mins and msecs:
  1077. return "%smin %sms" % (mins, msecs)
  1078. elif mins:
  1079. return "%smin" % (mins)
  1080. else:
  1081. return "%ss" % (secs)
  1082. def getBefore(conf):
  1083. result = []
  1084. beforelist = conf.getlist(Unit, "Before", [])
  1085. for befores in beforelist:
  1086. for before in befores.split(" "):
  1087. name = before.strip()
  1088. if name and name not in result:
  1089. result.append(name)
  1090. return result
  1091. def getAfter(conf):
  1092. result = []
  1093. afterlist = conf.getlist(Unit, "After", [])
  1094. for afters in afterlist:
  1095. for after in afters.split(" "):
  1096. name = after.strip()
  1097. if name and name not in result:
  1098. result.append(name)
  1099. return result
  1100. def compareAfter(confA, confB):
  1101. idA = confA.name()
  1102. idB = confB.name()
  1103. for after in getAfter(confA):
  1104. if after == idB:
  1105. logg.debug("%s After %s", idA, idB)
  1106. return -1
  1107. for after in getAfter(confB):
  1108. if after == idA:
  1109. logg.debug("%s After %s", idB, idA)
  1110. return 1
  1111. for before in getBefore(confA):
  1112. if before == idB:
  1113. logg.debug("%s Before %s", idA, idB)
  1114. return 1
  1115. for before in getBefore(confB):
  1116. if before == idA:
  1117. logg.debug("%s Before %s", idB, idA)
  1118. return -1
  1119. return 0
  1120. def conf_sortedAfter(conflist, cmp = compareAfter):
  1121. # the normal sorted() does only look at two items
  1122. # so if "A after C" and a list [A, B, C] then
  1123. # it will see "A = B" and "B = C" assuming that
  1124. # "A = C" and the list is already sorted.
  1125. #
  1126. # To make a totalsorted we have to create a marker
  1127. # that informs sorted() that also B has a relation.
  1128. # It only works when 'after' has a direction, so
  1129. # anything without 'before' is a 'after'. In that
  1130. # case we find that "B after C".
  1131. class SortTuple:
  1132. def __init__(self, rank, conf):
  1133. self.rank = rank
  1134. self.conf = conf
  1135. sortlist = [SortTuple(0, conf) for conf in conflist]
  1136. for check in xrange(len(sortlist)): # maxrank = len(sortlist)
  1137. changed = 0
  1138. for A in xrange(len(sortlist)):
  1139. for B in xrange(len(sortlist)):
  1140. if A != B:
  1141. itemA = sortlist[A]
  1142. itemB = sortlist[B]
  1143. before = compareAfter(itemA.conf, itemB.conf)
  1144. if before > 0 and itemA.rank <= itemB.rank:
  1145. logg_debug_after(" %-30s before %s", itemA.conf.name(), itemB.conf.name())
  1146. itemA.rank = itemB.rank + 1
  1147. changed += 1
  1148. if before < 0 and itemB.rank <= itemA.rank:
  1149. logg_debug_after(" %-30s before %s", itemB.conf.name(), itemA.conf.name())
  1150. itemB.rank = itemA.rank + 1
  1151. changed += 1
  1152. if not changed:
  1153. logg_debug_after("done in check %s of %s", check, len(sortlist))
  1154. break
  1155. # because Requires is almost always the same as the After clauses
  1156. # we are mostly done in round 1 as the list is in required order
  1157. for conf in conflist:
  1158. logg_debug_after(".. %s", conf.name())
  1159. for item in sortlist:
  1160. logg_debug_after("(%s) %s", item.rank, item.conf.name())
  1161. sortedlist = sorted(sortlist, key = lambda item: -item.rank)
  1162. for item in sortedlist:
  1163. logg_debug_after("[%s] %s", item.rank, item.conf.name())
  1164. return [item.conf for item in sortedlist]
  1165. class SystemctlListenThread(threading.Thread):
  1166. def __init__(self, systemctl):
  1167. threading.Thread.__init__(self, name="listen")
  1168. self.systemctl = systemctl
  1169. self.stopped = threading.Event()
  1170. def stop(self):
  1171. self.stopped.set()
  1172. def run(self):
  1173. READ_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR
  1174. READ_WRITE = READ_ONLY | select.POLLOUT
  1175. me = os.getpid()
  1176. if DEBUG_INITLOOP: # pragma: no cover
  1177. logg.info("[%s] listen: new thread", me)
  1178. if not self.systemctl._sockets:
  1179. return
  1180. if DEBUG_INITLOOP: # pragma: no cover
  1181. logg.info("[%s] listen: start thread", me)
  1182. listen = select.poll()
  1183. for sock in self.systemctl._sockets.values():
  1184. listen.register(sock, READ_ONLY)
  1185. sock.listen()
  1186. logg.debug("[%s] listen: %s :%s", me, sock.name(), sock.addr())
  1187. timestamp = time.time()
  1188. while not self.stopped.is_set():
  1189. try:
  1190. sleep_sec = InitLoopSleep - (time.time() - timestamp)
  1191. if sleep_sec < MinimumYield:
  1192. sleep_sec = MinimumYield
  1193. sleeping = sleep_sec
  1194. while sleeping > 2:
  1195. time.sleep(1) # accept signals atleast every second
  1196. sleeping = InitLoopSleep - (time.time() - timestamp)
  1197. if sleeping < MinimumYield:
  1198. sleeping = MinimumYield
  1199. break
  1200. time.sleep(sleeping) # remainder waits less that 2 seconds
  1201. if DEBUG_INITLOOP: # pragma: no cover
  1202. logg.debug("[%s] listen: poll", me)
  1203. accepting = listen.poll(100) # milliseconds
  1204. if DEBUG_INITLOOP: # pragma: no cover
  1205. logg.debug("[%s] listen: poll (%s)", me, len(accepting))
  1206. for sock_fileno, event in accepting:
  1207. for sock in self.systemctl._sockets.values():
  1208. if sock.fileno() == sock_fileno:
  1209. if not self.stopped.is_set():
  1210. if self.systemctl.loop.acquire():
  1211. logg.debug("[%s] listen: accept %s :%s", me, sock.name(), sock_fileno)
  1212. self.systemctl.do_accept_socket_from(sock.conf, sock.sock)
  1213. except Exception as e:
  1214. logg.info("[%s] listen: interrupted - exception %s", me, e)
  1215. raise
  1216. for sock in self.systemctl._sockets.values():
  1217. try:
  1218. listen.unregister(sock)
  1219. sock.close()
  1220. except Exception as e:
  1221. logg.warning("[%s] listen: close socket: %s", me, e)
  1222. return
  1223. class Systemctl:
  1224. # |
  1225. # |
  1226. # |
  1227. # |
  1228. # |
  1229. # |
  1230. # |
  1231. # |
  1232. # |
  1233. # |
  1234. # |
  1235. # |
  1236. # |
  1237. # |
  1238. # |
  1239. # |
  1240. # |
  1241. # |
  1242. # |
  1243. # |
  1244. # |
  1245. # |
  1246. # |
  1247. # |
  1248. # |
  1249. # |
  1250. # |
  1251. # |
  1252. # |
  1253. # |
  1254. # |
  1255. # |
  1256. # |
  1257. # |
  1258. # |
  1259. # |
  1260. # |
  1261. # |
  1262. # |
  1263. def __init__(self):
  1264. self.error = NOT_A_PROBLEM # program exitcode or process returncode
  1265. # from command line options or the defaults
  1266. self._extra_vars = _extra_vars
  1267. self._force = _force
  1268. self._full = _full
  1269. self._init = _init
  1270. self._no_ask_password = _no_ask_password
  1271. self._no_legend = _no_legend
  1272. self._now = _now
  1273. self._preset_mode = _preset_mode
  1274. self._quiet = _quiet
  1275. self._root = _root
  1276. self._show_all = _show_all
  1277. self._only_what = commalist(_only_what) or [""]
  1278. self._only_property = commalist(_only_property)
  1279. self._only_state = commalist(_only_state)
  1280. self._only_type = commalist(_only_type)
  1281. # some common constants that may be changed
  1282. self._systemd_version = SystemCompatibilityVersion
  1283. self._journal_log_folder = _journal_log_folder
  1284. # and the actual internal runtime state
  1285. self._loaded_file_sysv = {} # /etc/init.d/name => config data
  1286. self._loaded_file_sysd = {} # /etc/systemd/system/name.service => config data
  1287. self._file_for_unit_sysv = None # name.service => /etc/init.d/name
  1288. self._file_for_unit_sysd = None # name.service => /etc/systemd/system/name.service
  1289. self._preset_file_list = None # /etc/systemd/system-preset/* => file content
  1290. self._default_target = DefaultTarget
  1291. self._sysinit_target = None # stores a UnitConf()
  1292. self.doExitWhenNoMoreProcs = ExitWhenNoMoreProcs or False
  1293. self.doExitWhenNoMoreServices = ExitWhenNoMoreServices or False
  1294. self._user_mode = _user_mode
  1295. self._user_getlogin = os_getlogin()
  1296. self._log_file = {} # init-loop
  1297. self._log_hold = {} # init-loop
  1298. self._boottime = None # cache self.get_boottime()
  1299. self._SYSTEMD_UNIT_PATH = None
  1300. self._SYSTEMD_SYSVINIT_PATH = None
  1301. self._SYSTEMD_PRESET_PATH = None
  1302. self._restarted_unit = {}
  1303. self._restart_failed_units = {}
  1304. self._sockets = {}
  1305. self.loop = threading.Lock()
  1306. def user(self):
  1307. return self._user_getlogin
  1308. def user_mode(self):
  1309. return self._user_mode
  1310. def user_folder(self):
  1311. for folder in self.user_folders():
  1312. if folder: return folder
  1313. raise Exception("did not find any systemd/user folder")
  1314. def system_folder(self):
  1315. for folder in self.system_folders():
  1316. if folder: return folder
  1317. raise Exception("did not find any systemd/system folder")
  1318. def preset_folders(self):
  1319. SYSTEMD_PRESET_PATH = self.get_SYSTEMD_PRESET_PATH()
  1320. for path in SYSTEMD_PRESET_PATH.split(":"):
  1321. if path.strip(): yield expand_path(path.strip())
  1322. if SYSTEMD_PRESET_PATH.endswith(":"):
  1323. for p in _preset_folders:
  1324. yield expand_path(p.strip())
  1325. def init_folders(self):
  1326. SYSTEMD_SYSVINIT_PATH = self.get_SYSTEMD_SYSVINIT_PATH()
  1327. for path in SYSTEMD_SYSVINIT_PATH.split(":"):
  1328. if path.strip(): yield expand_path(path.strip())
  1329. if SYSTEMD_SYSVINIT_PATH.endswith(":"):
  1330. for p in _init_folders:
  1331. yield expand_path(p.strip())
  1332. def user_folders(self):
  1333. SYSTEMD_UNIT_PATH = self.get_SYSTEMD_UNIT_PATH()
  1334. for path in SYSTEMD_UNIT_PATH.split(":"):
  1335. if path.strip(): yield expand_path(path.strip())
  1336. if SYSTEMD_UNIT_PATH.endswith(":"):
  1337. for p in _user_folders:
  1338. yield expand_path(p.strip())
  1339. def system_folders(self):
  1340. SYSTEMD_UNIT_PATH = self.get_SYSTEMD_UNIT_PATH()
  1341. for path in SYSTEMD_UNIT_PATH.split(":"):
  1342. if path.strip(): yield expand_path(path.strip())
  1343. if SYSTEMD_UNIT_PATH.endswith(":"):
  1344. for p in _system_folders:
  1345. yield expand_path(p.strip())
  1346. def get_SYSTEMD_UNIT_PATH(self):
  1347. if self._SYSTEMD_UNIT_PATH is None:
  1348. self._SYSTEMD_UNIT_PATH = os.environ.get("SYSTEMD_UNIT_PATH", ":")
  1349. assert self._SYSTEMD_UNIT_PATH is not None
  1350. return self._SYSTEMD_UNIT_PATH
  1351. def get_SYSTEMD_SYSVINIT_PATH(self):
  1352. if self._SYSTEMD_SYSVINIT_PATH is None:
  1353. self._SYSTEMD_SYSVINIT_PATH = os.environ.get("SYSTEMD_SYSVINIT_PATH", ":")
  1354. assert self._SYSTEMD_SYSVINIT_PATH is not None
  1355. return self._SYSTEMD_SYSVINIT_PATH
  1356. def get_SYSTEMD_PRESET_PATH(self):
  1357. if self._SYSTEMD_PRESET_PATH is None:
  1358. self._SYSTEMD_PRESET_PATH = os.environ.get("SYSTEMD_PRESET_PATH", ":")
  1359. assert self._SYSTEMD_PRESET_PATH is not None
  1360. return self._SYSTEMD_PRESET_PATH
  1361. def sysd_folders(self):
  1362. """ if --user then these folders are preferred """
  1363. if self.user_mode():
  1364. for folder in self.user_folders():
  1365. yield folder
  1366. if True:
  1367. for folder in self.system_folders():
  1368. yield folder
  1369. def scan_unit_sysd_files(self, module = None): # -> [ unit-names,... ]
  1370. """ reads all unit files, returns the first filename for the unit given """
  1371. if self._file_for_unit_sysd is None:
  1372. self._file_for_unit_sysd = {}
  1373. for folder in self.sysd_folders():
  1374. if not folder:
  1375. continue
  1376. folder = os_path(self._root, folder)
  1377. if not os.path.isdir(folder):
  1378. continue
  1379. for name in os.listdir(folder):
  1380. path = os.path.join(folder, name)
  1381. if os.path.isdir(path):
  1382. continue
  1383. service_name = name
  1384. if service_name not in self._file_for_unit_sysd:
  1385. self._file_for_unit_sysd[service_name] = path
  1386. logg.debug("found %s sysd files", len(self._file_for_unit_sysd))
  1387. return list(self._file_for_unit_sysd.keys())
  1388. def scan_unit_sysv_files(self, module = None): # -> [ unit-names,... ]
  1389. """ reads all init.d files, returns the first filename when unit is a '.service' """
  1390. if self._file_for_unit_sysv is None:
  1391. self._file_for_unit_sysv = {}
  1392. for folder in self.init_folders():
  1393. if not folder:
  1394. continue
  1395. folder = os_path(self._root, folder)
  1396. if not os.path.isdir(folder):
  1397. continue
  1398. for name in os.listdir(folder):
  1399. path = os.path.join(folder, name)
  1400. if os.path.isdir(path):
  1401. continue
  1402. service_name = name + ".service" # simulate systemd
  1403. if service_name not in self._file_for_unit_sysv:
  1404. self._file_for_unit_sysv[service_name] = path
  1405. logg.debug("found %s sysv files", len(self._file_for_unit_sysv))
  1406. return list(self._file_for_unit_sysv.keys())
  1407. def unit_sysd_file(self, module = None): # -> filename?
  1408. """ file path for the given module (systemd) """
  1409. self.scan_unit_sysd_files()
  1410. assert self._file_for_unit_sysd is not None
  1411. if module and module in self._file_for_unit_sysd:
  1412. return self._file_for_unit_sysd[module]
  1413. if module and unit_of(module) in self._file_for_unit_sysd:
  1414. return self._file_for_unit_sysd[unit_of(module)]
  1415. return None
  1416. def unit_sysv_file(self, module = None): # -> filename?
  1417. """ file path for the given module (sysv) """
  1418. self.scan_unit_sysv_files()
  1419. assert self._file_for_unit_sysv is not None
  1420. if module and module in self._file_for_unit_sysv:
  1421. return self._file_for_unit_sysv[module]
  1422. if module and unit_of(module) in self._file_for_unit_sysv:
  1423. return self._file_for_unit_sysv[unit_of(module)]
  1424. return None
  1425. def unit_file(self, module = None): # -> filename?
  1426. """ file path for the given module (sysv or systemd) """
  1427. path = self.unit_sysd_file(module)
  1428. if path is not None: return path
  1429. path = self.unit_sysv_file(module)
  1430. if path is not None: return path
  1431. return None
  1432. def is_sysv_file(self, filename):
  1433. """ for routines that have a special treatment for init.d services """
  1434. self.unit_file() # scan all
  1435. assert self._file_for_unit_sysd is not None
  1436. assert self._file_for_unit_sysv is not None
  1437. if not filename: return None
  1438. if filename in self._file_for_unit_sysd.values(): return False
  1439. if filename in self._file_for_unit_sysv.values(): return True
  1440. return None # not True
  1441. def is_user_conf(self, conf):
  1442. if not conf: # pragma: no cover (is never null)
  1443. return False
  1444. filename = conf.nonloaded_path or conf.filename()
  1445. if filename and "/user/" in filename:
  1446. return True
  1447. return False
  1448. def not_user_conf(self, conf):
  1449. """ conf can not be started as user service (when --user)"""
  1450. if conf is None: # pragma: no cover (is never null)
  1451. return True
  1452. if not self.user_mode():
  1453. logg.debug("%s no --user mode >> accept", strQ(conf.filename()))
  1454. return False
  1455. if self.is_user_conf(conf):
  1456. logg.debug("%s is /user/ conf >> accept", strQ(conf.filename()))
  1457. return False
  1458. # to allow for 'docker run -u user' with system services
  1459. user = self.get_User(conf)
  1460. if user and user == self.user():
  1461. logg.debug("%s with User=%s >> accept", strQ(conf.filename()), user)
  1462. return False
  1463. return True
  1464. def find_drop_in_files(self, unit):
  1465. """ search for some.service.d/extra.conf files """
  1466. result = {}
  1467. basename_d = unit + ".d"
  1468. for folder in self.sysd_folders():
  1469. if not folder:
  1470. continue
  1471. folder = os_path(self._root, folder)
  1472. override_d = os_path(folder, basename_d)
  1473. if not os.path.isdir(override_d):
  1474. continue
  1475. for name in os.listdir(override_d):
  1476. path = os.path.join(override_d, name)
  1477. if os.path.isdir(path):
  1478. continue
  1479. if not path.endswith(".conf"):
  1480. continue
  1481. if name not in result:
  1482. result[name] = path
  1483. return result
  1484. def load_sysd_template_conf(self, module): # -> conf?
  1485. """ read the unit template with a UnitConfParser (systemd) """
  1486. if module and "@" in module:
  1487. unit = parse_unit(module)
  1488. service = "%s@.service" % unit.prefix
  1489. conf = self.load_sysd_unit_conf(service)
  1490. if conf:
  1491. conf.module = module
  1492. return conf
  1493. return None
  1494. def load_sysd_unit_conf(self, module): # -> conf?
  1495. """ read the unit file with a UnitConfParser (systemd) """
  1496. path = self.unit_sysd_file(module)
  1497. if not path: return None
  1498. assert self._loaded_file_sysd is not None
  1499. if path in self._loaded_file_sysd:
  1500. return self._loaded_file_sysd[path]
  1501. masked = None
  1502. if os.path.islink(path) and os.readlink(path).startswith("/dev"):
  1503. masked = os.readlink(path)
  1504. drop_in_files = {}
  1505. data = UnitConfParser()
  1506. if not masked:
  1507. data.read_sysd(path)
  1508. drop_in_files = self.find_drop_in_files(os.path.basename(path))
  1509. # load in alphabetic order, irrespective of location
  1510. for name in sorted(drop_in_files):
  1511. path = drop_in_files[name]
  1512. data.read_sysd(path)
  1513. conf = SystemctlConf(data, module)
  1514. conf.masked = masked
  1515. conf.nonloaded_path = path # if masked
  1516. conf.drop_in_files = drop_in_files
  1517. conf._root = self._root
  1518. self._loaded_file_sysd[path] = conf
  1519. return conf
  1520. def load_sysv_unit_conf(self, module): # -> conf?
  1521. """ read the unit file with a UnitConfParser (sysv) """
  1522. path = self.unit_sysv_file(module)
  1523. if not path: return None
  1524. assert self._loaded_file_sysv is not None
  1525. if path in self._loaded_file_sysv:
  1526. return self._loaded_file_sysv[path]
  1527. data = UnitConfParser()
  1528. data.read_sysv(path)
  1529. conf = SystemctlConf(data, module)
  1530. conf._root = self._root
  1531. self._loaded_file_sysv[path] = conf
  1532. return conf
  1533. def load_unit_conf(self, module): # -> conf | None(not-found)
  1534. """ read the unit file with a UnitConfParser (sysv or systemd) """
  1535. try:
  1536. conf = self.load_sysd_unit_conf(module)
  1537. if conf is not None:
  1538. return conf
  1539. conf = self.load_sysd_template_conf(module)
  1540. if conf is not None:
  1541. return conf
  1542. conf = self.load_sysv_unit_conf(module)
  1543. if conf is not None:
  1544. return conf
  1545. except Exception as e:
  1546. logg.warning("%s not loaded: %s", module, e)
  1547. return None
  1548. def default_unit_conf(self, module, description = None): # -> conf
  1549. """ a unit conf that can be printed to the user where
  1550. attributes are empty and loaded() is False """
  1551. data = UnitConfParser()
  1552. data.set(Unit, "Description", description or ("NOT-FOUND " + str(module)))
  1553. # assert(not data.loaded())
  1554. conf = SystemctlConf(data, module)
  1555. conf._root = self._root
  1556. return conf
  1557. def get_unit_conf(self, module): # -> conf (conf | default-conf)
  1558. """ accept that a unit does not exist
  1559. and return a unit conf that says 'not-loaded' """
  1560. conf = self.load_unit_conf(module)
  1561. if conf is not None:
  1562. return conf
  1563. return self.default_unit_conf(module)
  1564. def get_unit_type(self, module):
  1565. name, ext = os.path.splitext(module)
  1566. if ext in [".service", ".socket", ".target"]:
  1567. return ext[1:]
  1568. return None
  1569. def get_unit_section(self, module, default = Service):
  1570. return string.capwords(self.get_unit_type(module) or default)
  1571. def get_unit_section_from(self, conf, default = Service):
  1572. return self.get_unit_section(conf.name(), default)
  1573. def match_sysd_templates(self, modules = None, suffix=".service"): # -> generate[ unit ]
  1574. """ make a file glob on all known template units (systemd areas).
  1575. It returns no modules (!!) if no modules pattern were given.
  1576. The module string should contain an instance name already. """
  1577. modules = to_list(modules)
  1578. if not modules:
  1579. return
  1580. self.scan_unit_sysd_files()
  1581. assert self._file_for_unit_sysd is not None
  1582. for item in sorted(self._file_for_unit_sysd.keys()):
  1583. if "@" not in item:
  1584. continue
  1585. service_unit = parse_unit(item)
  1586. for module in modules:
  1587. if "@" not in module:
  1588. continue
  1589. module_unit = parse_unit(module)
  1590. if service_unit.prefix == module_unit.prefix:
  1591. yield "%s@%s.%s" % (service_unit.prefix, module_unit.instance, service_unit.suffix)
  1592. def match_sysd_units(self, modules = None, suffix=".service"): # -> generate[ unit ]
  1593. """ make a file glob on all known units (systemd areas).
  1594. It returns all modules if no modules pattern were given.
  1595. Also a single string as one module pattern may be given. """
  1596. modules = to_list(modules)
  1597. self.scan_unit_sysd_files()
  1598. assert self._file_for_unit_sysd is not None
  1599. for item in sorted(self._file_for_unit_sysd.keys()):
  1600. if "." not in item:
  1601. pass
  1602. elif not modules:
  1603. yield item
  1604. elif [module for module in modules if fnmatch.fnmatchcase(item, module)]:
  1605. yield item
  1606. elif [module for module in modules if module+suffix == item]:
  1607. yield item
  1608. def match_sysv_units(self, modules = None, suffix=".service"): # -> generate[ unit ]
  1609. """ make a file glob on all known units (sysv areas).
  1610. It returns all modules if no modules pattern were given.
  1611. Also a single string as one module pattern may be given. """
  1612. modules = to_list(modules)
  1613. self.scan_unit_sysv_files()
  1614. assert self._file_for_unit_sysv is not None
  1615. for item in sorted(self._file_for_unit_sysv.keys()):
  1616. if not modules:
  1617. yield item
  1618. elif [module for module in modules if fnmatch.fnmatchcase(item, module)]:
  1619. yield item
  1620. elif [module for module in modules if module+suffix == item]:
  1621. yield item
  1622. def match_units(self, modules = None, suffix=".service"): # -> [ units,.. ]
  1623. """ Helper for about any command with multiple units which can
  1624. actually be glob patterns on their respective unit name.
  1625. It returns all modules if no modules pattern were given.
  1626. Also a single string as one module pattern may be given. """
  1627. found = []
  1628. for unit in self.match_sysd_units(modules, suffix):
  1629. if unit not in found:
  1630. found.append(unit)
  1631. for unit in self.match_sysd_templates(modules, suffix):
  1632. if unit not in found:
  1633. found.append(unit)
  1634. for unit in self.match_sysv_units(modules, suffix):
  1635. if unit not in found:
  1636. found.append(unit)
  1637. return found
  1638. def list_service_unit_basics(self):
  1639. """ show all the basic loading state of services """
  1640. filename = self.unit_file() # scan all
  1641. assert self._file_for_unit_sysd is not None
  1642. assert self._file_for_unit_sysv is not None
  1643. result = []
  1644. for name, value in self._file_for_unit_sysd.items():
  1645. result += [(name, "SysD", value)]
  1646. for name, value in self._file_for_unit_sysv.items():
  1647. result += [(name, "SysV", value)]
  1648. return result
  1649. def list_service_units(self, *modules): # -> [ (unit,loaded+active+substate,description) ]
  1650. """ show all the service units """
  1651. result = {}
  1652. active = {}
  1653. substate = {}
  1654. description = {}
  1655. for unit in self.match_units(to_list(modules)):
  1656. result[unit] = "not-found"
  1657. active[unit] = "inactive"
  1658. substate[unit] = "dead"
  1659. description[unit] = ""
  1660. try:
  1661. conf = self.get_unit_conf(unit)
  1662. result[unit] = "loaded"
  1663. description[unit] = self.get_description_from(conf)
  1664. active[unit] = self.get_active_from(conf)
  1665. substate[unit] = self.get_substate_from(conf) or "unknown"
  1666. except Exception as e:
  1667. logg.warning("list-units: %s", e)
  1668. if self._only_state:
  1669. if result[unit] in self._only_state:
  1670. pass
  1671. elif active[unit] in self._only_state:
  1672. pass
  1673. elif substate[unit] in self._only_state:
  1674. pass
  1675. else:
  1676. del result[unit]
  1677. return [(unit, result[unit] + " " + active[unit] + " " + substate[unit], description[unit]) for unit in sorted(result)]
  1678. def list_units_modules(self, *modules): # -> [ (unit,loaded,description) ]
  1679. """ [PATTERN]... -- List loaded units.
  1680. If one or more PATTERNs are specified, only units matching one of
  1681. them are shown. NOTE: This is the default command."""
  1682. hint = "To show all installed unit files use 'systemctl list-unit-files'."
  1683. result = self.list_service_units(*modules)
  1684. if self._no_legend:
  1685. return result
  1686. found = "%s loaded units listed." % len(result)
  1687. return result + [("", "", ""), (found, "", ""), (hint, "", "")]
  1688. def list_service_unit_files(self, *modules): # -> [ (unit,enabled) ]
  1689. """ show all the service units and the enabled status"""
  1690. logg.debug("list service unit files for %s", modules)
  1691. result = {}
  1692. enabled = {}
  1693. for unit in self.match_units(to_list(modules)):
  1694. if self._only_type and self.get_unit_type(unit) not in self._only_type:
  1695. continue
  1696. result[unit] = None
  1697. enabled[unit] = ""
  1698. try:
  1699. conf = self.get_unit_conf(unit)
  1700. if self.not_user_conf(conf):
  1701. result[unit] = None
  1702. continue
  1703. result[unit] = conf
  1704. enabled[unit] = self.enabled_from(conf)
  1705. except Exception as e:
  1706. logg.warning("list-units: %s", e)
  1707. return [(unit, enabled[unit]) for unit in sorted(result) if result[unit]]
  1708. def each_target_file(self):
  1709. folders = self.system_folders()
  1710. if self.user_mode():
  1711. folders = self.user_folders()
  1712. for folder1 in folders:
  1713. folder = os_path(self._root, folder1)
  1714. if not os.path.isdir(folder):
  1715. continue
  1716. for filename in os.listdir(folder):
  1717. if filename.endswith(".target"):
  1718. yield (filename, os.path.join(folder, filename))
  1719. def list_target_unit_files(self, *modules): # -> [ (unit,enabled) ]
  1720. """ show all the target units and the enabled status"""
  1721. enabled = {}
  1722. targets = {}
  1723. for target, filepath in self.each_target_file():
  1724. logg.info("target %s", filepath)
  1725. targets[target] = filepath
  1726. enabled[target] = "static"
  1727. for unit in _all_common_targets:
  1728. targets[unit] = None
  1729. enabled[unit] = "static"
  1730. if unit in _all_common_enabled:
  1731. enabled[unit] = "enabled"
  1732. if unit in _all_common_disabled:
  1733. enabled[unit] = "disabled"
  1734. return [(unit, enabled[unit]) for unit in sorted(targets)]
  1735. def list_unit_files_modules(self, *modules): # -> [ (unit,enabled) ]
  1736. """[PATTERN]... -- List installed unit files
  1737. List installed unit files and their enablement state (as reported
  1738. by is-enabled). If one or more PATTERNs are specified, only units
  1739. whose filename (just the last component of the path) matches one of
  1740. them are shown. This command reacts to limitations of --type being
  1741. --type=service or --type=target (and --now for some basics)."""
  1742. result = []
  1743. if self._now:
  1744. basics = self.list_service_unit_basics()
  1745. result = [(name, sysv + " " + filename) for name, sysv, filename in basics]
  1746. elif self._only_type:
  1747. if "target" in self._only_type:
  1748. result = self.list_target_unit_files()
  1749. if "service" in self._only_type:
  1750. result = self.list_service_unit_files()
  1751. else:
  1752. result = self.list_target_unit_files()
  1753. result += self.list_service_unit_files(*modules)
  1754. if self._no_legend:
  1755. return result
  1756. found = "%s unit files listed." % len(result)
  1757. return [("UNIT FILE", "STATE")] + result + [("", ""), (found, "")]
  1758. ##
  1759. ##
  1760. def get_description(self, unit, default = None):
  1761. return self.get_description_from(self.load_unit_conf(unit))
  1762. def get_description_from(self, conf, default = None): # -> text
  1763. """ Unit.Description could be empty sometimes """
  1764. if not conf: return default or ""
  1765. description = conf.get(Unit, "Description", default or "")
  1766. return self.expand_special(description, conf)
  1767. def read_pid_file(self, pid_file, default = None):
  1768. pid = default
  1769. if not pid_file:
  1770. return default
  1771. if not os.path.isfile(pid_file):
  1772. return default
  1773. if self.truncate_old(pid_file):
  1774. return default
  1775. try:
  1776. # some pid-files from applications contain multiple lines
  1777. for line in open(pid_file):
  1778. if line.strip():
  1779. pid = to_intN(line.strip())
  1780. break
  1781. except Exception as e:
  1782. logg.warning("bad read of pid file '%s': %s", pid_file, e)
  1783. return pid
  1784. def wait_pid_file(self, pid_file, timeout = None): # -> pid?
  1785. """ wait some seconds for the pid file to appear and return the pid """
  1786. timeout = int(timeout or (DefaultTimeoutStartSec/2))
  1787. timeout = max(timeout, (MinimumTimeoutStartSec))
  1788. dirpath = os.path.dirname(os.path.abspath(pid_file))
  1789. for x in xrange(timeout):
  1790. if not os.path.isdir(dirpath):
  1791. time.sleep(1) # until TimeoutStartSec/2
  1792. continue
  1793. pid = self.read_pid_file(pid_file)
  1794. if not pid:
  1795. time.sleep(1) # until TimeoutStartSec/2
  1796. continue
  1797. if not pid_exists(pid):
  1798. time.sleep(1) # until TimeoutStartSec/2
  1799. continue
  1800. return pid
  1801. return None
  1802. def get_status_pid_file(self, unit):
  1803. """ actual file path of pid file (internal) """
  1804. conf = self.get_unit_conf(unit)
  1805. return self.pid_file_from(conf) or self.get_status_file_from(conf)
  1806. def pid_file_from(self, conf, default = ""):
  1807. """ get the specified pid file path (not a computed default) """
  1808. pid_file = self.get_pid_file(conf) or default
  1809. return os_path(self._root, self.expand_special(pid_file, conf))
  1810. def get_pid_file(self, conf, default = None):
  1811. return conf.get(Service, "PIDFile", default)
  1812. def read_mainpid_from(self, conf, default = None):
  1813. """ MAINPID is either the PIDFile content written from the application
  1814. or it is the value in the status file written by this systemctl.py code """
  1815. pid_file = self.pid_file_from(conf)
  1816. if pid_file:
  1817. return self.read_pid_file(pid_file, default)
  1818. status = self.read_status_from(conf)
  1819. if "MainPID" in status:
  1820. return to_intN(status["MainPID"], default)
  1821. return default
  1822. def clean_pid_file_from(self, conf):
  1823. pid_file = self.pid_file_from(conf)
  1824. if pid_file and os.path.isfile(pid_file):
  1825. try:
  1826. os.remove(pid_file)
  1827. except OSError as e:
  1828. logg.warning("while rm %s: %s", pid_file, e)
  1829. self.write_status_from(conf, MainPID=None)
  1830. def get_status_file(self, unit): # for testing
  1831. conf = self.get_unit_conf(unit)
  1832. return self.get_status_file_from(conf)
  1833. def get_status_file_from(self, conf, default = None):
  1834. status_file = self.get_StatusFile(conf)
  1835. # this not a real setting, but do the expand_special anyway
  1836. return os_path(self._root, self.expand_special(status_file, conf))
  1837. def get_StatusFile(self, conf, default = None): # -> text
  1838. """ file where to store a status mark """
  1839. status_file = conf.get(Service, "StatusFile", default)
  1840. if status_file:
  1841. return status_file
  1842. root = conf.root_mode()
  1843. folder = get_PID_DIR(root)
  1844. name = "%s.status" % conf.name()
  1845. return os.path.join(folder, name)
  1846. def clean_status_from(self, conf):
  1847. status_file = self.get_status_file_from(conf)
  1848. if os.path.exists(status_file):
  1849. os.remove(status_file)
  1850. conf.status = {}
  1851. def write_status_from(self, conf, **status): # -> bool(written)
  1852. """ if a status_file is known then path is created and the
  1853. give status is written as the only content. """
  1854. status_file = self.get_status_file_from(conf)
  1855. # if not status_file: return False
  1856. dirpath = os.path.dirname(os.path.abspath(status_file))
  1857. if not os.path.isdir(dirpath):
  1858. os.makedirs(dirpath)
  1859. if conf.status is None:
  1860. conf.status = self.read_status_from(conf)
  1861. if True:
  1862. for key in sorted(status.keys()):
  1863. value = status[key]
  1864. if key.upper() == "AS": key = "ActiveState"
  1865. if key.upper() == "EXIT": key = "ExecMainCode"
  1866. if value is None:
  1867. try: del conf.status[key]
  1868. except KeyError: pass
  1869. else:
  1870. conf.status[key] = strE(value)
  1871. try:
  1872. with open(status_file, "w") as f:
  1873. for key in sorted(conf.status):
  1874. value = conf.status[key]
  1875. if key == "MainPID" and str(value) == "0":
  1876. logg.warning("ignore writing MainPID=0")
  1877. continue
  1878. content = "{}={}\n".format(key, str(value))
  1879. logg.debug("writing to %s\n\t%s", status_file, content.strip())
  1880. f.write(content)
  1881. except IOError as e:
  1882. logg.error("writing STATUS %s: %s\n\t to status file %s", status, e, status_file)
  1883. return True
  1884. def read_status_from(self, conf):
  1885. status_file = self.get_status_file_from(conf)
  1886. status = {}
  1887. # if not status_file: return status
  1888. if not os.path.isfile(status_file):
  1889. if DEBUG_STATUS: logg.debug("no status file: %s\n returning %s", status_file, status)
  1890. return status
  1891. if self.truncate_old(status_file):
  1892. if DEBUG_STATUS: logg.debug("old status file: %s\n returning %s", status_file, status)
  1893. return status
  1894. try:
  1895. if DEBUG_STATUS: logg.debug("reading %s", status_file)
  1896. for line in open(status_file):
  1897. if line.strip():
  1898. m = re.match(r"(\w+)[:=](.*)", line)
  1899. if m:
  1900. key, value = m.group(1), m.group(2)
  1901. if key.strip():
  1902. status[key.strip()] = value.strip()
  1903. else: # pragma: no cover
  1904. logg.warning("ignored %s", line.strip())
  1905. except:
  1906. logg.warning("bad read of status file '%s'", status_file)
  1907. return status
  1908. def get_status_from(self, conf, name, default = None):
  1909. if conf.status is None:
  1910. conf.status = self.read_status_from(conf)
  1911. return conf.status.get(name, default)
  1912. def set_status_from(self, conf, name, value):
  1913. if conf.status is None:
  1914. conf.status = self.read_status_from(conf)
  1915. if value is None:
  1916. try: del conf.status[name]
  1917. except KeyError: pass
  1918. else:
  1919. conf.status[name] = value
  1920. #
  1921. def get_boottime(self):
  1922. """ detects the boot time of the container - in general the start time of PID 1 """
  1923. if self._boottime is None:
  1924. self._boottime = self.get_boottime_from_proc()
  1925. assert self._boottime is not None
  1926. return self._boottime
  1927. def get_boottime_from_proc(self):
  1928. """ detects the latest boot time by looking at the start time of available process"""
  1929. pid1 = BOOT_PID_MIN or 0
  1930. pid_max = BOOT_PID_MAX
  1931. if pid_max < 0:
  1932. pid_max = pid1 - pid_max
  1933. for pid in xrange(pid1, pid_max):
  1934. proc = _proc_pid_stat.format(**locals())
  1935. try:
  1936. if os.path.exists(proc):
  1937. # return os.path.getmtime(proc) # did sometimes change
  1938. return self.path_proc_started(proc)
  1939. except Exception as e: # pragma: no cover
  1940. logg.warning("boottime - could not access %s: %s", proc, e)
  1941. if DEBUG_BOOTTIME:
  1942. logg.debug(" boottime from the oldest entry in /proc [nothing in %s..%s]", pid1, pid_max)
  1943. return self.get_boottime_from_old_proc()
  1944. def get_boottime_from_old_proc(self):
  1945. booted = time.time()
  1946. for pid in os.listdir(_proc_pid_dir):
  1947. proc = _proc_pid_stat.format(**locals())
  1948. try:
  1949. if os.path.exists(proc):
  1950. # ctime = os.path.getmtime(proc)
  1951. ctime = self.path_proc_started(proc)
  1952. if ctime < booted:
  1953. booted = ctime
  1954. except Exception as e: # pragma: no cover
  1955. logg.warning("could not access %s: %s", proc, e)
  1956. return booted
  1957. # Use uptime, time process running in ticks, and current time to determine process boot time
  1958. # You can't use the modified timestamp of the status file because it isn't static.
  1959. # ... using clock ticks it is known to be a linear time on Linux
  1960. def path_proc_started(self, proc):
  1961. # get time process started after boot in clock ticks
  1962. with open(proc) as file_stat:
  1963. data_stat = file_stat.readline()
  1964. file_stat.close()
  1965. stat_data = data_stat.split()
  1966. started_ticks = stat_data[21]
  1967. # man proc(5): "(22) starttime = The time the process started after system boot."
  1968. # ".. the value is expressed in clock ticks (divide by sysconf(_SC_CLK_TCK))."
  1969. # NOTE: for containers the start time is related to the boot time of host system.
  1970. clkTickInt = os.sysconf_names['SC_CLK_TCK']
  1971. clockTicksPerSec = os.sysconf(clkTickInt)
  1972. started_secs = float(started_ticks) / clockTicksPerSec
  1973. if DEBUG_BOOTTIME:
  1974. logg.debug(" BOOT .. Proc started time: %.3f (%s)", started_secs, proc)
  1975. # this value is the start time from the host system
  1976. # Variant 1:
  1977. system_uptime = _proc_sys_uptime
  1978. with open(system_uptime, "rb") as file_uptime:
  1979. data_uptime = file_uptime.readline()
  1980. file_uptime.close()
  1981. uptime_data = data_uptime.decode().split()
  1982. uptime_secs = float(uptime_data[0])
  1983. if DEBUG_BOOTTIME:
  1984. logg.debug(" BOOT 1. System uptime secs: %.3f (%s)", uptime_secs, system_uptime)
  1985. # get time now
  1986. now = time.time()
  1987. started_time = now - (uptime_secs - started_secs)
  1988. if DEBUG_BOOTTIME:
  1989. logg.debug(" BOOT 1. Proc has been running since: %s" % (datetime.datetime.fromtimestamp(started_time)))
  1990. # Variant 2:
  1991. system_stat = _proc_sys_stat
  1992. system_btime = 0.
  1993. with open(system_stat, "rb") as f:
  1994. for line in f:
  1995. assert isinstance(line, bytes)
  1996. if line.startswith(b"btime"):
  1997. system_btime = float(line.decode().split()[1])
  1998. f.closed
  1999. if DEBUG_BOOTTIME:
  2000. logg.debug(" BOOT 2. System btime secs: %.3f (%s)", system_btime, system_stat)
  2001. started_btime = system_btime + started_secs
  2002. if DEBUG_BOOTTIME:
  2003. logg.debug(" BOOT 2. Proc has been running since: %s" % (datetime.datetime.fromtimestamp(started_btime)))
  2004. # return started_time
  2005. return started_btime
  2006. def get_filetime(self, filename):
  2007. return os.path.getmtime(filename)
  2008. def truncate_old(self, filename):
  2009. filetime = self.get_filetime(filename)
  2010. boottime = self.get_boottime()
  2011. if filetime >= boottime:
  2012. if DEBUG_BOOTTIME:
  2013. logg.debug(" file time: %s (%s)", datetime.datetime.fromtimestamp(filetime), o22(filename))
  2014. logg.debug(" boot time: %s (%s)", datetime.datetime.fromtimestamp(boottime), "status modified later")
  2015. return False # OK
  2016. if DEBUG_BOOTTIME:
  2017. logg.info(" file time: %s (%s)", datetime.datetime.fromtimestamp(filetime), o22(filename))
  2018. logg.info(" boot time: %s (%s)", datetime.datetime.fromtimestamp(boottime), "status TRUNCATED NOW")
  2019. try:
  2020. shutil_truncate(filename)
  2021. except Exception as e:
  2022. logg.warning("while truncating: %s", e)
  2023. return True # truncated
  2024. def getsize(self, filename):
  2025. if filename is None: # pragma: no cover (is never null)
  2026. return 0
  2027. if not os.path.isfile(filename):
  2028. return 0
  2029. if self.truncate_old(filename):
  2030. return 0
  2031. try:
  2032. return os.path.getsize(filename)
  2033. except Exception as e:
  2034. logg.warning("while reading file size: %s\n of %s", e, filename)
  2035. return 0
  2036. #
  2037. def read_env_file(self, env_file): # -> generate[ (name,value) ]
  2038. """ EnvironmentFile=<name> is being scanned """
  2039. mode, env_file = load_path(env_file)
  2040. real_file = os_path(self._root, env_file)
  2041. if not os.path.exists(real_file):
  2042. if mode.check:
  2043. logg.error("file does not exist: %s", real_file)
  2044. else:
  2045. logg.debug("file does not exist: %s", real_file)
  2046. return
  2047. try:
  2048. for real_line in open(os_path(self._root, env_file)):
  2049. line = real_line.strip()
  2050. if not line or line.startswith("#"):
  2051. continue
  2052. m = re.match(r"(?:export +)?([\w_]+)[=]'([^']*)'", line)
  2053. if m:
  2054. yield m.group(1), m.group(2)
  2055. continue
  2056. m = re.match(r'(?:export +)?([\w_]+)[=]"([^"]*)"', line)
  2057. if m:
  2058. yield m.group(1), m.group(2)
  2059. continue
  2060. m = re.match(r'(?:export +)?([\w_]+)[=](.*)', line)
  2061. if m:
  2062. yield m.group(1), m.group(2)
  2063. continue
  2064. except Exception as e:
  2065. logg.info("while reading %s: %s", env_file, e)
  2066. def read_env_part(self, env_part): # -> generate[ (name, value) ]
  2067. """ Environment=<name>=<value> is being scanned """
  2068. # systemd Environment= spec says it is a space-separated list of
  2069. # assignments. In order to use a space or an equals sign in a value
  2070. # one should enclose the whole assignment with double quotes:
  2071. # Environment="VAR1=word word" VAR2=word3 "VAR3=$word 5 6"
  2072. # and the $word is not expanded by other environment variables.
  2073. try:
  2074. for real_line in env_part.split("\n"):
  2075. line = real_line.strip()
  2076. for found in re.finditer(r'\s*("[\w_]+=[^"]*"|[\w_]+=\S*)', line):
  2077. part = found.group(1)
  2078. if part.startswith('"'):
  2079. part = part[1:-1]
  2080. name, value = part.split("=", 1)
  2081. yield name, value
  2082. except Exception as e:
  2083. logg.info("while reading %s: %s", env_part, e)
  2084. def command_of_unit(self, unit):
  2085. """ [UNIT]. -- show service settings (experimental)
  2086. or use -p VarName to show another property than 'ExecStart' """
  2087. conf = self.load_unit_conf(unit)
  2088. if conf is None:
  2089. logg.error("Unit %s could not be found.", unit)
  2090. self.error |= NOT_FOUND
  2091. return None
  2092. if self._only_property:
  2093. found = []
  2094. for prop in self._only_property:
  2095. found += conf.getlist(Service, prop)
  2096. return found
  2097. return conf.getlist(Service, "ExecStart")
  2098. def environment_of_unit(self, unit):
  2099. """ [UNIT]. -- show environment parts """
  2100. conf = self.load_unit_conf(unit)
  2101. if conf is None:
  2102. logg.error("Unit %s could not be found.", unit)
  2103. self.error |= NOT_FOUND
  2104. return None
  2105. return self.get_env(conf)
  2106. def extra_vars(self):
  2107. return self._extra_vars # from command line
  2108. def get_env(self, conf):
  2109. env = os.environ.copy()
  2110. for env_part in conf.getlist(Service, "Environment", []):
  2111. for name, value in self.read_env_part(self.expand_special(env_part, conf)):
  2112. env[name] = value # a '$word' is not special here (lazy expansion)
  2113. for env_file in conf.getlist(Service, "EnvironmentFile", []):
  2114. for name, value in self.read_env_file(self.expand_special(env_file, conf)):
  2115. env[name] = self.expand_env(value, env) # but nonlazy expansion here
  2116. logg.debug("extra-vars %s", self.extra_vars())
  2117. for extra in self.extra_vars():
  2118. if extra.startswith("@"):
  2119. for name, value in self.read_env_file(extra[1:]):
  2120. logg.info("override %s=%s", name, value)
  2121. env[name] = self.expand_env(value, env)
  2122. else:
  2123. for name, value in self.read_env_part(extra):
  2124. logg.info("override %s=%s", name, value)
  2125. env[name] = value # a '$word' is not special here
  2126. return env
  2127. def expand_env(self, cmd, env):
  2128. def get_env1(m):
  2129. name = m.group(1)
  2130. if name in env:
  2131. return env[name]
  2132. namevar = "$%s" % name
  2133. logg.debug("can not expand %s", namevar)
  2134. return (EXPAND_KEEP_VARS and namevar or "")
  2135. def get_env2(m):
  2136. name = m.group(1)
  2137. if name in env:
  2138. return env[name]
  2139. namevar = "${%s}" % name
  2140. logg.debug("can not expand %s", namevar)
  2141. return (EXPAND_KEEP_VARS and namevar or "")
  2142. #
  2143. maxdepth = EXPAND_VARS_MAXDEPTH
  2144. expanded = re.sub(r"[$](\w+)", lambda m: get_env1(m), cmd.replace("\\\n", ""))
  2145. for depth in xrange(maxdepth):
  2146. new_text = re.sub(r"[$][{](\w+)[}]", lambda m: get_env2(m), expanded)
  2147. if new_text == expanded:
  2148. return expanded
  2149. expanded = new_text
  2150. logg.error("shell variable expansion exceeded maxdepth %s", maxdepth)
  2151. return expanded
  2152. def expand_special(self, cmd, conf):
  2153. """ expand %i %t and similar special vars. They are being expanded
  2154. before any other expand_env takes place which handles shell-style
  2155. $HOME references. """
  2156. def xx(arg): return unit_name_unescape(arg)
  2157. def yy(arg): return arg
  2158. def get_confs(conf):
  2159. confs={"%": "%"}
  2160. if conf is None: # pragma: no cover (is never null)
  2161. return confs
  2162. unit = parse_unit(conf.name())
  2163. #
  2164. root = conf.root_mode()
  2165. VARTMP = get_VARTMP(root) # $TMPDIR # "/var/tmp"
  2166. TMP = get_TMP(root) # $TMPDIR # "/tmp"
  2167. RUN = get_RUNTIME_DIR(root) # $XDG_RUNTIME_DIR # "/run"
  2168. ETC = get_CONFIG_HOME(root) # $XDG_CONFIG_HOME # "/etc"
  2169. DAT = get_VARLIB_HOME(root) # $XDG_CONFIG_HOME # "/var/lib"
  2170. LOG = get_LOG_DIR(root) # $XDG_CONFIG_HOME/log # "/var/log"
  2171. CACHE = get_CACHE_HOME(root) # $XDG_CACHE_HOME # "/var/cache"
  2172. HOME = get_HOME(root) # $HOME or ~ # "/root"
  2173. USER = get_USER(root) # geteuid().pw_name # "root"
  2174. USER_ID = get_USER_ID(root) # geteuid() # 0
  2175. GROUP = get_GROUP(root) # getegid().gr_name # "root"
  2176. GROUP_ID = get_GROUP_ID(root) # getegid() # 0
  2177. SHELL = get_SHELL(root) # $SHELL # "/bin/sh"
  2178. # confs["b"] = boot_ID
  2179. confs["C"] = os_path(self._root, CACHE) # Cache directory root
  2180. confs["E"] = os_path(self._root, ETC) # Configuration directory root
  2181. confs["F"] = strE(conf.filename()) # EXTRA
  2182. confs["f"] = "/%s" % xx(unit.instance or unit.prefix)
  2183. confs["h"] = HOME # User home directory
  2184. # confs["H"] = host_NAME
  2185. confs["i"] = yy(unit.instance)
  2186. confs["I"] = xx(unit.instance) # same as %i but escaping undone
  2187. confs["j"] = yy(unit.component) # final component of the prefix
  2188. confs["J"] = xx(unit.component) # unescaped final component
  2189. confs["L"] = os_path(self._root, LOG)
  2190. # confs["m"] = machine_ID
  2191. confs["n"] = yy(unit.fullname) # Full unit name
  2192. confs["N"] = yy(unit.name) # Same as "%n", but with the type suffix removed.
  2193. confs["p"] = yy(unit.prefix) # before the first "@" or same as %n
  2194. confs["P"] = xx(unit.prefix) # same as %p but escaping undone
  2195. confs["s"] = SHELL
  2196. confs["S"] = os_path(self._root, DAT)
  2197. confs["t"] = os_path(self._root, RUN)
  2198. confs["T"] = os_path(self._root, TMP)
  2199. confs["g"] = GROUP
  2200. confs["G"] = str(GROUP_ID)
  2201. confs["u"] = USER
  2202. confs["U"] = str(USER_ID)
  2203. confs["V"] = os_path(self._root, VARTMP)
  2204. return confs
  2205. def get_conf1(m):
  2206. confs = get_confs(conf)
  2207. if m.group(1) in confs:
  2208. return confs[m.group(1)]
  2209. logg.warning("can not expand %%%s", m.group(1))
  2210. return ""
  2211. result = ""
  2212. if cmd:
  2213. result = re.sub("[%](.)", lambda m: get_conf1(m), cmd)
  2214. # ++# logg.info("expanded => %s", result)
  2215. return result
  2216. def exec_newcmd(self, cmd, env, conf):
  2217. mode, exe = exec_path(cmd)
  2218. if mode.noexpand:
  2219. newcmd = self.split_cmd(exe)
  2220. else:
  2221. newcmd = self.expand_cmd(exe, env, conf)
  2222. if mode.argv0:
  2223. if len(newcmd) > 1:
  2224. del newcmd[1] # TODO: keep but allow execve calls to pick it up
  2225. return mode, newcmd
  2226. def split_cmd(self, cmd):
  2227. cmd2 = cmd.replace("\\\n", "")
  2228. newcmd = []
  2229. for part in shlex.split(cmd2):
  2230. newcmd += [part]
  2231. return newcmd
  2232. def expand_cmd(self, cmd, env, conf):
  2233. """ expand ExecCmd statements including %i and $MAINPID """
  2234. cmd2 = cmd.replace("\\\n", "")
  2235. # according to documentation, when bar="one two" then the expansion
  2236. # of '$bar' is ["one","two"] and '${bar}' becomes ["one two"]. We
  2237. # tackle that by expand $bar before shlex, and the rest thereafter.
  2238. def get_env1(m):
  2239. name = m.group(1)
  2240. if name in env:
  2241. return env[name]
  2242. logg.debug("can not expand $%s", name)
  2243. return "" # empty string
  2244. def get_env2(m):
  2245. name = m.group(1)
  2246. if name in env:
  2247. return env[name]
  2248. logg.debug("can not expand $%s}}", name)
  2249. return "" # empty string
  2250. cmd3 = re.sub(r"[$](\w+)", lambda m: get_env1(m), cmd2)
  2251. newcmd = []
  2252. for part in shlex.split(cmd3):
  2253. part2 = self.expand_special(part, conf)
  2254. newcmd += [re.sub(r"[$][{](\w+)[}]", lambda m: get_env2(m), part2)] # type: ignore[arg-type]
  2255. return newcmd
  2256. def remove_service_directories(self, conf, section = Service):
  2257. # |
  2258. ok = True
  2259. nameRuntimeDirectory = self.get_RuntimeDirectory(conf, section)
  2260. keepRuntimeDirectory = self.get_RuntimeDirectoryPreserve(conf, section)
  2261. if not keepRuntimeDirectory:
  2262. root = conf.root_mode()
  2263. for name in nameRuntimeDirectory.split(" "):
  2264. if not name.strip(): continue
  2265. RUN = get_RUNTIME_DIR(root)
  2266. path = os.path.join(RUN, name)
  2267. dirpath = os_path(self._root, path)
  2268. ok = self.do_rm_tree(dirpath) and ok
  2269. if RUN == "/run":
  2270. for var_run in ("/var/run", "/tmp/run"):
  2271. if os.path.isdir(var_run):
  2272. var_path = os.path.join(var_run, name)
  2273. var_dirpath = os_path(self._root, var_path)
  2274. self.do_rm_tree(var_dirpath)
  2275. if not ok:
  2276. logg.debug("could not fully remove service directory %s", path)
  2277. return ok
  2278. def do_rm_tree(self, path):
  2279. ok = True
  2280. if os.path.isdir(path):
  2281. for dirpath, dirnames, filenames in os.walk(path, topdown=False):
  2282. for item in filenames:
  2283. filepath = os.path.join(dirpath, item)
  2284. try:
  2285. os.remove(filepath)
  2286. except Exception as e: # pragma: no cover
  2287. logg.debug("not removed file: %s (%s)", filepath, e)
  2288. ok = False
  2289. for item in dirnames:
  2290. dir_path = os.path.join(dirpath, item)
  2291. try:
  2292. os.rmdir(dir_path)
  2293. except Exception as e: # pragma: no cover
  2294. logg.debug("not removed dir: %s (%s)", dir_path, e)
  2295. ok = False
  2296. try:
  2297. os.rmdir(path)
  2298. except Exception as e:
  2299. logg.debug("not removed top dir: %s (%s)", path, e)
  2300. ok = False # pragma: no cover
  2301. logg.debug("%s rm_tree %s", ok and "done" or "fail", path)
  2302. return ok
  2303. def get_RuntimeDirectoryPreserve(self, conf, section = Service):
  2304. return conf.getbool(section, "RuntimeDirectoryPreserve", "no")
  2305. def get_RuntimeDirectory(self, conf, section = Service):
  2306. return self.expand_special(conf.get(section, "RuntimeDirectory", ""), conf)
  2307. def get_StateDirectory(self, conf, section = Service):
  2308. return self.expand_special(conf.get(section, "StateDirectory", ""), conf)
  2309. def get_CacheDirectory(self, conf, section = Service):
  2310. return self.expand_special(conf.get(section, "CacheDirectory", ""), conf)
  2311. def get_LogsDirectory(self, conf, section = Service):
  2312. return self.expand_special(conf.get(section, "LogsDirectory", ""), conf)
  2313. def get_ConfigurationDirectory(self, conf, section = Service):
  2314. return self.expand_special(conf.get(section, "ConfigurationDirectory", ""), conf)
  2315. def get_RuntimeDirectoryMode(self, conf, section = Service):
  2316. return conf.get(section, "RuntimeDirectoryMode", "")
  2317. def get_StateDirectoryMode(self, conf, section = Service):
  2318. return conf.get(section, "StateDirectoryMode", "")
  2319. def get_CacheDirectoryMode(self, conf, section = Service):
  2320. return conf.get(section, "CacheDirectoryMode", "")
  2321. def get_LogsDirectoryMode(self, conf, section = Service):
  2322. return conf.get(section, "LogsDirectoryMode", "")
  2323. def get_ConfigurationDirectoryMode(self, conf, section = Service):
  2324. return conf.get(section, "ConfigurationDirectoryMode", "")
  2325. def clean_service_directories(self, conf, which = ""):
  2326. ok = True
  2327. section = self.get_unit_section_from(conf)
  2328. nameRuntimeDirectory = self.get_RuntimeDirectory(conf, section)
  2329. nameStateDirectory = self.get_StateDirectory(conf, section)
  2330. nameCacheDirectory = self.get_CacheDirectory(conf, section)
  2331. nameLogsDirectory = self.get_LogsDirectory(conf, section)
  2332. nameConfigurationDirectory = self.get_ConfigurationDirectory(conf, section)
  2333. root = conf.root_mode()
  2334. for name in nameRuntimeDirectory.split(" "):
  2335. if not name.strip(): continue
  2336. RUN = get_RUNTIME_DIR(root)
  2337. path = os.path.join(RUN, name)
  2338. if which in ["all", "runtime", ""]:
  2339. dirpath = os_path(self._root, path)
  2340. ok = self.do_rm_tree(dirpath) and ok
  2341. if RUN == "/run":
  2342. for var_run in ("/var/run", "/tmp/run"):
  2343. var_path = os.path.join(var_run, name)
  2344. var_dirpath = os_path(self._root, var_path)
  2345. self.do_rm_tree(var_dirpath)
  2346. for name in nameStateDirectory.split(" "):
  2347. if not name.strip(): continue
  2348. DAT = get_VARLIB_HOME(root)
  2349. path = os.path.join(DAT, name)
  2350. if which in ["all", "state"]:
  2351. dirpath = os_path(self._root, path)
  2352. ok = self.do_rm_tree(dirpath) and ok
  2353. for name in nameCacheDirectory.split(" "):
  2354. if not name.strip(): continue
  2355. CACHE = get_CACHE_HOME(root)
  2356. path = os.path.join(CACHE, name)
  2357. if which in ["all", "cache", ""]:
  2358. dirpath = os_path(self._root, path)
  2359. ok = self.do_rm_tree(dirpath) and ok
  2360. for name in nameLogsDirectory.split(" "):
  2361. if not name.strip(): continue
  2362. LOGS = get_LOG_DIR(root)
  2363. path = os.path.join(LOGS, name)
  2364. if which in ["all", "logs"]:
  2365. dirpath = os_path(self._root, path)
  2366. ok = self.do_rm_tree(dirpath) and ok
  2367. for name in nameConfigurationDirectory.split(" "):
  2368. if not name.strip(): continue
  2369. CONFIG = get_CONFIG_HOME(root)
  2370. path = os.path.join(CONFIG, name)
  2371. if which in ["all", "configuration", ""]:
  2372. dirpath = os_path(self._root, path)
  2373. ok = self.do_rm_tree(dirpath) and ok
  2374. return ok
  2375. def env_service_directories(self, conf):
  2376. envs = {}
  2377. section = self.get_unit_section_from(conf)
  2378. nameRuntimeDirectory = self.get_RuntimeDirectory(conf, section)
  2379. nameStateDirectory = self.get_StateDirectory(conf, section)
  2380. nameCacheDirectory = self.get_CacheDirectory(conf, section)
  2381. nameLogsDirectory = self.get_LogsDirectory(conf, section)
  2382. nameConfigurationDirectory = self.get_ConfigurationDirectory(conf, section)
  2383. root = conf.root_mode()
  2384. for name in nameRuntimeDirectory.split(" "):
  2385. if not name.strip(): continue
  2386. RUN = get_RUNTIME_DIR(root)
  2387. path = os.path.join(RUN, name)
  2388. envs["RUNTIME_DIRECTORY"] = path
  2389. for name in nameStateDirectory.split(" "):
  2390. if not name.strip(): continue
  2391. DAT = get_VARLIB_HOME(root)
  2392. path = os.path.join(DAT, name)
  2393. envs["STATE_DIRECTORY"] = path
  2394. for name in nameCacheDirectory.split(" "):
  2395. if not name.strip(): continue
  2396. CACHE = get_CACHE_HOME(root)
  2397. path = os.path.join(CACHE, name)
  2398. envs["CACHE_DIRECTORY"] = path
  2399. for name in nameLogsDirectory.split(" "):
  2400. if not name.strip(): continue
  2401. LOGS = get_LOG_DIR(root)
  2402. path = os.path.join(LOGS, name)
  2403. envs["LOGS_DIRECTORY"] = path
  2404. for name in nameConfigurationDirectory.split(" "):
  2405. if not name.strip(): continue
  2406. CONFIG = get_CONFIG_HOME(root)
  2407. path = os.path.join(CONFIG, name)
  2408. envs["CONFIGURATION_DIRECTORY"] = path
  2409. return envs
  2410. def create_service_directories(self, conf):
  2411. envs = {}
  2412. section = self.get_unit_section_from(conf)
  2413. nameRuntimeDirectory = self.get_RuntimeDirectory(conf, section)
  2414. modeRuntimeDirectory = self.get_RuntimeDirectoryMode(conf, section)
  2415. nameStateDirectory = self.get_StateDirectory(conf, section)
  2416. modeStateDirectory = self.get_StateDirectoryMode(conf, section)
  2417. nameCacheDirectory = self.get_CacheDirectory(conf, section)
  2418. modeCacheDirectory = self.get_CacheDirectoryMode(conf, section)
  2419. nameLogsDirectory = self.get_LogsDirectory(conf, section)
  2420. modeLogsDirectory = self.get_LogsDirectoryMode(conf, section)
  2421. nameConfigurationDirectory = self.get_ConfigurationDirectory(conf, section)
  2422. modeConfigurationDirectory = self.get_ConfigurationDirectoryMode(conf, section)
  2423. root = conf.root_mode()
  2424. user = self.get_User(conf)
  2425. group = self.get_Group(conf)
  2426. for name in nameRuntimeDirectory.split(" "):
  2427. if not name.strip(): continue
  2428. RUN = get_RUNTIME_DIR(root)
  2429. path = os.path.join(RUN, name)
  2430. logg.debug("RuntimeDirectory %s", path)
  2431. self.make_service_directory(path, modeRuntimeDirectory)
  2432. self.chown_service_directory(path, user, group)
  2433. envs["RUNTIME_DIRECTORY"] = path
  2434. if RUN == "/run":
  2435. for var_run in ("/var/run", "/tmp/run"):
  2436. if os.path.isdir(var_run):
  2437. var_path = os.path.join(var_run, name)
  2438. var_dirpath = os_path(self._root, var_path)
  2439. if os.path.isdir(var_dirpath):
  2440. if not os.path.islink(var_dirpath):
  2441. logg.debug("not a symlink: %s", var_dirpath)
  2442. continue
  2443. dirpath = os_path(self._root, path)
  2444. basepath = os.path.dirname(var_dirpath)
  2445. if not os.path.isdir(basepath):
  2446. os.makedirs(basepath)
  2447. try:
  2448. os.symlink(dirpath, var_dirpath)
  2449. except Exception as e:
  2450. logg.debug("var symlink %s\n\t%s", var_dirpath, e)
  2451. for name in nameStateDirectory.split(" "):
  2452. if not name.strip(): continue
  2453. DAT = get_VARLIB_HOME(root)
  2454. path = os.path.join(DAT, name)
  2455. logg.debug("StateDirectory %s", path)
  2456. self.make_service_directory(path, modeStateDirectory)
  2457. self.chown_service_directory(path, user, group)
  2458. envs["STATE_DIRECTORY"] = path
  2459. for name in nameCacheDirectory.split(" "):
  2460. if not name.strip(): continue
  2461. CACHE = get_CACHE_HOME(root)
  2462. path = os.path.join(CACHE, name)
  2463. logg.debug("CacheDirectory %s", path)
  2464. self.make_service_directory(path, modeCacheDirectory)
  2465. self.chown_service_directory(path, user, group)
  2466. envs["CACHE_DIRECTORY"] = path
  2467. for name in nameLogsDirectory.split(" "):
  2468. if not name.strip(): continue
  2469. LOGS = get_LOG_DIR(root)
  2470. path = os.path.join(LOGS, name)
  2471. logg.debug("LogsDirectory %s", path)
  2472. self.make_service_directory(path, modeLogsDirectory)
  2473. self.chown_service_directory(path, user, group)
  2474. envs["LOGS_DIRECTORY"] = path
  2475. for name in nameConfigurationDirectory.split(" "):
  2476. if not name.strip(): continue
  2477. CONFIG = get_CONFIG_HOME(root)
  2478. path = os.path.join(CONFIG, name)
  2479. logg.debug("ConfigurationDirectory %s", path)
  2480. self.make_service_directory(path, modeConfigurationDirectory)
  2481. # not done according the standard
  2482. # self.chown_service_directory(path, user, group)
  2483. envs["CONFIGURATION_DIRECTORY"] = path
  2484. return envs
  2485. def make_service_directory(self, path, mode):
  2486. ok = True
  2487. dirpath = os_path(self._root, path)
  2488. if not os.path.isdir(dirpath):
  2489. try:
  2490. os.makedirs(dirpath)
  2491. logg.info("created directory path: %s", dirpath)
  2492. except Exception as e: # pragma: no cover
  2493. logg.debug("errors directory path: %s\n\t%s", dirpath, e)
  2494. ok = False
  2495. filemode = int_mode(mode)
  2496. if filemode:
  2497. try:
  2498. os.chmod(dirpath, filemode)
  2499. except Exception as e: # pragma: no cover
  2500. logg.debug("errors directory path: %s\n\t%s", dirpath, e)
  2501. ok = False
  2502. else:
  2503. logg.debug("path did already exist: %s", dirpath)
  2504. if not ok:
  2505. logg.debug("could not fully create service directory %s", path)
  2506. return ok
  2507. def chown_service_directory(self, path, user, group):
  2508. # the standard defines an optimization so that if the parent
  2509. # directory does have the correct user and group then there
  2510. # is no other chown on files and subdirectories to be done.
  2511. dirpath = os_path(self._root, path)
  2512. if not os.path.isdir(dirpath):
  2513. logg.debug("chown did not find %s", dirpath)
  2514. return True
  2515. if user or group:
  2516. st = os.stat(dirpath)
  2517. st_user = pwd.getpwuid(st.st_uid).pw_name
  2518. st_group = grp.getgrgid(st.st_gid).gr_name
  2519. change = False
  2520. if user and (user.strip() != st_user and user.strip() != str(st.st_uid)):
  2521. change = True
  2522. if group and (group.strip() != st_group and group.strip() != str(st.st_gid)):
  2523. change = True
  2524. if change:
  2525. logg.debug("do chown %s", dirpath)
  2526. try:
  2527. ok = self.do_chown_tree(dirpath, user, group)
  2528. logg.info("changed %s:%s %s", user, group, ok)
  2529. return ok
  2530. except Exception as e:
  2531. logg.info("oops %s\n\t%s", dirpath, e)
  2532. else:
  2533. logg.debug("untouched %s", dirpath)
  2534. return True
  2535. def do_chown_tree(self, path, user, group):
  2536. ok = True
  2537. uid, gid = -1, -1
  2538. if user:
  2539. uid = pwd.getpwnam(user).pw_uid
  2540. gid = pwd.getpwnam(user).pw_gid
  2541. if group:
  2542. gid = grp.getgrnam(group).gr_gid
  2543. for dirpath, dirnames, filenames in os.walk(path, topdown=False):
  2544. for item in filenames:
  2545. filepath = os.path.join(dirpath, item)
  2546. try:
  2547. os.chown(filepath, uid, gid)
  2548. except Exception as e: # pragma: no cover
  2549. logg.debug("could not set %s:%s on %s\n\t%s", user, group, filepath, e)
  2550. ok = False
  2551. for item in dirnames:
  2552. dir_path = os.path.join(dirpath, item)
  2553. try:
  2554. os.chown(dir_path, uid, gid)
  2555. except Exception as e: # pragma: no cover
  2556. logg.debug("could not set %s:%s on %s\n\t%s", user, group, dir_path, e)
  2557. ok = False
  2558. try:
  2559. os.chown(path, uid, gid)
  2560. except Exception as e: # pragma: no cover
  2561. logg.debug("could not set %s:%s on %s\n\t%s", user, group, path, e)
  2562. ok = False
  2563. if not ok:
  2564. logg.debug("could not chown %s:%s service directory %s", user, group, path)
  2565. return ok
  2566. def clean_modules(self, *modules):
  2567. """ [UNIT]... -- remove the state directories
  2568. /// it recognizes --what=all or any of configuration, state, cache, logs, runtime
  2569. while an empty value (the default) removes cache and runtime directories"""
  2570. found_all = True
  2571. units = []
  2572. for module in modules:
  2573. matched = self.match_units(to_list(module))
  2574. if not matched:
  2575. logg.error("Unit %s not found.", unit_of(module))
  2576. self.error |= NOT_FOUND
  2577. found_all = False
  2578. continue
  2579. for unit in matched:
  2580. if unit not in units:
  2581. units += [unit]
  2582. lines = _log_lines
  2583. follow = _force
  2584. ok = self.clean_units(units)
  2585. return ok and found_all
  2586. def clean_units(self, units, what = ""):
  2587. if not what:
  2588. what = self._only_what[0]
  2589. ok = True
  2590. for unit in units:
  2591. ok = self.clean_unit(unit, what) and ok
  2592. return ok
  2593. def clean_unit(self, unit, what = ""):
  2594. conf = self.load_unit_conf(unit)
  2595. if not conf: return False
  2596. return self.clean_unit_from(conf, what)
  2597. def clean_unit_from(self, conf, what):
  2598. if self.is_active_from(conf):
  2599. logg.warning("can not clean active unit: %s", conf.name())
  2600. return False
  2601. return self.clean_service_directories(conf, what)
  2602. def log_modules(self, *modules):
  2603. """ [UNIT]... -- start 'less' on the log files for the services
  2604. /// use '-f' to follow and '-n lines' to limit output using 'tail',
  2605. using '--no-pager' just does a full 'cat'"""
  2606. found_all = True
  2607. units = []
  2608. for module in modules:
  2609. matched = self.match_units(to_list(module))
  2610. if not matched:
  2611. logg.error("Unit %s not found.", unit_of(module))
  2612. self.error |= NOT_FOUND
  2613. found_all = False
  2614. continue
  2615. for unit in matched:
  2616. if unit not in units:
  2617. units += [unit]
  2618. lines = _log_lines
  2619. follow = _force
  2620. result = self.log_units(units, lines, follow)
  2621. if result:
  2622. self.error = result
  2623. return False
  2624. return found_all
  2625. def log_units(self, units, lines = None, follow = False):
  2626. result = 0
  2627. for unit in self.sortedAfter(units):
  2628. exitcode = self.log_unit(unit, lines, follow)
  2629. if exitcode < 0:
  2630. return exitcode
  2631. if exitcode > result:
  2632. result = exitcode
  2633. return result
  2634. def log_unit(self, unit, lines = None, follow = False):
  2635. conf = self.load_unit_conf(unit)
  2636. if not conf: return -1
  2637. return self.log_unit_from(conf, lines, follow)
  2638. def log_unit_from(self, conf, lines = None, follow = False):
  2639. cmd_args = []
  2640. log_path = self.get_journal_log_from(conf)
  2641. if follow:
  2642. tail_cmd = get_exist_path(TAIL_CMDS)
  2643. if tail_cmd is None:
  2644. print("tail command not found")
  2645. return 1
  2646. cmd = [tail_cmd, "-n", str(lines or 10), "-F", log_path]
  2647. logg.debug("journalctl %s -> %s", conf.name(), cmd)
  2648. cmd_args = [arg for arg in cmd] # satisfy mypy
  2649. return os.execvp(cmd_args[0], cmd_args)
  2650. elif lines:
  2651. tail_cmd = get_exist_path(TAIL_CMDS)
  2652. if tail_cmd is None:
  2653. print("tail command not found")
  2654. return 1
  2655. cmd = [tail_cmd, "-n", str(lines or 10), log_path]
  2656. logg.debug("journalctl %s -> %s", conf.name(), cmd)
  2657. cmd_args = [arg for arg in cmd] # satisfy mypy
  2658. return os.execvp(cmd_args[0], cmd_args)
  2659. elif _no_pager:
  2660. cat_cmd = get_exist_path(CAT_CMDS)
  2661. if cat_cmd is None:
  2662. print("cat command not found")
  2663. return 1
  2664. cmd = [cat_cmd, log_path]
  2665. logg.debug("journalctl %s -> %s", conf.name(), cmd)
  2666. cmd_args = [arg for arg in cmd] # satisfy mypy
  2667. return os.execvp(cmd_args[0], cmd_args)
  2668. else:
  2669. less_cmd = get_exist_path(LESS_CMDS)
  2670. if less_cmd is None:
  2671. print("less command not found")
  2672. return 1
  2673. cmd = [less_cmd, log_path]
  2674. logg.debug("journalctl %s -> %s", conf.name(), cmd)
  2675. cmd_args = [arg for arg in cmd] # satisfy mypy
  2676. return os.execvp(cmd_args[0], cmd_args)
  2677. def get_journal_log_from(self, conf):
  2678. return os_path(self._root, self.get_journal_log(conf))
  2679. def get_journal_log(self, conf):
  2680. """ /var/log/zzz.service.log or /var/log/default.unit.log """
  2681. filename = os.path.basename(strE(conf.filename()))
  2682. unitname = (conf.name() or "default")+".unit"
  2683. name = filename or unitname
  2684. log_folder = expand_path(self._journal_log_folder, conf.root_mode())
  2685. log_file = name.replace(os.path.sep, ".") + ".log"
  2686. if log_file.startswith("."):
  2687. log_file = "dot."+log_file
  2688. return os.path.join(log_folder, log_file)
  2689. def open_journal_log(self, conf):
  2690. log_file = self.get_journal_log_from(conf)
  2691. log_folder = os.path.dirname(log_file)
  2692. if not os.path.isdir(log_folder):
  2693. os.makedirs(log_folder)
  2694. return open(os.path.join(log_file), "a")
  2695. def get_WorkingDirectory(self, conf):
  2696. return conf.get(Service, "WorkingDirectory", "")
  2697. def chdir_workingdir(self, conf):
  2698. """ if specified then change the working directory """
  2699. # the original systemd will start in '/' even if User= is given
  2700. if self._root:
  2701. os.chdir(self._root)
  2702. workingdir = self.get_WorkingDirectory(conf)
  2703. mode, workingdir = load_path(workingdir)
  2704. if workingdir:
  2705. into = os_path(self._root, self.expand_special(workingdir, conf))
  2706. try:
  2707. logg.debug("chdir workingdir '%s'", into)
  2708. os.chdir(into)
  2709. return False
  2710. except Exception as e:
  2711. if mode.check:
  2712. logg.error("chdir workingdir '%s': %s", into, e)
  2713. return into
  2714. else:
  2715. logg.debug("chdir workingdir '%s': %s", into, e)
  2716. return None
  2717. return None
  2718. NotifySocket = collections.namedtuple("NotifySocket", ["socket", "socketfile"])
  2719. def get_notify_socket_from(self, conf, socketfile = None, debug = False):
  2720. """ creates a notify-socket for the (non-privileged) user """
  2721. notify_socket_folder = expand_path(_notify_socket_folder, conf.root_mode())
  2722. notify_folder = os_path(self._root, notify_socket_folder)
  2723. notify_name = "notify." + str(conf.name() or "systemctl")
  2724. notify_socket = os.path.join(notify_folder, notify_name)
  2725. socketfile = socketfile or notify_socket
  2726. if len(socketfile) > 100:
  2727. # occurs during testsuite.py for ~user/test.tmp/root path
  2728. if debug:
  2729. logg.debug("https://unix.stackexchange.com/questions/367008/%s",
  2730. "why-is-socket-path-length-limited-to-a-hundred-chars")
  2731. logg.debug("old notify socketfile (%s) = %s", len(socketfile), socketfile)
  2732. notify_name44 = o44(notify_name)
  2733. notify_name77 = o77(notify_name)
  2734. socketfile = os.path.join(notify_folder, notify_name77)
  2735. if len(socketfile) > 100:
  2736. socketfile = os.path.join(notify_folder, notify_name44)
  2737. pref = "zz.%i.%s" % (get_USER_ID(), o22(os.path.basename(notify_socket_folder)))
  2738. if len(socketfile) > 100:
  2739. socketfile = os.path.join(get_TMP(), pref, notify_name)
  2740. if len(socketfile) > 100:
  2741. socketfile = os.path.join(get_TMP(), pref, notify_name77)
  2742. if len(socketfile) > 100: # pragma: no cover
  2743. socketfile = os.path.join(get_TMP(), pref, notify_name44)
  2744. if len(socketfile) > 100: # pragma: no cover
  2745. socketfile = os.path.join(get_TMP(), notify_name44)
  2746. if debug:
  2747. logg.info("new notify socketfile (%s) = %s", len(socketfile), socketfile)
  2748. return socketfile
  2749. def notify_socket_from(self, conf, socketfile = None):
  2750. socketfile = self.get_notify_socket_from(conf, socketfile, debug=True)
  2751. try:
  2752. if not os.path.isdir(os.path.dirname(socketfile)):
  2753. os.makedirs(os.path.dirname(socketfile))
  2754. if os.path.exists(socketfile):
  2755. os.unlink(socketfile)
  2756. except Exception as e:
  2757. logg.warning("error %s: %s", socketfile, e)
  2758. sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
  2759. sock.bind(socketfile)
  2760. os.chmod(socketfile, 0o777) # the service my run under some User=setting
  2761. return Systemctl.NotifySocket(sock, socketfile)
  2762. def read_notify_socket(self, notify, timeout):
  2763. notify.socket.settimeout(timeout or DefaultMaximumTimeout)
  2764. result = ""
  2765. try:
  2766. result, client_address = notify.socket.recvfrom(4096)
  2767. assert isinstance(result, bytes)
  2768. if result:
  2769. result = result.decode("utf-8")
  2770. result_txt = result.replace("\n", "|")
  2771. result_len = len(result)
  2772. logg.debug("read_notify_socket(%s):%s", result_len, result_txt)
  2773. except socket.timeout as e:
  2774. if timeout > 2:
  2775. logg.debug("socket.timeout %s", e)
  2776. return result
  2777. def wait_notify_socket(self, notify, timeout, pid = None, pid_file = None):
  2778. if not os.path.exists(notify.socketfile):
  2779. logg.info("no $NOTIFY_SOCKET exists")
  2780. return {}
  2781. #
  2782. lapseTimeout = max(3, int(timeout / 100))
  2783. mainpidTimeout = lapseTimeout # Apache sends READY before MAINPID
  2784. status = ""
  2785. logg.info("wait $NOTIFY_SOCKET, timeout %s (lapse %s)", timeout, lapseTimeout)
  2786. waiting = " ---"
  2787. results = {}
  2788. for attempt in xrange(int(timeout)+1):
  2789. if pid and not self.is_active_pid(pid):
  2790. logg.info("seen dead PID %s", pid)
  2791. return results
  2792. if not attempt: # first one
  2793. time.sleep(1) # until TimeoutStartSec
  2794. continue
  2795. result = self.read_notify_socket(notify, 1) # sleep max 1 second
  2796. for line in result.splitlines():
  2797. # for name, value in self.read_env_part(line)
  2798. if "=" not in line:
  2799. continue
  2800. name, value = line.split("=", 1)
  2801. results[name] = value
  2802. if name in ["STATUS", "ACTIVESTATE", "MAINPID", "READY"]:
  2803. hint="seen notify %s " % (waiting)
  2804. logg.debug("%s :%s=%s", hint, name, value)
  2805. if status != results.get("STATUS", ""):
  2806. mainpidTimeout = lapseTimeout
  2807. status = results.get("STATUS", "")
  2808. if "READY" not in results:
  2809. time.sleep(1) # until TimeoutStart
  2810. continue
  2811. if "MAINPID" not in results and not pid_file:
  2812. mainpidTimeout -= 1
  2813. if mainpidTimeout > 0:
  2814. waiting = "%4i" % (-mainpidTimeout)
  2815. time.sleep(1) # until TimeoutStart
  2816. continue
  2817. break # READY and MAINPID
  2818. if "READY" not in results:
  2819. logg.info(".... timeout while waiting for 'READY=1' status on $NOTIFY_SOCKET")
  2820. elif "MAINPID" not in results:
  2821. logg.info(".... seen 'READY=1' but no MAINPID update status on $NOTIFY_SOCKET")
  2822. logg.debug("notify = %s", results)
  2823. try:
  2824. notify.socket.close()
  2825. except Exception as e:
  2826. logg.debug("socket.close %s", e)
  2827. return results
  2828. def start_modules(self, *modules):
  2829. """ [UNIT]... -- start these units
  2830. /// SPECIAL: with --now or --init it will
  2831. run the init-loop and stop the units afterwards """
  2832. found_all = True
  2833. units = []
  2834. for module in modules:
  2835. matched = self.match_units(to_list(module))
  2836. if not matched:
  2837. logg.error("Unit %s not found.", unit_of(module))
  2838. self.error |= NOT_FOUND
  2839. found_all = False
  2840. continue
  2841. for unit in matched:
  2842. if unit not in units:
  2843. units += [unit]
  2844. init = self._now or self._init
  2845. return self.start_units(units, init) and found_all
  2846. def start_units(self, units, init = None):
  2847. """ fails if any unit does not start
  2848. /// SPECIAL: may run the init-loop and
  2849. stop the named units afterwards """
  2850. self.wait_system()
  2851. done = True
  2852. started_units = []
  2853. for unit in self.sortedAfter(units):
  2854. started_units.append(unit)
  2855. if not self.start_unit(unit):
  2856. done = False
  2857. if init:
  2858. logg.info("init-loop start")
  2859. sig = self.init_loop_until_stop(started_units)
  2860. logg.info("init-loop %s", sig)
  2861. for unit in reversed(started_units):
  2862. self.stop_unit(unit)
  2863. return done
  2864. def start_unit(self, unit):
  2865. conf = self.load_unit_conf(unit)
  2866. if conf is None:
  2867. logg.debug("unit could not be loaded (%s)", unit)
  2868. logg.error("Unit %s not found.", unit)
  2869. return False
  2870. if self.not_user_conf(conf):
  2871. logg.error("Unit %s not for --user mode", unit)
  2872. return False
  2873. return self.start_unit_from(conf)
  2874. def get_TimeoutStartSec(self, conf):
  2875. timeout = conf.get(Service, "TimeoutSec", strE(DefaultTimeoutStartSec))
  2876. timeout = conf.get(Service, "TimeoutStartSec", timeout)
  2877. return time_to_seconds(timeout, DefaultMaximumTimeout)
  2878. def get_SocketTimeoutSec(self, conf):
  2879. timeout = conf.get(Socket, "TimeoutSec", strE(DefaultTimeoutStartSec))
  2880. return time_to_seconds(timeout, DefaultMaximumTimeout)
  2881. def get_RemainAfterExit(self, conf):
  2882. return conf.getbool(Service, "RemainAfterExit", "no")
  2883. def start_unit_from(self, conf):
  2884. if not conf: return False
  2885. if self.syntax_check(conf) > 100: return False
  2886. with waitlock(conf):
  2887. logg.debug(" start unit %s => %s", conf.name(), strQ(conf.filename()))
  2888. return self.do_start_unit_from(conf)
  2889. def do_start_unit_from(self, conf):
  2890. if conf.name().endswith(".service"):
  2891. return self.do_start_service_from(conf)
  2892. elif conf.name().endswith(".socket"):
  2893. return self.do_start_socket_from(conf)
  2894. elif conf.name().endswith(".target"):
  2895. return self.do_start_target_from(conf)
  2896. else:
  2897. logg.error("start not implemented for unit type: %s", conf.name())
  2898. return False
  2899. def do_start_service_from(self, conf):
  2900. timeout = self.get_TimeoutStartSec(conf)
  2901. doRemainAfterExit = self.get_RemainAfterExit(conf)
  2902. runs = conf.get(Service, "Type", "simple").lower()
  2903. env = self.get_env(conf)
  2904. if not self._quiet:
  2905. okee = self.exec_check_unit(conf, env, Service, "Exec") # all...
  2906. if not okee and _no_reload: return False
  2907. service_directories = self.create_service_directories(conf)
  2908. env.update(service_directories) # atleast sshd did check for /run/sshd
  2909. # for StopPost on failure:
  2910. returncode = 0
  2911. service_result = "success"
  2912. if True:
  2913. if runs in ["simple", "exec", "forking", "notify", "idle"]:
  2914. env["MAINPID"] = strE(self.read_mainpid_from(conf))
  2915. for cmd in conf.getlist(Service, "ExecStartPre", []):
  2916. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  2917. logg.info(" pre-start %s", shell_cmd(newcmd))
  2918. forkpid = os.fork()
  2919. if not forkpid:
  2920. self.execve_from(conf, newcmd, env) # pragma: no cover
  2921. run = subprocess_waitpid(forkpid)
  2922. logg.debug(" pre-start done (%s) <-%s>",
  2923. run.returncode or "OK", run.signal or "")
  2924. if run.returncode and exe.check:
  2925. logg.error("the ExecStartPre control process exited with error code")
  2926. active = "failed"
  2927. self.write_status_from(conf, AS=active)
  2928. if self._only_what[0] not in ["none", "keep"]:
  2929. self.remove_service_directories(conf) # cleanup that /run/sshd
  2930. return False
  2931. if runs in ["oneshot"]:
  2932. status_file = self.get_status_file_from(conf)
  2933. if self.get_status_from(conf, "ActiveState", "unknown") == "active":
  2934. logg.warning("the service was already up once")
  2935. return True
  2936. for cmd in conf.getlist(Service, "ExecStart", []):
  2937. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  2938. logg.info("%s start %s", runs, shell_cmd(newcmd))
  2939. forkpid = os.fork()
  2940. if not forkpid: # pragma: no cover
  2941. os.setsid() # detach child process from parent
  2942. self.execve_from(conf, newcmd, env)
  2943. run = subprocess_waitpid(forkpid)
  2944. if run.returncode and exe.check:
  2945. returncode = run.returncode
  2946. service_result = "failed"
  2947. logg.error("%s start %s (%s) <-%s>", runs, service_result,
  2948. run.returncode or "OK", run.signal or "")
  2949. break
  2950. logg.info("%s start done (%s) <-%s>", runs,
  2951. run.returncode or "OK", run.signal or "")
  2952. if True:
  2953. self.set_status_from(conf, "ExecMainCode", strE(returncode))
  2954. active = returncode and "failed" or "active"
  2955. self.write_status_from(conf, AS=active)
  2956. elif runs in ["simple", "exec", "idle"]:
  2957. status_file = self.get_status_file_from(conf)
  2958. pid = self.read_mainpid_from(conf)
  2959. if self.is_active_pid(pid):
  2960. logg.warning("the service is already running on PID %s", pid)
  2961. return True
  2962. if doRemainAfterExit:
  2963. logg.debug("%s RemainAfterExit -> AS=active", runs)
  2964. self.write_status_from(conf, AS="active")
  2965. cmdlist = conf.getlist(Service, "ExecStart", [])
  2966. for idx, cmd in enumerate(cmdlist):
  2967. logg.debug("ExecStart[%s]: %s", idx, cmd)
  2968. for cmd in cmdlist:
  2969. pid = self.read_mainpid_from(conf)
  2970. env["MAINPID"] = strE(pid)
  2971. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  2972. logg.info("%s start %s", runs, shell_cmd(newcmd))
  2973. forkpid = os.fork()
  2974. if not forkpid: # pragma: no cover
  2975. os.setsid() # detach child process from parent
  2976. self.execve_from(conf, newcmd, env)
  2977. self.write_status_from(conf, MainPID=forkpid)
  2978. logg.info("%s started PID %s", runs, forkpid)
  2979. env["MAINPID"] = strE(forkpid)
  2980. time.sleep(MinimumYield)
  2981. run = subprocess_testpid(forkpid)
  2982. if run.returncode is not None:
  2983. logg.info("%s stopped PID %s (%s) <-%s>", runs, run.pid,
  2984. run.returncode or "OK", run.signal or "")
  2985. if doRemainAfterExit:
  2986. self.set_status_from(conf, "ExecMainCode", strE(run.returncode))
  2987. active = run.returncode and "failed" or "active"
  2988. self.write_status_from(conf, AS=active)
  2989. if run.returncode and exe.check:
  2990. service_result = "failed"
  2991. break
  2992. elif runs in ["notify"]:
  2993. # "notify" is the same as "simple" but we create a $NOTIFY_SOCKET
  2994. # and wait for startup completion by checking the socket messages
  2995. pid_file = self.pid_file_from(conf)
  2996. pid = self.read_mainpid_from(conf)
  2997. if self.is_active_pid(pid):
  2998. logg.error("the service is already running on PID %s", pid)
  2999. return False
  3000. notify = self.notify_socket_from(conf)
  3001. if notify:
  3002. env["NOTIFY_SOCKET"] = notify.socketfile
  3003. logg.debug("use NOTIFY_SOCKET=%s", notify.socketfile)
  3004. if doRemainAfterExit:
  3005. logg.debug("%s RemainAfterExit -> AS=active", runs)
  3006. self.write_status_from(conf, AS="active")
  3007. cmdlist = conf.getlist(Service, "ExecStart", [])
  3008. for idx, cmd in enumerate(cmdlist):
  3009. logg.debug("ExecStart[%s]: %s", idx, cmd)
  3010. mainpid = None
  3011. for cmd in cmdlist:
  3012. mainpid = self.read_mainpid_from(conf)
  3013. env["MAINPID"] = strE(mainpid)
  3014. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3015. logg.info("%s start %s", runs, shell_cmd(newcmd))
  3016. forkpid = os.fork()
  3017. if not forkpid: # pragma: no cover
  3018. os.setsid() # detach child process from parent
  3019. self.execve_from(conf, newcmd, env)
  3020. # via NOTIFY # self.write_status_from(conf, MainPID=forkpid)
  3021. logg.info("%s started PID %s", runs, forkpid)
  3022. mainpid = forkpid
  3023. self.write_status_from(conf, MainPID=mainpid)
  3024. env["MAINPID"] = strE(mainpid)
  3025. time.sleep(MinimumYield)
  3026. run = subprocess_testpid(forkpid)
  3027. if run.returncode is not None:
  3028. logg.info("%s stopped PID %s (%s) <-%s>", runs, run.pid,
  3029. run.returncode or "OK", run.signal or "")
  3030. if doRemainAfterExit:
  3031. self.set_status_from(conf, "ExecMainCode", strE(run.returncode))
  3032. active = run.returncode and "failed" or "active"
  3033. self.write_status_from(conf, AS=active)
  3034. if run.returncode and exe.check:
  3035. service_result = "failed"
  3036. break
  3037. if service_result in ["success"] and mainpid:
  3038. logg.debug("okay, waiting on socket for %ss", timeout)
  3039. results = self.wait_notify_socket(notify, timeout, mainpid, pid_file)
  3040. if "MAINPID" in results:
  3041. new_pid = to_intN(results["MAINPID"])
  3042. if new_pid and new_pid != mainpid:
  3043. logg.info("NEW PID %s from sd_notify (was PID %s)", new_pid, mainpid)
  3044. self.write_status_from(conf, MainPID=new_pid)
  3045. mainpid = new_pid
  3046. logg.info("%s start done %s", runs, mainpid)
  3047. pid = self.read_mainpid_from(conf)
  3048. if pid:
  3049. env["MAINPID"] = strE(pid)
  3050. else:
  3051. service_result = "timeout" # "could not start service"
  3052. elif runs in ["forking"]:
  3053. pid_file = self.pid_file_from(conf)
  3054. for cmd in conf.getlist(Service, "ExecStart", []):
  3055. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3056. if not newcmd: continue
  3057. logg.info("%s start %s", runs, shell_cmd(newcmd))
  3058. forkpid = os.fork()
  3059. if not forkpid: # pragma: no cover
  3060. os.setsid() # detach child process from parent
  3061. self.execve_from(conf, newcmd, env)
  3062. logg.info("%s started PID %s", runs, forkpid)
  3063. run = subprocess_waitpid(forkpid)
  3064. if run.returncode and exe.check:
  3065. returncode = run.returncode
  3066. service_result = "failed"
  3067. logg.info("%s stopped PID %s (%s) <-%s>", runs, run.pid,
  3068. run.returncode or "OK", run.signal or "")
  3069. if pid_file and service_result in ["success"]:
  3070. pid = self.wait_pid_file(pid_file) # application PIDFile
  3071. logg.info("%s start done PID %s [%s]", runs, pid, pid_file)
  3072. if pid:
  3073. env["MAINPID"] = strE(pid)
  3074. if not pid_file:
  3075. time.sleep(MinimumTimeoutStartSec)
  3076. logg.warning("No PIDFile for forking %s", strQ(conf.filename()))
  3077. status_file = self.get_status_file_from(conf)
  3078. self.set_status_from(conf, "ExecMainCode", strE(returncode))
  3079. active = returncode and "failed" or "active"
  3080. self.write_status_from(conf, AS=active)
  3081. else:
  3082. logg.error("unsupported run type '%s'", runs)
  3083. return False
  3084. # POST sequence
  3085. if not self.is_active_from(conf):
  3086. logg.warning("%s start not active", runs)
  3087. # according to the systemd documentation, a failed start-sequence
  3088. # should execute the ExecStopPost sequence allowing some cleanup.
  3089. env["SERVICE_RESULT"] = service_result
  3090. for cmd in conf.getlist(Service, "ExecStopPost", []):
  3091. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3092. logg.info("post-fail %s", shell_cmd(newcmd))
  3093. forkpid = os.fork()
  3094. if not forkpid:
  3095. self.execve_from(conf, newcmd, env) # pragma: no cover
  3096. run = subprocess_waitpid(forkpid)
  3097. logg.debug("post-fail done (%s) <-%s>",
  3098. run.returncode or "OK", run.signal or "")
  3099. if self._only_what[0] not in ["none", "keep"]:
  3100. self.remove_service_directories(conf)
  3101. return False
  3102. else:
  3103. for cmd in conf.getlist(Service, "ExecStartPost", []):
  3104. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3105. logg.info("post-start %s", shell_cmd(newcmd))
  3106. forkpid = os.fork()
  3107. if not forkpid:
  3108. self.execve_from(conf, newcmd, env) # pragma: no cover
  3109. run = subprocess_waitpid(forkpid)
  3110. logg.debug("post-start done (%s) <-%s>",
  3111. run.returncode or "OK", run.signal or "")
  3112. return True
  3113. def listen_modules(self, *modules):
  3114. """ [UNIT]... -- listen socket units"""
  3115. found_all = True
  3116. units = []
  3117. for module in modules:
  3118. matched = self.match_units(to_list(module))
  3119. if not matched:
  3120. logg.error("Unit %s not found.", unit_of(module))
  3121. self.error |= NOT_FOUND
  3122. found_all = False
  3123. continue
  3124. for unit in matched:
  3125. if unit not in units:
  3126. units += [unit]
  3127. return self.listen_units(units) and found_all
  3128. def listen_units(self, units):
  3129. """ fails if any socket does not start """
  3130. self.wait_system()
  3131. done = True
  3132. started_units = []
  3133. active_units = []
  3134. for unit in self.sortedAfter(units):
  3135. started_units.append(unit)
  3136. if not self.listen_unit(unit):
  3137. done = False
  3138. else:
  3139. active_units.append(unit)
  3140. if active_units:
  3141. logg.info("init-loop start")
  3142. sig = self.init_loop_until_stop(started_units)
  3143. logg.info("init-loop %s", sig)
  3144. for unit in reversed(started_units):
  3145. pass # self.stop_unit(unit)
  3146. return done
  3147. def listen_unit(self, unit):
  3148. conf = self.load_unit_conf(unit)
  3149. if conf is None:
  3150. logg.debug("unit could not be loaded (%s)", unit)
  3151. logg.error("Unit %s not found.", unit)
  3152. return False
  3153. if self.not_user_conf(conf):
  3154. logg.error("Unit %s not for --user mode", unit)
  3155. return False
  3156. return self.listen_unit_from(conf)
  3157. def listen_unit_from(self, conf):
  3158. if not conf: return False
  3159. with waitlock(conf):
  3160. logg.debug(" listen unit %s => %s", conf.name(), strQ(conf.filename()))
  3161. return self.do_listen_unit_from(conf)
  3162. def do_listen_unit_from(self, conf):
  3163. if conf.name().endswith(".socket"):
  3164. return self.do_start_socket_from(conf)
  3165. else:
  3166. logg.error("listen not implemented for unit type: %s", conf.name())
  3167. return False
  3168. def do_accept_socket_from(self, conf, sock):
  3169. logg.debug("%s: accepting %s", conf.name(), sock.fileno())
  3170. service_unit = self.get_socket_service_from(conf)
  3171. service_conf = self.load_unit_conf(service_unit)
  3172. if service_conf is None or TestAccept: # pragma: no cover
  3173. if sock.type == socket.SOCK_STREAM:
  3174. conn, addr = sock.accept()
  3175. data = conn.recv(1024)
  3176. logg.debug("%s: '%s'", conf.name(), data)
  3177. conn.send(b"ERROR: "+data.upper())
  3178. conn.close()
  3179. return False
  3180. if sock.type == socket.SOCK_DGRAM:
  3181. data, sender = sock.recvfrom(1024)
  3182. logg.debug("%s: '%s'", conf.name(), data)
  3183. sock.sendto(b"ERROR: "+data.upper(), sender)
  3184. return False
  3185. logg.error("can not accept socket type %s", strINET(sock.type))
  3186. return False
  3187. return self.do_start_service_from(service_conf)
  3188. def get_socket_service_from(self, conf):
  3189. socket_unit = conf.name()
  3190. accept = conf.getbool(Socket, "Accept", "no")
  3191. service_type = accept and "@.service" or ".service"
  3192. service_name = path_replace_extension(socket_unit, ".socket", service_type)
  3193. service_unit = conf.get(Socket, Service, service_name)
  3194. logg.debug("socket %s -> service %s", socket_unit, service_unit)
  3195. return service_unit
  3196. def do_start_socket_from(self, conf):
  3197. runs = "socket"
  3198. timeout = self.get_SocketTimeoutSec(conf)
  3199. accept = conf.getbool(Socket, "Accept", "no")
  3200. stream = conf.get(Socket, "ListenStream", "")
  3201. service_unit = self.get_socket_service_from(conf)
  3202. service_conf = self.load_unit_conf(service_unit)
  3203. if service_conf is None:
  3204. logg.debug("unit could not be loaded (%s)", service_unit)
  3205. logg.error("Unit %s not found.", service_unit)
  3206. return False
  3207. env = self.get_env(conf)
  3208. if not self._quiet:
  3209. okee = self.exec_check_unit(conf, env, Socket, "Exec") # all...
  3210. if not okee and _no_reload: return False
  3211. if True:
  3212. for cmd in conf.getlist(Socket, "ExecStartPre", []):
  3213. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3214. logg.info(" pre-start %s", shell_cmd(newcmd))
  3215. forkpid = os.fork()
  3216. if not forkpid:
  3217. self.execve_from(conf, newcmd, env) # pragma: no cover
  3218. run = subprocess_waitpid(forkpid)
  3219. logg.debug(" pre-start done (%s) <-%s>",
  3220. run.returncode or "OK", run.signal or "")
  3221. if run.returncode and exe.check:
  3222. logg.error("the ExecStartPre control process exited with error code")
  3223. active = "failed"
  3224. self.write_status_from(conf, AS=active)
  3225. return False
  3226. # service_directories = self.create_service_directories(conf)
  3227. # env.update(service_directories)
  3228. listening=False
  3229. if not accept:
  3230. sock = self.create_socket(conf)
  3231. if sock and TestListen:
  3232. listening=True
  3233. self._sockets[conf.name()] = SystemctlSocket(conf, sock)
  3234. service_result = "success"
  3235. state = sock and "active" or "failed"
  3236. self.write_status_from(conf, AS=state)
  3237. if not listening:
  3238. # we do not listen but have the service started right away
  3239. done = self.do_start_service_from(service_conf)
  3240. service_result = done and "success" or "failed"
  3241. if not self.is_active_from(service_conf):
  3242. service_result = "failed"
  3243. state = service_result
  3244. if service_result in ["success"]:
  3245. state = "active"
  3246. self.write_status_from(conf, AS=state)
  3247. # POST sequence
  3248. if service_result in ["failed"]:
  3249. # according to the systemd documentation, a failed start-sequence
  3250. # should execute the ExecStopPost sequence allowing some cleanup.
  3251. env["SERVICE_RESULT"] = service_result
  3252. for cmd in conf.getlist(Socket, "ExecStopPost", []):
  3253. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3254. logg.info("post-fail %s", shell_cmd(newcmd))
  3255. forkpid = os.fork()
  3256. if not forkpid:
  3257. self.execve_from(conf, newcmd, env) # pragma: no cover
  3258. run = subprocess_waitpid(forkpid)
  3259. logg.debug("post-fail done (%s) <-%s>",
  3260. run.returncode or "OK", run.signal or "")
  3261. return False
  3262. else:
  3263. for cmd in conf.getlist(Socket, "ExecStartPost", []):
  3264. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3265. logg.info("post-start %s", shell_cmd(newcmd))
  3266. forkpid = os.fork()
  3267. if not forkpid:
  3268. self.execve_from(conf, newcmd, env) # pragma: no cover
  3269. run = subprocess_waitpid(forkpid)
  3270. logg.debug("post-start done (%s) <-%s>",
  3271. run.returncode or "OK", run.signal or "")
  3272. return True
  3273. def create_socket(self, conf):
  3274. unsupported = ["ListenUSBFunction", "ListenMessageQueue", "ListenNetlink"]
  3275. unsupported += ["ListenSpecial", "ListenFIFO", "ListenSequentialPacket"]
  3276. for item in unsupported:
  3277. if conf.get(Socket, item, ""):
  3278. logg.warning("%s: %s sockets are not implemented", conf.name(), item)
  3279. self.error |= NOT_OK
  3280. return None
  3281. vListenDatagram = conf.get(Socket, "ListenDatagram", "")
  3282. vListenStream = conf.get(Socket, "ListenStream", "")
  3283. address = vListenStream or vListenDatagram
  3284. m = re.match(r"(/.*)", address)
  3285. if m:
  3286. path = m.group(1)
  3287. sock = self.create_unix_socket(conf, path, not vListenStream)
  3288. self.set_status_from(conf, "path", path)
  3289. return sock
  3290. m = re.match(r"(\d+[.]\d*[.]\d*[.]\d+):(\d+)", address)
  3291. if m:
  3292. addr, port = m.group(1), m.group(2)
  3293. sock = self.create_port_ipv4_socket(conf, addr, port, not vListenStream)
  3294. self.set_status_from(conf, "port", port)
  3295. self.set_status_from(conf, "addr", addr)
  3296. return sock
  3297. m = re.match(r"\[([0-9a-fA-F:]*)\]:(\d+)", address)
  3298. if m:
  3299. addr, port = m.group(1), m.group(2)
  3300. sock = self.create_port_ipv6_socket(conf, addr, port, not vListenStream)
  3301. self.set_status_from(conf, "port", port)
  3302. self.set_status_from(conf, "addr", addr)
  3303. return sock
  3304. m = re.match(r"(\d+)$", address)
  3305. if m:
  3306. port = m.group(1)
  3307. sock = self.create_port_socket(conf, port, not vListenStream)
  3308. self.set_status_from(conf, "port", port)
  3309. return sock
  3310. if re.match("@.*", address):
  3311. logg.warning("%s: abstract namespace socket not implemented (%s)", conf.name(), address)
  3312. return None
  3313. if re.match("vsock:.*", address):
  3314. logg.warning("%s: virtual machine socket not implemented (%s)", conf.name(), address)
  3315. return None
  3316. logg.error("%s: unknown socket address type (%s)", conf.name(), address)
  3317. return None
  3318. def create_unix_socket(self, conf, path, dgram):
  3319. sock_stream = dgram and socket.SOCK_DGRAM or socket.SOCK_STREAM
  3320. sock = socket.socket(socket.AF_UNIX, sock_stream)
  3321. try:
  3322. dirmode = conf.get(Socket, "DirectoryMode", "0755")
  3323. mode = conf.get(Socket, "SocketMode", "0666")
  3324. user = conf.get(Socket, "SocketUser", "")
  3325. group = conf.get(Socket, "SocketGroup", "")
  3326. symlinks = conf.getlist(Socket, "SymLinks", [])
  3327. dirpath = os.path.dirname(path)
  3328. if not os.path.isdir(dirpath):
  3329. os.makedirs(dirpath, int(dirmode, 8))
  3330. if os.path.exists(path):
  3331. os.unlink(path)
  3332. sock.bind(path)
  3333. os.fchmod(sock.fileno(), int(mode, 8))
  3334. shutil_fchown(sock.fileno(), user, group)
  3335. if symlinks:
  3336. logg.warning("%s: symlinks for socket not implemented (%s)", conf.name(), path)
  3337. except Exception as e:
  3338. logg.error("%s: create socket failed [%s]: %s", conf.name(), path, e)
  3339. sock.close()
  3340. return None
  3341. return sock
  3342. def create_port_socket(self, conf, port, dgram):
  3343. inet = dgram and socket.SOCK_DGRAM or socket.SOCK_STREAM
  3344. sock = socket.socket(socket.AF_INET, inet)
  3345. try:
  3346. sock.bind(('', int(port)))
  3347. logg.info("%s: bound socket at %s %s:%s", conf.name(), strINET(inet), "*", port)
  3348. except Exception as e:
  3349. logg.error("%s: create socket failed (%s:%s): %s", conf.name(), "*", port, e)
  3350. sock.close()
  3351. return None
  3352. return sock
  3353. def create_port_ipv4_socket(self, conf, addr, port, dgram):
  3354. inet = dgram and socket.SOCK_DGRAM or socket.SOCK_STREAM
  3355. sock = socket.socket(socket.AF_INET, inet)
  3356. try:
  3357. sock.bind((addr, int(port)))
  3358. logg.info("%s: bound socket at %s %s:%s", conf.name(), strINET(inet), addr, port)
  3359. except Exception as e:
  3360. logg.error("%s: create socket failed (%s:%s): %s", conf.name(), addr, port, e)
  3361. sock.close()
  3362. return None
  3363. return sock
  3364. def create_port_ipv6_socket(self, conf, addr, port, dgram):
  3365. inet = dgram and socket.SOCK_DGRAM or socket.SOCK_STREAM
  3366. sock = socket.socket(socket.AF_INET6, inet)
  3367. try:
  3368. sock.bind((addr, int(port)))
  3369. logg.info("%s: bound socket at %s [%s]:%s", conf.name(), strINET(inet), addr, port)
  3370. except Exception as e:
  3371. logg.error("%s: create socket failed ([%s]:%s): %s", conf.name(), addr, port, e)
  3372. sock.close()
  3373. return None
  3374. return sock
  3375. def extend_exec_env(self, env):
  3376. env = env.copy()
  3377. # implant DefaultPath into $PATH
  3378. path = env.get("PATH", DefaultPath)
  3379. parts = path.split(os.pathsep)
  3380. for part in DefaultPath.split(os.pathsep):
  3381. if part and part not in parts:
  3382. parts.append(part)
  3383. env["PATH"] = str(os.pathsep).join(parts)
  3384. # reset locale to system default
  3385. for name in ResetLocale:
  3386. if name in env:
  3387. del env[name]
  3388. locale = {}
  3389. path = env.get("LOCALE_CONF", LocaleConf)
  3390. parts = path.split(os.pathsep)
  3391. for part in parts:
  3392. if os.path.isfile(part):
  3393. for var, val in self.read_env_file("-"+part):
  3394. locale[var] = val
  3395. env[var] = val
  3396. if "LANG" not in locale:
  3397. env["LANG"] = locale.get("LANGUAGE", locale.get("LC_CTYPE", "C"))
  3398. return env
  3399. def expand_list(self, group_lines, conf):
  3400. result = []
  3401. for line in group_lines:
  3402. for item in line.split():
  3403. if item:
  3404. result.append(self.expand_special(item, conf))
  3405. return result
  3406. def get_User(self, conf):
  3407. return self.expand_special(conf.get(Service, "User", ""), conf)
  3408. def get_Group(self, conf):
  3409. return self.expand_special(conf.get(Service, "Group", ""), conf)
  3410. def get_SupplementaryGroups(self, conf):
  3411. return self.expand_list(conf.getlist(Service, "SupplementaryGroups", []), conf)
  3412. def skip_journal_log(self, conf):
  3413. if self.get_unit_type(conf.name()) not in ["service"]:
  3414. return True
  3415. std_out = conf.get(Service, "StandardOutput", DefaultStandardOutput)
  3416. std_err = conf.get(Service, "StandardError", DefaultStandardError)
  3417. out, err = False, False
  3418. if std_out in ["null"]: out = True
  3419. if std_out.startswith("file:"): out = True
  3420. if std_err in ["inherit"]: std_err = std_out
  3421. if std_err in ["null"]: err = True
  3422. if std_err.startswith("file:"): err = True
  3423. if std_err.startswith("append:"): err = True
  3424. return out and err
  3425. def dup2_journal_log(self, conf):
  3426. msg = ""
  3427. std_inp = conf.get(Service, "StandardInput", DefaultStandardInput)
  3428. std_out = conf.get(Service, "StandardOutput", DefaultStandardOutput)
  3429. std_err = conf.get(Service, "StandardError", DefaultStandardError)
  3430. inp, out, err = None, None, None
  3431. if std_inp in ["null"]:
  3432. inp = open(_dev_null, "r")
  3433. elif std_inp.startswith("file:"):
  3434. fname = std_inp[len("file:"):]
  3435. if os.path.exists(fname):
  3436. inp = open(fname, "r")
  3437. else:
  3438. inp = open(_dev_zero, "r")
  3439. else:
  3440. inp = open(_dev_zero, "r")
  3441. assert inp is not None
  3442. try:
  3443. if std_out in ["null"]:
  3444. out = open(_dev_null, "w")
  3445. elif std_out.startswith("file:"):
  3446. fname = std_out[len("file:"):]
  3447. fdir = os.path.dirname(fname)
  3448. if not os.path.exists(fdir):
  3449. os.makedirs(fdir)
  3450. out = open(fname, "w")
  3451. elif std_out.startswith("append:"):
  3452. fname = std_out[len("append:"):]
  3453. fdir = os.path.dirname(fname)
  3454. if not os.path.exists(fdir):
  3455. os.makedirs(fdir)
  3456. out = open(fname, "a")
  3457. except Exception as e:
  3458. msg += "\n%s: %s" % (fname, e)
  3459. if out is None:
  3460. out = self.open_journal_log(conf)
  3461. err = out
  3462. assert out is not None
  3463. try:
  3464. if std_err in ["inherit"]:
  3465. err = out
  3466. elif std_err in ["null"]:
  3467. err = open(_dev_null, "w")
  3468. elif std_err.startswith("file:"):
  3469. fname = std_err[len("file:"):]
  3470. fdir = os.path.dirname(fname)
  3471. if not os.path.exists(fdir):
  3472. os.makedirs(fdir)
  3473. err = open(fname, "w")
  3474. elif std_err.startswith("append:"):
  3475. fname = std_err[len("append:"):]
  3476. fdir = os.path.dirname(fname)
  3477. if not os.path.exists(fdir):
  3478. os.makedirs(fdir)
  3479. err = open(fname, "a")
  3480. except Exception as e:
  3481. msg += "\n%s: %s" % (fname, e)
  3482. if err is None:
  3483. err = self.open_journal_log(conf)
  3484. assert err is not None
  3485. if msg:
  3486. err.write("ERROR:")
  3487. err.write(msg.strip())
  3488. err.write("\n")
  3489. if EXEC_DUP2:
  3490. os.dup2(inp.fileno(), sys.stdin.fileno())
  3491. os.dup2(out.fileno(), sys.stdout.fileno())
  3492. os.dup2(err.fileno(), sys.stderr.fileno())
  3493. def execve_from(self, conf, cmd, env):
  3494. """ this code is commonly run in a child process // returns exit-code"""
  3495. # |
  3496. runs = conf.get(Service, "Type", "simple").lower()
  3497. # logg.debug("%s process for %s => %s", runs, strE(conf.name()), strQ(conf.filename()))
  3498. self.dup2_journal_log(conf)
  3499. cmd_args = []
  3500. #
  3501. runuser = self.get_User(conf)
  3502. rungroup = self.get_Group(conf)
  3503. xgroups = self.get_SupplementaryGroups(conf)
  3504. envs = shutil_setuid(runuser, rungroup, xgroups)
  3505. badpath = self.chdir_workingdir(conf) # some dirs need setuid before
  3506. if badpath:
  3507. logg.error("(%s): bad workingdir: '%s'", shell_cmd(cmd), badpath)
  3508. sys.exit(1)
  3509. env = self.extend_exec_env(env)
  3510. env.update(envs) # set $HOME to ~$USER
  3511. try:
  3512. if EXEC_SPAWN:
  3513. cmd_args = [arg for arg in cmd] # satisfy mypy
  3514. exitcode = os.spawnvpe(os.P_WAIT, cmd[0], cmd_args, env)
  3515. sys.exit(exitcode)
  3516. else: # pragma: no cover
  3517. os.execve(cmd[0], cmd, env)
  3518. sys.exit(11) # pragma: no cover (can not be reached / bug like mypy#8401)
  3519. except Exception as e:
  3520. logg.error("(%s): %s", shell_cmd(cmd), e)
  3521. sys.exit(1)
  3522. def test_start_unit(self, unit):
  3523. """ helper function to test the code that is normally forked off """
  3524. conf = self.load_unit_conf(unit)
  3525. if not conf: return None
  3526. env = self.get_env(conf)
  3527. for cmd in conf.getlist(Service, "ExecStart", []):
  3528. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3529. self.execve_from(conf, newcmd, env)
  3530. return None
  3531. def stop_modules(self, *modules):
  3532. """ [UNIT]... -- stop these units """
  3533. found_all = True
  3534. units = []
  3535. for module in modules:
  3536. matched = self.match_units(to_list(module))
  3537. if not matched:
  3538. logg.error("Unit %s not found.", unit_of(module))
  3539. self.error |= NOT_FOUND
  3540. found_all = False
  3541. continue
  3542. for unit in matched:
  3543. if unit not in units:
  3544. units += [unit]
  3545. return self.stop_units(units) and found_all
  3546. def stop_units(self, units):
  3547. """ fails if any unit fails to stop """
  3548. self.wait_system()
  3549. done = True
  3550. for unit in self.sortedBefore(units):
  3551. if not self.stop_unit(unit):
  3552. done = False
  3553. return done
  3554. def stop_unit(self, unit):
  3555. conf = self.load_unit_conf(unit)
  3556. if conf is None:
  3557. logg.error("Unit %s not found.", unit)
  3558. return False
  3559. if self.not_user_conf(conf):
  3560. logg.error("Unit %s not for --user mode", unit)
  3561. return False
  3562. return self.stop_unit_from(conf)
  3563. def get_TimeoutStopSec(self, conf):
  3564. timeout = conf.get(Service, "TimeoutSec", strE(DefaultTimeoutStartSec))
  3565. timeout = conf.get(Service, "TimeoutStopSec", timeout)
  3566. return time_to_seconds(timeout, DefaultMaximumTimeout)
  3567. def stop_unit_from(self, conf):
  3568. if not conf: return False
  3569. if self.syntax_check(conf) > 100: return False
  3570. with waitlock(conf):
  3571. logg.info(" stop unit %s => %s", conf.name(), strQ(conf.filename()))
  3572. return self.do_stop_unit_from(conf)
  3573. def do_stop_unit_from(self, conf):
  3574. if conf.name().endswith(".service"):
  3575. return self.do_stop_service_from(conf)
  3576. elif conf.name().endswith(".socket"):
  3577. return self.do_stop_socket_from(conf)
  3578. elif conf.name().endswith(".target"):
  3579. return self.do_stop_target_from(conf)
  3580. else:
  3581. logg.error("stop not implemented for unit type: %s", conf.name())
  3582. return False
  3583. def do_stop_service_from(self, conf):
  3584. # |
  3585. timeout = self.get_TimeoutStopSec(conf)
  3586. runs = conf.get(Service, "Type", "simple").lower()
  3587. env = self.get_env(conf)
  3588. if not self._quiet:
  3589. okee = self.exec_check_unit(conf, env, Service, "ExecStop")
  3590. if not okee and _no_reload: return False
  3591. service_directories = self.env_service_directories(conf)
  3592. env.update(service_directories)
  3593. returncode = 0
  3594. service_result = "success"
  3595. if runs in ["oneshot"]:
  3596. status_file = self.get_status_file_from(conf)
  3597. if self.get_status_from(conf, "ActiveState", "unknown") == "inactive":
  3598. logg.warning("the service is already down once")
  3599. return True
  3600. for cmd in conf.getlist(Service, "ExecStop", []):
  3601. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3602. logg.info("%s stop %s", runs, shell_cmd(newcmd))
  3603. forkpid = os.fork()
  3604. if not forkpid:
  3605. self.execve_from(conf, newcmd, env) # pragma: no cover
  3606. run = subprocess_waitpid(forkpid)
  3607. if run.returncode and exe.check:
  3608. returncode = run.returncode
  3609. service_result = "failed"
  3610. break
  3611. if True:
  3612. if returncode:
  3613. self.set_status_from(conf, "ExecStopCode", strE(returncode))
  3614. self.write_status_from(conf, AS="failed")
  3615. else:
  3616. self.clean_status_from(conf) # "inactive"
  3617. # fallback Stop => Kill for ["simple","notify","forking"]
  3618. elif not conf.getlist(Service, "ExecStop", []):
  3619. logg.info("no ExecStop => systemctl kill")
  3620. if True:
  3621. self.do_kill_unit_from(conf)
  3622. self.clean_pid_file_from(conf)
  3623. self.clean_status_from(conf) # "inactive"
  3624. elif runs in ["simple", "exec", "notify", "idle"]:
  3625. status_file = self.get_status_file_from(conf)
  3626. size = os.path.exists(status_file) and os.path.getsize(status_file)
  3627. logg.info("STATUS %s %s", status_file, size)
  3628. pid = 0
  3629. for cmd in conf.getlist(Service, "ExecStop", []):
  3630. env["MAINPID"] = strE(self.read_mainpid_from(conf))
  3631. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3632. logg.info("%s stop %s", runs, shell_cmd(newcmd))
  3633. forkpid = os.fork()
  3634. if not forkpid:
  3635. self.execve_from(conf, newcmd, env) # pragma: no cover
  3636. run = subprocess_waitpid(forkpid)
  3637. run = must_have_failed(run, newcmd) # TODO: a workaround
  3638. # self.write_status_from(conf, MainPID=run.pid) # no ExecStop
  3639. if run.returncode and exe.check:
  3640. returncode = run.returncode
  3641. service_result = "failed"
  3642. break
  3643. pid = to_intN(env.get("MAINPID"))
  3644. if pid:
  3645. if self.wait_vanished_pid(pid, timeout):
  3646. self.clean_pid_file_from(conf)
  3647. self.clean_status_from(conf) # "inactive"
  3648. else:
  3649. logg.info("%s sleep as no PID was found on Stop", runs)
  3650. time.sleep(MinimumTimeoutStopSec)
  3651. pid = self.read_mainpid_from(conf)
  3652. if not pid or not pid_exists(pid) or pid_zombie(pid):
  3653. self.clean_pid_file_from(conf)
  3654. self.clean_status_from(conf) # "inactive"
  3655. elif runs in ["forking"]:
  3656. status_file = self.get_status_file_from(conf)
  3657. pid_file = self.pid_file_from(conf)
  3658. for cmd in conf.getlist(Service, "ExecStop", []):
  3659. # active = self.is_active_from(conf)
  3660. if pid_file:
  3661. new_pid = self.read_mainpid_from(conf)
  3662. if new_pid:
  3663. env["MAINPID"] = strE(new_pid)
  3664. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3665. logg.info("fork stop %s", shell_cmd(newcmd))
  3666. forkpid = os.fork()
  3667. if not forkpid:
  3668. self.execve_from(conf, newcmd, env) # pragma: no cover
  3669. run = subprocess_waitpid(forkpid)
  3670. if run.returncode and exe.check:
  3671. returncode = run.returncode
  3672. service_result = "failed"
  3673. break
  3674. pid = to_intN(env.get("MAINPID"))
  3675. if pid:
  3676. if self.wait_vanished_pid(pid, timeout):
  3677. self.clean_pid_file_from(conf)
  3678. else:
  3679. logg.info("%s sleep as no PID was found on Stop", runs)
  3680. time.sleep(MinimumTimeoutStopSec)
  3681. pid = self.read_mainpid_from(conf)
  3682. if not pid or not pid_exists(pid) or pid_zombie(pid):
  3683. self.clean_pid_file_from(conf)
  3684. if returncode:
  3685. if os.path.isfile(status_file):
  3686. self.set_status_from(conf, "ExecStopCode", strE(returncode))
  3687. self.write_status_from(conf, AS="failed")
  3688. else:
  3689. self.clean_status_from(conf) # "inactive"
  3690. else:
  3691. logg.error("unsupported run type '%s'", runs)
  3692. return False
  3693. # POST sequence
  3694. if not self.is_active_from(conf):
  3695. env["SERVICE_RESULT"] = service_result
  3696. for cmd in conf.getlist(Service, "ExecStopPost", []):
  3697. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3698. logg.info("post-stop %s", shell_cmd(newcmd))
  3699. forkpid = os.fork()
  3700. if not forkpid:
  3701. self.execve_from(conf, newcmd, env) # pragma: no cover
  3702. run = subprocess_waitpid(forkpid)
  3703. logg.debug("post-stop done (%s) <-%s>",
  3704. run.returncode or "OK", run.signal or "")
  3705. if self._only_what[0] not in ["none", "keep"]:
  3706. self.remove_service_directories(conf)
  3707. return service_result == "success"
  3708. def do_stop_socket_from(self, conf):
  3709. runs = "socket"
  3710. timeout = self.get_SocketTimeoutSec(conf)
  3711. accept = conf.getbool(Socket, "Accept", "no")
  3712. service_unit = self.get_socket_service_from(conf)
  3713. service_conf = self.load_unit_conf(service_unit)
  3714. if service_conf is None:
  3715. logg.debug("unit could not be loaded (%s)", service_unit)
  3716. logg.error("Unit %s not found.", service_unit)
  3717. return False
  3718. env = self.get_env(conf)
  3719. if not self._quiet:
  3720. okee = self.exec_check_unit(conf, env, Socket, "ExecStop")
  3721. if not okee and _no_reload: return False
  3722. if not accept:
  3723. # we do not listen but have the service started right away
  3724. done = self.do_stop_service_from(service_conf)
  3725. service_result = done and "success" or "failed"
  3726. else:
  3727. done = self.do_stop_service_from(service_conf)
  3728. service_result = done and "success" or "failed"
  3729. # service_directories = self.env_service_directories(conf)
  3730. # env.update(service_directories)
  3731. # POST sequence
  3732. if not self.is_active_from(conf):
  3733. env["SERVICE_RESULT"] = service_result
  3734. for cmd in conf.getlist(Socket, "ExecStopPost", []):
  3735. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3736. logg.info("post-stop %s", shell_cmd(newcmd))
  3737. forkpid = os.fork()
  3738. if not forkpid:
  3739. self.execve_from(conf, newcmd, env) # pragma: no cover
  3740. run = subprocess_waitpid(forkpid)
  3741. logg.debug("post-stop done (%s) <-%s>",
  3742. run.returncode or "OK", run.signal or "")
  3743. return service_result == "success"
  3744. def wait_vanished_pid(self, pid, timeout):
  3745. if not pid:
  3746. return True
  3747. if not self.is_active_pid(pid):
  3748. return True
  3749. logg.info("wait for PID %s to vanish (%ss)", pid, timeout)
  3750. for x in xrange(int(timeout)):
  3751. time.sleep(1) # until TimeoutStopSec
  3752. if not self.is_active_pid(pid):
  3753. logg.info("wait for PID %s is done (%s.)", pid, x)
  3754. return True
  3755. logg.info("wait for PID %s failed (%s.)", pid, timeout)
  3756. return False
  3757. def reload_modules(self, *modules):
  3758. """ [UNIT]... -- reload these units """
  3759. self.wait_system()
  3760. found_all = True
  3761. units = []
  3762. for module in modules:
  3763. matched = self.match_units(to_list(module))
  3764. if not matched:
  3765. logg.error("Unit %s not found.", unit_of(module))
  3766. self.error |= NOT_FOUND
  3767. found_all = False
  3768. continue
  3769. for unit in matched:
  3770. if unit not in units:
  3771. units += [unit]
  3772. return self.reload_units(units) and found_all
  3773. def reload_units(self, units):
  3774. """ fails if any unit fails to reload """
  3775. self.wait_system()
  3776. done = True
  3777. for unit in self.sortedAfter(units):
  3778. if not self.reload_unit(unit):
  3779. done = False
  3780. return done
  3781. def reload_unit(self, unit):
  3782. conf = self.load_unit_conf(unit)
  3783. if conf is None:
  3784. logg.error("Unit %s not found.", unit)
  3785. return False
  3786. if self.not_user_conf(conf):
  3787. logg.error("Unit %s not for --user mode", unit)
  3788. return False
  3789. return self.reload_unit_from(conf)
  3790. def reload_unit_from(self, conf):
  3791. if not conf: return False
  3792. if self.syntax_check(conf) > 100: return False
  3793. with waitlock(conf):
  3794. logg.info(" reload unit %s => %s", conf.name(), strQ(conf.filename()))
  3795. return self.do_reload_unit_from(conf)
  3796. def do_reload_unit_from(self, conf):
  3797. if conf.name().endswith(".service"):
  3798. return self.do_reload_service_from(conf)
  3799. elif conf.name().endswith(".socket"):
  3800. service_unit = self.get_socket_service_from(conf)
  3801. service_conf = self.load_unit_conf(service_unit)
  3802. if service_conf:
  3803. return self.do_reload_service_from(service_conf)
  3804. else:
  3805. logg.error("no %s found for unit type: %s", service_unit, conf.name())
  3806. return False
  3807. elif conf.name().endswith(".target"):
  3808. return self.do_reload_target_from(conf)
  3809. else:
  3810. logg.error("reload not implemented for unit type: %s", conf.name())
  3811. return False
  3812. def do_reload_service_from(self, conf):
  3813. runs = conf.get(Service, "Type", "simple").lower()
  3814. env = self.get_env(conf)
  3815. if not self._quiet:
  3816. okee = self.exec_check_unit(conf, env, Service, "ExecReload")
  3817. if not okee and _no_reload: return False
  3818. initscript = conf.filename()
  3819. if self.is_sysv_file(initscript):
  3820. status_file = self.get_status_file_from(conf)
  3821. if initscript:
  3822. newcmd = [initscript, "reload"]
  3823. env["SYSTEMCTL_SKIP_REDIRECT"] = "yes"
  3824. logg.info("%s reload %s", runs, shell_cmd(newcmd))
  3825. forkpid = os.fork()
  3826. if not forkpid:
  3827. self.execve_from(conf, newcmd, env) # pragma: nocover
  3828. run = subprocess_waitpid(forkpid)
  3829. self.set_status_from(conf, "ExecReloadCode", run.returncode)
  3830. if run.returncode:
  3831. self.write_status_from(conf, AS="failed")
  3832. return False
  3833. else:
  3834. self.write_status_from(conf, AS="active")
  3835. return True
  3836. service_directories = self.env_service_directories(conf)
  3837. env.update(service_directories)
  3838. if runs in ["simple", "exec", "notify", "forking", "idle"]:
  3839. if not self.is_active_from(conf):
  3840. logg.info("no reload on inactive service %s", conf.name())
  3841. return True
  3842. for cmd in conf.getlist(Service, "ExecReload", []):
  3843. env["MAINPID"] = strE(self.read_mainpid_from(conf))
  3844. exe, newcmd = self.exec_newcmd(cmd, env, conf)
  3845. logg.info("%s reload %s", runs, shell_cmd(newcmd))
  3846. forkpid = os.fork()
  3847. if not forkpid:
  3848. self.execve_from(conf, newcmd, env) # pragma: no cover
  3849. run = subprocess_waitpid(forkpid)
  3850. if run.returncode and exe.check:
  3851. logg.error("Job for %s failed because the control process exited with error code. (%s)",
  3852. conf.name(), run.returncode)
  3853. return False
  3854. time.sleep(MinimumYield)
  3855. return True
  3856. elif runs in ["oneshot"]:
  3857. logg.debug("ignored run type '%s' for reload", runs)
  3858. return True
  3859. else:
  3860. logg.error("unsupported run type '%s'", runs)
  3861. return False
  3862. def restart_modules(self, *modules):
  3863. """ [UNIT]... -- restart these units """
  3864. found_all = True
  3865. units = []
  3866. for module in modules:
  3867. matched = self.match_units(to_list(module))
  3868. if not matched:
  3869. logg.error("Unit %s not found.", unit_of(module))
  3870. self.error |= NOT_FOUND
  3871. found_all = False
  3872. continue
  3873. for unit in matched:
  3874. if unit not in units:
  3875. units += [unit]
  3876. return self.restart_units(units) and found_all
  3877. def restart_units(self, units):
  3878. """ fails if any unit fails to restart """
  3879. self.wait_system()
  3880. done = True
  3881. for unit in self.sortedAfter(units):
  3882. if not self.restart_unit(unit):
  3883. done = False
  3884. return done
  3885. def restart_unit(self, unit):
  3886. conf = self.load_unit_conf(unit)
  3887. if conf is None:
  3888. logg.error("Unit %s not found.", unit)
  3889. return False
  3890. if self.not_user_conf(conf):
  3891. logg.error("Unit %s not for --user mode", unit)
  3892. return False
  3893. return self.restart_unit_from(conf)
  3894. def restart_unit_from(self, conf):
  3895. if not conf: return False
  3896. if self.syntax_check(conf) > 100: return False
  3897. with waitlock(conf):
  3898. if conf.name().endswith(".service"):
  3899. logg.info(" restart service %s => %s", conf.name(), strQ(conf.filename()))
  3900. if not self.is_active_from(conf):
  3901. return self.do_start_unit_from(conf)
  3902. else:
  3903. return self.do_restart_unit_from(conf)
  3904. else:
  3905. return self.do_restart_unit_from(conf)
  3906. def do_restart_unit_from(self, conf):
  3907. logg.info("(restart) => stop/start %s", conf.name())
  3908. self.do_stop_unit_from(conf)
  3909. return self.do_start_unit_from(conf)
  3910. def try_restart_modules(self, *modules):
  3911. """ [UNIT]... -- try-restart these units """
  3912. found_all = True
  3913. units = []
  3914. for module in modules:
  3915. matched = self.match_units(to_list(module))
  3916. if not matched:
  3917. logg.error("Unit %s not found.", unit_of(module))
  3918. self.error |= NOT_FOUND
  3919. found_all = False
  3920. continue
  3921. for unit in matched:
  3922. if unit not in units:
  3923. units += [unit]
  3924. return self.try_restart_units(units) and found_all
  3925. def try_restart_units(self, units):
  3926. """ fails if any module fails to try-restart """
  3927. self.wait_system()
  3928. done = True
  3929. for unit in self.sortedAfter(units):
  3930. if not self.try_restart_unit(unit):
  3931. done = False
  3932. return done
  3933. def try_restart_unit(self, unit):
  3934. """ only do 'restart' if 'active' """
  3935. conf = self.load_unit_conf(unit)
  3936. if conf is None:
  3937. logg.error("Unit %s not found.", unit)
  3938. return False
  3939. if self.not_user_conf(conf):
  3940. logg.error("Unit %s not for --user mode", unit)
  3941. return False
  3942. with waitlock(conf):
  3943. logg.info(" try-restart unit %s => %s", conf.name(), strQ(conf.filename()))
  3944. if self.is_active_from(conf):
  3945. return self.do_restart_unit_from(conf)
  3946. return True
  3947. def reload_or_restart_modules(self, *modules):
  3948. """ [UNIT]... -- reload-or-restart these units """
  3949. found_all = True
  3950. units = []
  3951. for module in modules:
  3952. matched = self.match_units(to_list(module))
  3953. if not matched:
  3954. logg.error("Unit %s not found.", unit_of(module))
  3955. self.error |= NOT_FOUND
  3956. found_all = False
  3957. continue
  3958. for unit in matched:
  3959. if unit not in units:
  3960. units += [unit]
  3961. return self.reload_or_restart_units(units) and found_all
  3962. def reload_or_restart_units(self, units):
  3963. """ fails if any unit does not reload-or-restart """
  3964. self.wait_system()
  3965. done = True
  3966. for unit in self.sortedAfter(units):
  3967. if not self.reload_or_restart_unit(unit):
  3968. done = False
  3969. return done
  3970. def reload_or_restart_unit(self, unit):
  3971. """ do 'reload' if specified, otherwise do 'restart' """
  3972. conf = self.load_unit_conf(unit)
  3973. if conf is None:
  3974. logg.error("Unit %s not found.", unit)
  3975. return False
  3976. if self.not_user_conf(conf):
  3977. logg.error("Unit %s not for --user mode", unit)
  3978. return False
  3979. return self.reload_or_restart_unit_from(conf)
  3980. def reload_or_restart_unit_from(self, conf):
  3981. """ do 'reload' if specified, otherwise do 'restart' """
  3982. if not conf: return False
  3983. with waitlock(conf):
  3984. logg.info(" reload-or-restart unit %s => %s", conf.name(), strQ(conf.filename()))
  3985. return self.do_reload_or_restart_unit_from(conf)
  3986. def do_reload_or_restart_unit_from(self, conf):
  3987. if not self.is_active_from(conf):
  3988. # try: self.stop_unit_from(conf)
  3989. # except Exception as e: pass
  3990. return self.do_start_unit_from(conf)
  3991. elif conf.getlist(Service, "ExecReload", []):
  3992. logg.info("found service to have ExecReload -> 'reload'")
  3993. return self.do_reload_unit_from(conf)
  3994. else:
  3995. logg.info("found service without ExecReload -> 'restart'")
  3996. return self.do_restart_unit_from(conf)
  3997. def reload_or_try_restart_modules(self, *modules):
  3998. """ [UNIT]... -- reload-or-try-restart these units """
  3999. found_all = True
  4000. units = []
  4001. for module in modules:
  4002. matched = self.match_units(to_list(module))
  4003. if not matched:
  4004. logg.error("Unit %s not found.", unit_of(module))
  4005. self.error |= NOT_FOUND
  4006. found_all = False
  4007. continue
  4008. for unit in matched:
  4009. if unit not in units:
  4010. units += [unit]
  4011. return self.reload_or_try_restart_units(units) and found_all
  4012. def reload_or_try_restart_units(self, units):
  4013. """ fails if any unit fails to reload-or-try-restart """
  4014. self.wait_system()
  4015. done = True
  4016. for unit in self.sortedAfter(units):
  4017. if not self.reload_or_try_restart_unit(unit):
  4018. done = False
  4019. return done
  4020. def reload_or_try_restart_unit(self, unit):
  4021. conf = self.load_unit_conf(unit)
  4022. if conf is None:
  4023. logg.error("Unit %s not found.", unit)
  4024. return False
  4025. if self.not_user_conf(conf):
  4026. logg.error("Unit %s not for --user mode", unit)
  4027. return False
  4028. return self.reload_or_try_restart_unit_from(conf)
  4029. def reload_or_try_restart_unit_from(self, conf):
  4030. with waitlock(conf):
  4031. logg.info(" reload-or-try-restart unit %s => %s", conf.name(), strQ(conf.filename()))
  4032. return self.do_reload_or_try_restart_unit_from(conf)
  4033. def do_reload_or_try_restart_unit_from(self, conf):
  4034. if conf.getlist(Service, "ExecReload", []):
  4035. return self.do_reload_unit_from(conf)
  4036. elif not self.is_active_from(conf):
  4037. return True
  4038. else:
  4039. return self.do_restart_unit_from(conf)
  4040. def kill_modules(self, *modules):
  4041. """ [UNIT]... -- kill these units """
  4042. found_all = True
  4043. units = []
  4044. for module in modules:
  4045. matched = self.match_units(to_list(module))
  4046. if not matched:
  4047. logg.error("Unit %s not found.", unit_of(module))
  4048. # self.error |= NOT_FOUND
  4049. found_all = False
  4050. continue
  4051. for unit in matched:
  4052. if unit not in units:
  4053. units += [unit]
  4054. return self.kill_units(units) and found_all
  4055. def kill_units(self, units):
  4056. """ fails if any unit could not be killed """
  4057. self.wait_system()
  4058. done = True
  4059. for unit in self.sortedBefore(units):
  4060. if not self.kill_unit(unit):
  4061. done = False
  4062. return done
  4063. def kill_unit(self, unit):
  4064. conf = self.load_unit_conf(unit)
  4065. if conf is None:
  4066. logg.error("Unit %s not found.", unit)
  4067. return False
  4068. if self.not_user_conf(conf):
  4069. logg.error("Unit %s not for --user mode", unit)
  4070. return False
  4071. return self.kill_unit_from(conf)
  4072. def kill_unit_from(self, conf):
  4073. if not conf: return False
  4074. with waitlock(conf):
  4075. logg.info(" kill unit %s => %s", conf.name(), strQ(conf.filename()))
  4076. return self.do_kill_unit_from(conf)
  4077. def do_kill_unit_from(self, conf):
  4078. started = time.time()
  4079. doSendSIGKILL = self.get_SendSIGKILL(conf)
  4080. doSendSIGHUP = self.get_SendSIGHUP(conf)
  4081. useKillMode = self.get_KillMode(conf)
  4082. useKillSignal = self.get_KillSignal(conf)
  4083. kill_signal = getattr(signal, useKillSignal)
  4084. timeout = self.get_TimeoutStopSec(conf)
  4085. status_file = self.get_status_file_from(conf)
  4086. size = os.path.exists(status_file) and os.path.getsize(status_file)
  4087. logg.info("STATUS %s %s", status_file, size)
  4088. mainpid = self.read_mainpid_from(conf)
  4089. self.clean_status_from(conf) # clear RemainAfterExit and TimeoutStartSec
  4090. if not mainpid:
  4091. if useKillMode in ["control-group"]:
  4092. logg.warning("no main PID %s", strQ(conf.filename()))
  4093. logg.warning("and there is no control-group here")
  4094. else:
  4095. logg.info("no main PID %s", strQ(conf.filename()))
  4096. return False
  4097. if not pid_exists(mainpid) or pid_zombie(mainpid):
  4098. logg.debug("ignoring children when mainpid is already dead")
  4099. # because we list child processes, not processes in control-group
  4100. return True
  4101. pidlist = self.pidlist_of(mainpid) # here
  4102. if pid_exists(mainpid):
  4103. logg.info("stop kill PID %s", mainpid)
  4104. self._kill_pid(mainpid, kill_signal)
  4105. if useKillMode in ["control-group"]:
  4106. if len(pidlist) > 1:
  4107. logg.info("stop control-group PIDs %s", pidlist)
  4108. for pid in pidlist:
  4109. if pid != mainpid:
  4110. self._kill_pid(pid, kill_signal)
  4111. if doSendSIGHUP:
  4112. logg.info("stop SendSIGHUP to PIDs %s", pidlist)
  4113. for pid in pidlist:
  4114. self._kill_pid(pid, signal.SIGHUP)
  4115. # wait for the processes to have exited
  4116. while True:
  4117. dead = True
  4118. for pid in pidlist:
  4119. if pid_exists(pid) and not pid_zombie(pid):
  4120. dead = False
  4121. break
  4122. if dead:
  4123. break
  4124. if time.time() > started + timeout:
  4125. logg.info("service PIDs not stopped after %s", timeout)
  4126. break
  4127. time.sleep(1) # until TimeoutStopSec
  4128. if dead or not doSendSIGKILL:
  4129. logg.info("done kill PID %s %s", mainpid, dead and "OK")
  4130. return dead
  4131. if useKillMode in ["control-group", "mixed"]:
  4132. logg.info("hard kill PIDs %s", pidlist)
  4133. for pid in pidlist:
  4134. if pid != mainpid:
  4135. self._kill_pid(pid, signal.SIGKILL)
  4136. time.sleep(MinimumYield)
  4137. # useKillMode in [ "control-group", "mixed", "process" ]
  4138. if pid_exists(mainpid):
  4139. logg.info("hard kill PID %s", mainpid)
  4140. self._kill_pid(mainpid, signal.SIGKILL)
  4141. time.sleep(MinimumYield)
  4142. dead = not pid_exists(mainpid) or pid_zombie(mainpid)
  4143. logg.info("done hard kill PID %s %s", mainpid, dead and "OK")
  4144. return dead
  4145. def _kill_pid(self, pid, kill_signal = None):
  4146. try:
  4147. sig = kill_signal or signal.SIGTERM
  4148. os.kill(pid, sig)
  4149. except OSError as e:
  4150. if e.errno == errno.ESRCH or e.errno == errno.ENOENT:
  4151. logg.debug("kill PID %s => No such process", pid)
  4152. return True
  4153. else:
  4154. logg.error("kill PID %s => %s", pid, str(e))
  4155. return False
  4156. return not pid_exists(pid) or pid_zombie(pid)
  4157. def is_active_modules(self, *modules):
  4158. """ [UNIT].. -- check if these units are in active state
  4159. implements True if all is-active = True """
  4160. # systemctl returns multiple lines, one for each argument
  4161. # "active" when is_active
  4162. # "inactive" when not is_active
  4163. # "unknown" when not enabled
  4164. # The return code is set to
  4165. # 0 when "active"
  4166. # 1 when unit is not found
  4167. # 3 when any "inactive" or "unknown"
  4168. # However: # TODO! BUG in original systemctl!
  4169. # documentation says " exit code 0 if at least one is active"
  4170. # and "Unless --quiet is specified, print the unit state"
  4171. # |
  4172. units = []
  4173. results = []
  4174. for module in modules:
  4175. units = self.match_units(to_list(module))
  4176. if not units:
  4177. logg.error("Unit %s not found.", unit_of(module))
  4178. # self.error |= NOT_FOUND
  4179. self.error |= NOT_ACTIVE
  4180. results += ["inactive"]
  4181. continue
  4182. for unit in units:
  4183. active = self.get_active_unit(unit)
  4184. enabled = self.enabled_unit(unit)
  4185. if enabled != "enabled" and ACTIVE_IF_ENABLED:
  4186. active = "inactive" # "unknown"
  4187. results += [active]
  4188. break
  4189. # how it should work:
  4190. status = "active" in results
  4191. # how 'systemctl' works:
  4192. non_active = [result for result in results if result != "active"]
  4193. if non_active:
  4194. self.error |= NOT_ACTIVE
  4195. if non_active:
  4196. self.error |= NOT_OK # status
  4197. if _quiet:
  4198. return []
  4199. return results
  4200. def is_active_from(self, conf):
  4201. """ used in try-restart/other commands to check if needed. """
  4202. if not conf: return False
  4203. return self.get_active_from(conf) == "active"
  4204. def active_pid_from(self, conf):
  4205. if not conf: return False
  4206. pid = self.read_mainpid_from(conf)
  4207. return self.is_active_pid(pid)
  4208. def is_active_pid(self, pid):
  4209. """ returns pid if the pid is still an active process """
  4210. if pid and pid_exists(pid) and not pid_zombie(pid):
  4211. return pid # usually a string (not null)
  4212. return None
  4213. def get_active_unit(self, unit):
  4214. """ returns 'active' 'inactive' 'failed' 'unknown' """
  4215. conf = self.load_unit_conf(unit)
  4216. if not conf:
  4217. logg.warning("Unit %s not found.", unit)
  4218. return "unknown"
  4219. else:
  4220. return self.get_active_from(conf)
  4221. def get_active_from(self, conf):
  4222. if conf.name().endswith(".service"):
  4223. return self.get_active_service_from(conf)
  4224. elif conf.name().endswith(".socket"):
  4225. service_unit = self.get_socket_service_from(conf)
  4226. service_conf = self.load_unit_conf(service_unit)
  4227. return self.get_active_service_from(service_conf)
  4228. elif conf.name().endswith(".target"):
  4229. return self.get_active_target_from(conf)
  4230. else:
  4231. logg.debug("is-active not implemented for unit type: %s", conf.name())
  4232. return "unknown" # TODO: "inactive" ?
  4233. def get_active_service_from(self, conf):
  4234. """ returns 'active' 'inactive' 'failed' 'unknown' """
  4235. # used in try-restart/other commands to check if needed.
  4236. if not conf: return "unknown"
  4237. pid_file = self.pid_file_from(conf)
  4238. if pid_file: # application PIDFile
  4239. if not os.path.exists(pid_file):
  4240. return "inactive"
  4241. status_file = self.get_status_file_from(conf)
  4242. if self.getsize(status_file):
  4243. state = self.get_status_from(conf, "ActiveState", "")
  4244. if state:
  4245. if DEBUG_STATUS:
  4246. logg.info("get_status_from %s => %s", conf.name(), state)
  4247. return state
  4248. pid = self.read_mainpid_from(conf)
  4249. if DEBUG_STATUS:
  4250. logg.debug("pid_file '%s' => PID %s", pid_file or status_file, strE(pid))
  4251. if pid:
  4252. if not pid_exists(pid) or pid_zombie(pid):
  4253. return "failed"
  4254. return "active"
  4255. else:
  4256. return "inactive"
  4257. def get_active_target_from(self, conf):
  4258. """ returns 'active' 'inactive' 'failed' 'unknown' """
  4259. return self.get_active_target(conf.name())
  4260. def get_active_target(self, target):
  4261. """ returns 'active' 'inactive' 'failed' 'unknown' """
  4262. if target in self.get_active_target_list():
  4263. status = self.is_system_running()
  4264. if status in ["running"]:
  4265. return "active"
  4266. return "inactive"
  4267. else:
  4268. services = self.target_default_services(target)
  4269. result = "active"
  4270. for service in services:
  4271. conf = self.load_unit_conf(service)
  4272. if conf:
  4273. state = self.get_active_from(conf)
  4274. if state in ["failed"]:
  4275. result = state
  4276. elif state not in ["active"]:
  4277. result = state
  4278. return result
  4279. def get_active_target_list(self):
  4280. current_target = self.get_default_target()
  4281. target_list = self.get_target_list(current_target)
  4282. target_list += [DefaultUnit] # upper end
  4283. target_list += [SysInitTarget] # lower end
  4284. return target_list
  4285. def get_substate_from(self, conf):
  4286. """ returns 'running' 'exited' 'dead' 'failed' 'plugged' 'mounted' """
  4287. if not conf: return None
  4288. pid_file = self.pid_file_from(conf)
  4289. if pid_file:
  4290. if not os.path.exists(pid_file):
  4291. return "dead"
  4292. status_file = self.get_status_file_from(conf)
  4293. if self.getsize(status_file):
  4294. state = self.get_status_from(conf, "ActiveState", "")
  4295. if state:
  4296. if state in ["active"]:
  4297. return self.get_status_from(conf, "SubState", "running")
  4298. else:
  4299. return self.get_status_from(conf, "SubState", "dead")
  4300. pid = self.read_mainpid_from(conf)
  4301. if DEBUG_STATUS:
  4302. logg.debug("pid_file '%s' => PID %s", pid_file or status_file, strE(pid))
  4303. if pid:
  4304. if not pid_exists(pid) or pid_zombie(pid):
  4305. return "failed"
  4306. return "running"
  4307. else:
  4308. return "dead"
  4309. def is_failed_modules(self, *modules):
  4310. """ [UNIT]... -- check if these units are in failes state
  4311. implements True if any is-active = True """
  4312. units = []
  4313. results = []
  4314. for module in modules:
  4315. units = self.match_units(to_list(module))
  4316. if not units:
  4317. logg.error("Unit %s not found.", unit_of(module))
  4318. # self.error |= NOT_FOUND
  4319. results += ["inactive"]
  4320. continue
  4321. for unit in units:
  4322. active = self.get_active_unit(unit)
  4323. enabled = self.enabled_unit(unit)
  4324. if enabled != "enabled" and ACTIVE_IF_ENABLED:
  4325. active = "inactive"
  4326. results += [active]
  4327. break
  4328. if "failed" in results:
  4329. self.error = 0
  4330. else:
  4331. self.error |= NOT_OK
  4332. if _quiet:
  4333. return []
  4334. return results
  4335. def is_failed_from(self, conf):
  4336. if conf is None: return True
  4337. return self.get_active_from(conf) == "failed"
  4338. def reset_failed_modules(self, *modules):
  4339. """ [UNIT]... -- Reset failed state for all, one, or more units """
  4340. units = []
  4341. status = True
  4342. for module in modules:
  4343. units = self.match_units(to_list(module))
  4344. if not units:
  4345. logg.error("Unit %s not found.", unit_of(module))
  4346. # self.error |= NOT_FOUND
  4347. return False
  4348. for unit in units:
  4349. if not self.reset_failed_unit(unit):
  4350. logg.error("Unit %s could not be reset.", unit_of(module))
  4351. status = False
  4352. break
  4353. return status
  4354. def reset_failed_unit(self, unit):
  4355. conf = self.load_unit_conf(unit)
  4356. if not conf:
  4357. logg.warning("Unit %s not found.", unit)
  4358. return False
  4359. if self.not_user_conf(conf):
  4360. logg.error("Unit %s not for --user mode", unit)
  4361. return False
  4362. return self.reset_failed_from(conf)
  4363. def reset_failed_from(self, conf):
  4364. if conf is None: return True
  4365. if not self.is_failed_from(conf): return False
  4366. done = False
  4367. status_file = self.get_status_file_from(conf)
  4368. if status_file and os.path.exists(status_file):
  4369. try:
  4370. os.remove(status_file)
  4371. done = True
  4372. logg.debug("done rm %s", status_file)
  4373. except Exception as e:
  4374. logg.error("while rm %s: %s", status_file, e)
  4375. pid_file = self.pid_file_from(conf)
  4376. if pid_file and os.path.exists(pid_file):
  4377. try:
  4378. os.remove(pid_file)
  4379. done = True
  4380. logg.debug("done rm %s", pid_file)
  4381. except Exception as e:
  4382. logg.error("while rm %s: %s", pid_file, e)
  4383. return done
  4384. def status_modules(self, *modules):
  4385. """ [UNIT]... check the status of these units.
  4386. """
  4387. found_all = True
  4388. units = []
  4389. for module in modules:
  4390. matched = self.match_units(to_list(module))
  4391. if not matched:
  4392. logg.error("Unit %s could not be found.", unit_of(module))
  4393. self.error |= NOT_FOUND
  4394. found_all = False
  4395. continue
  4396. for unit in matched:
  4397. if unit not in units:
  4398. units += [unit]
  4399. result = self.status_units(units)
  4400. # if not found_all:
  4401. # self.error |= NOT_OK | NOT_ACTIVE # 3
  4402. # # same as (dead) # original behaviour
  4403. return result
  4404. def status_units(self, units):
  4405. """ concatenates the status output of all units
  4406. and the last non-successful statuscode """
  4407. status = 0
  4408. result = ""
  4409. for unit in units:
  4410. status1, result1 = self.status_unit(unit)
  4411. if status1: status = status1
  4412. if result: result += "\n\n"
  4413. result += result1
  4414. if status:
  4415. self.error |= NOT_OK | NOT_ACTIVE # 3
  4416. return result
  4417. def status_unit(self, unit):
  4418. conf = self.get_unit_conf(unit)
  4419. result = "%s - %s" % (unit, self.get_description_from(conf))
  4420. loaded = conf.loaded()
  4421. if loaded:
  4422. filename = str(conf.filename())
  4423. enabled = self.enabled_from(conf)
  4424. result += "\n Loaded: {loaded} ({filename}, {enabled})".format(**locals())
  4425. for path in conf.overrides():
  4426. result += "\n Drop-In: {path}".format(**locals())
  4427. else:
  4428. result += "\n Loaded: failed"
  4429. return 3, result
  4430. active = self.get_active_from(conf)
  4431. substate = self.get_substate_from(conf)
  4432. result += "\n Active: {} ({})".format(active, substate)
  4433. if active == "active":
  4434. return 0, result
  4435. else:
  4436. return 3, result
  4437. def cat_modules(self, *modules):
  4438. """ [UNIT]... show the *.system file for these"
  4439. """
  4440. found_all = True
  4441. units = []
  4442. for module in modules:
  4443. matched = self.match_units(to_list(module))
  4444. if not matched:
  4445. logg.error("Unit %s could not be found.", unit_of(module))
  4446. # self.error |= NOT_FOUND
  4447. found_all = False
  4448. continue
  4449. for unit in matched:
  4450. if unit not in units:
  4451. units += [unit]
  4452. result = self.cat_units(units)
  4453. if not found_all:
  4454. self.error |= NOT_OK
  4455. return result
  4456. def cat_units(self, units):
  4457. done = True
  4458. result = ""
  4459. for unit in units:
  4460. text = self.cat_unit(unit)
  4461. if not text:
  4462. done = False
  4463. else:
  4464. if result:
  4465. result += "\n\n"
  4466. result += text
  4467. if not done:
  4468. self.error = NOT_OK
  4469. return result
  4470. def cat_unit(self, unit):
  4471. try:
  4472. unit_file = self.unit_file(unit)
  4473. if unit_file:
  4474. return open(unit_file).read()
  4475. logg.error("No files found for %s", unit)
  4476. except Exception as e:
  4477. print("Unit {} is not-loaded: {}".format(unit, e))
  4478. self.error |= NOT_OK
  4479. return None
  4480. ##
  4481. ##
  4482. def load_preset_files(self, module = None): # -> [ preset-file-names,... ]
  4483. """ reads all preset files, returns the scanned files """
  4484. if self._preset_file_list is None:
  4485. self._preset_file_list = {}
  4486. assert self._preset_file_list is not None
  4487. for folder in self.preset_folders():
  4488. if not folder:
  4489. continue
  4490. if self._root:
  4491. folder = os_path(self._root, folder)
  4492. if not os.path.isdir(folder):
  4493. continue
  4494. for name in os.listdir(folder):
  4495. if not name.endswith(".preset"):
  4496. continue
  4497. if name not in self._preset_file_list:
  4498. path = os.path.join(folder, name)
  4499. if os.path.isdir(path):
  4500. continue
  4501. preset = PresetFile().read(path)
  4502. self._preset_file_list[name] = preset
  4503. logg.debug("found %s preset files", len(self._preset_file_list))
  4504. return sorted(self._preset_file_list.keys())
  4505. def get_preset_of_unit(self, unit):
  4506. """ [UNIT] check the *.preset of this unit
  4507. """
  4508. self.load_preset_files()
  4509. assert self._preset_file_list is not None
  4510. for filename in sorted(self._preset_file_list.keys()):
  4511. preset = self._preset_file_list[filename]
  4512. status = preset.get_preset(unit)
  4513. if status:
  4514. return status
  4515. return None
  4516. def preset_modules(self, *modules):
  4517. """ [UNIT]... -- set 'enabled' when in *.preset
  4518. """
  4519. if self.user_mode():
  4520. logg.warning("preset makes no sense in --user mode")
  4521. return True
  4522. found_all = True
  4523. units = []
  4524. for module in modules:
  4525. matched = self.match_units(to_list(module))
  4526. if not matched:
  4527. logg.error("Unit %s could not be found.", unit_of(module))
  4528. found_all = False
  4529. continue
  4530. for unit in matched:
  4531. if unit not in units:
  4532. units += [unit]
  4533. return self.preset_units(units) and found_all
  4534. def preset_units(self, units):
  4535. """ fails if any unit could not be changed """
  4536. self.wait_system()
  4537. fails = 0
  4538. found = 0
  4539. for unit in units:
  4540. status = self.get_preset_of_unit(unit)
  4541. if not status: continue
  4542. found += 1
  4543. if status.startswith("enable"):
  4544. if self._preset_mode == "disable": continue
  4545. logg.info("preset enable %s", unit)
  4546. if not self.enable_unit(unit):
  4547. logg.warning("failed to enable %s", unit)
  4548. fails += 1
  4549. if status.startswith("disable"):
  4550. if self._preset_mode == "enable": continue
  4551. logg.info("preset disable %s", unit)
  4552. if not self.disable_unit(unit):
  4553. logg.warning("failed to disable %s", unit)
  4554. fails += 1
  4555. return not fails and not not found
  4556. def preset_all_modules(self, *modules):
  4557. """ 'preset' all services
  4558. enable or disable services according to *.preset files
  4559. """
  4560. if self.user_mode():
  4561. logg.warning("preset-all makes no sense in --user mode")
  4562. return True
  4563. found_all = True
  4564. units = self.match_units() # TODO: how to handle module arguments
  4565. return self.preset_units(units) and found_all
  4566. def wanted_from(self, conf, default = None):
  4567. if not conf: return default
  4568. return conf.get(Install, "WantedBy", default, True)
  4569. def enablefolders(self, wanted):
  4570. if self.user_mode():
  4571. for folder in self.user_folders():
  4572. yield self.default_enablefolder(wanted, folder)
  4573. if True:
  4574. for folder in self.system_folders():
  4575. yield self.default_enablefolder(wanted, folder)
  4576. def enablefolder(self, wanted):
  4577. if self.user_mode():
  4578. user_folder = self.user_folder()
  4579. return self.default_enablefolder(wanted, user_folder)
  4580. else:
  4581. return self.default_enablefolder(wanted)
  4582. def default_enablefolder(self, wanted, basefolder = None):
  4583. basefolder = basefolder or self.system_folder()
  4584. if not wanted:
  4585. return wanted
  4586. if not wanted.endswith(".wants"):
  4587. wanted = wanted + ".wants"
  4588. return os.path.join(basefolder, wanted)
  4589. def enable_modules(self, *modules):
  4590. """ [UNIT]... -- enable these units """
  4591. found_all = True
  4592. units = []
  4593. for module in modules:
  4594. matched = self.match_units(to_list(module))
  4595. if not matched:
  4596. logg.error("Unit %s not found.", unit_of(module))
  4597. # self.error |= NOT_FOUND
  4598. found_all = False
  4599. continue
  4600. for unit in matched:
  4601. logg.info("matched %s", unit) # ++
  4602. if unit not in units:
  4603. units += [unit]
  4604. return self.enable_units(units) and found_all
  4605. def enable_units(self, units):
  4606. self.wait_system()
  4607. done = True
  4608. for unit in units:
  4609. if not self.enable_unit(unit):
  4610. done = False
  4611. elif self._now:
  4612. self.start_unit(unit)
  4613. return done
  4614. def enable_unit(self, unit):
  4615. conf = self.load_unit_conf(unit)
  4616. if conf is None:
  4617. logg.error("Unit %s not found.", unit)
  4618. return False
  4619. unit_file = conf.filename()
  4620. if unit_file is None:
  4621. logg.error("Unit file %s not found.", unit)
  4622. return False
  4623. if self.is_sysv_file(unit_file):
  4624. if self.user_mode():
  4625. logg.error("Initscript %s not for --user mode", unit)
  4626. return False
  4627. return self.enable_unit_sysv(unit_file)
  4628. if self.not_user_conf(conf):
  4629. logg.error("Unit %s not for --user mode", unit)
  4630. return False
  4631. return self.enable_unit_from(conf)
  4632. def enable_unit_from(self, conf):
  4633. wanted = self.wanted_from(conf)
  4634. if not wanted and not self._force:
  4635. logg.debug("%s has no target", conf.name())
  4636. return False # "static" is-enabled
  4637. target = wanted or self.get_default_target()
  4638. folder = self.enablefolder(target)
  4639. if self._root:
  4640. folder = os_path(self._root, folder)
  4641. if not os.path.isdir(folder):
  4642. os.makedirs(folder)
  4643. source = conf.filename()
  4644. if not source: # pragma: no cover (was checked before)
  4645. logg.debug("%s has no real file", conf.name())
  4646. return False
  4647. symlink = os.path.join(folder, conf.name())
  4648. if True:
  4649. _f = self._force and "-f" or ""
  4650. logg.info("ln -s {_f} '{source}' '{symlink}'".format(**locals()))
  4651. if self._force and os.path.islink(symlink):
  4652. os.remove(target)
  4653. if not os.path.islink(symlink):
  4654. os.symlink(source, symlink)
  4655. return True
  4656. def rc3_root_folder(self):
  4657. old_folder = os_path(self._root, _rc3_boot_folder)
  4658. new_folder = os_path(self._root, _rc3_init_folder)
  4659. if os.path.isdir(old_folder): # pragma: no cover
  4660. return old_folder
  4661. return new_folder
  4662. def rc5_root_folder(self):
  4663. old_folder = os_path(self._root, _rc5_boot_folder)
  4664. new_folder = os_path(self._root, _rc5_init_folder)
  4665. if os.path.isdir(old_folder): # pragma: no cover
  4666. return old_folder
  4667. return new_folder
  4668. def enable_unit_sysv(self, unit_file):
  4669. # a "multi-user.target"/rc3 is also started in /rc5
  4670. rc3 = self._enable_unit_sysv(unit_file, self.rc3_root_folder())
  4671. rc5 = self._enable_unit_sysv(unit_file, self.rc5_root_folder())
  4672. return rc3 and rc5
  4673. def _enable_unit_sysv(self, unit_file, rc_folder):
  4674. name = os.path.basename(unit_file)
  4675. nameS = "S50"+name
  4676. nameK = "K50"+name
  4677. if not os.path.isdir(rc_folder):
  4678. os.makedirs(rc_folder)
  4679. # do not double existing entries
  4680. for found in os.listdir(rc_folder):
  4681. m = re.match(r"S\d\d(.*)", found)
  4682. if m and m.group(1) == name:
  4683. nameS = found
  4684. m = re.match(r"K\d\d(.*)", found)
  4685. if m and m.group(1) == name:
  4686. nameK = found
  4687. target = os.path.join(rc_folder, nameS)
  4688. if not os.path.exists(target):
  4689. os.symlink(unit_file, target)
  4690. target = os.path.join(rc_folder, nameK)
  4691. if not os.path.exists(target):
  4692. os.symlink(unit_file, target)
  4693. return True
  4694. def disable_modules(self, *modules):
  4695. """ [UNIT]... -- disable these units """
  4696. found_all = True
  4697. units = []
  4698. for module in modules:
  4699. matched = self.match_units(to_list(module))
  4700. if not matched:
  4701. logg.error("Unit %s not found.", unit_of(module))
  4702. # self.error |= NOT_FOUND
  4703. found_all = False
  4704. continue
  4705. for unit in matched:
  4706. if unit not in units:
  4707. units += [unit]
  4708. return self.disable_units(units) and found_all
  4709. def disable_units(self, units):
  4710. self.wait_system()
  4711. done = True
  4712. for unit in units:
  4713. if not self.disable_unit(unit):
  4714. done = False
  4715. elif self._now:
  4716. self.stop_unit(unit)
  4717. return done
  4718. def disable_unit(self, unit):
  4719. conf = self.load_unit_conf(unit)
  4720. if conf is None:
  4721. logg.error("Unit %s not found.", unit)
  4722. return False
  4723. unit_file = conf.filename()
  4724. if unit_file is None:
  4725. logg.error("Unit file %s not found.", unit)
  4726. return False
  4727. if self.is_sysv_file(unit_file):
  4728. if self.user_mode():
  4729. logg.error("Initscript %s not for --user mode", unit)
  4730. return False
  4731. return self.disable_unit_sysv(unit_file)
  4732. if self.not_user_conf(conf):
  4733. logg.error("Unit %s not for --user mode", unit)
  4734. return False
  4735. return self.disable_unit_from(conf)
  4736. def disable_unit_from(self, conf):
  4737. wanted = self.wanted_from(conf)
  4738. if not wanted and not self._force:
  4739. logg.debug("%s has no target", conf.name())
  4740. return False # "static" is-enabled
  4741. target = wanted or self.get_default_target()
  4742. for folder in self.enablefolders(target):
  4743. if self._root:
  4744. folder = os_path(self._root, folder)
  4745. symlink = os.path.join(folder, conf.name())
  4746. if os.path.exists(symlink):
  4747. try:
  4748. _f = self._force and "-f" or ""
  4749. logg.info("rm {_f} '{symlink}'".format(**locals()))
  4750. if os.path.islink(symlink) or self._force:
  4751. os.remove(symlink)
  4752. except IOError as e:
  4753. logg.error("disable %s: %s", symlink, e)
  4754. except OSError as e:
  4755. logg.error("disable %s: %s", symlink, e)
  4756. return True
  4757. def disable_unit_sysv(self, unit_file):
  4758. rc3 = self._disable_unit_sysv(unit_file, self.rc3_root_folder())
  4759. rc5 = self._disable_unit_sysv(unit_file, self.rc5_root_folder())
  4760. return rc3 and rc5
  4761. def _disable_unit_sysv(self, unit_file, rc_folder):
  4762. # a "multi-user.target"/rc3 is also started in /rc5
  4763. name = os.path.basename(unit_file)
  4764. nameS = "S50"+name
  4765. nameK = "K50"+name
  4766. # do not forget the existing entries
  4767. for found in os.listdir(rc_folder):
  4768. m = re.match(r"S\d\d(.*)", found)
  4769. if m and m.group(1) == name:
  4770. nameS = found
  4771. m = re.match(r"K\d\d(.*)", found)
  4772. if m and m.group(1) == name:
  4773. nameK = found
  4774. target = os.path.join(rc_folder, nameS)
  4775. if os.path.exists(target):
  4776. os.unlink(target)
  4777. target = os.path.join(rc_folder, nameK)
  4778. if os.path.exists(target):
  4779. os.unlink(target)
  4780. return True
  4781. def is_enabled_sysv(self, unit_file):
  4782. name = os.path.basename(unit_file)
  4783. target = os.path.join(self.rc3_root_folder(), "S50%s" % name)
  4784. if os.path.exists(target):
  4785. return True
  4786. return False
  4787. def is_enabled_modules(self, *modules):
  4788. """ [UNIT]... -- check if these units are enabled
  4789. returns True if any of them is enabled."""
  4790. found_all = True
  4791. units = []
  4792. for module in modules:
  4793. matched = self.match_units(to_list(module))
  4794. if not matched:
  4795. logg.error("Unit %s not found.", unit_of(module))
  4796. # self.error |= NOT_FOUND
  4797. found_all = False
  4798. continue
  4799. for unit in matched:
  4800. if unit not in units:
  4801. units += [unit]
  4802. return self.is_enabled_units(units) # and found_all
  4803. def is_enabled_units(self, units):
  4804. """ true if any is enabled, and a list of infos """
  4805. result = False
  4806. infos = []
  4807. for unit in units:
  4808. infos += [self.enabled_unit(unit)]
  4809. if self.is_enabled(unit):
  4810. result = True
  4811. if not result:
  4812. self.error |= NOT_OK
  4813. return infos
  4814. def is_enabled(self, unit):
  4815. conf = self.load_unit_conf(unit)
  4816. if conf is None:
  4817. logg.error("Unit %s not found.", unit)
  4818. return False
  4819. unit_file = conf.filename()
  4820. if not unit_file:
  4821. logg.error("Unit %s not found.", unit)
  4822. return False
  4823. if self.is_sysv_file(unit_file):
  4824. return self.is_enabled_sysv(unit_file)
  4825. state = self.get_enabled_from(conf)
  4826. if state in ["enabled", "static"]:
  4827. return True
  4828. return False # ["disabled", "masked"]
  4829. def enabled_unit(self, unit):
  4830. conf = self.get_unit_conf(unit)
  4831. return self.enabled_from(conf)
  4832. def enabled_from(self, conf):
  4833. unit_file = strE(conf.filename())
  4834. if self.is_sysv_file(unit_file):
  4835. state = self.is_enabled_sysv(unit_file)
  4836. if state:
  4837. return "enabled"
  4838. return "disabled"
  4839. return self.get_enabled_from(conf)
  4840. def get_enabled_from(self, conf):
  4841. if conf.masked:
  4842. return "masked"
  4843. wanted = self.wanted_from(conf)
  4844. target = wanted or self.get_default_target()
  4845. for folder in self.enablefolders(target):
  4846. if self._root:
  4847. folder = os_path(self._root, folder)
  4848. target = os.path.join(folder, conf.name())
  4849. if os.path.isfile(target):
  4850. return "enabled"
  4851. if not wanted:
  4852. return "static"
  4853. return "disabled"
  4854. def mask_modules(self, *modules):
  4855. """ [UNIT]... -- mask non-startable units """
  4856. found_all = True
  4857. units = []
  4858. for module in modules:
  4859. matched = self.match_units(to_list(module))
  4860. if not matched:
  4861. logg.error("Unit %s not found.", unit_of(module))
  4862. self.error |= NOT_FOUND
  4863. found_all = False
  4864. continue
  4865. for unit in matched:
  4866. if unit not in units:
  4867. units += [unit]
  4868. return self.mask_units(units) and found_all
  4869. def mask_units(self, units):
  4870. self.wait_system()
  4871. done = True
  4872. for unit in units:
  4873. if not self.mask_unit(unit):
  4874. done = False
  4875. return done
  4876. def mask_unit(self, unit):
  4877. unit_file = self.unit_file(unit)
  4878. if not unit_file:
  4879. logg.error("Unit %s not found.", unit)
  4880. return False
  4881. if self.is_sysv_file(unit_file):
  4882. logg.error("Initscript %s can not be masked", unit)
  4883. return False
  4884. conf = self.get_unit_conf(unit)
  4885. if self.not_user_conf(conf):
  4886. logg.error("Unit %s not for --user mode", unit)
  4887. return False
  4888. folder = self.mask_folder()
  4889. if self._root:
  4890. folder = os_path(self._root, folder)
  4891. if not os.path.isdir(folder):
  4892. os.makedirs(folder)
  4893. target = os.path.join(folder, os.path.basename(unit_file))
  4894. dev_null = _dev_null
  4895. if True:
  4896. _f = self._force and "-f" or ""
  4897. logg.debug("ln -s {_f} {dev_null} '{target}'".format(**locals()))
  4898. if self._force and os.path.islink(target):
  4899. os.remove(target)
  4900. if not os.path.exists(target):
  4901. os.symlink(dev_null, target)
  4902. logg.info("Created symlink {target} -> {dev_null}".format(**locals()))
  4903. return True
  4904. elif os.path.islink(target):
  4905. logg.debug("mask symlink does already exist: %s", target)
  4906. return True
  4907. else:
  4908. logg.error("mask target does already exist: %s", target)
  4909. return False
  4910. def mask_folder(self):
  4911. for folder in self.mask_folders():
  4912. if folder: return folder
  4913. raise Exception("did not find any systemd/system folder")
  4914. def mask_folders(self):
  4915. if self.user_mode():
  4916. for folder in self.user_folders():
  4917. yield folder
  4918. if True:
  4919. for folder in self.system_folders():
  4920. yield folder
  4921. def unmask_modules(self, *modules):
  4922. """ [UNIT]... -- unmask non-startable units """
  4923. found_all = True
  4924. units = []
  4925. for module in modules:
  4926. matched = self.match_units(to_list(module))
  4927. if not matched:
  4928. logg.error("Unit %s not found.", unit_of(module))
  4929. self.error |= NOT_FOUND
  4930. found_all = False
  4931. continue
  4932. for unit in matched:
  4933. if unit not in units:
  4934. units += [unit]
  4935. return self.unmask_units(units) and found_all
  4936. def unmask_units(self, units):
  4937. self.wait_system()
  4938. done = True
  4939. for unit in units:
  4940. if not self.unmask_unit(unit):
  4941. done = False
  4942. return done
  4943. def unmask_unit(self, unit):
  4944. unit_file = self.unit_file(unit)
  4945. if not unit_file:
  4946. logg.error("Unit %s not found.", unit)
  4947. return False
  4948. if self.is_sysv_file(unit_file):
  4949. logg.error("Initscript %s can not be un/masked", unit)
  4950. return False
  4951. conf = self.get_unit_conf(unit)
  4952. if self.not_user_conf(conf):
  4953. logg.error("Unit %s not for --user mode", unit)
  4954. return False
  4955. folder = self.mask_folder()
  4956. if self._root:
  4957. folder = os_path(self._root, folder)
  4958. target = os.path.join(folder, os.path.basename(unit_file))
  4959. if True:
  4960. _f = self._force and "-f" or ""
  4961. logg.info("rm {_f} '{target}'".format(**locals()))
  4962. if os.path.islink(target):
  4963. os.remove(target)
  4964. return True
  4965. elif not os.path.exists(target):
  4966. logg.debug("Symlink did not exist anymore: %s", target)
  4967. return True
  4968. else:
  4969. logg.warning("target is not a symlink: %s", target)
  4970. return True
  4971. def list_dependencies_modules(self, *modules):
  4972. """ [UNIT]... show the dependency tree"
  4973. """
  4974. found_all = True
  4975. units = []
  4976. for module in modules:
  4977. matched = self.match_units(to_list(module))
  4978. if not matched:
  4979. logg.error("Unit %s could not be found.", unit_of(module))
  4980. found_all = False
  4981. continue
  4982. for unit in matched:
  4983. if unit not in units:
  4984. units += [unit]
  4985. return self.list_dependencies_units(units) # and found_all
  4986. def list_dependencies_units(self, units):
  4987. result = []
  4988. for unit in units:
  4989. if result:
  4990. result += ["", ""]
  4991. result += self.list_dependencies_unit(unit)
  4992. return result
  4993. def list_dependencies_unit(self, unit):
  4994. result = []
  4995. for line in self.list_dependencies(unit, ""):
  4996. result += [line]
  4997. return result
  4998. def list_dependencies(self, unit, indent = None, mark = None, loop = []):
  4999. mapping = {}
  5000. mapping["Requires"] = "required to start"
  5001. mapping["Wants"] = "wanted to start"
  5002. mapping["Requisite"] = "required started"
  5003. mapping["Bindsto"] = "binds to start"
  5004. mapping["PartOf"] = "part of started"
  5005. mapping[".requires"] = ".required to start"
  5006. mapping[".wants"] = ".wanted to start"
  5007. mapping["PropagateReloadTo"] = "(to be reloaded as well)"
  5008. mapping["Conflicts"] = "(to be stopped on conflict)"
  5009. restrict = ["Requires", "Requisite", "ConsistsOf", "Wants",
  5010. "BindsTo", ".requires", ".wants"]
  5011. indent = indent or ""
  5012. mark = mark or ""
  5013. deps = self.get_dependencies_unit(unit)
  5014. conf = self.get_unit_conf(unit)
  5015. if not conf.loaded():
  5016. if not self._show_all:
  5017. return
  5018. yield "%s(%s): %s" % (indent, unit, mark)
  5019. else:
  5020. yield "%s%s: %s" % (indent, unit, mark)
  5021. for stop_recursion in ["Conflict", "conflict", "reloaded", "Propagate"]:
  5022. if stop_recursion in mark:
  5023. return
  5024. for dep in deps:
  5025. if dep in loop:
  5026. logg.debug("detected loop at %s", dep)
  5027. continue
  5028. new_loop = loop + list(deps.keys())
  5029. new_indent = indent + "| "
  5030. new_mark = deps[dep]
  5031. if not self._show_all:
  5032. if new_mark not in restrict:
  5033. continue
  5034. if new_mark in mapping:
  5035. new_mark = mapping[new_mark]
  5036. restrict = ["Requires", "Wants", "Requisite", "BindsTo", "PartOf", "ConsistsOf",
  5037. ".requires", ".wants"]
  5038. for line in self.list_dependencies(dep, new_indent, new_mark, new_loop):
  5039. yield line
  5040. def get_dependencies_unit(self, unit, styles = None):
  5041. styles = styles or ["Requires", "Wants", "Requisite", "BindsTo", "PartOf", "ConsistsOf",
  5042. ".requires", ".wants", "PropagateReloadTo", "Conflicts", ]
  5043. conf = self.get_unit_conf(unit)
  5044. deps = {}
  5045. for style in styles:
  5046. if style.startswith("."):
  5047. for folder in self.sysd_folders():
  5048. if not folder:
  5049. continue
  5050. require_path = os.path.join(folder, unit + style)
  5051. if self._root:
  5052. require_path = os_path(self._root, require_path)
  5053. if os.path.isdir(require_path):
  5054. for required in os.listdir(require_path):
  5055. if required not in deps:
  5056. deps[required] = style
  5057. else:
  5058. for requirelist in conf.getlist(Unit, style, []):
  5059. for required in requirelist.strip().split(" "):
  5060. deps[required.strip()] = style
  5061. return deps
  5062. def get_required_dependencies(self, unit, styles = None):
  5063. styles = styles or ["Requires", "Wants", "Requisite", "BindsTo",
  5064. ".requires", ".wants"]
  5065. return self.get_dependencies_unit(unit, styles)
  5066. def get_start_dependencies(self, unit, styles = None): # pragma: no cover
  5067. """ the list of services to be started as well / TODO: unused """
  5068. styles = styles or ["Requires", "Wants", "Requisite", "BindsTo", "PartOf", "ConsistsOf",
  5069. ".requires", ".wants"]
  5070. deps = {}
  5071. unit_deps = self.get_dependencies_unit(unit)
  5072. for dep_unit, dep_style in unit_deps.items():
  5073. if dep_style in styles:
  5074. if dep_unit in deps:
  5075. if dep_style not in deps[dep_unit]:
  5076. deps[dep_unit].append(dep_style)
  5077. else:
  5078. deps[dep_unit] = [dep_style]
  5079. next_deps = self.get_start_dependencies(dep_unit)
  5080. for dep, styles in next_deps.items():
  5081. for style in styles:
  5082. if dep in deps:
  5083. if style not in deps[dep]:
  5084. deps[dep].append(style)
  5085. else:
  5086. deps[dep] = [style]
  5087. return deps
  5088. def list_start_dependencies_modules(self, *modules):
  5089. """ [UNIT]... show the dependency tree (experimental)"
  5090. """
  5091. return self.list_start_dependencies_units(list(modules))
  5092. def list_start_dependencies_units(self, units):
  5093. unit_order = []
  5094. deps = {}
  5095. for unit in units:
  5096. unit_order.append(unit)
  5097. # unit_deps = self.get_start_dependencies(unit) # TODO
  5098. unit_deps = self.get_dependencies_unit(unit)
  5099. for dep_unit, styles in unit_deps.items():
  5100. dep_styles = to_list(styles)
  5101. for dep_style in dep_styles:
  5102. if dep_unit in deps:
  5103. if dep_style not in deps[dep_unit]:
  5104. deps[dep_unit].append(dep_style)
  5105. else:
  5106. deps[dep_unit] = [dep_style]
  5107. deps_conf = []
  5108. for dep in deps:
  5109. if dep in unit_order:
  5110. continue
  5111. conf = self.get_unit_conf(dep)
  5112. if conf.loaded():
  5113. deps_conf.append(conf)
  5114. for unit in unit_order:
  5115. deps[unit] = ["Requested"]
  5116. conf = self.get_unit_conf(unit)
  5117. if conf.loaded():
  5118. deps_conf.append(conf)
  5119. result = []
  5120. sortlist = conf_sortedAfter(deps_conf, cmp=compareAfter)
  5121. for item in sortlist:
  5122. line = (item.name(), "(%s)" % (" ".join(deps[item.name()])))
  5123. result.append(line)
  5124. return result
  5125. def sortedAfter(self, unitlist):
  5126. """ get correct start order for the unit list (ignoring masked units) """
  5127. conflist = [self.get_unit_conf(unit) for unit in unitlist]
  5128. if True:
  5129. conflist = []
  5130. for unit in unitlist:
  5131. conf = self.get_unit_conf(unit)
  5132. if conf.masked:
  5133. logg.debug("ignoring masked unit %s", unit)
  5134. continue
  5135. conflist.append(conf)
  5136. sortlist = conf_sortedAfter(conflist)
  5137. return [item.name() for item in sortlist]
  5138. def sortedBefore(self, unitlist):
  5139. """ get correct start order for the unit list (ignoring masked units) """
  5140. conflist = [self.get_unit_conf(unit) for unit in unitlist]
  5141. if True:
  5142. conflist = []
  5143. for unit in unitlist:
  5144. conf = self.get_unit_conf(unit)
  5145. if conf.masked:
  5146. logg.debug("ignoring masked unit %s", unit)
  5147. continue
  5148. conflist.append(conf)
  5149. sortlist = conf_sortedAfter(reversed(conflist))
  5150. return [item.name() for item in reversed(sortlist)]
  5151. def daemon_reload_target(self):
  5152. """ reload does will only check the service files here.
  5153. The returncode will tell the number of warnings,
  5154. and it is over 100 if it can not continue even
  5155. for the relaxed systemctl.py style of execution. """
  5156. errors = 0
  5157. for unit in self.match_units():
  5158. try:
  5159. conf = self.get_unit_conf(unit)
  5160. except Exception as e:
  5161. logg.error("%s: can not read unit file %s\n\t%s",
  5162. unit, strQ(conf.filename()), e)
  5163. continue
  5164. errors += self.syntax_check(conf)
  5165. if errors:
  5166. logg.warning(" (%s) found %s problems", errors, errors % 100)
  5167. return True # errors
  5168. def syntax_check(self, conf):
  5169. filename = conf.filename()
  5170. if filename and filename.endswith(".service"):
  5171. return self.syntax_check_service(conf)
  5172. return 0
  5173. def syntax_check_service(self, conf, section = Service):
  5174. unit = conf.name()
  5175. if not conf.data.has_section(Service):
  5176. logg.error(" %s: a .service file without [Service] section", unit)
  5177. return 101
  5178. errors = 0
  5179. haveType = conf.get(section, "Type", "simple")
  5180. haveExecStart = conf.getlist(section, "ExecStart", [])
  5181. haveExecStop = conf.getlist(section, "ExecStop", [])
  5182. haveExecReload = conf.getlist(section, "ExecReload", [])
  5183. usedExecStart = []
  5184. usedExecStop = []
  5185. usedExecReload = []
  5186. if haveType not in ["simple", "exec", "forking", "notify", "oneshot", "dbus", "idle"]:
  5187. logg.error(" %s: Failed to parse service type, ignoring: %s", unit, haveType)
  5188. errors += 100
  5189. for line in haveExecStart:
  5190. mode, exe = exec_path(line)
  5191. if not exe.startswith("/"):
  5192. if mode.check:
  5193. logg.error(" %s: %s Executable path is not absolute.", unit, section)
  5194. else:
  5195. logg.warning("%s: %s Executable path is not absolute.", unit, section)
  5196. logg.info("%s: %s exe = %s", unit, section, exe)
  5197. errors += 1
  5198. usedExecStart.append(line)
  5199. for line in haveExecStop:
  5200. mode, exe = exec_path(line)
  5201. if not exe.startswith("/"):
  5202. if mode.check:
  5203. logg.error(" %s: %s Executable path is not absolute.", unit, section)
  5204. else:
  5205. logg.warning("%s: %s Executable path is not absolute.", unit, section)
  5206. logg.info("%s: %s exe = %s", unit, section, exe)
  5207. errors += 1
  5208. usedExecStop.append(line)
  5209. for line in haveExecReload:
  5210. mode, exe = exec_path(line)
  5211. if not exe.startswith("/"):
  5212. if mode.check:
  5213. logg.error(" %s: %s Executable path is not absolute.", unit, section)
  5214. else:
  5215. logg.warning("%s: %s Executable path is not absolute.", unit, section)
  5216. logg.info("%s: %s exe = %s", unit, section, exe)
  5217. errors += 1
  5218. usedExecReload.append(line)
  5219. if haveType in ["simple", "exec", "notify", "forking", "idle"]:
  5220. if not usedExecStart and not usedExecStop:
  5221. logg.error(" %s: %s lacks both ExecStart and ExecStop= setting. Refusing.", unit, section)
  5222. errors += 101
  5223. elif not usedExecStart and haveType != "oneshot":
  5224. logg.error(" %s: %s has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.", unit, section)
  5225. errors += 101
  5226. if len(usedExecStart) > 1 and haveType != "oneshot":
  5227. logg.error(" %s: there may be only one %s ExecStart statement (unless for 'oneshot' services)."
  5228. + "\n\t\t\tYou can use ExecStartPre / ExecStartPost to add additional commands.", unit, section)
  5229. errors += 1
  5230. if len(usedExecStop) > 1 and haveType != "oneshot":
  5231. logg.info(" %s: there should be only one %s ExecStop statement (unless for 'oneshot' services)."
  5232. + "\n\t\t\tYou can use ExecStopPost to add additional commands (also executed on failed Start)", unit, section)
  5233. if len(usedExecReload) > 1:
  5234. logg.info(" %s: there should be only one %s ExecReload statement."
  5235. + "\n\t\t\tUse ' ; ' for multiple commands (ExecReloadPost or ExedReloadPre do not exist)", unit, section)
  5236. if len(usedExecReload) > 0 and "/bin/kill " in usedExecReload[0]:
  5237. logg.warning(" %s: the use of /bin/kill is not recommended for %s ExecReload as it is asynchronous."
  5238. + "\n\t\t\tThat means all the dependencies will perform the reload simultaneously / out of order.", unit, section)
  5239. if conf.getlist(Service, "ExecRestart", []): # pragma: no cover
  5240. logg.error(" %s: there no such thing as an %s ExecRestart (ignored)", unit, section)
  5241. if conf.getlist(Service, "ExecRestartPre", []): # pragma: no cover
  5242. logg.error(" %s: there no such thing as an %s ExecRestartPre (ignored)", unit, section)
  5243. if conf.getlist(Service, "ExecRestartPost", []): # pragma: no cover
  5244. logg.error(" %s: there no such thing as an %s ExecRestartPost (ignored)", unit, section)
  5245. if conf.getlist(Service, "ExecReloadPre", []): # pragma: no cover
  5246. logg.error(" %s: there no such thing as an %s ExecReloadPre (ignored)", unit, section)
  5247. if conf.getlist(Service, "ExecReloadPost", []): # pragma: no cover
  5248. logg.error(" %s: there no such thing as an %s ExecReloadPost (ignored)", unit, section)
  5249. if conf.getlist(Service, "ExecStopPre", []): # pragma: no cover
  5250. logg.error(" %s: there no such thing as an %s ExecStopPre (ignored)", unit, section)
  5251. for env_file in conf.getlist(Service, "EnvironmentFile", []):
  5252. if env_file.startswith("-"): continue
  5253. if not os.path.isfile(os_path(self._root, self.expand_special(env_file, conf))):
  5254. logg.error(" %s: Failed to load environment files: %s", unit, env_file)
  5255. errors += 101
  5256. return errors
  5257. def exec_check_unit(self, conf, env, section = Service, exectype = ""):
  5258. if conf is None: # pragma: no cover (is never null)
  5259. return True
  5260. if not conf.data.has_section(section):
  5261. return True # pragma: no cover
  5262. haveType = conf.get(section, "Type", "simple")
  5263. if self.is_sysv_file(conf.filename()):
  5264. return True # we don't care about that
  5265. unit = conf.name()
  5266. abspath = 0
  5267. notexists = 0
  5268. badusers = 0
  5269. badgroups = 0
  5270. for execs in ["ExecStartPre", "ExecStart", "ExecStartPost", "ExecStop", "ExecStopPost", "ExecReload"]:
  5271. if not execs.startswith(exectype):
  5272. continue
  5273. for cmd in conf.getlist(section, execs, []):
  5274. mode, newcmd = self.exec_newcmd(cmd, env, conf)
  5275. if not newcmd:
  5276. continue
  5277. exe = newcmd[0]
  5278. if not exe:
  5279. continue
  5280. if exe[0] != "/":
  5281. logg.error(" %s: Exec is not an absolute path: %s=%s", unit, execs, cmd)
  5282. abspath += 1
  5283. if not os.path.isfile(exe):
  5284. logg.error(" %s: Exec command does not exist: (%s) %s", unit, execs, exe)
  5285. if mode.check:
  5286. notexists += 1
  5287. newexe1 = os.path.join("/usr/bin", exe)
  5288. newexe2 = os.path.join("/bin", exe)
  5289. if os.path.exists(newexe1):
  5290. logg.error(" %s: but this does exist: %s %s", unit, " " * len(execs), newexe1)
  5291. elif os.path.exists(newexe2):
  5292. logg.error(" %s: but this does exist: %s %s", unit, " " * len(execs), newexe2)
  5293. users = [conf.get(section, "User", ""), conf.get(section, "SocketUser", "")]
  5294. groups = [conf.get(section, "Group", ""), conf.get(section, "SocketGroup", "")] + conf.getlist(section, "SupplementaryGroups")
  5295. for user in users:
  5296. if user:
  5297. try: pwd.getpwnam(self.expand_special(user, conf))
  5298. except Exception as e:
  5299. logg.error(" %s: User does not exist: %s (%s)", unit, user, getattr(e, "__doc__", ""))
  5300. badusers += 1
  5301. for group in groups:
  5302. if group:
  5303. try: grp.getgrnam(self.expand_special(group, conf))
  5304. except Exception as e:
  5305. logg.error(" %s: Group does not exist: %s (%s)", unit, group, getattr(e, "__doc__", ""))
  5306. badgroups += 1
  5307. tmpproblems = 0
  5308. for setting in ("RootDirectory", "RootImage", "BindPaths", "BindReadOnlyPaths",
  5309. "ReadWritePaths", "ReadOnlyPaths", "TemporaryFileSystem"):
  5310. setting_value = conf.get(section, setting, "")
  5311. if setting_value:
  5312. logg.info("%s: %s private directory remounts ignored: %s=%s", unit, section, setting, setting_value)
  5313. tmpproblems += 1
  5314. for setting in ("PrivateTmp", "PrivateDevices", "PrivateNetwork", "PrivateUsers", "DynamicUser",
  5315. "ProtectSystem", "ProjectHome", "ProtectHostname", "PrivateMounts", "MountAPIVFS"):
  5316. setting_yes = conf.getbool(section, setting, "no")
  5317. if setting_yes:
  5318. logg.info("%s: %s private directory option is ignored: %s=yes", unit, section, setting)
  5319. tmpproblems += 1
  5320. if not abspath and not notexists and not badusers and not badgroups:
  5321. return True
  5322. if True:
  5323. filename = strE(conf.filename())
  5324. if len(filename) > 44: filename = o44(filename)
  5325. logg.error(" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  5326. if abspath:
  5327. logg.error(" The SystemD ExecXY commands must always be absolute paths by definition.")
  5328. time.sleep(1)
  5329. if notexists:
  5330. logg.error(" Oops, %s executable paths were not found in the current environment. Refusing.", notexists)
  5331. time.sleep(1)
  5332. if badusers or badgroups:
  5333. logg.error(" Oops, %s user names and %s group names were not found. Refusing.", badusers, badgroups)
  5334. time.sleep(1)
  5335. if tmpproblems:
  5336. logg.info(" Note, %s private directory settings are ignored. The application should not depend on it.", tmpproblems)
  5337. time.sleep(1)
  5338. logg.error(" !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  5339. return False
  5340. def show_modules(self, *modules):
  5341. """ [PATTERN]... -- Show properties of one or more units
  5342. Show properties of one or more units (or the manager itself).
  5343. If no argument is specified, properties of the manager will be
  5344. shown. If a unit name is specified, properties of the unit is
  5345. shown. By default, empty properties are suppressed. Use --all to
  5346. show those too. To select specific properties to show, use
  5347. --property=. This command is intended to be used whenever
  5348. computer-parsable output is required. Use status if you are looking
  5349. for formatted human-readable output.
  5350. /
  5351. NOTE: only a subset of properties is implemented """
  5352. notfound = []
  5353. units = []
  5354. found_all = True
  5355. for module in modules:
  5356. matched = self.match_units(to_list(module))
  5357. if not matched:
  5358. logg.error("Unit %s could not be found.", unit_of(module))
  5359. units += [module]
  5360. # self.error |= NOT_FOUND
  5361. found_all = False
  5362. continue
  5363. for unit in matched:
  5364. if unit not in units:
  5365. units += [unit]
  5366. return self.show_units(units) + notfound # and found_all
  5367. def show_units(self, units):
  5368. logg.debug("show --property=%s", ",".join(self._only_property))
  5369. result = []
  5370. for unit in units:
  5371. if result: result += [""]
  5372. for var, value in self.show_unit_items(unit):
  5373. if self._only_property:
  5374. if var not in self._only_property:
  5375. continue
  5376. else:
  5377. if not value and not self._show_all:
  5378. continue
  5379. result += ["%s=%s" % (var, value)]
  5380. return result
  5381. def show_unit_items(self, unit):
  5382. """ [UNIT]... -- show properties of a unit.
  5383. """
  5384. logg.info("try read unit %s", unit)
  5385. conf = self.get_unit_conf(unit)
  5386. for entry in self.each_unit_items(unit, conf):
  5387. yield entry
  5388. def each_unit_items(self, unit, conf):
  5389. loaded = conf.loaded()
  5390. if not loaded:
  5391. loaded = "not-loaded"
  5392. if "NOT-FOUND" in self.get_description_from(conf):
  5393. loaded = "not-found"
  5394. names = {unit: 1, conf.name(): 1}
  5395. yield "Id", conf.name()
  5396. yield "Names", " ".join(sorted(names.keys()))
  5397. yield "Description", self.get_description_from(conf) # conf.get(Unit, "Description")
  5398. yield "PIDFile", self.get_pid_file(conf) # not self.pid_file_from w/o default location
  5399. yield "PIDFilePath", self.pid_file_from(conf)
  5400. yield "MainPID", strE(self.active_pid_from(conf)) # status["MainPID"] or PIDFile-read
  5401. yield "SubState", self.get_substate_from(conf) or "unknown" # status["SubState"] or notify-result
  5402. yield "ActiveState", self.get_active_from(conf) or "unknown" # status["ActiveState"]
  5403. yield "LoadState", loaded
  5404. yield "UnitFileState", self.enabled_from(conf)
  5405. yield "StatusFile", self.get_StatusFile(conf)
  5406. yield "StatusFilePath", self.get_status_file_from(conf)
  5407. yield "JournalFile", self.get_journal_log(conf)
  5408. yield "JournalFilePath", self.get_journal_log_from(conf)
  5409. yield "NotifySocket", self.get_notify_socket_from(conf)
  5410. yield "User", self.get_User(conf) or ""
  5411. yield "Group", self.get_Group(conf) or ""
  5412. yield "SupplementaryGroups", " ".join(self.get_SupplementaryGroups(conf))
  5413. yield "TimeoutStartUSec", seconds_to_time(self.get_TimeoutStartSec(conf))
  5414. yield "TimeoutStopUSec", seconds_to_time(self.get_TimeoutStopSec(conf))
  5415. yield "NeedDaemonReload", "no"
  5416. yield "SendSIGKILL", strYes(self.get_SendSIGKILL(conf))
  5417. yield "SendSIGHUP", strYes(self.get_SendSIGHUP(conf))
  5418. yield "KillMode", strE(self.get_KillMode(conf))
  5419. yield "KillSignal", strE(self.get_KillSignal(conf))
  5420. yield "StartLimitBurst", strE(self.get_StartLimitBurst(conf))
  5421. yield "StartLimitIntervalSec", seconds_to_time(self.get_StartLimitIntervalSec(conf))
  5422. yield "RestartSec", seconds_to_time(self.get_RestartSec(conf))
  5423. yield "RemainAfterExit", strYes(self.get_RemainAfterExit(conf))
  5424. yield "WorkingDirectory", strE(self.get_WorkingDirectory(conf))
  5425. env_parts = []
  5426. for env_part in conf.getlist(Service, "Environment", []):
  5427. env_parts.append(self.expand_special(env_part, conf))
  5428. if env_parts:
  5429. yield "Environment", " ".join(env_parts)
  5430. env_files = []
  5431. for env_file in conf.getlist(Service, "EnvironmentFile", []):
  5432. env_files.append(self.expand_special(env_file, conf))
  5433. if env_files:
  5434. yield "EnvironmentFile", " ".join(env_files)
  5435. def get_SendSIGKILL(self, conf):
  5436. return conf.getbool(Service, "SendSIGKILL", "yes")
  5437. def get_SendSIGHUP(self, conf):
  5438. return conf.getbool(Service, "SendSIGHUP", "no")
  5439. def get_KillMode(self, conf):
  5440. return conf.get(Service, "KillMode", "control-group")
  5441. def get_KillSignal(self, conf):
  5442. return conf.get(Service, "KillSignal", "SIGTERM")
  5443. #
  5444. igno_centos = ["netconsole", "network"]
  5445. igno_opensuse = ["raw", "pppoe", "*.local", "boot.*", "rpmconf*", "postfix*"]
  5446. igno_ubuntu = ["mount*", "umount*", "ondemand", "*.local"]
  5447. igno_always = ["network*", "dbus*", "systemd-*", "kdump*", "kmod*"]
  5448. igno_always += ["purge-kernels.service", "after-local.service", "dm-event.*"] # as on opensuse
  5449. igno_targets = ["remote-fs.target"]
  5450. def _ignored_unit(self, unit, ignore_list):
  5451. for ignore in ignore_list:
  5452. if fnmatch.fnmatchcase(unit, ignore):
  5453. return True # ignore
  5454. if fnmatch.fnmatchcase(unit, ignore+".service"):
  5455. return True # ignore
  5456. return False
  5457. def default_services_modules(self, *modules):
  5458. """ show the default services
  5459. This is used internally to know the list of service to be started in the 'get-default'
  5460. target runlevel when the container is started through default initialisation. It will
  5461. ignore a number of services - use '--all' to show a longer list of services and
  5462. use '--all --force' if not even a minimal filter shall be used.
  5463. """
  5464. results = []
  5465. targets = modules or [self.get_default_target()]
  5466. for target in targets:
  5467. units = self.target_default_services(target)
  5468. logg.debug(" %s # %s", " ".join(units), target)
  5469. for unit in units:
  5470. if unit not in results:
  5471. results.append(unit)
  5472. return results
  5473. def target_default_services(self, target = None, sysv = "S"):
  5474. """ get the default services for a target - this will ignore a number of services,
  5475. use '--all' and --force' to get more services.
  5476. """
  5477. igno = self.igno_centos + self.igno_opensuse + self.igno_ubuntu + self.igno_always
  5478. if self._show_all:
  5479. igno = self.igno_always
  5480. if self._force:
  5481. igno = []
  5482. logg.debug("ignored services filter for default.target:\n\t%s", igno)
  5483. default_target = target or self.get_default_target()
  5484. return self.enabled_target_services(default_target, sysv, igno)
  5485. def enabled_target_services(self, target, sysv = "S", igno = []):
  5486. units = []
  5487. if self.user_mode():
  5488. targetlist = self.get_target_list(target)
  5489. logg.debug("check for %s user services : %s", target, targetlist)
  5490. for targets in targetlist:
  5491. for unit in self.enabled_target_user_local_units(targets, ".target", igno):
  5492. if unit not in units:
  5493. units.append(unit)
  5494. for targets in targetlist:
  5495. for unit in self.required_target_units(targets, ".socket", igno):
  5496. if unit not in units:
  5497. units.append(unit)
  5498. for targets in targetlist:
  5499. for unit in self.enabled_target_user_local_units(targets, ".socket", igno):
  5500. if unit not in units:
  5501. units.append(unit)
  5502. for targets in targetlist:
  5503. for unit in self.required_target_units(targets, ".service", igno):
  5504. if unit not in units:
  5505. units.append(unit)
  5506. for targets in targetlist:
  5507. for unit in self.enabled_target_user_local_units(targets, ".service", igno):
  5508. if unit not in units:
  5509. units.append(unit)
  5510. for targets in targetlist:
  5511. for unit in self.enabled_target_user_system_units(targets, ".service", igno):
  5512. if unit not in units:
  5513. units.append(unit)
  5514. else:
  5515. targetlist = self.get_target_list(target)
  5516. logg.debug("check for %s system services: %s", target, targetlist)
  5517. for targets in targetlist:
  5518. for unit in self.enabled_target_configured_system_units(targets, ".target", igno + self.igno_targets):
  5519. if unit not in units:
  5520. units.append(unit)
  5521. for targets in targetlist:
  5522. for unit in self.required_target_units(targets, ".socket", igno):
  5523. if unit not in units:
  5524. units.append(unit)
  5525. for targets in targetlist:
  5526. for unit in self.enabled_target_installed_system_units(targets, ".socket", igno):
  5527. if unit not in units:
  5528. units.append(unit)
  5529. for targets in targetlist:
  5530. for unit in self.required_target_units(targets, ".service", igno):
  5531. if unit not in units:
  5532. units.append(unit)
  5533. for targets in targetlist:
  5534. for unit in self.enabled_target_installed_system_units(targets, ".service", igno):
  5535. if unit not in units:
  5536. units.append(unit)
  5537. for targets in targetlist:
  5538. for unit in self.enabled_target_sysv_units(targets, sysv, igno):
  5539. if unit not in units:
  5540. units.append(unit)
  5541. return units
  5542. def enabled_target_user_local_units(self, target, unit_kind = ".service", igno = []):
  5543. units = []
  5544. for basefolder in self.user_folders():
  5545. if not basefolder:
  5546. continue
  5547. folder = self.default_enablefolder(target, basefolder)
  5548. if self._root:
  5549. folder = os_path(self._root, folder)
  5550. if os.path.isdir(folder):
  5551. for unit in sorted(os.listdir(folder)):
  5552. path = os.path.join(folder, unit)
  5553. if os.path.isdir(path): continue
  5554. if self._ignored_unit(unit, igno):
  5555. continue # ignore
  5556. if unit.endswith(unit_kind):
  5557. units.append(unit)
  5558. return units
  5559. def enabled_target_user_system_units(self, target, unit_kind = ".service", igno = []):
  5560. units = []
  5561. for basefolder in self.system_folders():
  5562. if not basefolder:
  5563. continue
  5564. folder = self.default_enablefolder(target, basefolder)
  5565. if self._root:
  5566. folder = os_path(self._root, folder)
  5567. if os.path.isdir(folder):
  5568. for unit in sorted(os.listdir(folder)):
  5569. path = os.path.join(folder, unit)
  5570. if os.path.isdir(path): continue
  5571. if self._ignored_unit(unit, igno):
  5572. continue # ignore
  5573. if unit.endswith(unit_kind):
  5574. conf = self.load_unit_conf(unit)
  5575. if conf is None:
  5576. pass
  5577. elif self.not_user_conf(conf):
  5578. pass
  5579. else:
  5580. units.append(unit)
  5581. return units
  5582. def enabled_target_installed_system_units(self, target, unit_type = ".service", igno = []):
  5583. units = []
  5584. for basefolder in self.system_folders():
  5585. if not basefolder:
  5586. continue
  5587. folder = self.default_enablefolder(target, basefolder)
  5588. if self._root:
  5589. folder = os_path(self._root, folder)
  5590. if os.path.isdir(folder):
  5591. for unit in sorted(os.listdir(folder)):
  5592. path = os.path.join(folder, unit)
  5593. if os.path.isdir(path): continue
  5594. if self._ignored_unit(unit, igno):
  5595. continue # ignore
  5596. if unit.endswith(unit_type):
  5597. units.append(unit)
  5598. return units
  5599. def enabled_target_configured_system_units(self, target, unit_type = ".service", igno = []):
  5600. units = []
  5601. if True:
  5602. folder = self.default_enablefolder(target)
  5603. if self._root:
  5604. folder = os_path(self._root, folder)
  5605. if os.path.isdir(folder):
  5606. for unit in sorted(os.listdir(folder)):
  5607. path = os.path.join(folder, unit)
  5608. if os.path.isdir(path): continue
  5609. if self._ignored_unit(unit, igno):
  5610. continue # ignore
  5611. if unit.endswith(unit_type):
  5612. units.append(unit)
  5613. return units
  5614. def enabled_target_sysv_units(self, target, sysv = "S", igno = []):
  5615. units = []
  5616. folders = []
  5617. if target in ["multi-user.target", DefaultUnit]:
  5618. folders += [self.rc3_root_folder()]
  5619. if target in ["graphical.target"]:
  5620. folders += [self.rc5_root_folder()]
  5621. for folder in folders:
  5622. if not os.path.isdir(folder):
  5623. logg.warning("non-existent %s", folder)
  5624. continue
  5625. for unit in sorted(os.listdir(folder)):
  5626. path = os.path.join(folder, unit)
  5627. if os.path.isdir(path): continue
  5628. m = re.match(sysv+r"\d\d(.*)", unit)
  5629. if m:
  5630. service = m.group(1)
  5631. unit = service + ".service"
  5632. if self._ignored_unit(unit, igno):
  5633. continue # ignore
  5634. units.append(unit)
  5635. return units
  5636. def required_target_units(self, target, unit_type, igno):
  5637. units = []
  5638. deps = self.get_required_dependencies(target)
  5639. for unit in sorted(deps):
  5640. if self._ignored_unit(unit, igno):
  5641. continue # ignore
  5642. if unit.endswith(unit_type):
  5643. if unit not in units:
  5644. units.append(unit)
  5645. return units
  5646. def get_target_conf(self, module): # -> conf (conf | default-conf)
  5647. """ accept that a unit does not exist
  5648. and return a unit conf that says 'not-loaded' """
  5649. conf = self.load_unit_conf(module)
  5650. if conf is not None:
  5651. return conf
  5652. target_conf = self.default_unit_conf(module)
  5653. if module in target_requires:
  5654. target_conf.set(Unit, "Requires", target_requires[module])
  5655. return target_conf
  5656. def get_target_list(self, module):
  5657. """ the Requires= in target units are only accepted if known """
  5658. target = module
  5659. if "." not in target: target += ".target"
  5660. targets = [target]
  5661. conf = self.get_target_conf(module)
  5662. requires = conf.get(Unit, "Requires", "")
  5663. while requires in target_requires:
  5664. targets = [requires] + targets
  5665. requires = target_requires[requires]
  5666. logg.debug("the %s requires %s", module, targets)
  5667. return targets
  5668. def default_system(self, arg = True):
  5669. """ start units for default system level
  5670. This will go through the enabled services in the default 'multi-user.target'.
  5671. However some services are ignored as being known to be installation garbage
  5672. from unintended services. Use '--all' so start all of the installed services
  5673. and with '--all --force' even those services that are otherwise wrong.
  5674. /// SPECIAL: with --now or --init the init-loop is run and afterwards
  5675. a system_halt is performed with the enabled services to be stopped."""
  5676. self.sysinit_status(SubState = "initializing")
  5677. logg.info("system default requested - %s", arg)
  5678. init = self._now or self._init
  5679. return self.start_system_default(init = init)
  5680. def start_system_default(self, init = False):
  5681. """ detect the default.target services and start them.
  5682. When --init is given then the init-loop is run and
  5683. the services are stopped again by 'systemctl halt'."""
  5684. target = self.get_default_target()
  5685. services = self.start_target_system(target, init)
  5686. logg.info("%s system is up", target)
  5687. if init:
  5688. logg.info("init-loop start")
  5689. sig = self.init_loop_until_stop(services)
  5690. logg.info("init-loop %s", sig)
  5691. self.stop_system_default()
  5692. return not not services
  5693. def start_target_system(self, target, init = False):
  5694. services = self.target_default_services(target, "S")
  5695. self.sysinit_status(SubState = "starting")
  5696. self.start_units(services)
  5697. return services
  5698. def do_start_target_from(self, conf):
  5699. target = conf.name()
  5700. # services = self.start_target_system(target)
  5701. services = self.target_default_services(target, "S")
  5702. units = [service for service in services if not self.is_running_unit(service)]
  5703. logg.debug("start %s is starting %s from %s", target, units, services)
  5704. return self.start_units(units)
  5705. def stop_system_default(self):
  5706. """ detect the default.target services and stop them.
  5707. This is commonly run through 'systemctl halt' or
  5708. at the end of a 'systemctl --init default' loop."""
  5709. target = self.get_default_target()
  5710. services = self.stop_target_system(target)
  5711. logg.info("%s system is down", target)
  5712. return not not services
  5713. def stop_target_system(self, target):
  5714. services = self.target_default_services(target, "K")
  5715. self.sysinit_status(SubState = "stopping")
  5716. self.stop_units(services)
  5717. return services
  5718. def do_stop_target_from(self, conf):
  5719. target = conf.name()
  5720. # services = self.stop_target_system(target)
  5721. services = self.target_default_services(target, "K")
  5722. units = [service for service in services if self.is_running_unit(service)]
  5723. logg.debug("stop %s is stopping %s from %s", target, units, services)
  5724. return self.stop_units(units)
  5725. def do_reload_target_from(self, conf):
  5726. target = conf.name()
  5727. return self.reload_target_system(target)
  5728. def reload_target_system(self, target):
  5729. services = self.target_default_services(target, "S")
  5730. units = [service for service in services if self.is_running_unit(service)]
  5731. return self.reload_units(units)
  5732. def halt_target(self, arg = True):
  5733. """ stop units from default system level """
  5734. logg.info("system halt requested - %s", arg)
  5735. done = self.stop_system_default()
  5736. try:
  5737. os.kill(1, signal.SIGQUIT) # exit init-loop on no_more_procs
  5738. except Exception as e:
  5739. logg.warning("SIGQUIT to init-loop on PID-1: %s", e)
  5740. return done
  5741. def system_get_default(self):
  5742. """ get current default run-level"""
  5743. return self.get_default_target()
  5744. def get_targets_folder(self):
  5745. return os_path(self._root, self.mask_folder())
  5746. def get_default_target_file(self):
  5747. targets_folder = self.get_targets_folder()
  5748. return os.path.join(targets_folder, DefaultUnit)
  5749. def get_default_target(self, default_target = None):
  5750. """ get current default run-level"""
  5751. current = default_target or self._default_target
  5752. default_target_file = self.get_default_target_file()
  5753. if os.path.islink(default_target_file):
  5754. current = os.path.basename(os.readlink(default_target_file))
  5755. return current
  5756. def set_default_modules(self, *modules):
  5757. """ set current default run-level"""
  5758. if not modules:
  5759. logg.debug(".. no runlevel given")
  5760. self.error |= NOT_OK
  5761. return "Too few arguments"
  5762. current = self.get_default_target()
  5763. default_target_file = self.get_default_target_file()
  5764. msg = ""
  5765. for module in modules:
  5766. if module == current:
  5767. continue
  5768. targetfile = None
  5769. for targetname, targetpath in self.each_target_file():
  5770. if targetname == module:
  5771. targetfile = targetpath
  5772. if not targetfile:
  5773. self.error |= NOT_OK | NOT_ACTIVE # 3
  5774. msg = "No such runlevel %s" % (module)
  5775. continue
  5776. #
  5777. if os.path.islink(default_target_file):
  5778. os.unlink(default_target_file)
  5779. if not os.path.isdir(os.path.dirname(default_target_file)):
  5780. os.makedirs(os.path.dirname(default_target_file))
  5781. os.symlink(targetfile, default_target_file)
  5782. msg = "Created symlink from %s -> %s" % (default_target_file, targetfile)
  5783. logg.debug("%s", msg)
  5784. return msg
  5785. def init_modules(self, *modules):
  5786. """ [UNIT*] -- init loop: '--init default' or '--init start UNIT*'
  5787. The systemctl init service will start the enabled 'default' services,
  5788. and then wait for any zombies to be reaped. When a SIGINT is received
  5789. then a clean shutdown of the enabled services is ensured. A Control-C in
  5790. in interactive mode will also run 'stop' on all the enabled services. //
  5791. When a UNIT name is given then only that one is started instead of the
  5792. services in the 'default.target'. Using 'init UNIT' is better than
  5793. '--init start UNIT' because the UNIT is also stopped cleanly even when
  5794. it was never enabled in the system.
  5795. /// SPECIAL: when using --now then only the init-loop is started,
  5796. with the reap-zombies function and waiting for an interrupt.
  5797. (and no unit is started/stoppped wether given or not).
  5798. """
  5799. if self._now:
  5800. result = self.init_loop_until_stop([])
  5801. return not not result
  5802. if not modules:
  5803. # like 'systemctl --init default'
  5804. if self._now or self._show_all:
  5805. logg.debug("init default --now --all => no_more_procs")
  5806. self.doExitWhenNoMoreProcs = True
  5807. return self.start_system_default(init = True)
  5808. #
  5809. # otherwise quit when all the init-services have died
  5810. self.doExitWhenNoMoreServices = True
  5811. if self._now or self._show_all:
  5812. logg.debug("init services --now --all => no_more_procs")
  5813. self.doExitWhenNoMoreProcs = True
  5814. found_all = True
  5815. units = []
  5816. for module in modules:
  5817. matched = self.match_units(to_list(module))
  5818. if not matched:
  5819. logg.error("Unit %s could not be found.", unit_of(module))
  5820. found_all = False
  5821. continue
  5822. for unit in matched:
  5823. if unit not in units:
  5824. units += [unit]
  5825. logg.info("init %s -> start %s", ",".join(modules), ",".join(units))
  5826. done = self.start_units(units, init = True)
  5827. logg.info("-- init is done")
  5828. return done # and found_all
  5829. def start_log_files(self, units):
  5830. self._log_file = {}
  5831. self._log_hold = {}
  5832. for unit in units:
  5833. conf = self.load_unit_conf(unit)
  5834. if not conf: continue
  5835. if self.skip_journal_log(conf): continue
  5836. log_path = self.get_journal_log_from(conf)
  5837. try:
  5838. opened = os.open(log_path, os.O_RDONLY | os.O_NONBLOCK)
  5839. self._log_file[unit] = opened
  5840. self._log_hold[unit] = b""
  5841. except Exception as e:
  5842. logg.error("can not open %s log: %s\n\t%s", unit, log_path, e)
  5843. def read_log_files(self, units):
  5844. self.print_log_files(units)
  5845. def print_log_files(self, units, stdout = 1):
  5846. BUFSIZE=8192
  5847. printed = 0
  5848. for unit in units:
  5849. if unit in self._log_file:
  5850. new_text = b""
  5851. while True:
  5852. buf = os.read(self._log_file[unit], BUFSIZE)
  5853. if not buf: break
  5854. new_text += buf
  5855. continue
  5856. text = self._log_hold[unit] + new_text
  5857. if not text: continue
  5858. lines = text.split(b"\n")
  5859. if not text.endswith(b"\n"):
  5860. self._log_hold[unit] = lines[-1]
  5861. lines = lines[:-1]
  5862. for line in lines:
  5863. prefix = unit.encode("utf-8")
  5864. content = prefix+b": "+line+b"\n"
  5865. try:
  5866. os.write(stdout, content)
  5867. try:
  5868. os.fsync(stdout)
  5869. except Exception:
  5870. pass
  5871. printed += 1
  5872. except BlockingIOError:
  5873. pass
  5874. return printed
  5875. def stop_log_files(self, units):
  5876. for unit in units:
  5877. try:
  5878. if unit in self._log_file:
  5879. if self._log_file[unit]:
  5880. os.close(self._log_file[unit])
  5881. except Exception as e:
  5882. logg.error("can not close log: %s\n\t%s", unit, e)
  5883. self._log_file = {}
  5884. self._log_hold = {}
  5885. def get_StartLimitBurst(self, conf):
  5886. defaults = DefaultStartLimitBurst
  5887. return to_int(conf.get(Service, "StartLimitBurst", strE(defaults)), defaults) # 5
  5888. def get_StartLimitIntervalSec(self, conf, maximum = None):
  5889. maximum = maximum or 999
  5890. defaults = DefaultStartLimitIntervalSec
  5891. interval = conf.get(Service, "StartLimitIntervalSec", strE(defaults)) # 10s
  5892. return time_to_seconds(interval, maximum)
  5893. def get_RestartSec(self, conf, maximum = None):
  5894. maximum = maximum or DefaultStartLimitIntervalSec
  5895. delay = conf.get(Service, "RestartSec", strE(DefaultRestartSec))
  5896. return time_to_seconds(delay, maximum)
  5897. def restart_failed_units(self, units, maximum = None):
  5898. """ This function will restart failed units.
  5899. /
  5900. NOTE that with standard settings the LimitBurst implementation has no effect. If
  5901. the InitLoopSleep is ticking at the Default of 5sec and the LimitBurst Default
  5902. is 5x within a Default 10secs time frame then within those 10sec only 2 loop
  5903. rounds have come here checking for possible restarts. You can directly shorten
  5904. the interval ('-c InitLoopSleep=1') or have it indirectly shorter from the
  5905. service descriptor's RestartSec ("RestartSec=2s").
  5906. """
  5907. global InitLoopSleep
  5908. me = os.getpid()
  5909. maximum = maximum or DefaultStartLimitIntervalSec
  5910. restartDelay = MinimumYield
  5911. for unit in units:
  5912. now = time.time()
  5913. try:
  5914. conf = self.load_unit_conf(unit)
  5915. if not conf: continue
  5916. restartPolicy = conf.get(Service, "Restart", "no")
  5917. if restartPolicy in ["no", "on-success"]:
  5918. logg.debug("[%s] [%s] Current NoCheck (Restart=%s)", me, unit, restartPolicy)
  5919. continue
  5920. restartSec = self.get_RestartSec(conf)
  5921. if restartSec == 0:
  5922. if InitLoopSleep > 1:
  5923. logg.warning("[%s] set InitLoopSleep from %ss to 1 (caused by RestartSec=0!)",
  5924. unit, InitLoopSleep)
  5925. InitLoopSleep = 1
  5926. elif restartSec > 0.9 and restartSec < InitLoopSleep:
  5927. restartSleep = int(restartSec + 0.2)
  5928. if restartSleep < InitLoopSleep:
  5929. logg.warning("[%s] set InitLoopSleep from %ss to %s (caused by RestartSec=%.3fs)",
  5930. unit, InitLoopSleep, restartSleep, restartSec)
  5931. InitLoopSleep = restartSleep
  5932. isUnitState = self.get_active_from(conf)
  5933. isUnitFailed = isUnitState in ["failed"]
  5934. logg.debug("[%s] [%s] Current Status: %s (%s)", me, unit, isUnitState, isUnitFailed)
  5935. if not isUnitFailed:
  5936. if unit in self._restart_failed_units:
  5937. del self._restart_failed_units[unit]
  5938. continue
  5939. limitBurst = self.get_StartLimitBurst(conf)
  5940. limitSecs = self.get_StartLimitIntervalSec(conf)
  5941. if limitBurst > 1 and limitSecs >= 1:
  5942. try:
  5943. if unit not in self._restarted_unit:
  5944. self._restarted_unit[unit] = []
  5945. # we want to register restarts from now on
  5946. restarted = self._restarted_unit[unit]
  5947. logg.debug("[%s] [%s] Current limitSecs=%ss limitBurst=%sx (restarted %sx)",
  5948. me, unit, limitSecs, limitBurst, len(restarted))
  5949. oldest = 0.
  5950. interval = 0.
  5951. if len(restarted) >= limitBurst:
  5952. logg.debug("[%s] [%s] restarted %s",
  5953. me, unit, ["%.3fs" % (t - now) for t in restarted])
  5954. while len(restarted):
  5955. oldest = restarted[0]
  5956. interval = time.time() - oldest
  5957. if interval > limitSecs:
  5958. restarted = restarted[1:]
  5959. continue
  5960. break
  5961. self._restarted_unit[unit] = restarted
  5962. logg.debug("[%s] [%s] ratelimit %s",
  5963. me, unit, ["%.3fs" % (t - now) for t in restarted])
  5964. # all values in restarted have a time below limitSecs
  5965. if len(restarted) >= limitBurst:
  5966. logg.info("[%s] [%s] Blocking Restart - oldest %s is %s ago (allowed %s)",
  5967. me, unit, oldest, interval, limitSecs)
  5968. self.write_status_from(conf, AS="error")
  5969. unit = "" # dropped out
  5970. continue
  5971. except Exception as e:
  5972. logg.error("[%s] burst exception %s", unit, e)
  5973. if unit: # not dropped out
  5974. if unit not in self._restart_failed_units:
  5975. self._restart_failed_units[unit] = now + restartSec
  5976. logg.debug("[%s] [%s] restart scheduled in %+.3fs",
  5977. me, unit, (self._restart_failed_units[unit] - now))
  5978. except Exception as e:
  5979. logg.error("[%s] [%s] An error occurred while restart checking: %s", me, unit, e)
  5980. if not self._restart_failed_units:
  5981. self.error |= NOT_OK
  5982. return []
  5983. # NOTE: this function is only called from InitLoop when "running"
  5984. # let's check if any of the restart_units has its restartSec expired
  5985. now = time.time()
  5986. restart_done = []
  5987. logg.debug("[%s] Restart checking %s",
  5988. me, ["%+.3fs" % (t - now) for t in self._restart_failed_units.values()])
  5989. for unit in sorted(self._restart_failed_units):
  5990. restartAt = self._restart_failed_units[unit]
  5991. if restartAt > now:
  5992. continue
  5993. restart_done.append(unit)
  5994. try:
  5995. conf = self.load_unit_conf(unit)
  5996. if not conf: continue
  5997. isUnitState = self.get_active_from(conf)
  5998. isUnitFailed = isUnitState in ["failed"]
  5999. logg.debug("[%s] [%s] Restart Status: %s (%s)", me, unit, isUnitState, isUnitFailed)
  6000. if isUnitFailed:
  6001. logg.debug("[%s] [%s] --- restarting failed unit...", me, unit)
  6002. self.restart_unit(unit)
  6003. logg.debug("[%s] [%s] --- has been restarted.", me, unit)
  6004. if unit in self._restarted_unit:
  6005. self._restarted_unit[unit].append(time.time())
  6006. except Exception as e:
  6007. logg.error("[%s] [%s] An error occurred while restarting: %s", me, unit, e)
  6008. for unit in restart_done:
  6009. if unit in self._restart_failed_units:
  6010. del self._restart_failed_units[unit]
  6011. logg.debug("[%s] Restart remaining %s",
  6012. me, ["%+.3fs" % (t - now) for t in self._restart_failed_units.values()])
  6013. return restart_done
  6014. def init_loop_until_stop(self, units):
  6015. """ this is the init-loop - it checks for any zombies to be reaped and
  6016. waits for an interrupt. When a SIGTERM /SIGINT /Control-C signal
  6017. is received then the signal name is returned. Any other signal will
  6018. just raise an Exception like one would normally expect. As a special
  6019. the 'systemctl halt' emits SIGQUIT which puts it into no_more_procs mode."""
  6020. signal.signal(signal.SIGQUIT, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt("SIGQUIT"))
  6021. signal.signal(signal.SIGINT, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt("SIGINT"))
  6022. signal.signal(signal.SIGTERM, lambda signum, frame: ignore_signals_and_raise_keyboard_interrupt("SIGTERM"))
  6023. result = None
  6024. #
  6025. self.start_log_files(units)
  6026. logg.debug("start listen")
  6027. listen = SystemctlListenThread(self)
  6028. logg.debug("starts listen")
  6029. listen.start()
  6030. logg.debug("started listen")
  6031. self.sysinit_status(ActiveState = "active", SubState = "running")
  6032. timestamp = time.time()
  6033. while True:
  6034. try:
  6035. if DEBUG_INITLOOP: # pragma: no cover
  6036. logg.debug("DONE InitLoop (sleep %ss)", InitLoopSleep)
  6037. sleep_sec = InitLoopSleep - (time.time() - timestamp)
  6038. if sleep_sec < MinimumYield:
  6039. sleep_sec = MinimumYield
  6040. sleeping = sleep_sec
  6041. while sleeping > 2:
  6042. time.sleep(1) # accept signals atleast every second
  6043. sleeping = InitLoopSleep - (time.time() - timestamp)
  6044. if sleeping < MinimumYield:
  6045. sleeping = MinimumYield
  6046. break
  6047. time.sleep(sleeping) # remainder waits less that 2 seconds
  6048. timestamp = time.time()
  6049. self.loop.acquire()
  6050. if DEBUG_INITLOOP: # pragma: no cover
  6051. logg.debug("NEXT InitLoop (after %ss)", sleep_sec)
  6052. self.read_log_files(units)
  6053. if DEBUG_INITLOOP: # pragma: no cover
  6054. logg.debug("reap zombies - check current processes")
  6055. running = self.reap_zombies()
  6056. if DEBUG_INITLOOP: # pragma: no cover
  6057. logg.debug("reap zombies - init-loop found %s running procs", running)
  6058. if self.doExitWhenNoMoreServices:
  6059. active = False
  6060. for unit in units:
  6061. conf = self.load_unit_conf(unit)
  6062. if not conf: continue
  6063. if self.is_active_from(conf):
  6064. active = True
  6065. if not active:
  6066. logg.info("no more services - exit init-loop")
  6067. break
  6068. if self.doExitWhenNoMoreProcs:
  6069. if not running:
  6070. logg.info("no more procs - exit init-loop")
  6071. break
  6072. if RESTART_FAILED_UNITS:
  6073. self.restart_failed_units(units)
  6074. self.loop.release()
  6075. except KeyboardInterrupt as e:
  6076. if e.args and e.args[0] == "SIGQUIT":
  6077. # the original systemd puts a coredump on that signal.
  6078. logg.info("SIGQUIT - switch to no more procs check")
  6079. self.doExitWhenNoMoreProcs = True
  6080. continue
  6081. signal.signal(signal.SIGTERM, signal.SIG_DFL)
  6082. signal.signal(signal.SIGINT, signal.SIG_DFL)
  6083. logg.info("interrupted - exit init-loop")
  6084. result = str(e) or "STOPPED"
  6085. break
  6086. except Exception as e:
  6087. logg.info("interrupted - exception %s", e)
  6088. raise
  6089. self.sysinit_status(ActiveState = None, SubState = "degraded")
  6090. try: self.loop.release()
  6091. except: pass
  6092. listen.stop()
  6093. listen.join(2)
  6094. self.read_log_files(units)
  6095. self.read_log_files(units)
  6096. self.stop_log_files(units)
  6097. logg.debug("done - init loop")
  6098. return result
  6099. def reap_zombies_target(self):
  6100. """ -- check to reap children (internal) """
  6101. running = self.reap_zombies()
  6102. return "remaining {running} process".format(**locals())
  6103. def reap_zombies(self):
  6104. """ check to reap children """
  6105. selfpid = os.getpid()
  6106. running = 0
  6107. for pid_entry in os.listdir(_proc_pid_dir):
  6108. pid = to_intN(pid_entry)
  6109. if pid is None:
  6110. continue
  6111. if pid == selfpid:
  6112. continue
  6113. proc_status = _proc_pid_status.format(**locals())
  6114. if os.path.isfile(proc_status):
  6115. zombie = False
  6116. ppid = -1
  6117. try:
  6118. for line in open(proc_status):
  6119. m = re.match(r"State:\s*Z.*", line)
  6120. if m: zombie = True
  6121. m = re.match(r"PPid:\s*(\d+)", line)
  6122. if m: ppid = int(m.group(1))
  6123. except IOError as e:
  6124. logg.warning("%s : %s", proc_status, e)
  6125. continue
  6126. if zombie and ppid == os.getpid():
  6127. logg.info("reap zombie %s", pid)
  6128. try: os.waitpid(pid, os.WNOHANG)
  6129. except OSError as e:
  6130. logg.warning("reap zombie %s: %s", e.strerror)
  6131. if os.path.isfile(proc_status):
  6132. if pid > 1:
  6133. running += 1
  6134. return running # except PID 0 and PID 1
  6135. def sysinit_status(self, **status):
  6136. conf = self.sysinit_target()
  6137. self.write_status_from(conf, **status)
  6138. def sysinit_target(self):
  6139. if not self._sysinit_target:
  6140. self._sysinit_target = self.default_unit_conf(SysInitTarget, "System Initialization")
  6141. assert self._sysinit_target is not None
  6142. return self._sysinit_target
  6143. def is_system_running(self):
  6144. conf = self.sysinit_target()
  6145. if not self.is_running_unit_from(conf):
  6146. time.sleep(MinimumYield)
  6147. if not self.is_running_unit_from(conf):
  6148. return "offline"
  6149. status = self.read_status_from(conf)
  6150. return status.get("SubState", "unknown")
  6151. def is_system_running_info(self):
  6152. state = self.is_system_running()
  6153. if state not in ["running"]:
  6154. self.error |= NOT_OK # 1
  6155. if self._quiet:
  6156. return None
  6157. return state
  6158. def wait_system(self, target = None):
  6159. target = target or SysInitTarget
  6160. for attempt in xrange(int(SysInitWait)):
  6161. state = self.is_system_running()
  6162. if "init" in state:
  6163. if target in [SysInitTarget, "basic.target"]:
  6164. logg.info("system not initialized - wait %s", target)
  6165. time.sleep(1)
  6166. continue
  6167. if "start" in state or "stop" in state:
  6168. if target in ["basic.target"]:
  6169. logg.info("system not running - wait %s", target)
  6170. time.sleep(1)
  6171. continue
  6172. if "running" not in state:
  6173. logg.info("system is %s", state)
  6174. break
  6175. def is_running_unit_from(self, conf):
  6176. status_file = self.get_status_file_from(conf)
  6177. pid_file = self.pid_file_from(conf)
  6178. return self.getsize(status_file) > 0 or self.getsize(pid_file) > 0
  6179. def is_running_unit(self, unit):
  6180. conf = self.get_unit_conf(unit)
  6181. return self.is_running_unit_from(conf)
  6182. def pidlist_of(self, pid):
  6183. if not pid:
  6184. return []
  6185. pidlist = [pid]
  6186. pids = [pid]
  6187. for depth in xrange(PROC_MAX_DEPTH):
  6188. for pid_entry in os.listdir(_proc_pid_dir):
  6189. pid = to_intN(pid_entry)
  6190. if pid is None:
  6191. continue
  6192. proc_status = _proc_pid_status.format(**locals())
  6193. if os.path.isfile(proc_status):
  6194. try:
  6195. for line in open(proc_status):
  6196. if line.startswith("PPid:"):
  6197. ppid_text = line[len("PPid:"):].strip()
  6198. try: ppid = int(ppid_text)
  6199. except: continue
  6200. if ppid in pidlist and pid not in pids:
  6201. pids += [pid]
  6202. except IOError as e:
  6203. logg.warning("%s : %s", proc_status, e)
  6204. continue
  6205. if len(pids) != len(pidlist):
  6206. pidlist = pids[:]
  6207. continue
  6208. return pids
  6209. def echo(self, *targets):
  6210. line = " ".join(*targets)
  6211. logg.info(" == echo == %s", line)
  6212. return line
  6213. def killall(self, *targets):
  6214. mapping = {}
  6215. mapping[":3"] = signal.SIGQUIT
  6216. mapping[":QUIT"] = signal.SIGQUIT
  6217. mapping[":6"] = signal.SIGABRT
  6218. mapping[":ABRT"] = signal.SIGABRT
  6219. mapping[":9"] = signal.SIGKILL
  6220. mapping[":KILL"] = signal.SIGKILL
  6221. sig = signal.SIGTERM
  6222. for target in targets:
  6223. if target.startswith(":"):
  6224. if target in mapping:
  6225. sig = mapping[target]
  6226. else: # pragma: no cover
  6227. logg.error("unsupported %s", target)
  6228. continue
  6229. for pid_entry in os.listdir(_proc_pid_dir):
  6230. pid = to_intN(pid_entry)
  6231. if pid:
  6232. try:
  6233. cmdline = _proc_pid_cmdline.format(**locals())
  6234. cmd = open(cmdline).read().split("\0")
  6235. if DEBUG_KILLALL: logg.debug("cmdline %s", cmd)
  6236. found = None
  6237. cmd_exe = os.path.basename(cmd[0])
  6238. if DEBUG_KILLALL: logg.debug("cmd.exe '%s'", cmd_exe)
  6239. if fnmatch.fnmatchcase(cmd_exe, target): found = "exe"
  6240. if len(cmd) > 1 and cmd_exe.startswith("python"):
  6241. X = 1
  6242. while cmd[X].startswith("-"): X += 1 # atleast '-u' unbuffered
  6243. cmd_arg = os.path.basename(cmd[X])
  6244. if DEBUG_KILLALL: logg.debug("cmd.arg '%s'", cmd_arg)
  6245. if fnmatch.fnmatchcase(cmd_arg, target): found = "arg"
  6246. if cmd_exe.startswith("coverage") or cmd_arg.startswith("coverage"):
  6247. x = cmd.index("--")
  6248. if x > 0 and x+1 < len(cmd):
  6249. cmd_run = os.path.basename(cmd[x+1])
  6250. if DEBUG_KILLALL: logg.debug("cmd.run '%s'", cmd_run)
  6251. if fnmatch.fnmatchcase(cmd_run, target): found = "run"
  6252. if found:
  6253. if DEBUG_KILLALL: logg.debug("%s found %s %s", found, pid, [c for c in cmd])
  6254. if pid != os.getpid():
  6255. logg.debug(" kill -%s %s # %s", sig, pid, target)
  6256. os.kill(pid, sig)
  6257. except Exception as e:
  6258. logg.error("kill -%s %s : %s", sig, pid, e)
  6259. return True
  6260. def force_ipv4(self, *args):
  6261. """ only ipv4 localhost in /etc/hosts """
  6262. logg.debug("checking hosts sysconf for '::1 localhost'")
  6263. lines = []
  6264. sysconf_hosts = os_path(self._root, _etc_hosts)
  6265. for line in open(sysconf_hosts):
  6266. if "::1" in line:
  6267. newline = re.sub("\\slocalhost\\s", " ", line)
  6268. if line != newline:
  6269. logg.info("%s: '%s' => '%s'", _etc_hosts, line.rstrip(), newline.rstrip())
  6270. line = newline
  6271. lines.append(line)
  6272. f = open(sysconf_hosts, "w")
  6273. for line in lines:
  6274. f.write(line)
  6275. f.close()
  6276. def force_ipv6(self, *args):
  6277. """ only ipv4 localhost in /etc/hosts """
  6278. logg.debug("checking hosts sysconf for '127.0.0.1 localhost'")
  6279. lines = []
  6280. sysconf_hosts = os_path(self._root, _etc_hosts)
  6281. for line in open(sysconf_hosts):
  6282. if "127.0.0.1" in line:
  6283. newline = re.sub("\\slocalhost\\s", " ", line)
  6284. if line != newline:
  6285. logg.info("%s: '%s' => '%s'", _etc_hosts, line.rstrip(), newline.rstrip())
  6286. line = newline
  6287. lines.append(line)
  6288. f = open(sysconf_hosts, "w")
  6289. for line in lines:
  6290. f.write(line)
  6291. f.close()
  6292. def help_modules(self, *args):
  6293. """[command] -- show this help
  6294. """
  6295. lines = []
  6296. okay = True
  6297. prog = os.path.basename(sys.argv[0])
  6298. if not args:
  6299. argz = {}
  6300. for name in dir(self):
  6301. arg = None
  6302. if name.startswith("system_"):
  6303. arg = name[len("system_"):].replace("_", "-")
  6304. if name.startswith("show_"):
  6305. arg = name[len("show_"):].replace("_", "-")
  6306. if name.endswith("_of_unit"):
  6307. arg = name[:-len("_of_unit")].replace("_", "-")
  6308. if name.endswith("_modules"):
  6309. arg = name[:-len("_modules")].replace("_", "-")
  6310. if arg:
  6311. argz[arg] = name
  6312. lines.append("%s command [options]..." % prog)
  6313. lines.append("")
  6314. lines.append("Commands:")
  6315. for arg in sorted(argz):
  6316. name = argz[arg]
  6317. method = getattr(self, name)
  6318. doc = "..."
  6319. doctext = getattr(method, "__doc__")
  6320. if doctext:
  6321. doc = doctext
  6322. elif not self._show_all:
  6323. continue # pragma: no cover
  6324. firstline = doc.split("\n")[0]
  6325. doc_text = firstline.strip()
  6326. if "--" not in firstline:
  6327. doc_text = "-- " + doc_text
  6328. lines.append(" %s %s" % (arg, firstline.strip()))
  6329. return lines
  6330. for arg in args:
  6331. arg = arg.replace("-", "_")
  6332. func1 = getattr(self.__class__, arg+"_modules", None)
  6333. func2 = getattr(self.__class__, arg+"_of_unit", None)
  6334. func3 = getattr(self.__class__, "show_"+arg, None)
  6335. func4 = getattr(self.__class__, "system_"+arg, None)
  6336. func5 = None
  6337. if arg.startswith("__"):
  6338. func5 = getattr(self.__class__, arg[2:], None)
  6339. func = func1 or func2 or func3 or func4 or func5
  6340. if func is None:
  6341. print("error: no such command '%s'" % arg)
  6342. okay = False
  6343. else:
  6344. doc_text = "..."
  6345. doc = getattr(func, "__doc__", "")
  6346. if doc:
  6347. doc_text = doc.replace("\n", "\n\n", 1).strip()
  6348. if "--" not in doc_text:
  6349. doc_text = "-- " + doc_text
  6350. else:
  6351. func_name = arg # FIXME
  6352. logg.debug("__doc__ of %s is none", func_name)
  6353. if not self._show_all: continue
  6354. lines.append("%s %s %s" % (prog, arg, doc_text))
  6355. if not okay:
  6356. self.help_modules()
  6357. self.error |= NOT_OK
  6358. return []
  6359. return lines
  6360. def systemd_version(self):
  6361. """ the version line for systemd compatibility """
  6362. return "systemd %s\n - via systemctl.py %s" % (self._systemd_version, __version__)
  6363. def systemd_features(self):
  6364. """ the info line for systemd features """
  6365. features1 = "-PAM -AUDIT -SELINUX -IMA -APPARMOR -SMACK"
  6366. features2 = " +SYSVINIT -UTMP -LIBCRYPTSETUP -GCRYPT -GNUTLS"
  6367. features3 = " -ACL -XZ -LZ4 -SECCOMP -BLKID -ELFUTILS -KMOD -IDN"
  6368. return features1+features2+features3
  6369. def version_info(self):
  6370. return [self.systemd_version(), self.systemd_features()]
  6371. def test_float(self):
  6372. return 0. # "Unknown result type"
  6373. def print_begin(argv, args):
  6374. script = os.path.realpath(argv[0])
  6375. system = _user_mode and " --user" or " --system"
  6376. init = _init and " --init" or ""
  6377. logg.info("EXEC BEGIN %s %s%s%s", script, " ".join(args), system, init)
  6378. if _root and not is_good_root(_root):
  6379. root44 = path44(_root)
  6380. logg.warning("the --root=%s should have atleast three levels /tmp/test_123/root", root44)
  6381. def print_begin2(args):
  6382. logg.debug("======= systemctl.py %s", " ".join(args))
  6383. def is_not_ok(result):
  6384. if DebugPrintResult:
  6385. logg.log(HINT, "EXEC END %s", result)
  6386. if result is False:
  6387. return NOT_OK
  6388. return 0
  6389. def print_str(result):
  6390. if result is None:
  6391. if DebugPrintResult:
  6392. logg.debug(" END %s", result)
  6393. return
  6394. print(result)
  6395. if DebugPrintResult:
  6396. result1 = result.split("\n")[0][:-20]
  6397. if result == result1:
  6398. logg.log(HINT, "EXEC END '%s'", result)
  6399. else:
  6400. logg.log(HINT, "EXEC END '%s...'", result1)
  6401. logg.debug(" END '%s'", result)
  6402. def print_str_list(result):
  6403. if result is None:
  6404. if DebugPrintResult:
  6405. logg.debug(" END %s", result)
  6406. return
  6407. shown = 0
  6408. for element in result:
  6409. print(element)
  6410. shown += 1
  6411. if DebugPrintResult:
  6412. logg.log(HINT, "EXEC END %i items", shown)
  6413. logg.debug(" END %s", result)
  6414. def print_str_list_list(result):
  6415. shown = 0
  6416. for element in result:
  6417. print("\t".join([str(elem) for elem in element]))
  6418. shown += 1
  6419. if DebugPrintResult:
  6420. logg.log(HINT, "EXEC END %i items", shown)
  6421. logg.debug(" END %s", result)
  6422. def print_str_dict(result):
  6423. if result is None:
  6424. if DebugPrintResult:
  6425. logg.debug(" END %s", result)
  6426. return
  6427. shown = 0
  6428. for key in sorted(result.keys()):
  6429. element = result[key]
  6430. print("%s=%s" % (key, element))
  6431. shown += 1
  6432. if DebugPrintResult:
  6433. logg.log(HINT, "EXEC END %i items", shown)
  6434. logg.debug(" END %s", result)
  6435. def print_str_dict_dict(result):
  6436. if result is None:
  6437. if DebugPrintResult:
  6438. logg.debug(" END %s", result)
  6439. return
  6440. shown = 0
  6441. for key in sorted(result):
  6442. element = result[key]
  6443. for name in sorted(element):
  6444. value = element[name]
  6445. print("%s [%s] %s" % (key, value, name))
  6446. shown += 1
  6447. if DebugPrintResult:
  6448. logg.log(HINT, "EXEC END %i items", shown)
  6449. logg.debug(" END %s", result)
  6450. def run(command, *modules):
  6451. exitcode = 0
  6452. if command in ["help"]:
  6453. print_str_list(systemctl.help_modules(*modules))
  6454. elif command in ["cat"]:
  6455. print_str(systemctl.cat_modules(*modules))
  6456. elif command in ["clean"]:
  6457. exitcode = is_not_ok(systemctl.clean_modules(*modules))
  6458. elif command in ["command"]:
  6459. print_str_list(systemctl.command_of_unit(*modules))
  6460. elif command in ["daemon-reload"]:
  6461. exitcode = is_not_ok(systemctl.daemon_reload_target())
  6462. elif command in ["default"]:
  6463. exitcode = is_not_ok(systemctl.default_system())
  6464. elif command in ["default-services"]:
  6465. print_str_list(systemctl.default_services_modules(*modules))
  6466. elif command in ["disable"]:
  6467. exitcode = is_not_ok(systemctl.disable_modules(*modules))
  6468. elif command in ["enable"]:
  6469. exitcode = is_not_ok(systemctl.enable_modules(*modules))
  6470. elif command in ["environment"]:
  6471. print_str_dict(systemctl.environment_of_unit(*modules))
  6472. elif command in ["get-default"]:
  6473. print_str(systemctl.get_default_target())
  6474. elif command in ["get-preset"]:
  6475. print_str(systemctl.get_preset_of_unit(*modules))
  6476. elif command in ["halt"]:
  6477. exitcode = is_not_ok(systemctl.halt_target())
  6478. elif command in ["init"]:
  6479. exitcode = is_not_ok(systemctl.init_modules(*modules))
  6480. elif command in ["is-active"]:
  6481. print_str_list(systemctl.is_active_modules(*modules))
  6482. elif command in ["is-enabled"]:
  6483. print_str_list(systemctl.is_enabled_modules(*modules))
  6484. elif command in ["is-failed"]:
  6485. print_str_list(systemctl.is_failed_modules(*modules))
  6486. elif command in ["is-system-running"]:
  6487. print_str(systemctl.is_system_running_info())
  6488. elif command in ["kill"]:
  6489. exitcode = is_not_ok(systemctl.kill_modules(*modules))
  6490. elif command in ["list-start-dependencies"]:
  6491. print_str_list_list(systemctl.list_start_dependencies_modules(*modules))
  6492. elif command in ["list-dependencies"]:
  6493. print_str_list(systemctl.list_dependencies_modules(*modules))
  6494. elif command in ["list-unit-files"]:
  6495. print_str_list_list(systemctl.list_unit_files_modules(*modules))
  6496. elif command in ["list-units"]:
  6497. print_str_list_list(systemctl.list_units_modules(*modules))
  6498. elif command in ["listen"]:
  6499. exitcode = is_not_ok(systemctl.listen_modules(*modules))
  6500. elif command in ["log", "logs"]:
  6501. exitcode = is_not_ok(systemctl.log_modules(*modules))
  6502. elif command in ["mask"]:
  6503. exitcode = is_not_ok(systemctl.mask_modules(*modules))
  6504. elif command in ["preset"]:
  6505. exitcode = is_not_ok(systemctl.preset_modules(*modules))
  6506. elif command in ["preset-all"]:
  6507. exitcode = is_not_ok(systemctl.preset_all_modules())
  6508. elif command in ["reap-zombies"]:
  6509. print_str(systemctl.reap_zombies_target())
  6510. elif command in ["reload"]:
  6511. exitcode = is_not_ok(systemctl.reload_modules(*modules))
  6512. elif command in ["reload-or-restart"]:
  6513. exitcode = is_not_ok(systemctl.reload_or_restart_modules(*modules))
  6514. elif command in ["reload-or-try-restart"]:
  6515. exitcode = is_not_ok(systemctl.reload_or_try_restart_modules(*modules))
  6516. elif command in ["reset-failed"]:
  6517. exitcode = is_not_ok(systemctl.reset_failed_modules(*modules))
  6518. elif command in ["restart"]:
  6519. exitcode = is_not_ok(systemctl.restart_modules(*modules))
  6520. elif command in ["set-default"]:
  6521. print_str(systemctl.set_default_modules(*modules))
  6522. elif command in ["show"]:
  6523. print_str_list(systemctl.show_modules(*modules))
  6524. elif command in ["start"]:
  6525. exitcode = is_not_ok(systemctl.start_modules(*modules))
  6526. elif command in ["status"]:
  6527. print_str(systemctl.status_modules(*modules))
  6528. elif command in ["stop"]:
  6529. exitcode = is_not_ok(systemctl.stop_modules(*modules))
  6530. elif command in ["try-restart"]:
  6531. exitcode = is_not_ok(systemctl.try_restart_modules(*modules))
  6532. elif command in ["unmask"]:
  6533. exitcode = is_not_ok(systemctl.unmask_modules(*modules))
  6534. elif command in ["version"]:
  6535. print_str_list(systemctl.version_info())
  6536. elif command in ["__cat_unit"]:
  6537. print_str(systemctl.cat_unit(*modules))
  6538. elif command in ["__get_active_unit"]:
  6539. print_str(systemctl.get_active_unit(*modules))
  6540. elif command in ["__get_description"]:
  6541. print_str(systemctl.get_description(*modules))
  6542. elif command in ["__get_status_file"]:
  6543. print_str(systemctl.get_status_file(modules[0]))
  6544. elif command in ["__get_status_pid_file", "__get_pid_file"]:
  6545. print_str(systemctl.get_status_pid_file(modules[0]))
  6546. elif command in ["__disable_unit"]:
  6547. exitcode = is_not_ok(systemctl.disable_unit(*modules))
  6548. elif command in ["__enable_unit"]:
  6549. exitcode = is_not_ok(systemctl.enable_unit(*modules))
  6550. elif command in ["__is_enabled"]:
  6551. exitcode = is_not_ok(systemctl.is_enabled(*modules))
  6552. elif command in ["__killall"]:
  6553. exitcode = is_not_ok(systemctl.killall(*modules))
  6554. elif command in ["__kill_unit"]:
  6555. exitcode = is_not_ok(systemctl.kill_unit(*modules))
  6556. elif command in ["__load_preset_files"]:
  6557. print_str_list(systemctl.load_preset_files(*modules))
  6558. elif command in ["__mask_unit"]:
  6559. exitcode = is_not_ok(systemctl.mask_unit(*modules))
  6560. elif command in ["__read_env_file"]:
  6561. print_str_list_list(list(systemctl.read_env_file(*modules)))
  6562. elif command in ["__reload_unit"]:
  6563. exitcode = is_not_ok(systemctl.reload_unit(*modules))
  6564. elif command in ["__reload_or_restart_unit"]:
  6565. exitcode = is_not_ok(systemctl.reload_or_restart_unit(*modules))
  6566. elif command in ["__reload_or_try_restart_unit"]:
  6567. exitcode = is_not_ok(systemctl.reload_or_try_restart_unit(*modules))
  6568. elif command in ["__reset_failed_unit"]:
  6569. exitcode = is_not_ok(systemctl.reset_failed_unit(*modules))
  6570. elif command in ["__restart_unit"]:
  6571. exitcode = is_not_ok(systemctl.restart_unit(*modules))
  6572. elif command in ["__start_unit"]:
  6573. exitcode = is_not_ok(systemctl.start_unit(*modules))
  6574. elif command in ["__stop_unit"]:
  6575. exitcode = is_not_ok(systemctl.stop_unit(*modules))
  6576. elif command in ["__try_restart_unit"]:
  6577. exitcode = is_not_ok(systemctl.try_restart_unit(*modules))
  6578. elif command in ["__test_start_unit"]:
  6579. systemctl.test_start_unit(*modules)
  6580. elif command in ["__unmask_unit"]:
  6581. exitcode = is_not_ok(systemctl.unmask_unit(*modules))
  6582. elif command in ["__show_unit_items"]:
  6583. print_str_list_list(list(systemctl.show_unit_items(*modules)))
  6584. else:
  6585. logg.error("Unknown operation %s", command)
  6586. return EXIT_FAILURE
  6587. #
  6588. exitcode |= systemctl.error
  6589. return exitcode
  6590. if __name__ == "__main__":
  6591. import optparse
  6592. _o = optparse.OptionParser("%prog [options] command [name...]",
  6593. epilog="use 'help' command for more information")
  6594. _o.add_option("--version", action="store_true",
  6595. help="Show package version")
  6596. _o.add_option("--system", action="store_true", default=False,
  6597. help="Connect to system manager (default)") # overrides --user
  6598. _o.add_option("--user", action="store_true", default=_user_mode,
  6599. help="Connect to user service manager")
  6600. # _o.add_option("-H", "--host", metavar="[USER@]HOST",
  6601. # help="Operate on remote host*")
  6602. # _o.add_option("-M", "--machine", metavar="CONTAINER",
  6603. # help="Operate on local container*")
  6604. _o.add_option("-t", "--type", metavar="TYPE", action="append", dest="only_type", default=_only_type,
  6605. help="List units of a particual type")
  6606. _o.add_option("--state", metavar="STATE", action="append", dest="only_state", default=_only_state,
  6607. help="List units with particular LOAD or SUB or ACTIVE state")
  6608. _o.add_option("-p", "--property", metavar="NAME", action="append", dest="only_property", default=_only_property,
  6609. help="Show only properties by this name")
  6610. _o.add_option("--what", metavar="TYPE", action="append", dest="only_what", default=_only_what,
  6611. help="Defines the service directories to be cleaned (configuration, state, cache, logs, runtime)")
  6612. _o.add_option("-a", "--all", action="store_true", dest="show_all", default=_show_all,
  6613. help="Show all loaded units/properties, including dead empty ones. To list all units installed on the system, use the 'list-unit-files' command instead")
  6614. _o.add_option("-l", "--full", action="store_true", default=_full,
  6615. help="Don't ellipsize unit names on output (never ellipsized)")
  6616. _o.add_option("--reverse", action="store_true",
  6617. help="Show reverse dependencies with 'list-dependencies' (ignored)")
  6618. _o.add_option("--job-mode", metavar="MODE",
  6619. help="Specify how to deal with already queued jobs, when queuing a new job (ignored)")
  6620. _o.add_option("--show-types", action="store_true",
  6621. help="When showing sockets, explicitly show their type (ignored)")
  6622. _o.add_option("-i", "--ignore-inhibitors", action="store_true",
  6623. help="When shutting down or sleeping, ignore inhibitors (ignored)")
  6624. _o.add_option("--kill-who", metavar="WHO",
  6625. help="Who to send signal to (ignored)")
  6626. _o.add_option("-s", "--signal", metavar="SIG",
  6627. help="Which signal to send (ignored)")
  6628. _o.add_option("--now", action="store_true", default=_now,
  6629. help="Start or stop unit in addition to enabling or disabling it")
  6630. _o.add_option("-q", "--quiet", action="store_true", default=_quiet,
  6631. help="Suppress output")
  6632. _o.add_option("--no-block", action="store_true", default=False,
  6633. help="Do not wait until operation finished (ignored)")
  6634. _o.add_option("--no-legend", action="store_true", default=_no_legend,
  6635. help="Do not print a legend (column headers and hints)")
  6636. _o.add_option("--no-wall", action="store_true", default=False,
  6637. help="Don't send wall message before halt/power-off/reboot (ignored)")
  6638. _o.add_option("--no-reload", action="store_true", default=_no_reload,
  6639. help="Don't reload daemon after en-/dis-abling unit files")
  6640. _o.add_option("--no-ask-password", action="store_true", default=_no_ask_password,
  6641. help="Do not ask for system passwords")
  6642. # _o.add_option("--global", action="store_true", dest="globally", default=_globally,
  6643. # help="Enable/disable unit files globally") # for all user logins
  6644. # _o.add_option("--runtime", action="store_true",
  6645. # help="Enable unit files only temporarily until next reboot")
  6646. _o.add_option("-f", "--force", action="store_true", default=_force,
  6647. help="When enabling unit files, override existing symblinks / When shutting down, execute action immediately")
  6648. _o.add_option("--preset-mode", metavar="TYPE", default=_preset_mode,
  6649. help="Apply only enable, only disable, or all presets [%default]")
  6650. _o.add_option("--root", metavar="PATH", default=_root,
  6651. help="Enable unit files in the specified root directory (used for alternative root prefix)")
  6652. _o.add_option("-n", "--lines", metavar="NUM",
  6653. help="Number of journal entries to show")
  6654. _o.add_option("-o", "--output", metavar="CAT",
  6655. help="change journal output mode [short, ..., cat] (ignored)")
  6656. _o.add_option("--plain", action="store_true",
  6657. help="Print unit dependencies as a list instead of a tree (ignored)")
  6658. _o.add_option("--no-pager", action="store_true",
  6659. help="Do not pipe output into pager (mostly ignored)")
  6660. _o.add_option("--no-warn", action="store_true",
  6661. help="Do not generate certain warnings (ignored)")
  6662. #
  6663. _o.add_option("-c", "--config", metavar="NAME=VAL", action="append", default=[],
  6664. help="..override internal variables (InitLoopSleep,SysInitTarget) {%default}")
  6665. _o.add_option("-e", "--extra-vars", "--environment", metavar="NAME=VAL", action="append", default=[],
  6666. help="..override settings in the syntax of 'Environment='")
  6667. _o.add_option("-v", "--verbose", action="count", default=0,
  6668. help="..increase debugging information level")
  6669. _o.add_option("-4", "--ipv4", action="store_true", default=False,
  6670. help="..only keep ipv4 localhost in /etc/hosts")
  6671. _o.add_option("-6", "--ipv6", action="store_true", default=False,
  6672. help="..only keep ipv6 localhost in /etc/hosts")
  6673. _o.add_option("-1", "--init", action="store_true", default=False,
  6674. help="..keep running as init-process (default if PID 1)")
  6675. opt, args = _o.parse_args()
  6676. logging.basicConfig(level = max(0, logging.FATAL - 10 * opt.verbose))
  6677. logg.setLevel(max(0, logging.ERROR - 10 * opt.verbose))
  6678. #
  6679. _extra_vars = opt.extra_vars
  6680. _force = opt.force
  6681. _full = opt.full
  6682. _log_lines = opt.lines
  6683. _no_pager = opt.no_pager
  6684. _no_reload = opt.no_reload
  6685. _no_legend = opt.no_legend
  6686. _no_ask_password = opt.no_ask_password
  6687. _now = opt.now
  6688. _preset_mode = opt.preset_mode
  6689. _quiet = opt.quiet
  6690. _root = opt.root
  6691. _show_all = opt.show_all
  6692. _only_state = opt.only_state
  6693. _only_type = opt.only_type
  6694. _only_property = opt.only_property
  6695. _only_what = opt.only_what
  6696. # being PID 1 (or 0) in a container will imply --init
  6697. _pid = os.getpid()
  6698. _init = opt.init or _pid in [1, 0]
  6699. _user_mode = opt.user
  6700. if os.geteuid() and _pid in [1, 0]:
  6701. _user_mode = True
  6702. if opt.system:
  6703. _user_mode = False # override --user
  6704. #
  6705. for setting in opt.config:
  6706. nam, val = setting, "1"
  6707. if "=" in setting:
  6708. nam, val = setting.split("=", 1)
  6709. elif nam.startswith("no-") or nam.startswith("NO-"):
  6710. nam, val = nam[3:], "0"
  6711. elif nam.startswith("No") or nam.startswith("NO"):
  6712. nam, val = nam[2:], "0"
  6713. if nam in globals():
  6714. old = globals()[nam]
  6715. if old is False or old is True:
  6716. logg.debug("yes %s=%s", nam, val)
  6717. globals()[nam] = (val in ("true", "True", "TRUE", "yes", "y", "Y", "YES", "1"))
  6718. logg.debug("... _show_all=%s", _show_all)
  6719. elif isinstance(old, float):
  6720. logg.debug("num %s=%s", nam, val)
  6721. globals()[nam] = float(val)
  6722. logg.debug("... MinimumYield=%s", MinimumYield)
  6723. elif isinstance(old, int):
  6724. logg.debug("int %s=%s", nam, val)
  6725. globals()[nam] = int(val)
  6726. logg.debug("... InitLoopSleep=%s", InitLoopSleep)
  6727. elif isinstance(old, basestring):
  6728. logg.debug("str %s=%s", nam, val)
  6729. globals()[nam] = val.strip()
  6730. logg.debug("... SysInitTarget=%s", SysInitTarget)
  6731. elif isinstance(old, list):
  6732. logg.debug("str %s+=[%s]", nam, val)
  6733. globals()[nam] += val.strip().split(",")
  6734. logg.debug("... _extra_vars=%s", _extra_vars)
  6735. else:
  6736. logg.warning("(ignored) unknown target type -c '%s' : %s", nam, type(old))
  6737. else:
  6738. logg.warning("(ignored) unknown target config -c '%s' : no such variable", nam)
  6739. #
  6740. systemctl_debug_log = os_path(_root, expand_path(SYSTEMCTL_DEBUG_LOG, not _user_mode))
  6741. systemctl_extra_log = os_path(_root, expand_path(SYSTEMCTL_EXTRA_LOG, not _user_mode))
  6742. if os.access(systemctl_extra_log, os.W_OK):
  6743. loggfile = logging.FileHandler(systemctl_extra_log)
  6744. loggfile.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
  6745. logg.addHandler(loggfile)
  6746. logg.setLevel(max(0, logging.INFO - 10 * opt.verbose))
  6747. if os.access(systemctl_debug_log, os.W_OK):
  6748. loggfile = logging.FileHandler(systemctl_debug_log)
  6749. loggfile.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(message)s"))
  6750. logg.addHandler(loggfile)
  6751. logg.setLevel(logging.DEBUG)
  6752. #
  6753. print_begin(sys.argv, args)
  6754. #
  6755. systemctl = Systemctl()
  6756. if opt.version:
  6757. args = ["version"]
  6758. if not args:
  6759. if _init:
  6760. args = ["default"]
  6761. else:
  6762. args = ["list-units"]
  6763. print_begin2(args)
  6764. command = args[0]
  6765. modules = args[1:]
  6766. try:
  6767. modules.remove("service")
  6768. except ValueError:
  6769. pass
  6770. if opt.ipv4:
  6771. systemctl.force_ipv4()
  6772. elif opt.ipv6:
  6773. systemctl.force_ipv6()
  6774. sys.exit(run(command, *modules))