Debian Codegraph @

lib/ansible/module_utils/service.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c) Ansible Inc, 2016
8 # All rights reserved.
9 #
10 # Redistribution and use in source and binary forms, with or without modification,
11 # are permitted provided that the following conditions are met:
12 #
13 # * Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
23 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
27 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 from __future__ import annotations
30
31 import glob
32 import os
33 import pickle
34 import platform
35 import select
36 import shlex
37 import subprocess
38
39 from ansible.module_utils.common.text.converters import to_bytes, to_text
40
41
42 def sysv_is_enabled(name, runlevel=None):
43 """
44 This function will check if the service name supplied
45 is enabled in any of the sysv runlevels
46
47 :arg name: name of the service to test for
48 :kw runlevel: runlevel to check (default: None)
49 """
50 if runlevel:
51 if not os.path.isdir('/etc/rc0.d/'):
52 return bool(glob.glob('/etc/init.d/rc%s.d/S??%s' % (runlevel, name)))
53 return bool(glob.glob('/etc/rc%s.d/S??%s' % (runlevel, name)))
54 else:
55 if not os.path.isdir('/etc/rc0.d/'):
56 return bool(glob.glob('/etc/init.d/rc?.d/S??%s' % name))
57 return bool(glob.glob('/etc/rc?.d/S??%s' % name))
58
59
60 def get_sysv_script(name):
61 """
62 This function will return the expected path for an init script
63 corresponding to the service name supplied.
64
65 :arg name: name or path of the service to test for
66 """
67 if name.startswith('/'):
68 result = name
69 else:
70 result = '/etc/init.d/%s' % name
71
72 return result
73
74
75 def sysv_exists(name):
76 """
77 This function will return True or False depending on
78 the existence of an init script corresponding to the service name supplied.
79
80 :arg name: name of the service to test for
81 """
82 return os.path.exists(get_sysv_script(name))
83
84
85 def get_ps(module, pattern):
86 """
87 Last resort to find a service by trying to match pattern to programs in memory
88 """
89 found = False
90 if platform.system() == 'SunOS':
91 flags = '-ef'
92 else:
93 flags = 'auxww'
94 psbin = module.get_bin_path('ps', True)
95
96 (rc, psout, pserr) = module.run_command([psbin, flags])
97 if rc == 0:
98 for line in psout.splitlines():
99 if pattern in line:
100 # FIXME: should add logic to prevent matching 'self', though that should be extremely rare
101 found = True
102 break
103 return found
104
105
106 def fail_if_missing(module, found, service, msg=''):
107 """
108 This function will return an error or exit gracefully depending on check mode status
109 and if the service is missing or not.
110
111 :arg module: is an AnsibleModule object, used for it's utility methods
112 :arg found: boolean indicating if services were found or not
113 :arg service: name of service
114 :kw msg: extra info to append to error/success msg when missing
115 """
116 if not found:
117 module.fail_json(msg='Could not find the requested service %s: %s' % (service, msg))
118
119
120 def fork_process():
121 """
122 This function performs the double fork process to detach from the
123 parent process and execute.
124 """
125 pid = os.fork()
126
127 if pid == 0:
128 # Set stdin/stdout/stderr to /dev/null
129 fd = os.open(os.devnull, os.O_RDWR)
130
131 # clone stdin/out/err
132 for num in range(3):
133 if fd != num:
134 os.dup2(fd, num)
135
136 # close otherwise
137 if fd not in range(3):
138 os.close(fd)
139
140 # Make us a daemon
141 pid = os.fork()
142
143 # end if not in child
144 if pid > 0:
145 os._exit(0)
146
147 # get new process session and detach
148 os.setsid()
149
150 # avoid possible problems with cwd being removed
151 os.chdir("/")
152
153 pid = os.fork()
154 if pid > 0:
155 os._exit(0)
156
157 return pid
158
159
160 def daemonize(module, cmd):
161 """
162 Execute a command while detaching as a daemon, returns rc, stdout, and stderr.
163
164 :arg module: is an AnsibleModule object, used for it's utility methods
165 :arg cmd: is a list or string representing the command and options to run
166
167 This is complex because daemonization is hard for people.
168 What we do is daemonize a part of this module, the daemon runs the command,
169 picks up the return code and output, and returns it to the main process.
170 """
171
172 # init some vars
173 chunk = 4096 # FIXME: pass in as arg?
174 errors = 'surrogate_or_strict'
175
176 # start it!
177 try:
178 pipe = os.pipe()
179 pid = fork_process()
180 except (OSError, RuntimeError):
181 module.fail_json(msg="Error while attempting to fork.")
182 except Exception as exc:
183 module.fail_json(msg=to_text(exc))
184
185 # we don't do any locking as this should be a unique module/process
186 if pid == 0:
187 os.close(pipe[0])
188
189 if not isinstance(cmd, list):
190 cmd = shlex.split(to_text(cmd, errors=errors))
191
192 # make sure we always use byte strings
193 run_cmd = []
194 for c in cmd:
195 run_cmd.append(to_bytes(c, errors=errors))
196
197 # execute the command in forked process
198 p = subprocess.Popen(run_cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, preexec_fn=lambda: os.close(pipe[1]))
199 fds = [p.stdout, p.stderr]
200
201 # loop reading output till it is done
202 output = {p.stdout: b"", p.stderr: b""}
203 while fds:
204 rfd, wfd, efd = select.select(fds, [], fds, 1)
205 if (rfd + wfd + efd) or p.poll() is None:
206 for out in list(fds):
207 if out in rfd:
208 data = os.read(out.fileno(), chunk)
209 if data:
210 output[out] += to_bytes(data, errors=errors)
211 else:
212 fds.remove(out)
213 else:
214 break
215
216 # even after fds close, we might want to wait for pid to die
217 p.wait()
218
219 # Return a pickled data of parent
220 return_data = pickle.dumps([p.returncode, to_text(output[p.stdout]), to_text(output[p.stderr])], protocol=pickle.HIGHEST_PROTOCOL)
221 os.write(pipe[1], to_bytes(return_data, errors=errors))
222
223 # clean up
224 os.close(pipe[1])
225 os._exit(0)
226
227 elif pid == -1:
228 module.fail_json(msg="Unable to fork, no exception thrown, probably due to lack of resources, check logs.")
229
230 else:
231 # in parent
232 os.close(pipe[1])
233 os.waitpid(pid, 0)
234
235 # Grab response data after child finishes
236 return_data = b""
237 while True:
238 rfd, wfd, efd = select.select([pipe[0]], [], [pipe[0]])
239 if pipe[0] in rfd:
240 data = os.read(pipe[0], chunk)
241 if not data:
242 break
243 return_data += to_bytes(data, errors=errors)
244
245 return pickle.loads(to_bytes(return_data, errors=errors))
246
247
248 def check_ps(module, pattern):
249
250 # Set ps flags
251 if platform.system() == 'SunOS':
252 psflags = '-ef'
253 else:
254 psflags = 'auxww'
255
256 # Find ps binary
257 psbin = module.get_bin_path('ps', True)
258
259 (rc, out, err) = module.run_command('%s %s' % (psbin, psflags))
260 # If rc is 0, set running as appropriate
261 if rc == 0:
262 for line in out.split('\n'):
263 if pattern in line:
264 return True
265 return False
266
267
268 def is_systemd_managed(module):
269 """
270 Find out if the machine supports systemd or not
271 :arg module: is an AnsibleModule object, used for it's utility methods
272
273 Returns True if the system supports systemd, False if not.
274 """
275 # tools must be installed
276 if module.get_bin_path('systemctl'):
277 # This should show if systemd is the boot init system, if checking init failed to mark as systemd
278 # these mirror systemd's own sd_boot test http://www.freedesktop.org/software/systemd/man/sd_booted.html
279 for canary in ["/run/systemd/system/", "/dev/.run/systemd/", "/dev/.systemd/"]:
280 if os.path.exists(canary):
281 return True
282
283 # If all else fails, check if init is the systemd command, using comm as cmdline could be symlink
284 try:
285 with open('/proc/1/comm', 'r') as init_proc:
286 init = init_proc.readline().strip()
287 return init == 'systemd'
288 except OSError:
289 # If comm doesn't exist, old kernel, no systemd
290 return False
291
292 return False