Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015, Brian Coca <[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: svc
11 author:
12 - Brian Coca (@bcoca)
13 short_description: Manage C(daemontools) services
14 description:
15 - Controls C(daemontools) services on remote hosts using the C(svc) utility.
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: none
23 options:
24 name:
25 description:
26 - Name of the service to manage.
27 type: str
28 required: true
29 state:
30 description:
31 - V(started)/V(stopped) are idempotent actions that do not run commands unless necessary.
32 - V(restarted) always bounces the svc (svc -t) and V(killed) always bounces the svc (svc -k).
33 - V(reloaded) sends a sigusr1 (svc -1).
34 - V(once) runs a normally downed svc once (svc -o), not really an idempotent operation.
35 type: str
36 choices: [killed, once, reloaded, restarted, started, stopped]
37 downed:
38 description:
39 - Should a C(down) file exist or not, if it exists it disables auto startup. Defaults to V(false). Downed does not imply
40 stopped.
41 type: bool
42 enabled:
43 description:
44 - Whether the service is enabled or not, if disabled it also implies O(state=stopped). Take note that a service can
45 be enabled and downed (no auto restart).
46 type: bool
47 service_dir:
48 description:
49 - Directory C(svscan) watches for services.
50 type: str
51 default: /service
52 service_src:
53 description:
54 - Directory where services are defined, the source of symlinks to O(service_dir).
55 type: str
56 default: /etc/service
57 """
58
59 EXAMPLES = r"""
60 - name: Start svc dnscache, if not running
61 community.general.svc:
62 name: dnscache
63 state: started
64
65 - name: Stop svc dnscache, if running
66 community.general.svc:
67 name: dnscache
68 state: stopped
69
70 - name: Kill svc dnscache, in all cases
71 community.general.svc:
72 name: dnscache
73 state: killed
74
75 - name: Restart svc dnscache, in all cases
76 community.general.svc:
77 name: dnscache
78 state: restarted
79
80 - name: Reload svc dnscache, in all cases
81 community.general.svc:
82 name: dnscache
83 state: reloaded
84
85 - name: Using alternative svc directory location
86 community.general.svc:
87 name: dnscache
88 state: reloaded
89 service_dir: /var/service
90 """
91
92 import os
93 import re
94 import traceback
95
96 from ansible.module_utils.basic import AnsibleModule
97
98
99 def _load_dist_subclass(cls, *args, **kwargs):
100 """
101 Used for derivative implementations
102 """
103 subclass = None
104
105 distro = kwargs["module"].params["distro"]
106
107 # get the most specific superclass for this platform
108 if distro is not None:
109 for sc in cls.__subclasses__():
110 if sc.distro is not None and sc.distro == distro:
111 subclass = sc
112 if subclass is None:
113 subclass = cls
114
115 return super(cls, subclass).__new__(subclass)
116
117
118 class Svc:
119 """
120 Main class that handles daemontools, can be subclassed and overridden in case
121 we want to use a 'derivative' like encore, s6, etc
122 """
123
124 # def __new__(cls, *args, **kwargs):
125 # return _load_dist_subclass(cls, args, kwargs)
126
127 def __init__(self, module):
128 self.extra_paths = ["/command", "/usr/local/bin"]
129 self.report_vars = ["state", "enabled", "downed", "svc_full", "src_full", "pid", "duration", "full_state"]
130
131 self.module = module
132
133 self.name = module.params["name"]
134 self.service_dir = module.params["service_dir"]
135 self.service_src = module.params["service_src"]
136 self.enabled = None
137 self.downed = None
138 self.full_state = None
139 self.state = None
140 self.pid = None
141 self.duration = None
142
143 self.svc_cmd = module.get_bin_path("svc", opt_dirs=self.extra_paths)
144 self.svstat_cmd = module.get_bin_path("svstat", opt_dirs=self.extra_paths)
145 self.svc_full = f"{self.service_dir}/{self.name}"
146 self.src_full = f"{self.service_src}/{self.name}"
147
148 self.enabled = os.path.lexists(self.svc_full)
149 if self.enabled:
150 self.downed = os.path.lexists(f"{self.svc_full}/down")
151 self.get_status()
152 else:
153 self.downed = os.path.lexists(f"{self.src_full}/down")
154 self.state = "stopped"
155
156 def enable(self):
157 if os.path.exists(self.src_full):
158 try:
159 os.symlink(self.src_full, self.svc_full)
160 except OSError as e:
161 self.module.fail_json(path=self.src_full, msg=f"Error while linking: {e}")
162 else:
163 self.module.fail_json(msg=f"Could not find source for service to enable ({self.src_full}).")
164
165 def disable(self):
166 try:
167 os.unlink(self.svc_full)
168 except OSError as e:
169 self.module.fail_json(path=self.svc_full, msg=f"Error while unlinking: {e}")
170 self.execute_command([self.svc_cmd, "-dx", self.src_full])
171
172 src_log = f"{self.src_full}/log"
173 if os.path.exists(src_log):
174 self.execute_command([self.svc_cmd, "-dx", src_log])
175
176 def get_status(self):
177 rc, out, err = self.execute_command([self.svstat_cmd, self.svc_full])
178
179 if err is not None and err:
180 self.full_state = self.state = err
181 else:
182 self.full_state = out
183
184 m = re.search(r"\(pid (\d+)\)", out)
185 if m:
186 self.pid = m.group(1)
187
188 m = re.search(r"(\d+) seconds", out)
189 if m:
190 self.duration = m.group(1)
191
192 if re.search(" up ", out):
193 self.state = "start"
194 elif re.search(" down ", out):
195 self.state = "stopp"
196 else:
197 self.state = "unknown"
198 return
199
200 if re.search(" want ", out):
201 self.state += "ing"
202 else:
203 self.state += "ed"
204
205 def start(self):
206 return self.execute_command([self.svc_cmd, "-u", self.svc_full])
207
208 def stopp(self):
209 return self.stop()
210
211 def stop(self):
212 return self.execute_command([self.svc_cmd, "-d", self.svc_full])
213
214 def once(self):
215 return self.execute_command([self.svc_cmd, "-o", self.svc_full])
216
217 def reload(self):
218 return self.execute_command([self.svc_cmd, "-1", self.svc_full])
219
220 def restart(self):
221 return self.execute_command([self.svc_cmd, "-t", self.svc_full])
222
223 def kill(self):
224 return self.execute_command([self.svc_cmd, "-k", self.svc_full])
225
226 def execute_command(self, cmd):
227 try:
228 rc, out, err = self.module.run_command(cmd)
229 except Exception as e:
230 self.module.fail_json(msg=f"failed to execute: {e}", exception=traceback.format_exc())
231 return (rc, out, err)
232
233 def report(self):
234 self.get_status()
235 states = {}
236 for k in self.report_vars:
237 states[k] = self.__dict__[k]
238 return states
239
240
241 # ===========================================
242 # Main control flow
243
244
245 def main():
246 module = AnsibleModule(
247 argument_spec=dict(
248 name=dict(type="str", required=True),
249 state=dict(type="str", choices=["killed", "once", "reloaded", "restarted", "started", "stopped"]),
250 enabled=dict(type="bool"),
251 downed=dict(type="bool"),
252 service_dir=dict(type="str", default="/service"),
253 service_src=dict(type="str", default="/etc/service"),
254 ),
255 supports_check_mode=True,
256 )
257
258 module.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C")
259
260 state = module.params["state"]
261 enabled = module.params["enabled"]
262 downed = module.params["downed"]
263
264 svc = Svc(module)
265 changed = False
266 dummy_orig_state = svc.report() # TODO - is this not needed?
267
268 if enabled is not None and enabled != svc.enabled:
269 changed = True
270 if not module.check_mode:
271 try:
272 if enabled:
273 svc.enable()
274 else:
275 svc.disable()
276 except OSError as e:
277 module.fail_json(msg=f"Could not change service link: {e}")
278
279 if state is not None and state != svc.state:
280 changed = True
281 if not module.check_mode:
282 getattr(svc, state[:-2])()
283
284 if downed is not None and downed != svc.downed:
285 changed = True
286 if not module.check_mode:
287 d_file = f"{svc.svc_full}/down"
288 try:
289 if downed:
290 open(d_file, "a").close()
291 else:
292 os.unlink(d_file)
293 except OSError as e:
294 module.fail_json(msg=f"Could not change downed file: {e} ")
295
296 module.exit_json(changed=changed, svc=svc.report())
297
298
299 if __name__ == "__main__":
300 main()