Debian Codegraph @

lib/ansible/executor/process/worker.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import errno
21 import io
22 import os
23 import signal
24 import sys
25 import textwrap
26 import traceback
27 import types
28 import typing as t
29
30 from multiprocessing.queues import Queue
31
32 from ansible._internal import _task
33 from ansible import constants as C
34 from ansible.errors import AnsibleError
35 from ansible.executor.task_executor import TaskExecutor
36 from ansible.executor.task_queue_manager import FinalQueue, STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO
37 from ansible.inventory.host import Host
38 from ansible.module_utils._internal import _debug
39 from ansible.parsing.dataloader import DataLoader
40 from ansible.playbook.task import Task
41 from ansible.playbook.play_context import PlayContext
42 from ansible.utils.context_objects import CLIArgs
43 from ansible.utils.display import Display
44 from ansible.utils.multiprocessing import context as multiprocessing_context
45 from ansible.vars.manager import VariableManager
46
47 __all__ = ['WorkerProcess']
48
49 display = Display()
50
51 current_worker = None
52
53
54 class WorkerQueue(Queue):
55 """Queue that raises AnsibleError items on get()."""
56 def get(self, *args, **kwargs):
57 result = super(WorkerQueue, self).get(*args, **kwargs)
58 if isinstance(result, AnsibleError):
59 raise result
60 return result
61
62
63 class WorkerProcess(multiprocessing_context.Process): # type: ignore[name-defined]
64 """
65 The worker thread class, which uses TaskExecutor to run tasks
66 read from a job queue and pushes results into a results queue
67 for reading later.
68 """
69
70 def __init__(
71 self,
72 *,
73 final_q: FinalQueue,
74 task_vars: dict,
75 host: Host,
76 task: Task,
77 play_context: PlayContext,
78 loader: DataLoader,
79 variable_manager: VariableManager,
80 shared_loader_obj: types.SimpleNamespace,
81 worker_id: int,
82 cliargs: CLIArgs,
83 stacktrace_dir: str | None = None,
84 ) -> None:
85
86 super(WorkerProcess, self).__init__()
87 # takes a task queue manager as the sole param:
88 self._final_q = final_q
89 self._task_vars = task_vars
90 self._host = host
91 self._task = task
92 self._play_context = play_context
93 self._loader = loader
94 self._variable_manager = variable_manager
95 self._shared_loader_obj = shared_loader_obj
96
97 # NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files
98 # clear var to ensure we only delete files for this child
99 self._loader._tempfiles = set()
100
101 self.worker_queue = WorkerQueue(ctx=multiprocessing_context)
102 self.worker_id = worker_id
103
104 self._cliargs = cliargs
105 self._stacktrace_dir = stacktrace_dir
106
107 def _term(self, signum, frame) -> None:
108 """In child termination when notified by the parent"""
109 signal.signal(signum, signal.SIG_DFL)
110
111 try:
112 os.killpg(self.pid, signum)
113 os.kill(self.pid, signum)
114 except OSError as e:
115 if e.errno != errno.ESRCH:
116 signame = signal.strsignal(signum)
117 display.error(f'Unable to send {signame} to child[{self.pid}]: {e}')
118
119 # fallthrough, if we are still here, just die
120 os._exit(1)
121
122 def start(self) -> None:
123 """
124 multiprocessing.Process replaces the worker's stdin with a new file
125 but we wish to preserve it if it is connected to a terminal.
126 Therefore dup a copy prior to calling the real start(),
127 ensuring the descriptor is preserved somewhere in the new child, and
128 make sure it is closed in the parent when start() completes.
129 """
130
131 # FUTURE: this lock can be removed once a more generalized pre-fork thread pause is in place
132 with display._lock:
133 super(WorkerProcess, self).start()
134
135 def _hard_exit(self, e: str) -> t.NoReturn:
136 """
137 There is no safe exception to return to higher level code that does not
138 risk an innocent try/except finding itself executing in the wrong
139 process. All code executing above WorkerProcess.run() on the stack
140 conceptually belongs to another program.
141 """
142
143 try:
144 display.error(e)
145 except BaseException:
146 # If the cause of the fault is OSError being generated by stdio,
147 # attempting to log a debug message may trigger another OSError.
148 # Try printing once then give up.
149 pass
150
151 os._exit(1)
152
153 def _detach(self) -> None:
154 """
155 The intent here is to detach the child process from the inherited stdio fds,
156 including /dev/tty. Children should use Display instead of direct interactions
157 with stdio fds.
158 """
159 try:
160 if C.config.get_config_value('WORKER_SESSION_ISOLATION', variables=self._task_vars):
161 os.setsid() # create a new session and process group for this worker (fully isolated from parent session resources, e.g., inherited TTY)
162 else:
163 os.setpgid(0, 0) # isolation disabled, just make this worker a new process group leader for granular child process tracking
164
165 # Create new fds for stdin/stdout/stderr, but also capture python uses of sys.stdout/stderr
166 for fds, mode in (
167 ((STDIN_FILENO,), os.O_RDWR | os.O_NONBLOCK),
168 ((STDOUT_FILENO, STDERR_FILENO), os.O_WRONLY),
169 ):
170 stdio = os.open(os.devnull, mode)
171 for fd in fds:
172 os.dup2(stdio, fd)
173 os.close(stdio)
174 sys.stdout = io.StringIO()
175 sys.stderr = io.StringIO()
176 sys.stdin = os.fdopen(STDIN_FILENO, 'r', closefd=False)
177 # Close stdin so we don't get hanging workers
178 # We use sys.stdin.close() for places where sys.stdin is used,
179 # to give better errors, and to prevent fd 0 reuse
180 sys.stdin.close()
181 except Exception as e:
182 display.error(f'Could not detach from stdio: {e}')
183 os._exit(1)
184
185 def run(self) -> None:
186 """
187 Wrap _run() to ensure no possibility an errant exception can cause
188 control to return to the StrategyBase task loop, or any other code
189 higher in the stack.
190
191 As multiprocessing in Python 2.x provides no protection, it is possible
192 a try/except added in far-away code can cause a crashed child process
193 to suddenly assume the role and prior state of its parent.
194 """
195 # Set the queue on Display so calls to Display.display are proxied over the queue
196 display.set_queue(self._final_q)
197 self._detach()
198
199 # No need to create the stacktrace directory since TQM does that for us.
200 _debug.register_for_stacktrace(self._stacktrace_dir)
201
202 # propagate signals
203 signal.signal(signal.SIGINT, self._term)
204 signal.signal(signal.SIGTERM, self._term)
205
206 try:
207 with _task.TaskContext.create(task=self._task, task_vars=self._task_vars, host_name=self._host.name):
208 return self._run()
209 except BaseException:
210 self._hard_exit(traceback.format_exc())
211
212 def _run(self) -> None:
213 """
214 Called when the process is started. Pushes the result onto the
215 results queue. We also remove the host from the blocked hosts list, to
216 signify that they are ready for their next task.
217 """
218
219 global current_worker
220
221 current_worker = self
222
223 self._task.squash()
224
225 te = TaskExecutor(
226 self._host,
227 self._play_context,
228 self._loader,
229 self._shared_loader_obj,
230 self._final_q,
231 self._variable_manager,
232 )
233
234 utr = te.run()
235 utr.finalize_registered_values()
236
237 self._host.vars = dict()
238 self._host.groups = []
239
240 for name, stdio in (('stdout', sys.stdout), ('stderr', sys.stderr)):
241 if data := stdio.getvalue(): # type: ignore[union-attr]
242 display.warning(
243 (
244 f'WorkerProcess for [{self._host}/{self._task}] errantly sent data directly to {name} instead of using Display:\n'
245 f'{textwrap.indent(data[:256], " ")}\n'
246 ),
247 formatted=True
248 )
249
250 # manually update the original task object's values with final post-loop-resolved values since callbacks consult them
251 self._task.ignore_errors = utr.ignore_errors
252 self._task.ignore_unreachable = utr.ignore_unreachable
253
254 try:
255 self._final_q.send_task_result(self._host, self._task, utr)
256 except Exception as ex:
257 try:
258 raise AnsibleError("Task result omitted due to queue send failure.") from ex
259 except Exception as ex_wrapper:
260 host = Host(name=self._host.name)
261
262 task = Task()
263 task._uuid = self._task._uuid
264
265 utr = _task.UnifiedTaskResult.create_from_action_exception(ex_wrapper)
266 utr.finalize_registered_values()
267
268 # ignore the real task result and don't allow result object contribution from the exception (in case the pickling error was related)
269 # also use a synthesized host and task object to avoid issues with values from them, particularly task_fields
270 self._final_q.send_task_result(host, task, utr)