Debian Codegraph @

lib/ansible/modules/async_wrapper.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Michael DeHaan <[email protected]>, and others
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 import json
10 import shlex
11 import shutil
12 import os
13 import subprocess
14 import sys
15 import traceback
16 import signal
17 import time
18 import syslog
19 import multiprocessing
20
21 from ansible.module_utils.common.text.converters import to_text, to_bytes
22
23 syslog.openlog('ansible-%s' % os.path.basename(__file__))
24 syslog.syslog(syslog.LOG_NOTICE, 'Invoked with %s' % " ".join(sys.argv[1:]))
25
26 # pipe for communication between forked process and parent
27 ipc_watcher, ipc_notifier = multiprocessing.Pipe()
28
29 job_path = ''
30
31
32 def notice(msg):
33 syslog.syslog(syslog.LOG_NOTICE, msg)
34
35
36 def end(res=None, exit_msg=0):
37 if res is not None:
38 print(json.dumps(res))
39 sys.stdout.flush()
40 sys.exit(exit_msg)
41
42
43 def daemonize_self():
44 # daemonizing code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012
45 try:
46 pid = os.fork()
47 if pid > 0:
48 # exit first parent
49 end()
50 except OSError:
51 e = sys.exc_info()[1]
52 end({'msg': "fork #1 failed: %d (%s)\n" % (e.errno, e.strerror), 'failed': True}, 1)
53
54 # decouple from parent environment (does not chdir / to keep the directory context the same as for non async tasks)
55 os.setsid()
56 os.umask(int('022', 8))
57
58 # do second fork
59 try:
60 pid = os.fork()
61 if pid > 0:
62 # TODO: print 'async_wrapper_pid': pid, but careful as it will pollute expected output.
63 end()
64 except OSError:
65 e = sys.exc_info()[1]
66 end({'msg': "fork #2 failed: %d (%s)\n" % (e.errno, e.strerror), 'failed': True}, 1)
67
68 dev_null = open('/dev/null', 'w')
69 os.dup2(dev_null.fileno(), sys.stdin.fileno())
70 os.dup2(dev_null.fileno(), sys.stdout.fileno())
71 os.dup2(dev_null.fileno(), sys.stderr.fileno())
72
73
74 # NB: this function copied from module_utils/json_utils.py. Ensure any changes are propagated there.
75 # FUTURE: AnsibleModule-ify this module so it's Ansiballz-compatible and can use the module_utils copy of this function.
76 def _filter_non_json_lines(data):
77 """
78 Used to filter unrelated output around module JSON output, like messages from
79 tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
80
81 Filters leading lines before first line-starting occurrence of '{', and filter all
82 trailing lines after matching close character (working from the bottom of output).
83 """
84 warnings = []
85
86 # Filter initial junk
87 lines = data.splitlines()
88
89 for start, line in enumerate(lines):
90 line = line.strip()
91 if line.startswith(u'{'):
92 break
93 else:
94 raise ValueError('No start of json char found')
95
96 # Filter trailing junk
97 lines = lines[start:]
98
99 for reverse_end_offset, line in enumerate(reversed(lines)):
100 if line.strip().endswith(u'}'):
101 break
102 else:
103 raise ValueError('No end of json char found')
104
105 if reverse_end_offset > 0:
106 # Trailing junk is uncommon and can point to things the user might
107 # want to change. So print a warning if we find any
108 trailing_junk = lines[len(lines) - reverse_end_offset:]
109 for line in trailing_junk:
110 if line.strip():
111 warnings.append('Module invocation had junk after the JSON data: %s' % '\n'.join(trailing_junk))
112 break
113
114 lines = lines[:(len(lines) - reverse_end_offset)]
115
116 return ('\n'.join(lines), warnings)
117
118
119 def jwrite(info):
120 jobfile = job_path + ".tmp"
121 tjob = open(jobfile, "w")
122 try:
123 tjob.write(json.dumps(info))
124 except OSError as ex:
125 notice(f'failed to write to {jobfile!r}: {ex}')
126 raise
127 finally:
128 tjob.close()
129 os.rename(jobfile, job_path)
130
131
132 def _run_module(jid, *module_args):
133
134 # DTFIX-FUTURE: needs rework for serialization profiles
135
136 jwrite({"started": True, "finished": False, "ansible_job_id": jid})
137
138 result = {}
139
140 # signal grandchild process started and isolated from being terminated
141 # by the connection being closed sending a signal to the job group
142 ipc_notifier.send(True)
143 ipc_notifier.close()
144
145 outdata = ''
146 filtered_outdata = ''
147 stderr = ''
148 try:
149 cmd = [to_bytes(a) for a in module_args]
150
151 script = subprocess.Popen(
152 cmd,
153 stdin=subprocess.PIPE,
154 stdout=subprocess.PIPE,
155 stderr=subprocess.PIPE,
156 shell=False,
157 text=True,
158 encoding="utf-8",
159 errors="surrogateescape",
160 )
161
162 (outdata, stderr) = script.communicate()
163
164 (filtered_outdata, json_warnings) = _filter_non_json_lines(outdata)
165
166 result = json.loads(filtered_outdata)
167
168 if json_warnings:
169 # merge JSON junk warnings with any existing module warnings
170 module_warnings = result.get('warnings', [])
171 if not isinstance(module_warnings, list):
172 module_warnings = [module_warnings]
173
174 # this relies on the controller's fallback conversion of string warnings to WarningMessageDetail instances, and assumes
175 # that the module result and warning collection are basic JSON datatypes (eg, no tags or other custom collections).
176 module_warnings.extend(json_warnings)
177 result['warnings'] = module_warnings
178
179 if stderr:
180 result['stderr'] = stderr
181 jwrite(result)
182
183 except OSError:
184 e = sys.exc_info()[1]
185 result = {
186 "failed": True,
187 "cmd": shlex.join(module_args),
188 "msg": to_text(e),
189 "outdata": outdata, # temporary notice only
190 "stderr": stderr
191 }
192 result['ansible_job_id'] = jid
193 jwrite(result)
194
195 except Exception:
196 result = {
197 "failed": True,
198 "cmd": shlex.join(module_args),
199 "data": outdata, # temporary notice only
200 "stderr": stderr,
201 "msg": traceback.format_exc()
202 }
203 result['ansible_job_id'] = jid
204 jwrite(result)
205
206
207 def main():
208 if len(sys.argv) < 5:
209 end({
210 "failed": True,
211 "msg": "usage: async_wrapper <jid> <time_limit> <preserve_tmp> <module_path> <invocation_args> ..."
212 "Humans, do not call directly!"
213 }, 1)
214
215 jid = "%s.%d" % (sys.argv[1], os.getpid())
216 time_limit = sys.argv[2]
217 preserve_tmp = sys.argv[3].lower() == 'true'
218 wrapped_module = sys.argv[4]
219 invocation_args = sys.argv[5:]
220 step = 5
221
222 async_dir = os.environ.get('ANSIBLE_ASYNC_DIR', '~/.ansible_async')
223
224 # setup job output directory
225 jobdir = os.path.expanduser(async_dir)
226 global job_path
227 job_path = os.path.join(jobdir, jid)
228
229 try:
230 # TODO: Add checks for permissions on path.
231 os.makedirs(jobdir, exist_ok=True)
232 except Exception as e:
233 end({
234 "failed": True,
235 "msg": "could not create directory: %s - %s" % (jobdir, to_text(e)),
236 "exception": to_text(traceback.format_exc()), # NB: task executor compat will coerce to the correct dataclass type
237 }, 1)
238
239 # immediately exit this process, leaving an orphaned process
240 # running which immediately forks a supervisory timing process
241
242 try:
243 pid = os.fork()
244 if pid:
245 # Notify the overlord that the async process started
246
247 # we need to not return immediately such that the launched command has an attempt
248 # to initialize PRIOR to ansible trying to clean up the launch directory (and argsfile)
249 # this probably could be done with some IPC later. Modules should always read
250 # the argsfile at the very first start of their execution anyway
251
252 # close off notifier handle in grandparent, probably unnecessary as
253 # this process doesn't hang around long enough
254 ipc_notifier.close()
255
256 # allow waiting up to 2.5 seconds in total should be long enough for worst
257 # loaded environment in practice.
258 retries = 25
259 while retries > 0:
260 if ipc_watcher.poll(0.1):
261 break
262 else:
263 retries = retries - 1
264 continue
265
266 notice("Return async_wrapper task started.")
267 end({"failed": False, "started": True, "finished": False, "ansible_job_id": jid, "results_file": job_path,
268 "_ansible_suppress_tmpdir_delete": (not preserve_tmp)}, 0)
269 else:
270 # The actual wrapper process
271
272 # close off the receiving end of the pipe from child process
273 ipc_watcher.close()
274
275 # Daemonize, so we keep on running
276 daemonize_self()
277
278 # we are now daemonized, create a supervisory process
279 notice("Starting module and watcher")
280
281 sub_pid = os.fork()
282 if sub_pid:
283 # close off inherited pipe handles
284 ipc_watcher.close()
285 ipc_notifier.close()
286
287 # the parent stops the process after the time limit
288 remaining = int(time_limit)
289
290 # set the child process group id to kill all children
291 os.setpgid(sub_pid, sub_pid)
292
293 notice("Start watching %s (%s)" % (sub_pid, remaining))
294
295 if remaining != 0 and step >= remaining:
296 step = remaining / 2
297
298 time.sleep(step)
299
300 while os.waitpid(sub_pid, os.WNOHANG) == (0, 0):
301 remaining = remaining - step
302 notice("%s still running (%s)" % (sub_pid, remaining))
303 if remaining <= 0:
304 # actually kill it
305 notice("Timeout reached, now killing %s" % (sub_pid))
306 os.killpg(sub_pid, signal.SIGKILL)
307 notice("Sent kill to group %s " % sub_pid)
308 time.sleep(1)
309
310 # ensure we leave response in poll location
311 res = {'msg': 'Timeout exceeded', 'failed': True, 'child_pid': sub_pid}
312 jwrite(res)
313
314 if not preserve_tmp:
315 shutil.rmtree(os.path.dirname(wrapped_module), True)
316 end(res)
317
318 time.sleep(step)
319 notice("Done in kid B.")
320 if not preserve_tmp:
321 shutil.rmtree(os.path.dirname(wrapped_module), True)
322 end()
323 else:
324 # the child process runs the actual module
325 notice("Start module (%s)" % os.getpid())
326 _run_module(jid, *invocation_args)
327 notice("Module complete (%s)" % os.getpid())
328
329 except Exception as e:
330 notice("error: %s" % e)
331 end({"failed": True, "msg": "FATAL ERROR: %s" % e}, "async_wrapper exited prematurely")
332
333
334 if __name__ == '__main__':
335 main()