Debian Codegraph @

lib/ansible/modules/systemd_service.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2016, Brian Coca <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = """
10 module: systemd_service
11 author:
12 - Ansible Core Team
13 version_added: "2.2"
14 short_description: Manage systemd units
15 description:
16 - Controls systemd units (services, timers, and so on) on remote hosts.
17 - M(ansible.builtin.systemd) is renamed to M(ansible.builtin.systemd_service) to better reflect the scope of the module.
18 M(ansible.builtin.systemd) is kept as an alias for backward compatibility.
19 options:
20 name:
21 description:
22 - Name of the unit. This parameter takes the name of exactly one unit to work with.
23 - When no extension is given, it is implied to a C(.service) as systemd.
24 - When using in a chroot environment you always need to specify the name of the unit with the extension. For example, C(crond.service).
25 type: str
26 aliases: [ service, unit ]
27 state:
28 description:
29 - V(started)/V(stopped) are idempotent actions that will not run commands unless necessary.
30 V(restarted) will always bounce the unit.
31 V(reloaded) will always reload and if the service is not running at the moment of the reload, it is started.
32 - If set, requires O(name).
33 type: str
34 choices: [ reloaded, restarted, started, stopped ]
35 enabled:
36 description:
37 - Whether the unit should start on boot. At least one of O(state) or O(enabled) are required.
38 - If set, requires O(name).
39 type: bool
40 force:
41 description:
42 - Whether to override existing symlinks.
43 type: bool
44 version_added: 2.6
45 masked:
46 description:
47 - Whether the unit should be masked or not. A masked unit is impossible to start.
48 - If set, requires O(name).
49 type: bool
50 daemon_reload:
51 description:
52 - Run C(daemon-reload) before doing any other operations, to make sure systemd has read any changes.
53 - When set to V(true), runs C(daemon-reload) even if the module does not start or stop anything.
54 type: bool
55 default: no
56 aliases: [ daemon-reload ]
57 daemon_reexec:
58 description:
59 - Run daemon_reexec command before doing any other operations, the systemd manager will serialize the manager state.
60 type: bool
61 default: no
62 aliases: [ daemon-reexec ]
63 version_added: "2.8"
64 scope:
65 description:
66 - Run C(systemctl) within a given service manager scope, either as the default system scope V(system),
67 the current user's scope V(user), or the scope of all users V(global).
68 - "For systemd to work with V(user), the executing user must have its own instance of dbus started and accessible (systemd requirement)."
69 - "The user dbus process is normally started during normal login, but not during the run of Ansible tasks.
70 Otherwise you will probably get a 'Failed to connect to bus: no such file or directory' error."
71 - The user must have access, normally given via setting the C(XDG_RUNTIME_DIR) variable, see the example below.
72
73 type: str
74 choices: [ system, user, global ]
75 default: system
76 version_added: "2.7"
77 no_block:
78 description:
79 - Do not synchronously wait for the requested operation to finish.
80 Enqueued job will continue without Ansible blocking on its completion.
81 type: bool
82 default: no
83 version_added: "2.3"
84 extends_documentation_fragment: action_common_attributes
85 attributes:
86 check_mode:
87 support: full
88 diff_mode:
89 support: none
90 platform:
91 platforms: posix
92 notes:
93 - O(state), O(enabled), O(masked) requires O(name).
94 - Before 2.4 you always required O(name).
95 - Globs are not supported in name, in other words, C(postgres*.service).
96 - The service names might vary by specific OS/distribution.
97 - The order of execution when having multiple properties is to first enable/disable, then mask/unmask and then deal with the service state.
98 It has been reported that C(systemctl) can behave differently depending on the order of operations if you do the same manually.
99 requirements:
100 - A system managed by systemd.
101 """
102
103 EXAMPLES = """
104 - name: Make sure a service unit is running
105 ansible.builtin.systemd_service:
106 state: started
107 name: httpd
108
109 - name: Stop service cron on debian, if running
110 ansible.builtin.systemd_service:
111 name: cron
112 state: stopped
113
114 - name: Restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
115 ansible.builtin.systemd_service:
116 state: restarted
117 daemon_reload: true
118 name: crond
119
120 - name: Reload service httpd, in all cases
121 ansible.builtin.systemd_service:
122 name: httpd.service
123 state: reloaded
124
125 - name: Enable service httpd and ensure it is not masked
126 ansible.builtin.systemd_service:
127 name: httpd
128 enabled: true
129 masked: no
130
131 - name: Enable a timer unit for dnf-automatic
132 ansible.builtin.systemd_service:
133 name: dnf-automatic.timer
134 state: started
135 enabled: true
136
137 - name: Just force systemd to reread configs (2.4 and above)
138 ansible.builtin.systemd_service:
139 daemon_reload: true
140
141 - name: Just force systemd to re-execute itself (2.8 and above)
142 ansible.builtin.systemd_service:
143 daemon_reexec: true
144
145 - name: Run a user service when XDG_RUNTIME_DIR is not set on remote login
146 ansible.builtin.systemd_service:
147 name: myservice
148 state: started
149 scope: user
150 environment:
151 XDG_RUNTIME_DIR: "/run/user/{{ myuid }}"
152 """
153
154 RETURN = """
155 status:
156 description: A dictionary with the key=value pairs returned from C(systemctl show).
157 returned: success
158 type: dict
159 sample: {
160 "ActiveEnterTimestamp": "Sun 2016-05-15 18:28:49 EDT",
161 "ActiveEnterTimestampMonotonic": "8135942",
162 "ActiveExitTimestampMonotonic": "0",
163 "ActiveState": "active",
164 "After": "auditd.service systemd-user-sessions.service time-sync.target systemd-journald.socket basic.target system.slice",
165 "AllowIsolate": "no",
166 "Before": "shutdown.target multi-user.target",
167 "BlockIOAccounting": "no",
168 "BlockIOWeight": "1000",
169 "CPUAccounting": "no",
170 "CPUSchedulingPolicy": "0",
171 "CPUSchedulingPriority": "0",
172 "CPUSchedulingResetOnFork": "no",
173 "CPUShares": "1024",
174 "CanIsolate": "no",
175 "CanReload": "yes",
176 "CanStart": "yes",
177 "CanStop": "yes",
178 "CapabilityBoundingSet": "18446744073709551615",
179 "ConditionResult": "yes",
180 "ConditionTimestamp": "Sun 2016-05-15 18:28:49 EDT",
181 "ConditionTimestampMonotonic": "7902742",
182 "Conflicts": "shutdown.target",
183 "ControlGroup": "/system.slice/crond.service",
184 "ControlPID": "0",
185 "DefaultDependencies": "yes",
186 "Delegate": "no",
187 "Description": "Command Scheduler",
188 "DevicePolicy": "auto",
189 "EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)",
190 "ExecMainCode": "0",
191 "ExecMainExitTimestampMonotonic": "0",
192 "ExecMainPID": "595",
193 "ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT",
194 "ExecMainStartTimestampMonotonic": "8134990",
195 "ExecMainStatus": "0",
196 "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
197 "ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }",
198 "FragmentPath": "/usr/lib/systemd/system/crond.service",
199 "GuessMainPID": "yes",
200 "IOScheduling": "0",
201 "Id": "crond.service",
202 "IgnoreOnIsolate": "no",
203 "IgnoreOnSnapshot": "no",
204 "IgnoreSIGPIPE": "yes",
205 "InactiveEnterTimestampMonotonic": "0",
206 "InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT",
207 "InactiveExitTimestampMonotonic": "8135942",
208 "JobTimeoutUSec": "0",
209 "KillMode": "process",
210 "KillSignal": "15",
211 "LimitAS": "18446744073709551615",
212 "LimitCORE": "18446744073709551615",
213 "LimitCPU": "18446744073709551615",
214 "LimitDATA": "18446744073709551615",
215 "LimitFSIZE": "18446744073709551615",
216 "LimitLOCKS": "18446744073709551615",
217 "LimitMEMLOCK": "65536",
218 "LimitMSGQUEUE": "819200",
219 "LimitNICE": "0",
220 "LimitNOFILE": "4096",
221 "LimitNPROC": "3902",
222 "LimitRSS": "18446744073709551615",
223 "LimitRTPRIO": "0",
224 "LimitRTTIME": "18446744073709551615",
225 "LimitSIGPENDING": "3902",
226 "LimitSTACK": "18446744073709551615",
227 "LoadState": "loaded",
228 "MainPID": "595",
229 "MemoryAccounting": "no",
230 "MemoryLimit": "18446744073709551615",
231 "MountFlags": "0",
232 "Names": "crond.service",
233 "NeedDaemonReload": "no",
234 "Nice": "0",
235 "NoNewPrivileges": "no",
236 "NonBlocking": "no",
237 "NotifyAccess": "none",
238 "OOMScoreAdjust": "0",
239 "OnFailureIsolate": "no",
240 "PermissionsStartOnly": "no",
241 "PrivateNetwork": "no",
242 "PrivateTmp": "no",
243 "RefuseManualStart": "no",
244 "RefuseManualStop": "no",
245 "RemainAfterExit": "no",
246 "Requires": "basic.target",
247 "Restart": "no",
248 "RestartUSec": "100ms",
249 "Result": "success",
250 "RootDirectoryStartOnly": "no",
251 "SameProcessGroup": "no",
252 "SecureBits": "0",
253 "SendSIGHUP": "no",
254 "SendSIGKILL": "yes",
255 "Slice": "system.slice",
256 "StandardError": "inherit",
257 "StandardInput": "null",
258 "StandardOutput": "journal",
259 "StartLimitAction": "none",
260 "StartLimitBurst": "5",
261 "StartLimitInterval": "10000000",
262 "StatusErrno": "0",
263 "StopWhenUnneeded": "no",
264 "SubState": "running",
265 "SyslogLevelPrefix": "yes",
266 "SyslogPriority": "30",
267 "TTYReset": "no",
268 "TTYVHangup": "no",
269 "TTYVTDisallocate": "no",
270 "TimeoutStartUSec": "1min 30s",
271 "TimeoutStopUSec": "1min 30s",
272 "TimerSlackNSec": "50000",
273 "Transient": "no",
274 "Type": "simple",
275 "UMask": "0022",
276 "UnitFileState": "enabled",
277 "WantedBy": "multi-user.target",
278 "Wants": "system.slice",
279 "WatchdogTimestampMonotonic": "0",
280 "WatchdogUSec": "0",
281 }
282 """ # NOQA
283
284 import os
285
286 from ansible.module_utils.basic import AnsibleModule
287 from ansible.module_utils.facts.system.chroot import is_chroot
288 from ansible.module_utils.service import sysv_exists, sysv_is_enabled, fail_if_missing
289 from ansible.module_utils.common.text.converters import to_native
290
291
292 def is_running_service(service_status):
293 return service_status['ActiveState'] in set(['active', 'activating'])
294
295
296 def is_deactivating_service(service_status):
297 return service_status['ActiveState'] in set(['deactivating'])
298
299
300 def request_was_ignored(out):
301 return '=' not in out and ('ignoring request' in out or 'ignoring command' in out)
302
303
304 def parse_systemctl_show(lines):
305 # The output of 'systemctl show' can contain values that span multiple lines. At first glance it
306 # appears that such values are always surrounded by {}, so the previous version of this code
307 # assumed that any value starting with { was a multi-line value; it would then consume lines
308 # until it saw a line that ended with }. However, it is possible to have a single-line value
309 # that starts with { but does not end with } (this could happen in the value for Description=,
310 # for example), and the previous version of this code would then consume all remaining lines as
311 # part of that value. Cryptically, this would lead to Ansible reporting that the service file
312 # couldn't be found.
313 #
314 # To avoid this issue, the following code only accepts multi-line values for keys whose names
315 # start with Exec (e.g., ExecStart=), since these are the only keys whose values are known to
316 # span multiple lines.
317 parsed = {}
318 multival = []
319 k = None
320 for line in lines:
321 if k is None:
322 if '=' in line:
323 k, v = line.split('=', 1)
324 if k.startswith('Exec') and v.lstrip().startswith('{'):
325 if not v.rstrip().endswith('}'):
326 multival.append(v)
327 continue
328 parsed[k] = v.strip()
329 k = None
330 else:
331 multival.append(line)
332 if line.rstrip().endswith('}'):
333 parsed[k] = '\n'.join(multival).strip()
334 multival = []
335 k = None
336 return parsed
337
338
339 # ===========================================
340 # Main control flow
341
342 def main():
343 # initialize
344 module = AnsibleModule(
345 argument_spec=dict(
346 name=dict(type='str', aliases=['service', 'unit']),
347 state=dict(type='str', choices=['reloaded', 'restarted', 'started', 'stopped']),
348 enabled=dict(type='bool'),
349 force=dict(type='bool'),
350 masked=dict(type='bool'),
351 daemon_reload=dict(type='bool', default=False, aliases=['daemon-reload']),
352 daemon_reexec=dict(type='bool', default=False, aliases=['daemon-reexec']),
353 scope=dict(type='str', default='system', choices=['system', 'user', 'global']),
354 no_block=dict(type='bool', default=False),
355 ),
356 supports_check_mode=True,
357 required_one_of=[['state', 'enabled', 'masked', 'daemon_reload', 'daemon_reexec']],
358 required_by=dict(
359 state=('name', ),
360 enabled=('name', ),
361 masked=('name', ),
362 ),
363 )
364
365 unit = module.params['name']
366 if unit is not None:
367 for globpattern in (r"*", r"?", r"["):
368 if globpattern in unit:
369 module.fail_json(msg="This module does not currently support using glob patterns, found '%s' in service name: %s" % (globpattern, unit))
370
371 systemctl = module.get_bin_path('systemctl', True)
372
373 if os.getenv('XDG_RUNTIME_DIR') is None:
374 os.environ['XDG_RUNTIME_DIR'] = '/run/user/%s' % os.geteuid()
375
376 # Set CLI options depending on params
377 # if scope is 'system' or None, we can ignore as there is no extra switch.
378 # The other choices match the corresponding switch
379 if module.params['scope'] != 'system':
380 systemctl += " --%s" % module.params['scope']
381
382 if module.params['no_block']:
383 systemctl += " --no-block"
384
385 if module.params['force']:
386 systemctl += " --force"
387
388 rc = 0
389 out = err = ''
390 result = dict(
391 name=unit,
392 changed=False,
393 status=dict(),
394 )
395
396 # Run daemon-reload first, if requested
397 if module.params['daemon_reload'] and not module.check_mode:
398 (rc, out, err) = module.run_command("%s daemon-reload" % (systemctl))
399 if rc != 0:
400 if is_chroot(module) or os.environ.get('SYSTEMD_OFFLINE') == '1':
401 module.warn('daemon-reload failed, but target is a chroot or systemd is offline. Continuing. Error was: %d / %s' % (rc, err))
402 else:
403 module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err))
404
405 # Run daemon-reexec
406 if module.params['daemon_reexec'] and not module.check_mode:
407 (rc, out, err) = module.run_command("%s daemon-reexec" % (systemctl))
408 if rc != 0:
409 if is_chroot(module) or os.environ.get('SYSTEMD_OFFLINE') == '1':
410 module.warn('daemon-reexec failed, but target is a chroot or systemd is offline. Continuing. Error was: %d / %s' % (rc, err))
411 else:
412 module.fail_json(msg='failure %d during daemon-reexec: %s' % (rc, err))
413
414 if unit:
415 found = False
416 is_initd = sysv_exists(unit)
417 is_systemd = False
418
419 # check service data, cannot error out on rc as it changes across versions, assume not found
420 (rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit))
421
422 if rc == 0 and not (request_was_ignored(out) or request_was_ignored(err)):
423 # load return of systemctl show into dictionary for easy access and return
424 if out:
425 result['status'] = parse_systemctl_show(to_native(out).split('\n'))
426
427 is_systemd = 'LoadState' in result['status'] and result['status']['LoadState'] != 'not-found'
428
429 is_masked = 'LoadState' in result['status'] and result['status']['LoadState'] == 'masked'
430
431 # Check for loading error
432 if is_systemd and not is_masked and 'LoadError' in result['status']:
433 module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError']))
434
435 # Workaround for https://github.com/ansible/ansible/issues/71528
436 elif err and rc == 1 and 'Failed to parse bus message' in err:
437 result['status'] = parse_systemctl_show(to_native(out).split('\n'))
438
439 unit_base, sep, suffix = unit.partition('@')
440 unit_search = '{unit_base}{sep}'.format(unit_base=unit_base, sep=sep)
441 (rc, out, err) = module.run_command("{systemctl} list-unit-files '{unit_search}*'".format(systemctl=systemctl, unit_search=unit_search))
442 is_systemd = unit_search in out
443
444 (rc, out, err) = module.run_command("{systemctl} is-active '{unit}'".format(systemctl=systemctl, unit=unit))
445 result['status']['ActiveState'] = out.rstrip('\n')
446
447 else:
448 # list taken from man systemctl(1) for systemd 244
449 valid_enabled_states = [
450 "enabled",
451 "enabled-runtime",
452 "linked",
453 "linked-runtime",
454 "masked",
455 "masked-runtime",
456 "static",
457 "indirect",
458 "disabled",
459 "generated",
460 "transient"]
461
462 (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit))
463 if out.strip() in valid_enabled_states:
464 is_systemd = True
465 else:
466 # fallback list-unit-files as show does not work on some systems (chroot)
467 # not used as primary as it skips some services (like those using init.d) and requires .service/etc notation
468 (rc, out, err) = module.run_command("%s list-unit-files '%s'" % (systemctl, unit))
469 if rc == 0:
470 is_systemd = True
471 else:
472 # Check for systemctl command
473 module.run_command(systemctl, check_rc=True)
474
475 # Does service exist?
476 found = is_systemd or is_initd
477 if is_initd and not is_systemd:
478 module.warn('The service (%s) is actually an init script but the system is managed by systemd' % unit)
479
480 # mask/unmask the service, if requested, can operate on services before they are installed
481 if module.params['masked'] is not None:
482 # state is not masked unless systemd affirms otherwise
483 (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit))
484 masked = out.strip() == "masked"
485
486 if masked != module.params['masked']:
487 result['changed'] = True
488 if module.params['masked']:
489 action = 'mask'
490 else:
491 action = 'unmask'
492
493 if not module.check_mode:
494 (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
495 if rc != 0:
496 # some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't
497 fail_if_missing(module, found, unit, msg='host')
498 # here if service was not missing, but failed for other reasons
499 module.fail_json(msg=f"Failed to {action} the service ({unit}): {err.strip()}")
500
501 # Enable/disable service startup at boot if requested
502 if module.params['enabled'] is not None:
503
504 if module.params['enabled']:
505 action = 'enable'
506 else:
507 action = 'disable'
508
509 fail_if_missing(module, found, unit, msg='host')
510
511 # do we need to enable the service?
512 enabled = False
513 (rc, out, err) = module.run_command("%s is-enabled '%s' -l" % (systemctl, unit))
514
515 # check systemctl result or if it is a init script
516 if rc == 0:
517 # https://www.freedesktop.org/software/systemd/man/systemctl.html#is-enabled%20UNIT%E2%80%A6
518 if out.rstrip() in (
519 "enabled-runtime", # transiently enabled but we're trying to set a permanent enabled
520 "indirect", # We've been asked to enable this unit so do so despite possible reasons
521 # that systemctl may have for thinking it's enabled already.
522 "alias"): # Let systemd handle the alias as we can't be sure what's needed.
523 enabled = False
524 else:
525 enabled = True
526 elif rc == 1:
527 # if not a user or global user service and both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries
528 if module.params['scope'] == 'system' and \
529 is_initd and \
530 not out.strip().endswith('disabled') and \
531 sysv_is_enabled(unit):
532 enabled = True
533
534 # default to current state
535 result['enabled'] = enabled
536
537 # Change enable/disable if needed
538 if enabled != module.params['enabled']:
539 result['changed'] = True
540 if not module.check_mode:
541 (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
542 if rc != 0:
543 module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err))
544
545 result['enabled'] = not enabled
546
547 # set service state if requested
548 if module.params['state'] is not None:
549 fail_if_missing(module, found, unit, msg="host")
550
551 # default to desired state
552 result['state'] = module.params['state']
553
554 # What is current service state?
555 if 'ActiveState' in result['status']:
556 action = None
557 if module.params['state'] == 'started':
558 if not is_running_service(result['status']):
559 action = 'start'
560 elif module.params['state'] == 'stopped':
561 if is_running_service(result['status']) or is_deactivating_service(result['status']):
562 action = 'stop'
563 else:
564 if not is_running_service(result['status']):
565 action = 'start'
566 else:
567 action = module.params['state'][:-2] # remove 'ed' from restarted/reloaded
568 result['state'] = 'started'
569
570 if action:
571 result['changed'] = True
572 if not module.check_mode:
573 (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit))
574 if rc != 0:
575 module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, err))
576 # check for chroot
577 elif is_chroot(module) or os.environ.get('SYSTEMD_OFFLINE') == '1':
578 module.warn("Target is a chroot or systemd is offline. This can lead to false positives or prevent the init system tools from working.")
579 else:
580 # this should not happen?
581 module.fail_json(msg="Service is in unknown state", status=result['status'])
582
583 module.exit_json(**result)
584
585
586 if __name__ == '__main__':
587 main()