Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Andrew Dunham <[email protected]>
4 # Copyright (c) 2013, Daniel Jaouen <[email protected]>
5 # Copyright (c) 2015, Indrajit Raychaudhuri <[email protected]>
6 # Copyright (c) 2024, Kit Ham <[email protected]>
7 #
8 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
9 # SPDX-License-Identifier: GPL-3.0-or-later
10
11 from __future__ import annotations
12
13 DOCUMENTATION = r"""
14 module: homebrew_services
15 author:
16 - "Kit Ham (@kitizz)"
17 requirements:
18 - homebrew must already be installed on the target system
19 short_description: Services manager for Homebrew
20 version_added: 9.3.0
21 description:
22 - Manages daemons and services using Homebrew.
23 extends_documentation_fragment:
24 - community.general._attributes
25 attributes:
26 check_mode:
27 support: full
28 diff_mode:
29 support: none
30 options:
31 name:
32 description:
33 - An installed homebrew package whose service is to be updated.
34 aliases: ['formula']
35 type: str
36 required: true
37 path:
38 description:
39 - A V(:) separated list of paths to search for C(brew) executable. Since a package (I(formula) in homebrew parlance)
40 location is prefixed relative to the actual path of C(brew) command, providing an alternative C(brew) path enables
41 managing different set of packages in an alternative location in the system.
42 default: '/usr/local/bin:/opt/homebrew/bin:/home/linuxbrew/.linuxbrew/bin'
43 type: path
44 state:
45 description:
46 - State of the package's service.
47 choices: ['present', 'absent', 'restarted']
48 default: present
49 type: str
50 """
51
52 EXAMPLES = r"""
53 - name: Install foo package
54 community.general.homebrew:
55 name: foo
56 state: present
57
58 - name: Start the foo service (equivalent to `brew services start foo`)
59 community.general.homebrew_services:
60 name: foo
61 state: present
62
63 - name: Restart the foo service (equivalent to `brew services restart foo`)
64 community.general.homebrew_services:
65 name: foo
66 state: restarted
67
68 - name: Remove the foo service (equivalent to `brew services stop foo`)
69 community.general.homebrew_services:
70 name: foo
71 state: absent
72 """
73
74 RETURN = r"""
75 pid:
76 description:
77 - If the service is now running, this is the PID of the service, otherwise -1.
78 returned: success
79 type: int
80 sample: 1234
81 running:
82 description:
83 - Whether the service is running after running this command.
84 returned: success
85 type: bool
86 sample: true
87 """
88
89 import json
90 import typing as t
91 from dataclasses import dataclass
92
93 from ansible.module_utils.basic import AnsibleModule
94
95 from ansible_collections.community.general.plugins.module_utils._homebrew import (
96 HomebrewValidate,
97 parse_brew_path,
98 )
99
100
101 @dataclass
102 class HomebrewServiceArgs:
103 name: str
104 state: str
105 brew_path: str
106
107
108 @dataclass
109 class HomebrewServiceState:
110 running: bool
111 pid: int | None
112
113
114 def _brew_service_state(args: HomebrewServiceArgs, module: AnsibleModule) -> HomebrewServiceState:
115 cmd = [args.brew_path, "services", "info", args.name, "--json"]
116 rc, stdout, stderr = module.run_command(cmd, check_rc=True)
117
118 try:
119 data = json.loads(stdout)[0]
120 except json.JSONDecodeError:
121 module.fail_json(msg=f"Failed to parse JSON output:\n{stdout}")
122
123 return HomebrewServiceState(running=data["status"] == "started", pid=data["pid"])
124
125
126 def _exit_with_state(
127 args: HomebrewServiceArgs, module: AnsibleModule, changed: bool = False, message: str | None = None
128 ) -> None:
129 state = _brew_service_state(args, module)
130 if message is None:
131 message = f"Running: {state.running}, Changed: {changed}, PID: {state.pid}"
132 module.exit_json(msg=message, pid=state.pid, running=state.running, changed=changed)
133
134
135 def validate_and_load_arguments(module: AnsibleModule) -> HomebrewServiceArgs:
136 """Reuse the Homebrew module's validation logic to validate these arguments."""
137 package: str = module.params["name"]
138 if not HomebrewValidate.valid_package(package):
139 module.fail_json(msg=f"Invalid package name: {package}")
140
141 state: t.Literal["present", "absent", "restarted"] = module.params["state"]
142 brew_path = parse_brew_path(module)
143
144 return HomebrewServiceArgs(name=package, state=state, brew_path=brew_path)
145
146
147 def start_service(args: HomebrewServiceArgs, module: AnsibleModule) -> None:
148 """Start the requested brew service if it is not already running."""
149 state = _brew_service_state(args, module)
150 if state.running:
151 # Nothing to do, return early.
152 _exit_with_state(args, module, changed=False, message="Service already running")
153
154 if module.check_mode:
155 _exit_with_state(args, module, changed=True, message="Service would be started")
156
157 start_cmd = [args.brew_path, "services", "start", args.name]
158 module.run_command(start_cmd, check_rc=True)
159
160 _exit_with_state(args, module, changed=True)
161
162
163 def stop_service(args: HomebrewServiceArgs, module: AnsibleModule) -> None:
164 """Stop the requested brew service if it is running."""
165 state = _brew_service_state(args, module)
166 if not state.running:
167 # Nothing to do, return early.
168 _exit_with_state(args, module, changed=False, message="Service already stopped")
169
170 if module.check_mode:
171 _exit_with_state(args, module, changed=True, message="Service would be stopped")
172
173 stop_cmd = [args.brew_path, "services", "stop", args.name]
174 module.run_command(stop_cmd, check_rc=True)
175
176 _exit_with_state(args, module, changed=True)
177
178
179 def restart_service(args: HomebrewServiceArgs, module: AnsibleModule) -> None:
180 """Restart the requested brew service. This always results in a change."""
181 if module.check_mode:
182 _exit_with_state(args, module, changed=True, message="Service would be restarted")
183
184 restart_cmd = [args.brew_path, "services", "restart", args.name]
185 module.run_command(restart_cmd, check_rc=True)
186
187 _exit_with_state(args, module, changed=True)
188
189
190 def main() -> None:
191 module = AnsibleModule(
192 argument_spec=dict(
193 name=dict(
194 aliases=["formula"],
195 required=True,
196 type="str",
197 ),
198 state=dict(
199 choices=["present", "absent", "restarted"],
200 default="present",
201 ),
202 path=dict(
203 default="/usr/local/bin:/opt/homebrew/bin:/home/linuxbrew/.linuxbrew/bin",
204 type="path",
205 ),
206 ),
207 supports_check_mode=True,
208 )
209
210 # Pre-validate arguments.
211 service_args = validate_and_load_arguments(module)
212
213 # Choose logic based on the desired state.
214 if service_args.state == "present":
215 start_service(service_args, module)
216 elif service_args.state == "absent":
217 stop_service(service_args, module)
218 elif service_args.state == "restarted":
219 restart_service(service_args, module)
220
221
222 if __name__ == "__main__":
223 main()