Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016-2023, Vlad Glagolev <[email protected]>
4 #
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: simpleinit_msb
12 short_description: Manage services on Source Mage GNU/Linux
13 version_added: 7.5.0
14 description:
15 - Controls services on remote hosts using C(simpleinit-msb).
16 author: "Vlad Glagolev (@vaygr)"
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 description:
28 - Name of the service.
29 required: true
30 aliases: ['service']
31 state:
32 type: str
33 choices: [running, started, stopped, restarted, reloaded]
34 description:
35 - V(started)/V(stopped) are idempotent actions that do not run commands unless necessary. V(restarted) always bounces
36 the service. V(reloaded) always reloads.
37 - At least one of O(state) and O(enabled) are required.
38 - Note that V(reloaded) starts the service if it is not already started, even if your chosen init system would not normally.
39 enabled:
40 type: bool
41 description:
42 - Whether the service should start on boot.
43 - At least one of O(state) and O(enabled) are required.
44 """
45
46 EXAMPLES = r"""
47 - name: Example action to start service httpd, if not running
48 community.general.simpleinit_msb:
49 name: httpd
50 state: started
51
52 - name: Example action to stop service httpd, if running
53 community.general.simpleinit_msb:
54 name: httpd
55 state: stopped
56
57 - name: Example action to restart service httpd, in all cases
58 community.general.simpleinit_msb:
59 name: httpd
60 state: restarted
61
62 - name: Example action to reload service httpd, in all cases
63 community.general.simpleinit_msb:
64 name: httpd
65 state: reloaded
66
67 - name: Example action to enable service httpd, and not touch the running state
68 community.general.simpleinit_msb:
69 name: httpd
70 enabled: true
71 """
72
73 import os
74 import re
75
76 from ansible.module_utils.basic import AnsibleModule
77 from ansible.module_utils.service import daemonize
78
79
80 class SimpleinitMSB:
81 """
82 Main simpleinit-msb service manipulation class
83 """
84
85 def __init__(self, module):
86 self.module = module
87 self.name = module.params["name"]
88 self.state = module.params["state"]
89 self.enable = module.params["enabled"]
90 self.changed = False
91 self.running = None
92 self.action = None
93 self.telinit_cmd = None
94 self.svc_change = False
95
96 def execute_command(self, cmd, daemon=False):
97 if not daemon:
98 return self.module.run_command(cmd)
99 else:
100 return daemonize(self.module, cmd)
101
102 def check_service_changed(self):
103 if self.state and self.running is None:
104 self.module.fail_json(msg="failed determining service state, possible typo of service name?")
105 # Find out if state has changed
106 if not self.running and self.state in ["started", "running", "reloaded"]:
107 self.svc_change = True
108 elif self.running and self.state in ["stopped", "reloaded"]:
109 self.svc_change = True
110 elif self.state == "restarted":
111 self.svc_change = True
112 if self.module.check_mode and self.svc_change:
113 self.module.exit_json(changed=True, msg="service state changed")
114
115 def modify_service_state(self):
116 # Only do something if state will change
117 if self.svc_change:
118 # Control service
119 if self.state in ["started", "running"]:
120 self.action = "start"
121 elif not self.running and self.state == "reloaded":
122 self.action = "start"
123 elif self.state == "stopped":
124 self.action = "stop"
125 elif self.state == "reloaded":
126 self.action = "reload"
127 elif self.state == "restarted":
128 self.action = "restart"
129
130 if self.module.check_mode:
131 self.module.exit_json(changed=True, msg="changing service state")
132
133 return self.service_control()
134 else:
135 # If nothing needs to change just say all is well
136 rc = 0
137 err = ""
138 out = ""
139 return rc, out, err
140
141 def get_service_tools(self):
142 paths = ["/sbin", "/usr/sbin", "/bin", "/usr/bin"]
143 binaries = ["telinit"]
144 location = dict()
145
146 for binary in binaries:
147 location[binary] = self.module.get_bin_path(binary, opt_dirs=paths)
148
149 if location.get("telinit", False) and os.path.exists("/etc/init.d/smgl_init"):
150 self.telinit_cmd = location["telinit"]
151
152 if self.telinit_cmd is None:
153 self.module.fail_json(msg="cannot find telinit script for simpleinit-msb, aborting...")
154
155 def get_service_status(self):
156 self.action = "status"
157 rc, status_stdout, status_stderr = self.service_control()
158
159 if self.running is None and status_stdout.count("\n") <= 1:
160 cleanout = status_stdout.lower().replace(self.name.lower(), "")
161
162 if "is not running" in cleanout:
163 self.running = False
164 elif "is running" in cleanout:
165 self.running = True
166
167 return self.running
168
169 def service_enable(self):
170 # Check if the service is already enabled/disabled
171 if not self.enable ^ self.service_enabled():
172 return
173
174 action = f"boot{'enable' if self.enable else 'disable'}"
175
176 (rc, out, err) = self.execute_command(f"{self.telinit_cmd} {action} {self.name}")
177
178 self.changed = True
179
180 for line in err.splitlines():
181 if self.enable and line.find("already enabled") != -1:
182 self.changed = False
183 break
184 if not self.enable and line.find("already disabled") != -1:
185 self.changed = False
186 break
187
188 if not self.changed:
189 return
190
191 return (rc, out, err)
192
193 def service_enabled(self):
194 self.service_exists()
195
196 (rc, out, err) = self.execute_command(f"{self.telinit_cmd} {self.enable}d")
197
198 service_enabled = not self.enable
199
200 rex = re.compile(rf"^{self.name}$")
201
202 for line in out.splitlines():
203 if rex.match(line):
204 service_enabled = True if self.enable else False
205 break
206
207 return service_enabled
208
209 def service_exists(self):
210 (rc, out, err) = self.execute_command(f"{self.telinit_cmd} list")
211
212 service_exists = False
213
214 rex = re.compile(rf"^\w+\s+{self.name}$")
215
216 for line in out.splitlines():
217 if rex.match(line):
218 service_exists = True
219 break
220
221 if not service_exists:
222 self.module.fail_json(msg=f"telinit could not find the requested service: {self.name}")
223
224 def service_control(self):
225 self.service_exists()
226
227 svc_cmd = f"{self.telinit_cmd} run {self.name}"
228
229 rc_state, stdout, stderr = self.execute_command(f"{svc_cmd} {self.action}", daemon=True)
230
231 return (rc_state, stdout, stderr)
232
233
234 def build_module():
235 return AnsibleModule(
236 argument_spec=dict(
237 name=dict(required=True, aliases=["service"]),
238 state=dict(choices=["running", "started", "stopped", "restarted", "reloaded"]),
239 enabled=dict(type="bool"),
240 ),
241 supports_check_mode=True,
242 required_one_of=[["state", "enabled"]],
243 )
244
245
246 def main():
247 module = build_module()
248
249 service = SimpleinitMSB(module)
250
251 rc = 0
252 out = ""
253 err = ""
254 result = {}
255 result["name"] = service.name
256
257 # Find service management tools
258 service.get_service_tools()
259
260 # Enable/disable service startup at boot if requested
261 if service.module.params["enabled"] is not None:
262 service.service_enable()
263 result["enabled"] = service.enable
264
265 if module.params["state"] is None:
266 # Not changing the running state, so bail out now.
267 result["changed"] = service.changed
268 module.exit_json(**result)
269
270 result["state"] = service.state
271
272 service.get_service_status()
273
274 # Calculate if request will change service state
275 service.check_service_changed()
276
277 # Modify service state if necessary
278 (rc, out, err) = service.modify_service_state()
279
280 if rc != 0:
281 if err:
282 module.fail_json(msg=err)
283 else:
284 module.fail_json(msg=out)
285
286 result["changed"] = service.changed | service.svc_change
287 if service.module.params["enabled"] is not None:
288 result["enabled"] = service.module.params["enabled"]
289
290 if not service.module.params["state"]:
291 status = service.get_service_status()
292 if status is None:
293 result["state"] = "absent"
294 elif status is False:
295 result["state"] = "started"
296 else:
297 result["state"] = "stopped"
298 else:
299 # as we may have just bounced the service the service command may not
300 # report accurate state at this moment so just show what we ran
301 if service.module.params["state"] in ["started", "restarted", "running", "reloaded"]:
302 result["state"] = "started"
303 else:
304 result["state"] = "stopped"
305
306 module.exit_json(**result)
307
308
309 if __name__ == "__main__":
310 main()