/
systemd_service.py
1495 lines (1203 loc) · 46.8 KB
/
systemd_service.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Provides the service module for systemd
.. versionadded:: 0.10.0
.. important::
If you feel that Salt should be using this module to manage services on a
minion, and it is using a different module (or gives an error similar to
*'service.start' is not available*), see :ref:`here
<module-provider-override>`.
.. important::
This is an implementation of virtual 'service' module. As such, you must
call it under the name 'service' and NOT 'systemd'. You can see that also
in the examples below.
"""
import errno
import fnmatch
import glob
import logging
import os
import re
import shlex
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.stringutils
import salt.utils.systemd
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
__func_alias__ = {
"reload_": "reload",
"unmask_": "unmask",
}
SYSTEM_CONFIG_PATHS = ("/lib/systemd/system", "/usr/lib/systemd/system")
LOCAL_CONFIG_PATH = "/etc/systemd/system"
INITSCRIPT_PATH = "/etc/init.d"
VALID_UNIT_TYPES = (
"service",
"socket",
"device",
"mount",
"automount",
"swap",
"target",
"path",
"timer",
)
# Define the module's virtual name
__virtualname__ = "service"
def __virtual__():
"""
Only work on systems that have been booted with systemd
"""
is_linux = __grains__.get("kernel") == "Linux"
is_booted = salt.utils.systemd.booted(__context__)
is_offline = salt.utils.systemd.offline(__context__)
if is_linux and (is_booted or is_offline):
return __virtualname__
return (
False,
"The systemd execution module failed to load: only available on Linux "
"systems which have been booted with systemd.",
)
def _root(path, root):
"""
Relocate an absolute path to a new root directory.
"""
if root:
return os.path.join(root, os.path.relpath(path, os.path.sep))
else:
return path
def _canonical_unit_name(name):
"""
Build a canonical unit name treating unit names without one
of the valid suffixes as a service.
"""
if not isinstance(name, str):
name = str(name)
if any(name.endswith(suffix) for suffix in VALID_UNIT_TYPES):
return name
return "%s.service" % name
def _check_available(name):
"""
Returns boolean telling whether or not the named service is available
"""
if offline():
raise CommandExecutionError(
"Cannot run in offline mode. Failed to get information on unit '%s'" % name
)
_status = _systemctl_status(name)
sd_version = salt.utils.systemd.version(__context__)
if sd_version is not None and sd_version >= 231:
# systemd 231 changed the output of "systemctl status" for unknown
# services, and also made it return an exit status of 4. If we are on
# a new enough version, check the retcode, otherwise fall back to
# parsing the "systemctl status" output.
# See: https://github.com/systemd/systemd/pull/3385
# Also: https://github.com/systemd/systemd/commit/3dced37
return 0 <= _status["retcode"] < 4
out = _status["stdout"].lower()
if "could not be found" in out:
# Catch cases where the systemd version is < 231 but the return code
# and output changes have been backported (e.g. RHEL 7.3).
return False
for line in salt.utils.itertools.split(out, "\n"):
match = re.match(r"\s+loaded:\s+(\S+)", line)
if match:
ret = match.group(1) != "not-found"
break
else:
raise CommandExecutionError("Failed to get information on unit '%s'" % name)
return ret
def _check_for_unit_changes(name):
"""
Check for modified/updated unit files, and run a daemon-reload if any are
found.
"""
contextkey = f"systemd._check_for_unit_changes.{name}"
if contextkey not in __context__:
if _untracked_custom_unit_found(name) or _unit_file_changed(name):
systemctl_reload()
# Set context key to avoid repeating this check
__context__[contextkey] = True
def _check_unmask(name, unmask, unmask_runtime, root=None):
"""
Common code for conditionally removing masks before making changes to a
service's state.
"""
if unmask:
unmask_(name, runtime=False, root=root)
if unmask_runtime:
unmask_(name, runtime=True, root=root)
def _clear_context():
"""
Remove context
"""
# Using list() here because modifying a dictionary during iteration will
# raise a RuntimeError.
for key in list(__context__):
try:
if key.startswith("systemd._systemctl_status."):
__context__.pop(key)
except AttributeError:
continue
def _default_runlevel():
"""
Try to figure out the default runlevel. It is kept in
/etc/init/rc-sysinit.conf, but can be overridden with entries
in /etc/inittab, or via the kernel command-line at boot
"""
# Try to get the "main" default. If this fails, throw up our
# hands and just guess "2", because things are horribly broken
try:
with salt.utils.files.fopen("/etc/init/rc-sysinit.conf") as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith("env DEFAULT_RUNLEVEL"):
runlevel = line.split("=")[-1].strip()
except Exception: # pylint: disable=broad-except
return "2"
# Look for an optional "legacy" override in /etc/inittab
try:
with salt.utils.files.fopen("/etc/inittab") as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
if not line.startswith("#") and "initdefault" in line:
runlevel = line.split(":")[1]
except Exception: # pylint: disable=broad-except
pass
# The default runlevel can also be set via the kernel command-line.
try:
valid_strings = {"0", "1", "2", "3", "4", "5", "6", "s", "S", "-s", "single"}
with salt.utils.files.fopen("/proc/cmdline") as fp_:
for line in fp_:
line = salt.utils.stringutils.to_unicode(line)
for arg in line.strip().split():
if arg in valid_strings:
runlevel = arg
break
except Exception: # pylint: disable=broad-except
pass
return runlevel
def _get_systemd_services(root):
"""
Use os.listdir() to get all the unit files
"""
ret = set()
for path in SYSTEM_CONFIG_PATHS + (LOCAL_CONFIG_PATH,):
# Make sure user has access to the path, and if the path is a
# link it's likely that another entry in SYSTEM_CONFIG_PATHS
# or LOCAL_CONFIG_PATH points to it, so we can ignore it.
path = _root(path, root)
if os.access(path, os.R_OK) and not os.path.islink(path):
for fullname in os.listdir(path):
try:
unit_name, unit_type = fullname.rsplit(".", 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == "service" else fullname)
return ret
def _get_sysv_services(root, systemd_services=None):
"""
Use os.listdir() and os.access() to get all the initscripts
"""
initscript_path = _root(INITSCRIPT_PATH, root)
try:
sysv_services = os.listdir(initscript_path)
except OSError as exc:
if exc.errno == errno.ENOENT:
pass
elif exc.errno == errno.EACCES:
log.error(
"Unable to check sysvinit scripts, permission denied to %s",
initscript_path,
)
else:
log.error(
"Error %d encountered trying to check sysvinit scripts: %s",
exc.errno,
exc.strerror,
)
return []
if systemd_services is None:
systemd_services = _get_systemd_services(root)
ret = []
for sysv_service in sysv_services:
if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):
if sysv_service in systemd_services:
log.debug(
"sysvinit script '%s' found, but systemd unit "
"'%s.service' already exists",
sysv_service,
sysv_service,
)
continue
ret.append(sysv_service)
return ret
def _get_service_exec():
"""
Returns the path to the sysv service manager (either update-rc.d or
chkconfig)
"""
contextkey = "systemd._get_service_exec"
if contextkey not in __context__:
executables = ("update-rc.d", "chkconfig")
for executable in executables:
service_exec = salt.utils.path.which(executable)
if service_exec is not None:
break
else:
raise CommandExecutionError(
"Unable to find sysv service manager (tried {})".format(
", ".join(executables)
)
)
__context__[contextkey] = service_exec
return __context__[contextkey]
def _runlevel():
"""
Return the current runlevel
"""
contextkey = "systemd._runlevel"
if contextkey in __context__:
return __context__[contextkey]
out = __salt__["cmd.run"](
salt.utils.path.which("runlevel"), python_shell=False, ignore_retcode=True
)
try:
ret = out.split()[1]
except IndexError:
# The runlevel is unknown, return the default
ret = _default_runlevel()
__context__[contextkey] = ret
return ret
def _strip_scope(msg):
"""
Strip unnecessary message about running the command with --scope from
stderr so that we can raise an exception with the remaining stderr text.
"""
ret = []
for line in msg.splitlines():
if not line.endswith(".scope"):
ret.append(line)
return "\n".join(ret).strip()
def _systemctl_cmd(
action, name=None, systemd_scope=False, no_block=False, root=None, extra_args=None
):
"""
Build a systemctl command line. Treat unit names without one
of the valid suffixes as a service.
"""
ret = []
if (
systemd_scope
and salt.utils.systemd.has_scope(__context__)
and __salt__["config.get"]("systemd.scope", True)
):
ret.extend([salt.utils.path.which("systemd-run"), "--scope"])
ret.append(salt.utils.path.which("systemctl"))
if no_block:
ret.append("--no-block")
if root:
ret.extend(["--root", root])
if isinstance(action, str):
action = shlex.split(action)
ret.extend(action)
if name is not None:
ret.append(_canonical_unit_name(name))
if "status" in ret:
ret.extend(["-n", "0"])
if isinstance(extra_args, list):
ret.extend(extra_args)
return ret
def _systemctl_status(name):
"""
Helper function which leverages __context__ to keep from running 'systemctl
status' more than once.
"""
contextkey = "systemd._systemctl_status.%s" % name
if contextkey in __context__:
return __context__[contextkey]
__context__[contextkey] = __salt__["cmd.run_all"](
_systemctl_cmd("status", name),
python_shell=False,
redirect_stderr=True,
ignore_retcode=True,
)
return __context__[contextkey]
def _sysv_enabled(name, root):
"""
A System-V style service is assumed disabled if the "startup" symlink
(starts with "S") to its script is found in /etc/init.d in the current
runlevel.
"""
# Find exact match (disambiguate matches like "S01anacron" for cron)
rc = _root(f"/etc/rc{_runlevel()}.d/S*{name}", root)
for match in glob.glob(rc):
if re.match(r"S\d{,2}%s" % name, os.path.basename(match)):
return True
return False
def _untracked_custom_unit_found(name, root=None):
"""
If the passed service name is not available, but a unit file exist in
/etc/systemd/system, return True. Otherwise, return False.
"""
system = _root("/etc/systemd/system", root)
unit_path = os.path.join(system, _canonical_unit_name(name))
return os.access(unit_path, os.R_OK) and not _check_available(name)
def _unit_file_changed(name):
"""
Returns True if systemctl reports that the unit file has changed, otherwise
returns False.
"""
status = _systemctl_status(name)["stdout"].lower()
return "'systemctl daemon-reload'" in status
def systemctl_reload():
"""
.. versionadded:: 0.15.0
Reloads systemctl, an action needed whenever unit files are updated.
CLI Example:
.. code-block:: bash
salt '*' service.systemctl_reload
"""
out = __salt__["cmd.run_all"](
_systemctl_cmd("--system daemon-reload"),
python_shell=False,
redirect_stderr=True,
)
if out["retcode"] != 0:
raise CommandExecutionError(
"Problem performing systemctl daemon-reload: %s" % out["stdout"]
)
_clear_context()
return True
def get_running():
"""
Return a list of all running services, so far as systemd is concerned
CLI Example:
.. code-block:: bash
salt '*' service.get_running
"""
ret = set()
# Get running systemd units
out = __salt__["cmd.run"](
_systemctl_cmd("--full --no-legend --no-pager"),
python_shell=False,
ignore_retcode=True,
)
for line in salt.utils.itertools.split(out, "\n"):
try:
comps = line.strip().split()
fullname = comps[0]
if len(comps) > 3:
active_state = comps[3]
except ValueError as exc:
log.error(exc)
continue
else:
if active_state != "running":
continue
try:
unit_name, unit_type = fullname.rsplit(".", 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == "service" else fullname)
return sorted(ret)
def get_enabled(root=None):
"""
Return a list of all enabled services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
"""
ret = set()
# Get enabled systemd units. Can't use --state=enabled here because it's
# not present until systemd 216.
out = __salt__["cmd.run"](
_systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
python_shell=False,
ignore_retcode=True,
)
for line in salt.utils.itertools.split(out, "\n"):
try:
fullname, unit_state = line.strip().split()[:2]
except ValueError:
continue
else:
# Arch Linux adds a third column, which we want to ignore
if unit_state.split()[0] != "enabled":
continue
try:
unit_name, unit_type = fullname.rsplit(".", 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == "service" else fullname)
# Add in any sysvinit services that are enabled
ret.update({x for x in _get_sysv_services(root) if _sysv_enabled(x, root)})
return sorted(ret)
def get_disabled(root=None):
"""
Return a list of all disabled services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
"""
ret = set()
# Get disabled systemd units. Can't use --state=disabled here because it's
# not present until systemd 216.
out = __salt__["cmd.run"](
_systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
python_shell=False,
ignore_retcode=True,
)
for line in salt.utils.itertools.split(out, "\n"):
try:
fullname, unit_state = line.strip().split()[:2]
except ValueError:
continue
else:
# Arch Linux adds a third column, which we want to ignore
if unit_state.split()[0] != "disabled":
continue
try:
unit_name, unit_type = fullname.rsplit(".", 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == "service" else fullname)
# Add in any sysvinit services that are disabled
ret.update({x for x in _get_sysv_services(root) if not _sysv_enabled(x, root)})
return sorted(ret)
def get_static(root=None):
"""
.. versionadded:: 2015.8.5
Return a list of all static services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_static
"""
ret = set()
# Get static systemd units. Can't use --state=static here because it's
# not present until systemd 216.
out = __salt__["cmd.run"](
_systemctl_cmd("--full --no-legend --no-pager list-unit-files", root=root),
python_shell=False,
ignore_retcode=True,
)
for line in salt.utils.itertools.split(out, "\n"):
try:
fullname, unit_state = line.strip().split()[:2]
except ValueError:
continue
else:
if unit_state != "static":
continue
try:
unit_name, unit_type = fullname.rsplit(".", 1)
except ValueError:
continue
if unit_type in VALID_UNIT_TYPES:
ret.add(unit_name if unit_type == "service" else fullname)
# sysvinit services cannot be static
return sorted(ret)
def get_all(root=None):
"""
Return a list of all available services
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.get_all
"""
ret = _get_systemd_services(root)
ret.update(set(_get_sysv_services(root, systemd_services=ret)))
return sorted(ret)
def available(name):
"""
.. versionadded:: 0.10.4
Check that the given service is available taking into account template
units.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
"""
_check_for_unit_changes(name)
return _check_available(name)
def missing(name):
"""
.. versionadded:: 2014.1.0
The inverse of :py:func:`service.available
<salt.modules.systemd.available>`. Returns ``True`` if the specified
service is not available, otherwise returns ``False``.
CLI Example:
.. code-block:: bash
salt '*' service.missing sshd
"""
return not available(name)
def unmask_(name, runtime=False, root=None):
"""
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Unmask the specified service with systemd
runtime : False
Set to ``True`` to unmask this service only until the next reboot
.. versionadded:: 2017.7.0
In previous versions, this function would remove whichever mask was
identified by running ``systemctl is-enabled`` on the service.
However, since it is possible to both have both indefinite and
runtime masks on a service simultaneously, this function now
removes a runtime mask only when this argument is set to ``True``,
and otherwise removes an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.unmask foo
salt '*' service.unmask foo runtime=True
"""
_check_for_unit_changes(name)
if not masked(name, runtime, root=root):
log.debug("Service '%s' is not %smasked", name, "runtime-" if runtime else "")
return True
cmd = "unmask --runtime" if runtime else "unmask"
out = __salt__["cmd.run_all"](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True,
)
if out["retcode"] != 0:
raise CommandExecutionError("Failed to unmask service '%s'" % name)
return True
def mask(name, runtime=False, root=None):
"""
.. versionadded:: 2015.5.0
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Mask the specified service with systemd
runtime : False
Set to ``True`` to mask this service only until the next reboot
.. versionadded:: 2015.8.5
root
Enable/disable/mask unit files in the specified root directory
CLI Example:
.. code-block:: bash
salt '*' service.mask foo
salt '*' service.mask foo runtime=True
"""
_check_for_unit_changes(name)
cmd = "mask --runtime" if runtime else "mask"
out = __salt__["cmd.run_all"](
_systemctl_cmd(cmd, name, systemd_scope=True, root=root),
python_shell=False,
redirect_stderr=True,
)
if out["retcode"] != 0:
raise CommandExecutionError(
"Failed to mask service '%s'" % name, info=out["stdout"]
)
return True
def masked(name, runtime=False, root=None):
"""
.. versionadded:: 2015.8.0
.. versionchanged:: 2015.8.5
The return data for this function has changed. If the service is
masked, the return value will now be the output of the ``systemctl
is-enabled`` command (so that a persistent mask can be distinguished
from a runtime mask). If the service is not masked, then ``False`` will
be returned.
.. versionchanged:: 2017.7.0
This function now returns a boolean telling the user whether a mask
specified by the new ``runtime`` argument is set. If ``runtime`` is
``False``, this function will return ``True`` if an indefinite mask is
set for the named service (otherwise ``False`` will be returned). If
``runtime`` is ``False``, this function will return ``True`` if a
runtime mask is set, otherwise ``False``.
Check whether or not a service is masked
runtime : False
Set to ``True`` to check for a runtime mask
.. versionadded:: 2017.7.0
In previous versions, this function would simply return the output
of ``systemctl is-enabled`` when the service was found to be
masked. However, since it is possible to both have both indefinite
and runtime masks on a service simultaneously, this function now
only checks for runtime masks if this argument is set to ``True``.
Otherwise, it will check for an indefinite mask.
root
Enable/disable/mask unit files in the specified root directory
CLI Examples:
.. code-block:: bash
salt '*' service.masked foo
salt '*' service.masked foo runtime=True
"""
_check_for_unit_changes(name)
root_dir = _root("/run" if runtime else "/etc", root)
link_path = os.path.join(root_dir, "systemd", "system", _canonical_unit_name(name))
try:
return os.readlink(link_path) == "/dev/null"
except OSError as exc:
if exc.errno == errno.ENOENT:
log.trace(
"Path %s does not exist. This is normal if service '%s' is "
"not masked or does not exist.",
link_path,
name,
)
elif exc.errno == errno.EINVAL:
log.error(
"Failed to check mask status for service %s. Path %s is a "
"file, not a symlink. This could be caused by changes in "
"systemd and is probably a bug in Salt. Please report this "
"to the developers.",
name,
link_path,
)
return False
def start(name, no_block=False, unmask=False, unmask_runtime=False):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Start the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to start
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
starting. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to start the
service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
starting. This behavior is no longer the default.
CLI Example:
.. code-block:: bash
salt '*' service.start <service name>
"""
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime)
ret = __salt__["cmd.run_all"](
_systemctl_cmd("start", name, systemd_scope=True, no_block=no_block),
python_shell=False,
)
if ret["retcode"] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret["stderr"]))
return True
def stop(name, no_block=False):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Stop the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' service.stop <service name>
"""
_check_for_unit_changes(name)
# Using cmd.run_all instead of cmd.retcode here to make unit tests easier
return (
__salt__["cmd.run_all"](
_systemctl_cmd("stop", name, systemd_scope=True, no_block=no_block),
python_shell=False,
)["retcode"]
== 0
)
def restart(name, no_block=False, unmask=False, unmask_runtime=False):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Restart the specified service with systemd
no_block : False
Set to ``True`` to start the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
restart the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to restart
the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
restarting. This behavior is no longer the default.
CLI Example:
.. code-block:: bash
salt '*' service.restart <service name>
"""
_check_for_unit_changes(name)
_check_unmask(name, unmask, unmask_runtime)
ret = __salt__["cmd.run_all"](
_systemctl_cmd("restart", name, systemd_scope=True, no_block=no_block),
python_shell=False,
)
if ret["retcode"] != 0:
# Instead of returning a bool, raise an exception so that we can
# include the error message in the return data. This helps give more
# information to the user in instances where the service is masked.
raise CommandExecutionError(_strip_scope(ret["stderr"]))
return True
def reload_(name, no_block=False, unmask=False, unmask_runtime=False):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands run by this function from the ``salt-minion`` daemon's
control group. This is done to avoid a race condition in cases where
the ``salt-minion`` service is restarted while a service is being
modified. If desired, usage of `systemd-run(1)`_ can be suppressed by
setting a :mod:`config option <salt.modules.config.get>` called
``systemd.scope``, with a value of ``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
Reload the specified service with systemd
no_block : False
Set to ``True`` to reload the service using ``--no-block``.
.. versionadded:: 2017.7.0
unmask : False
Set to ``True`` to remove an indefinite mask before attempting to
reload the service.
.. versionadded:: 2017.7.0
In previous releases, Salt would simply unmask a service before
reloading. This behavior is no longer the default.
unmask_runtime : False
Set to ``True`` to remove a runtime mask before attempting to reload