Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2018, Martin Migasiewicz <[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: launchd
11 author:
12 - Martin Migasiewicz (@martinm82)
13 short_description: Manage macOS services
14 version_added: 1.0.0
15 description:
16 - Manage launchd services on target macOS hosts.
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 description:
27 - Name of the service.
28 type: str
29 required: true
30 plist:
31 description:
32 - Name of the V(.plist) file for the service.
33 - Defaults to V({name}.plist).
34 type: str
35 version_added: 10.1.0
36 state:
37 description:
38 - V(started)/V(stopped) are idempotent actions that do not run commands unless necessary.
39 - C(launchd) does not support V(restarted) nor V(reloaded) natively. These states trigger a stop/start (restarted) or
40 an unload/load (reloaded).
41 - V(restarted) unloads and loads the service before start to ensure that the latest job definition (plist) is used.
42 - V(reloaded) unloads and loads the service to ensure that the latest job definition (plist) is used. Whether a service
43 is started or stopped depends on the content of the definition file.
44 type: str
45 choices: [reloaded, restarted, started, stopped, unloaded]
46 enabled:
47 description:
48 - Whether the service should start on boot.
49 - B(At least one of state and enabled are required).
50 type: bool
51 force_stop:
52 description:
53 - Whether the service should not be restarted automatically by launchd.
54 - Services might have the C(KeepAlive) attribute set to V(true) in a launchd configuration. In case this is set to V(true),
55 stopping a service causes that C(launchd) starts the service again.
56 - Set this option to V(true) to let this module change the C(KeepAlive) attribute to V(false).
57 type: bool
58 default: false
59 notes:
60 - A user must privileged to manage services using this module.
61 requirements:
62 - A system managed by launchd
63 - The plistlib Python library
64 """
65
66 EXAMPLES = r"""
67 - name: Make sure spotify webhelper is started
68 community.general.launchd:
69 name: com.spotify.webhelper
70 state: started
71
72 - name: Deploy custom memcached job definition
73 template:
74 src: org.memcached.plist.j2
75 dest: /Library/LaunchDaemons/org.memcached.plist
76
77 - name: Run memcached
78 community.general.launchd:
79 name: org.memcached
80 state: started
81
82 - name: Stop memcached
83 community.general.launchd:
84 name: org.memcached
85 state: stopped
86
87 - name: Stop memcached
88 community.general.launchd:
89 name: org.memcached
90 state: stopped
91 force_stop: true
92
93 - name: Restart memcached
94 community.general.launchd:
95 name: org.memcached
96 state: restarted
97
98 - name: Unload memcached
99 community.general.launchd:
100 name: org.memcached
101 state: unloaded
102
103 - name: restart sshd
104 community.general.launchd:
105 name: com.openssh.sshd
106 plist: ssh.plist
107 state: restarted
108 """
109
110 RETURN = r"""
111 status:
112 description: Metadata about service status.
113 returned: always
114 type: dict
115 sample:
116 {
117 "current_pid": "-",
118 "current_state": "stopped",
119 "previous_pid": "82636",
120 "previous_state": "running"
121 }
122 """
123
124 import os
125 import plistlib
126 from abc import ABCMeta, abstractmethod
127 from time import sleep
128
129 from ansible.module_utils.basic import AnsibleModule
130
131
132 class ServiceState:
133 UNKNOWN = 0
134 LOADED = 1
135 STOPPED = 2
136 STARTED = 3
137 UNLOADED = 4
138
139 @staticmethod
140 def to_string(state):
141 strings = {
142 ServiceState.UNKNOWN: "unknown",
143 ServiceState.LOADED: "loaded",
144 ServiceState.STOPPED: "stopped",
145 ServiceState.STARTED: "started",
146 ServiceState.UNLOADED: "unloaded",
147 }
148 return strings[state]
149
150
151 class Plist:
152 def __init__(self, module, service, filename=None):
153 self.__changed = False
154 self.__service = service
155 if filename is not None:
156 self.__filename = filename
157 else:
158 self.__filename = f"{service}.plist"
159
160 state, pid, dummy, dummy = LaunchCtlList(module, self.__service).run()
161
162 self.__file = self.__find_service_plist(self.__filename)
163 if self.__file is None:
164 msg = f"Unable to find the plist file {self.__filename} for service {self.__service}"
165 if pid is None and state == ServiceState.UNLOADED:
166 msg += " and it was not found among active services"
167 module.fail_json(msg=msg)
168 self.__update(module)
169
170 @staticmethod
171 def __find_service_plist(filename):
172 """Finds the plist file associated with a service"""
173
174 launchd_paths = [
175 os.path.join(os.getenv("HOME"), "Library/LaunchAgents"),
176 "/Library/LaunchAgents",
177 "/Library/LaunchDaemons",
178 "/System/Library/LaunchAgents",
179 "/System/Library/LaunchDaemons",
180 ]
181
182 for path in launchd_paths:
183 try:
184 files = os.listdir(path)
185 except OSError:
186 continue
187
188 if filename in files:
189 return os.path.join(path, filename)
190 return None
191
192 def __update(self, module):
193 self.__handle_param_enabled(module)
194 self.__handle_param_force_stop(module)
195
196 def __read_plist_file(self, module):
197 service_plist = {}
198 try:
199 with open(self.__file, "rb") as plist_fp:
200 service_plist = plistlib.load(plist_fp)
201 except Exception as e:
202 module.fail_json(msg=f"Failed to read plist file {self.__file} due to {e}")
203 return service_plist
204
205 def __write_plist_file(self, module, service_plist=None):
206 if not service_plist:
207 service_plist = {}
208
209 try:
210 with open(self.__file, "wb") as plist_fp:
211 plistlib.dump(service_plist, plist_fp)
212 except Exception as e:
213 module.fail_json(msg=f"Failed to write to plist file {self.__file} due to {e}")
214
215 def __handle_param_enabled(self, module):
216 if module.params["enabled"] is not None:
217 service_plist = self.__read_plist_file(module)
218
219 # Enable/disable service startup at boot if requested
220 # Launchctl does not expose functionality to set the RunAtLoad
221 # attribute of a job definition. So we parse and modify the job
222 # definition plist file directly for this purpose.
223 if module.params["enabled"] is not None:
224 enabled = service_plist.get("RunAtLoad", False)
225 if module.params["enabled"] != enabled:
226 service_plist["RunAtLoad"] = module.params["enabled"]
227
228 # Update the plist with one of the changes done.
229 if not module.check_mode:
230 self.__write_plist_file(module, service_plist)
231 self.__changed = True
232
233 def __handle_param_force_stop(self, module):
234 if module.params["force_stop"] is not None:
235 service_plist = self.__read_plist_file(module)
236
237 # Set KeepAlive to false in case force_stop is defined to avoid
238 # that the service gets restarted when stopping was requested.
239 if module.params["force_stop"] is not None:
240 keep_alive = service_plist.get("KeepAlive", False)
241 if module.params["force_stop"] and keep_alive:
242 service_plist["KeepAlive"] = not module.params["force_stop"]
243
244 # Update the plist with one of the changes done.
245 if not module.check_mode:
246 self.__write_plist_file(module, service_plist)
247 self.__changed = True
248
249 def is_changed(self):
250 return self.__changed
251
252 def get_file(self):
253 return self.__file
254
255
256 class LaunchCtlTask(metaclass=ABCMeta):
257 WAITING_TIME = 5 # seconds
258
259 def __init__(self, module, service, plist):
260 self._module = module
261 self._service = service
262 self._plist = plist
263 self._launch = self._module.get_bin_path("launchctl", True)
264
265 def run(self):
266 """Runs a launchd command like 'load', 'unload', 'start', 'stop', etc.
267 and returns the new state and pid.
268 """
269 self.runCommand()
270 return self.get_state()
271
272 @abstractmethod
273 def runCommand(self):
274 pass
275
276 def get_state(self):
277 rc, out, err = self._launchctl("list")
278 if rc != 0:
279 self._module.fail_json(msg=f"Failed to get status of {self._launch}")
280
281 state = ServiceState.UNLOADED
282 service_pid = "-"
283 status_code = None
284 for line in out.splitlines():
285 if line.strip():
286 pid, last_exit_code, label = line.split("\t")
287 if label.strip() == self._service:
288 service_pid = pid
289 status_code = last_exit_code
290
291 # From launchctl man page:
292 # If the number [...] is negative, it represents the
293 # negative of the signal which killed the job. Thus,
294 # "-15" would indicate that the job was terminated with
295 # SIGTERM.
296 if last_exit_code not in ["0", "-2", "-3", "-9", "-15"]:
297 # Something strange happened and we have no clue in
298 # which state the service is now. Therefore we mark
299 # the service state as UNKNOWN.
300 state = ServiceState.UNKNOWN
301 elif pid != "-":
302 # PID seems to be an integer so we assume the service
303 # is started.
304 state = ServiceState.STARTED
305 else:
306 # Exit code is 0 and PID is not available so we assume
307 # the service is stopped.
308 state = ServiceState.STOPPED
309 break
310 return (state, service_pid, status_code, err)
311
312 def start(self):
313 rc, out, err = self._launchctl("start")
314 # Unfortunately launchd does not wait until the process really started.
315 sleep(self.WAITING_TIME)
316 return (rc, out, err)
317
318 def stop(self):
319 rc, out, err = self._launchctl("stop")
320 # Unfortunately launchd does not wait until the process really stopped.
321 sleep(self.WAITING_TIME)
322 return (rc, out, err)
323
324 def restart(self):
325 # TODO: check for rc, out, err
326 self.stop()
327 return self.start()
328
329 def reload(self):
330 # TODO: check for rc, out, err
331 self.unload()
332 return self.load()
333
334 def load(self):
335 return self._launchctl("load")
336
337 def unload(self):
338 return self._launchctl("unload")
339
340 def _launchctl(self, command):
341 service_or_plist = (
342 self._plist.get_file()
343 if command in ["load", "unload"]
344 else self._service
345 if command in ["start", "stop"]
346 else ""
347 )
348
349 rc, out, err = self._module.run_command(f"{self._launch} {command} {service_or_plist}")
350
351 if rc != 0:
352 msg = f"Unable to {command} '{self._service}' ({self._plist.get_file()}): '{err}'"
353 self._module.fail_json(msg=msg)
354
355 return (rc, out, err)
356
357
358 class LaunchCtlStart(LaunchCtlTask):
359 def __init__(self, module, service, plist):
360 super().__init__(module, service, plist)
361
362 def runCommand(self):
363 state, dummy, dummy, dummy = self.get_state()
364
365 if state in (ServiceState.STOPPED, ServiceState.LOADED):
366 self.reload()
367 self.start()
368 elif state == ServiceState.STARTED:
369 # In case the service is already in started state but the
370 # job definition was changed we need to unload/load the
371 # service and start the service again.
372 if self._plist.is_changed():
373 self.reload()
374 self.start()
375 elif state == ServiceState.UNLOADED:
376 self.load()
377 self.start()
378 elif state == ServiceState.UNKNOWN:
379 # We are in an unknown state, let's try to reload the config
380 # and start the service again.
381 self.reload()
382 self.start()
383
384
385 class LaunchCtlStop(LaunchCtlTask):
386 def __init__(self, module, service, plist):
387 super().__init__(module, service, plist)
388
389 def runCommand(self):
390 state, dummy, dummy, dummy = self.get_state()
391
392 if state == ServiceState.STOPPED:
393 # In case the service is stopped and we might later decide
394 # to start it, we need to reload the job definition by
395 # forcing an unload and load first.
396 # Afterwards we need to stop it as it might have been
397 # started again (KeepAlive or RunAtLoad).
398 if self._plist.is_changed():
399 self.reload()
400 self.stop()
401 elif state in (ServiceState.STARTED, ServiceState.LOADED):
402 if self._plist.is_changed():
403 self.reload()
404 self.stop()
405 elif state == ServiceState.UNKNOWN:
406 # We are in an unknown state, let's try to reload the config
407 # and stop the service gracefully.
408 self.reload()
409 self.stop()
410
411
412 class LaunchCtlReload(LaunchCtlTask):
413 def __init__(self, module, service, plist):
414 super().__init__(module, service, plist)
415
416 def runCommand(self):
417 state, dummy, dummy, dummy = self.get_state()
418
419 if state == ServiceState.UNLOADED:
420 # launchd throws an error if we do an unload on an already
421 # unloaded service.
422 self.load()
423 else:
424 self.reload()
425
426
427 class LaunchCtlUnload(LaunchCtlTask):
428 def __init__(self, module, service, plist):
429 super().__init__(module, service, plist)
430
431 def runCommand(self):
432 state, dummy, dummy, dummy = self.get_state()
433 self.unload()
434
435
436 class LaunchCtlRestart(LaunchCtlReload):
437 def __init__(self, module, service, plist):
438 super().__init__(module, service, plist)
439
440 def runCommand(self):
441 super().runCommand()
442 self.start()
443
444
445 class LaunchCtlList(LaunchCtlTask):
446 def __init__(self, module, service):
447 super().__init__(module, service, None)
448
449 def runCommand(self):
450 # Do nothing, the list functionality is done by the
451 # base class run method.
452 pass
453
454
455 def main():
456 module = AnsibleModule(
457 argument_spec=dict(
458 name=dict(type="str", required=True),
459 plist=dict(type="str"),
460 state=dict(type="str", choices=["reloaded", "restarted", "started", "stopped", "unloaded"]),
461 enabled=dict(type="bool"),
462 force_stop=dict(type="bool", default=False),
463 ),
464 supports_check_mode=True,
465 required_one_of=[
466 ["state", "enabled"],
467 ],
468 )
469 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
470
471 service = module.params["name"]
472 plist_filename = module.params["plist"]
473 action = module.params["state"]
474 err = ""
475 result = {
476 "name": service,
477 "changed": False,
478 "status": {},
479 }
480
481 # We will tailor the plist file in case one of the options
482 # (enabled, force_stop) was specified.
483 plist = Plist(module, service, plist_filename)
484 result["changed"] = plist.is_changed()
485
486 # Gather information about the service to be controlled.
487 state, pid, dummy, dummy = LaunchCtlList(module, service).run()
488 result["status"]["previous_state"] = ServiceState.to_string(state)
489 result["status"]["previous_pid"] = pid
490
491 # Map the actions to specific tasks
492 tasks = {
493 "started": LaunchCtlStart(module, service, plist),
494 "stopped": LaunchCtlStop(module, service, plist),
495 "restarted": LaunchCtlRestart(module, service, plist),
496 "reloaded": LaunchCtlReload(module, service, plist),
497 "unloaded": LaunchCtlUnload(module, service, plist),
498 }
499
500 status_code = "0"
501 # Run the requested task
502 if not module.check_mode:
503 state, pid, status_code, err = tasks[action].run()
504
505 result["status"]["current_state"] = ServiceState.to_string(state)
506 result["status"]["current_pid"] = pid
507 result["status"]["status_code"] = status_code
508 result["status"]["error"] = err
509
510 if (
511 result["status"]["current_state"] != result["status"]["previous_state"]
512 or result["status"]["current_pid"] != result["status"]["previous_pid"]
513 ):
514 result["changed"] = True
515 if module.check_mode:
516 if result["status"]["current_state"] != action:
517 result["changed"] = True
518 module.exit_json(**result)
519
520
521 if __name__ == "__main__":
522 main()