Debian Codegraph @

ansible_collections/community/general/plugins/modules/nosh.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017, Thomas Caravia <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: nosh
11 author:
12 - "Thomas Caravia (@tacatac)"
13 short_description: Manage services with nosh
14 description:
15 - Control running and enabled state for system-wide or user services.
16 - BSD and Linux systems are supported.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 name:
26 type: str
27 required: true
28 description:
29 - Name of the service to manage.
30 state:
31 type: str
32 choices: [started, stopped, reset, restarted, reloaded]
33 description:
34 - V(started)/V(stopped) are idempotent actions that do not run commands unless necessary.
35 - V(restarted) always bounces the service.
36 - V(reloaded) sends a SIGHUP or starts the service.
37 - V(reset) starts or stops the service according to whether it is enabled or not.
38 enabled:
39 type: bool
40 description:
41 - Enable or disable the service, independently of C(*.preset) file preference or running state. Mutually exclusive with
42 O(preset). It takes effect prior to O(state=reset).
43 preset:
44 type: bool
45 description:
46 - Enable or disable the service according to local preferences in C(*.preset) files. Mutually exclusive with O(enabled).
47 Only has an effect if set to true. It takes effect prior to O(state=reset).
48 user:
49 default: false
50 type: bool
51 description:
52 - Run system-control talking to the calling user's service manager, rather than the system-wide service manager.
53 requirements:
54 - A system with an active nosh service manager, see Notes for further information.
55 notes:
56 - Information on the nosh utilities suite may be found at U(https://jdebp.eu/Softwares/nosh/).
57 """
58
59 EXAMPLES = r"""
60 - name: Start dnscache if not running
61 community.general.nosh:
62 name: dnscache
63 state: started
64
65 - name: Stop mpd, if running
66 community.general.nosh:
67 name: mpd
68 state: stopped
69
70 - name: Restart unbound or start it if not already running
71 community.general.nosh:
72 name: unbound
73 state: restarted
74
75 - name: Reload fail2ban or start it if not already running
76 community.general.nosh:
77 name: fail2ban
78 state: reloaded
79
80 - name: Disable nsd
81 community.general.nosh:
82 name: nsd
83 enabled: false
84
85 - name: For package installers, set nginx running state according to local enable settings, preset and reset
86 community.general.nosh:
87 name: nginx
88 preset: true
89 state: reset
90
91 - name: Reboot the host if nosh is the system manager, would need a "wait_for*" task at least, not recommended as-is
92 community.general.nosh:
93 name: reboot
94 state: started
95
96 - name: Using conditionals with the module facts
97 tasks:
98 - name: Obtain information on tinydns service
99 community.general.nosh:
100 name: tinydns
101 register: result
102
103 - name: Fail if service not loaded
104 ansible.builtin.fail:
105 msg: "The {{ result.name }} service is not loaded"
106 when: not result.status
107
108 - name: Fail if service is running
109 ansible.builtin.fail:
110 msg: "The {{ result.name }} service is running"
111 when: result.status and result.status['DaemontoolsEncoreState'] == "running"
112 """
113
114 RETURN = r"""
115 name:
116 description: Name used to find the service.
117 returned: success
118 type: str
119 sample: "sshd"
120 service_path:
121 description: Resolved path for the service.
122 returned: success
123 type: str
124 sample: "/var/sv/sshd"
125 enabled:
126 description: Whether the service is enabled at system bootstrap.
127 returned: success
128 type: bool
129 sample: true
130 preset:
131 description: Whether the enabled status reflects the one set in the relevant C(*.preset) file.
132 returned: success
133 type: bool
134 sample: 'False'
135 state:
136 description: Service process run state, V(none) if the service is not loaded and will not be started.
137 returned: if state option is used
138 type: str
139 sample: "reloaded"
140 status:
141 description: A dictionary with the key=value pairs returned by C(system-control show-json) or V(none) if the service is
142 not loaded.
143 returned: success
144 type: dict
145 contains:
146 After:
147 description: [] # FIXME
148 returned: success
149 type: list
150 sample: ["/etc/service-bundles/targets/basic", "../sshdgenkeys", "log"]
151 Before:
152 description: [] # FIXME
153 returned: success
154 type: list
155 sample: ["/etc/service-bundles/targets/shutdown"]
156 Conflicts:
157 description: [] # FIXME
158 returned: success
159 type: list
160 sample: []
161 DaemontoolsEncoreState:
162 description: [] # FIXME
163 returned: success
164 type: str
165 sample: "running"
166 DaemontoolsState:
167 description: [] # FIXME
168 returned: success
169 type: str
170 sample: "up"
171 Enabled:
172 description: [] # FIXME
173 returned: success
174 type: bool
175 sample: true
176 LogService:
177 description: [] # FIXME
178 returned: success
179 type: str
180 sample: "../cyclog@sshd"
181 MainPID:
182 description: [] # FIXME
183 returned: success
184 type: int
185 sample: 661
186 Paused:
187 description: [] # FIXME
188 returned: success
189 type: bool
190 sample: 'False'
191 ReadyAfterRun:
192 description: [] # FIXME
193 returned: success
194 type: bool
195 sample: 'False'
196 RemainAfterExit:
197 description: [] # FIXME
198 returned: success
199 type: bool
200 sample: 'False'
201 Required-By:
202 description: [] # FIXME
203 returned: success
204 type: list
205 sample: []
206 RestartExitStatusCode:
207 description: [] # FIXME
208 returned: success
209 type: int
210 sample: '0'
211 RestartExitStatusNumber:
212 description: [] # FIXME
213 returned: success
214 type: int
215 sample: '0'
216 RestartTimestamp:
217 description: [] # FIXME
218 returned: success
219 type: int
220 sample: 4611686019935648081
221 RestartUTCTimestamp:
222 description: [] # FIXME
223 returned: success
224 type: int
225 sample: 1508260140
226 RunExitStatusCode:
227 description: [] # FIXME
228 returned: success
229 type: int
230 sample: '0'
231 RunExitStatusNumber:
232 description: [] # FIXME
233 returned: success
234 type: int
235 sample: '0'
236 RunTimestamp:
237 description: [] # FIXME
238 returned: success
239 type: int
240 sample: 4611686019935648081
241 RunUTCTimestamp:
242 description: [] # FIXME
243 returned: success
244 type: int
245 sample: 1508260140
246 StartExitStatusCode:
247 description: [] # FIXME
248 returned: success
249 type: int
250 sample: 1
251 StartExitStatusNumber:
252 description: [] # FIXME
253 returned: success
254 type: int
255 sample: '0'
256 StartTimestamp:
257 description: [] # FIXME
258 returned: success
259 type: int
260 sample: 4611686019935648081
261 StartUTCTimestamp:
262 description: [] # FIXME
263 returned: success
264 type: int
265 sample: 1508260140
266 StopExitStatusCode:
267 description: [] # FIXME
268 returned: success
269 type: int
270 sample: '0'
271 StopExitStatusNumber:
272 description: [] # FIXME
273 returned: success
274 type: int
275 sample: '0'
276 StopTimestamp:
277 description: [] # FIXME
278 returned: success
279 type: int
280 sample: 4611686019935648081
281 StopUTCTimestamp:
282 description: [] # FIXME
283 returned: success
284 type: int
285 sample: 1508260140
286 Stopped-By:
287 description: [] # FIXME
288 returned: success
289 type: list
290 sample: ["/etc/service-bundles/targets/shutdown"]
291 Timestamp:
292 description: [] # FIXME
293 returned: success
294 type: int
295 sample: 4611686019935648081
296 UTCTimestamp:
297 description: [] # FIXME
298 returned: success
299 type: int
300 sample: 1508260140
301 Want:
302 description: [] # FIXME
303 returned: success
304 type: str
305 sample: "nothing"
306 Wanted-By:
307 description: [] # FIXME
308 returned: success
309 type: list
310 sample: ["/etc/service-bundles/targets/server", "/etc/service-bundles/targets/sockets"]
311 Wants:
312 description: [] # FIXME
313 returned: success
314 type: list
315 sample: ["/etc/service-bundles/targets/basic", "../sshdgenkeys"]
316 user:
317 description: Whether the user-level service manager is called.
318 returned: success
319 type: bool
320 sample: false
321 """
322
323
324 import json
325
326 from ansible.module_utils.basic import AnsibleModule
327 from ansible.module_utils.service import fail_if_missing
328
329
330 def run_sys_ctl(module, args):
331 sys_ctl = [module.get_bin_path("system-control", required=True)]
332 if module.params["user"]:
333 sys_ctl = sys_ctl + ["--user"]
334 return module.run_command(sys_ctl + args)
335
336
337 def get_service_path(module, service):
338 (rc, out, err) = run_sys_ctl(module, ["find", service])
339 # fail if service not found
340 if rc != 0:
341 fail_if_missing(module, False, service, msg="host")
342 else:
343 return out.strip()
344
345
346 def service_is_enabled(module, service_path):
347 (rc, out, err) = run_sys_ctl(module, ["is-enabled", service_path])
348 return rc == 0
349
350
351 def service_is_preset_enabled(module, service_path):
352 (rc, out, err) = run_sys_ctl(module, ["preset", "--dry-run", service_path])
353 return out.strip().startswith("enable")
354
355
356 def service_is_loaded(module, service_path):
357 (rc, out, err) = run_sys_ctl(module, ["is-loaded", service_path])
358 return rc == 0
359
360
361 def get_service_status(module, service_path):
362 (rc, out, err) = run_sys_ctl(module, ["show-json", service_path])
363 # will fail if not service is not loaded
364 if err is not None and err:
365 module.fail_json(msg=err)
366 else:
367 json_out = json.loads(out.strip())
368 status = json_out[service_path] # descend past service path header
369 return status
370
371
372 def service_is_running(service_status):
373 return service_status["DaemontoolsEncoreState"] in {"starting", "started", "running"}
374
375
376 def handle_enabled(module, result, service_path):
377 """Enable or disable a service as needed.
378
379 - 'preset' will set the enabled state according to available preset file settings.
380 - 'enabled' will set the enabled state explicitly, independently of preset settings.
381
382 These options are set to "mutually exclusive" but the explicit 'enabled' option will
383 have priority if the check is bypassed.
384 """
385
386 # computed prior in control flow
387 preset = result["preset"]
388 enabled = result["enabled"]
389
390 # preset, effect only if option set to true (no reverse preset)
391 if module.params["preset"]:
392 action = "preset"
393
394 # run preset if needed
395 if preset != module.params["preset"]:
396 result["changed"] = True
397 if not module.check_mode:
398 (rc, out, err) = run_sys_ctl(module, [action, service_path])
399 if rc != 0:
400 module.fail_json(msg=f"Unable to {action} service {service_path}: {out + err}")
401 result["preset"] = not preset
402 result["enabled"] = not enabled
403
404 # enabled/disabled state
405 if module.params["enabled"] is not None:
406 if module.params["enabled"]:
407 action = "enable"
408 else:
409 action = "disable"
410
411 # change enable/disable if needed
412 if enabled != module.params["enabled"]:
413 result["changed"] = True
414 if not module.check_mode:
415 (rc, out, err) = run_sys_ctl(module, [action, service_path])
416 if rc != 0:
417 module.fail_json(msg=f"Unable to {action} service {service_path}: {out + err}")
418 result["enabled"] = not enabled
419 result["preset"] = not preset
420
421
422 def handle_state(module, result, service_path):
423 """Set service running state as needed.
424
425 Takes into account the fact that a service may not be loaded (no supervise directory) in
426 which case it is 'stopped' as far as the service manager is concerned. No status information
427 can be obtained and the service can only be 'started'.
428 """
429 # default to desired state, no action
430 result["state"] = module.params["state"]
431 state = module.params["state"]
432 action = None
433
434 # computed prior in control flow, possibly modified by handle_enabled()
435 enabled = result["enabled"]
436
437 # service not loaded -> not started by manager, no status information
438 if not service_is_loaded(module, service_path):
439 if state in ["started", "restarted", "reloaded"]:
440 action = "start"
441 result["state"] = "started"
442 elif state == "reset":
443 if enabled:
444 action = "start"
445 result["state"] = "started"
446 else:
447 result["state"] = None
448 else:
449 result["state"] = None
450
451 # service is loaded
452 else:
453 # get status information
454 result["status"] = get_service_status(module, service_path)
455 running = service_is_running(result["status"])
456
457 if state == "started":
458 if not running:
459 action = "start"
460 elif state == "stopped":
461 if running:
462 action = "stop"
463 # reset = start/stop according to enabled status
464 elif state == "reset":
465 if enabled is not running:
466 if running:
467 action = "stop"
468 result["state"] = "stopped"
469 else:
470 action = "start"
471 result["state"] = "started"
472 # start if not running, 'service' module constraint
473 elif state == "restarted":
474 if not running:
475 action = "start"
476 result["state"] = "started"
477 else:
478 action = "condrestart"
479 # start if not running, 'service' module constraint
480 elif state == "reloaded":
481 if not running:
482 action = "start"
483 result["state"] = "started"
484 else:
485 action = "hangup"
486
487 # change state as needed
488 if action:
489 result["changed"] = True
490 if not module.check_mode:
491 (rc, out, err) = run_sys_ctl(module, [action, service_path])
492 if rc != 0:
493 module.fail_json(msg=f"Unable to {action} service {service_path}: {err}")
494
495
496 # ===========================================
497 # Main control flow
498
499
500 def main():
501 module = AnsibleModule(
502 argument_spec=dict(
503 name=dict(type="str", required=True),
504 state=dict(type="str", choices=["started", "stopped", "reset", "restarted", "reloaded"]),
505 enabled=dict(type="bool"),
506 preset=dict(type="bool"),
507 user=dict(type="bool", default=False),
508 ),
509 supports_check_mode=True,
510 mutually_exclusive=[["enabled", "preset"]],
511 )
512
513 service = module.params["name"]
514 result = {
515 "name": service,
516 "changed": False,
517 "status": None,
518 }
519
520 # check service can be found (or fail) and get path
521 service_path = get_service_path(module, service)
522
523 # get preliminary service facts
524 result["service_path"] = service_path
525 result["user"] = module.params["user"]
526 result["enabled"] = service_is_enabled(module, service_path)
527 result["preset"] = result["enabled"] is service_is_preset_enabled(module, service_path)
528
529 # set enabled state, service need not be loaded
530 if module.params["enabled"] is not None or module.params["preset"]:
531 handle_enabled(module, result, service_path)
532
533 # set service running state
534 if module.params["state"] is not None:
535 handle_state(module, result, service_path)
536
537 # get final service status if possible
538 if service_is_loaded(module, service_path):
539 result["status"] = get_service_status(module, service_path)
540
541 module.exit_json(**result)
542
543
544 if __name__ == "__main__":
545 main()