Debian Codegraph @

lib/ansible/plugins/strategy/free.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 from __future__ import annotations
18
19 DOCUMENTATION = """
20 name: free
21 short_description: Executes tasks without waiting for all hosts
22 description:
23 - Task execution is as fast as possible per batch as defined by C(serial) (default all).
24 Ansible will not wait for other hosts to finish the current task before queuing more tasks for other hosts.
25 All hosts are still attempted for the current task, but it prevents blocking new tasks for hosts that have already finished.
26 - With the free strategy, unlike the default linear strategy, a host that is slow or stuck on a specific task
27 won't hold up the rest of the hosts and tasks.
28 version_added: "2.0"
29 author: Ansible Core Team
30 """
31
32 import time
33
34 from ansible import constants as C
35 from ansible._internal import _task
36 from ansible.errors import AnsibleError, AnsibleParserError
37 from ansible.playbook.handler import Handler
38 from ansible.playbook.included_file import IncludedFile
39 from ansible.plugins.loader import action_loader
40 from ansible.plugins.strategy import StrategyBase
41 from ansible._internal._templating._engine import TemplateEngine
42 from ansible.utils.display import Display
43 from ansible.executor.play_iterator import PlayIterator
44 from ansible.playbook.play_context import PlayContext
45
46 display = Display()
47
48
49 class StrategyModule(StrategyBase):
50
51 # This strategy manages throttling on its own, so we don't want it done in queue_task
52 ALLOW_BASE_THROTTLING = False
53
54 def __init__(self, tqm):
55 super(StrategyModule, self).__init__(tqm)
56 self._host_pinned = False
57
58 def run(self, iterator: PlayIterator, play_context: PlayContext): # type: ignore[override]
59 """
60 The "free" strategy is a bit more complex, in that it allows tasks to
61 be sent to hosts as quickly as they can be processed. This means that
62 some hosts may finish very quickly if run tasks result in little or no
63 work being done versus other systems.
64
65 The algorithm used here also tries to be more "fair" when iterating
66 through hosts by remembering the last host in the list to be given a task
67 and starting the search from there as opposed to the top of the hosts
68 list again, which would end up favoring hosts near the beginning of the
69 list.
70 """
71
72 # the last host to be given a task
73 last_host = 0
74
75 result = int(self._tqm.RUN_OK)
76
77 # start with all workers being counted as being free
78 workers_free = len(self._workers)
79
80 self._set_hosts_cache(iterator._play)
81
82 if iterator._play.max_fail_percentage is not None:
83 display.warning("Using max_fail_percentage with the free strategy is not supported, as tasks are executed independently on each host")
84
85 work_to_do = True
86 while work_to_do and not self._tqm._terminated:
87
88 hosts_left = self.get_hosts_left(iterator)
89
90 if len(hosts_left) == 0:
91 self._tqm.send_callback('v2_playbook_on_no_hosts_remaining')
92 result = False
93 break
94
95 # Reset last_host if it's out of bounds for the current hosts_left
96 # This can happen when hosts become unreachable between iterations
97 if last_host >= len(hosts_left):
98 last_host = 0
99
100 work_to_do = False # assume we have no more work to do
101 starting_host = last_host # save current position so we know when we've looped back around and need to break
102
103 # try and find an unblocked host with a task to run
104 host_results = []
105 meta_task_dummy_results_count = 0
106 while True:
107 host = hosts_left[last_host]
108 display.debug("next free host: %s" % host)
109 host_name = host.get_name()
110
111 # peek at the next task for the host, to see if there's
112 # anything to do do for this host
113 (state, task) = iterator.get_next_task_for_host(host, peek=True)
114 display.debug("free host state: %s" % state, host=host_name)
115 display.debug("free host task: %s" % task, host=host_name)
116
117 # check if there is work to do, either there is a task or the host is still blocked which could
118 # mean that it is processing an include task and after its result is processed there might be
119 # more tasks to run
120 if (task or self._blocked_hosts.get(host_name, False)) and not self._tqm._unreachable_hosts.get(host_name, False):
121 display.debug("this host has work to do", host=host_name)
122 # set the flag so the outer loop knows we've still found
123 # some work which needs to be done
124 work_to_do = True
125
126 if not self._tqm._unreachable_hosts.get(host_name, False) and task:
127 # check to see if this host is blocked (still executing a previous task)
128 if not self._blocked_hosts.get(host_name, False):
129 display.debug("getting variables", host=host_name)
130 task_vars = self._variable_manager.get_vars(play=iterator._play, host=host, task=task,
131 _hosts=self._hosts_cache,
132 _hosts_all=self._hosts_cache_all)
133 self.add_tqm_variables(task_vars, play=iterator._play)
134 templar = TemplateEngine(loader=self._loader, variables=task_vars)
135 display.debug("done getting variables", host=host_name)
136
137 try:
138 throttle = int(templar.template(task.throttle))
139 except Exception as ex:
140 raise AnsibleError("Failed to convert the throttle value to an integer.", obj=task.throttle) from ex
141
142 if throttle > 0:
143 same_tasks = 0
144 for worker in self._workers:
145 if worker and worker.is_alive() and worker._task._uuid == task._uuid:
146 same_tasks += 1
147
148 display.debug("task: %s, same_tasks: %d" % (task.get_name(), same_tasks))
149 if same_tasks >= throttle:
150 break
151
152 iterator.set_state_for_host(host.name, state)
153 if isinstance(task, Handler):
154 task.remove_host(host)
155
156 try:
157 action = action_loader.get(task.action, class_only=True, collection_list=task.collections)
158 except KeyError:
159 # we don't care here, because the action may simply not have a
160 # corresponding action plugin
161 action = None
162
163 task.post_validate_attribute("name", templar=templar)
164
165 run_once = templar.template(task.run_once) or action and getattr(action, 'BYPASS_HOST_LOOP', False)
166 if run_once:
167 if action and getattr(action, 'BYPASS_HOST_LOOP', False):
168 raise AnsibleError("The '%s' module bypasses the host loop, which is currently not supported in the free strategy "
169 "and would instead execute for every host in the inventory list." % task.action, obj=task._ds)
170 else:
171 display.warning("Using run_once with the free strategy is not currently supported. This task will still be "
172 "executed for every host in the inventory list.")
173
174 if task.action in C._ACTION_META:
175 if self._host_pinned:
176 meta_task_dummy_results_count += 1
177 workers_free -= 1
178 self._execute_meta(task, play_context, iterator, target_host=host)
179 else:
180 # handle step if needed, skip meta actions as they are used internally
181 if not self._step or self._take_step(task, host_name):
182 if task.any_errors_fatal:
183 display.warning("Using any_errors_fatal with the free strategy is not supported, "
184 "as tasks are executed independently on each host")
185 if isinstance(task, Handler):
186 self._tqm.send_callback('v2_playbook_on_handler_task_start', task)
187 else:
188 self._tqm.send_callback('v2_playbook_on_task_start', task, is_conditional=False)
189 self._queue_task(host, task, task_vars, play_context)
190 # each task is counted as a worker being busy
191 workers_free -= 1
192 del task_vars
193 else:
194 display.debug("%s is blocked, skipping for now" % host_name)
195
196 # all workers have tasks to do (and the current host isn't done with the play).
197 # loop back to starting host and break out
198 if self._host_pinned and workers_free == 0 and work_to_do:
199 last_host = starting_host
200 break
201
202 # move on to the next host and make sure we
203 # haven't gone past the end of our hosts list
204 last_host += 1
205 if last_host > len(hosts_left) - 1:
206 last_host = 0
207
208 # if we've looped around back to the start, break out
209 if last_host == starting_host:
210 break
211
212 results = self._process_pending_results(iterator)
213 host_results.extend(results)
214
215 # each result is counted as a worker being free again
216 workers_free += len(results) + meta_task_dummy_results_count
217
218 self.update_active_connections(results)
219
220 included_files = IncludedFile.process_include_results(
221 host_results,
222 iterator=iterator,
223 loader=self._loader,
224 variable_manager=self._variable_manager
225 )
226
227 if len(included_files) > 0:
228 all_blocks = dict((host, []) for host in hosts_left)
229 failed_includes_hosts = set()
230 for included_file in included_files:
231 display.debug("collecting new blocks for %s" % included_file)
232 is_handler = False
233 try:
234 if included_file._is_role:
235 new_ir = self._copy_included_file(included_file)
236
237 new_blocks, handler_blocks = new_ir.get_block_list(
238 play=iterator._play,
239 variable_manager=self._variable_manager,
240 loader=self._loader,
241 )
242 else:
243 is_handler = isinstance(included_file._task, Handler)
244 new_blocks = self._load_included_file(
245 included_file,
246 iterator=iterator,
247 is_handler=is_handler,
248 )
249
250 # let PlayIterator know about any new handlers included via include_role or
251 # import_role within include_role/include_taks
252 iterator.handlers = [h for b in iterator._play.handlers for h in b.block]
253 except AnsibleParserError:
254 raise
255 except AnsibleError as ex:
256 for r in included_file._results:
257 # RPFIX-9: FUTURE: do this better, instead of creating a throw-away UTR to merge onto the existing one
258 utr = _task.UnifiedTaskResult._create_from_exception(ex, source_is_module=False)
259
260 r.utr.failed = utr.failed
261 r.utr.exception = utr.exception
262 r.utr.msg = utr.msg
263
264 self._tqm._stats.increment('failures', r.host.name)
265 self._tqm.send_callback('v2_runner_on_failed', r)
266 failed_includes_hosts.add(r.host)
267 continue
268 else:
269 # since we skip incrementing the stats when the task result is
270 # first processed, we do so now for each host in the list
271 for host in included_file._hosts:
272 self._tqm._stats.increment('ok', host.name)
273 self._tqm.send_callback('v2_playbook_on_include', included_file)
274
275 for new_block in new_blocks:
276 if is_handler:
277 for task in new_block.block:
278 task.notified_hosts = included_file._hosts[:]
279 final_block = new_block
280 else:
281 task_vars = self._variable_manager.get_vars(
282 play=iterator._play,
283 task=new_block.get_first_parent_include(),
284 _hosts=self._hosts_cache,
285 _hosts_all=self._hosts_cache_all,
286 )
287 final_block = new_block.filter_tagged_tasks(task_vars)
288 for host in hosts_left:
289 if host in included_file._hosts:
290 all_blocks[host].append(final_block)
291 display.debug("done collecting new blocks for %s" % included_file)
292
293 for host in failed_includes_hosts:
294 self._tqm._failed_hosts[host.name] = True
295 iterator.mark_host_failed(host)
296
297 display.debug("adding all collected blocks from %d included file(s) to iterator" % len(included_files))
298 for host in hosts_left:
299 iterator.add_tasks(host, all_blocks[host])
300 display.debug("done adding collected blocks to iterator")
301
302 # pause briefly so we don't spin lock
303 time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
304
305 # collect all the final results
306 results = self._wait_on_pending_results(iterator)
307
308 # run the base class run() method, which executes the cleanup function
309 # and runs any outstanding handlers which have been triggered
310 return super(StrategyModule, self).run(iterator, play_context, result)