Debian Codegraph @

lib/ansible/executor/playbook_executor.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 os
21
22 from ansible import constants as C
23 from ansible import context
24 from ansible.executor.task_queue_manager import TaskQueueManager, AnsibleEndPlay
25 from ansible.module_utils.common.text.converters import to_text
26 from ansible.module_utils.parsing.convert_bool import boolean
27 from ansible.plugins.loader import become_loader, connection_loader, shell_loader
28 from ansible.playbook import Playbook
29 from ansible._internal._templating._engine import TemplateEngine
30 from ansible.utils.helpers import pct_to_int
31 from ansible.utils.collection_loader import AnsibleCollectionConfig
32 from ansible.utils.collection_loader._collection_finder import _get_collection_name_from_path, _get_collection_playbook_path
33 from ansible.utils.path import makedirs_safe
34 from ansible.utils.display import Display
35
36
37 display = Display()
38
39
40 class PlaybookExecutor:
41
42 """
43 This is the primary class for executing playbooks, and thus the
44 basis for bin/ansible-playbook operation.
45 """
46
47 def __init__(self, playbooks, inventory, variable_manager, loader, passwords):
48 self._playbooks = playbooks
49 self._inventory = inventory
50 self._variable_manager = variable_manager
51 self._loader = loader
52 self.passwords = passwords
53 self._unreachable_hosts = dict()
54
55 if context.CLIARGS.get('listhosts') or context.CLIARGS.get('listtasks') or \
56 context.CLIARGS.get('listtags') or context.CLIARGS.get('syntax'):
57 self._tqm = None
58 else:
59 self._tqm = TaskQueueManager(
60 inventory=inventory,
61 variable_manager=variable_manager,
62 loader=loader,
63 passwords=self.passwords,
64 forks=context.CLIARGS.get('forks'),
65 )
66
67 def run(self):
68 """
69 Run the given playbook, based on the settings in the play which
70 may limit the runs to serialized groups, etc.
71 """
72
73 result = 0
74 entrylist = []
75 entry = {}
76 try:
77 # preload become/connection/shell to set config defs cached
78 list(connection_loader.all(class_only=True))
79 list(shell_loader.all(class_only=True))
80 list(become_loader.all(class_only=True))
81
82 for playbook in self._playbooks:
83
84 # deal with FQCN
85 resource = _get_collection_playbook_path(playbook)
86 if resource is not None:
87 playbook_path = resource[1]
88 playbook_collection = resource[2]
89 else:
90 playbook_path = playbook
91 # not fqcn, but might still be collection playbook
92 playbook_collection = _get_collection_name_from_path(playbook)
93
94 if playbook_collection:
95 display.v("running playbook inside collection {0}".format(playbook_collection))
96 AnsibleCollectionConfig.default_collection = playbook_collection
97 else:
98 AnsibleCollectionConfig.default_collection = None
99
100 pb = Playbook.load(playbook_path, variable_manager=self._variable_manager, loader=self._loader)
101 # FIXME: move out of inventory self._inventory.set_playbook_basedir(os.path.realpath(os.path.dirname(playbook_path)))
102
103 if self._tqm is None: # we are doing a listing
104 entry = {'playbook': playbook_path}
105 entry['plays'] = []
106 else:
107 # make sure the tqm has callbacks loaded
108 self._tqm.load_callbacks()
109 self._tqm.send_callback('v2_playbook_on_start', pb)
110
111 i = 1
112 plays = pb.get_plays()
113 display.vv(u'%d plays in %s' % (len(plays), to_text(playbook_path)))
114
115 for play in plays:
116 if play._included_path is not None:
117 self._loader.set_basedir(play._included_path)
118 else:
119 self._loader.set_basedir(pb._basedir)
120
121 # clear any filters which may have been applied to the inventory
122 self._inventory.remove_restriction()
123
124 # Allow variables to be used in vars_prompt fields.
125 all_vars = self._variable_manager.get_vars(play=play)
126 templar = TemplateEngine(loader=self._loader, variables=all_vars)
127 setattr(play, 'vars_prompt', templar.template(play.vars_prompt))
128
129 # FIXME: this should be a play 'sub object' like loop_control
130 if play.vars_prompt:
131 for var in play.vars_prompt:
132 vname = var['name']
133 prompt = var.get("prompt", vname)
134 default = var.get("default", None)
135 private = boolean(var.get("private", True))
136 confirm = boolean(var.get("confirm", False))
137 encrypt = var.get("encrypt", None)
138 salt_size = var.get("salt_size", None)
139 salt = var.get("salt", None)
140 unsafe = boolean(var.get("unsafe", False))
141
142 if vname not in self._variable_manager.extra_vars:
143 if self._tqm:
144 self._tqm.send_callback('v2_playbook_on_vars_prompt', vname, private, prompt, encrypt, confirm, salt_size, salt,
145 default, unsafe)
146 play.vars[vname] = display.do_var_prompt(vname, private, prompt, encrypt, confirm, salt_size, salt, default, unsafe)
147 else: # we are either in --list-<option> or syntax check
148 play.vars[vname] = default
149
150 # Post validate so any play level variables are templated
151 all_vars = self._variable_manager.get_vars(play=play)
152 templar = TemplateEngine(loader=self._loader, variables=all_vars)
153 play.post_validate(templar)
154
155 if context.CLIARGS['syntax']:
156 continue
157
158 if self._tqm is None:
159 # we are just doing a listing
160 entry['plays'].append(play)
161
162 else:
163 self._tqm._unreachable_hosts.update(self._unreachable_hosts)
164
165 previously_failed = len(self._tqm._failed_hosts)
166 previously_unreachable = len(self._tqm._unreachable_hosts)
167
168 break_play = False
169 # we are actually running plays
170 batches = self._get_serialized_batches(play)
171 if len(batches) == 0:
172 self._tqm.send_callback('v2_playbook_on_play_start', play)
173 self._tqm.send_callback('v2_playbook_on_no_hosts_matched')
174 for batch in batches:
175 # restrict the inventory to the hosts in the serialized batch
176 self._inventory.restrict_to_hosts(batch)
177 # and run it...
178 try:
179 result = self._tqm.run(play=play)
180 except AnsibleEndPlay as e:
181 result = e.result
182 break
183
184 # break the play if the result equals the special return code
185 if result & self._tqm.RUN_FAILED_BREAK_PLAY != 0:
186 result = self._tqm.RUN_FAILED_HOSTS
187 break_play = True
188
189 # check the number of failures here and break out if the entire batch failed
190 failed_hosts_count = len(self._tqm._failed_hosts) + len(self._tqm._unreachable_hosts) - \
191 (previously_failed + previously_unreachable)
192
193 if len(batch) == failed_hosts_count:
194 break_play = True
195 break
196
197 # update the previous counts so they don't accumulate incorrectly
198 # over multiple serial batches
199 previously_failed += len(self._tqm._failed_hosts) - previously_failed
200 previously_unreachable += len(self._tqm._unreachable_hosts) - previously_unreachable
201
202 # save the unreachable hosts from this batch
203 self._unreachable_hosts.update(self._tqm._unreachable_hosts)
204
205 if break_play:
206 break
207
208 i = i + 1 # per play
209
210 if entry:
211 entrylist.append(entry) # per playbook
212
213 # send the stats callback for this playbook
214 if self._tqm is not None:
215 if C.RETRY_FILES_ENABLED:
216 retries = set(self._tqm._failed_hosts.keys())
217 retries.update(self._tqm._unreachable_hosts.keys())
218 retries = sorted(retries)
219 if len(retries) > 0:
220 if C.RETRY_FILES_SAVE_PATH:
221 basedir = C.RETRY_FILES_SAVE_PATH
222 elif playbook_path:
223 basedir = os.path.dirname(os.path.abspath(playbook_path))
224 else:
225 basedir = '~/'
226
227 (retry_name, ext) = os.path.splitext(os.path.basename(playbook_path))
228 filename = os.path.join(basedir, "%s.retry" % retry_name)
229 if self._generate_retry_inventory(filename, retries):
230 display.display("\tto retry, use: --limit @%s\n" % filename)
231
232 self._tqm.send_callback('v2_playbook_on_stats', self._tqm._stats)
233
234 # if the last result wasn't zero, break out of the playbook file name loop
235 if result != 0:
236 break
237
238 if entrylist:
239 return entrylist
240
241 finally:
242 if self._tqm is not None:
243 self._tqm.cleanup()
244 if self._loader:
245 self._loader.cleanup_all_tmp_files()
246
247 if context.CLIARGS['syntax']:
248 display.display("No issues encountered")
249 return result
250
251 if context.CLIARGS['start_at_task'] and not self._tqm._start_at_done:
252 display.error(
253 "No matching task \"%s\" found."
254 " Note: --start-at-task can only follow static includes."
255 % context.CLIARGS['start_at_task']
256 )
257
258 return result
259
260 def _get_serialized_batches(self, play):
261 """
262 Returns a list of hosts, subdivided into batches based on
263 the serial size specified in the play.
264 """
265
266 # make sure we have a unique list of hosts
267 all_hosts = self._inventory.get_hosts(play.hosts, order=play.order)
268 all_hosts_len = len(all_hosts)
269
270 # the serial value can be listed as a scalar or a list of
271 # scalars, so we make sure it's a list here
272 serial_batch_list = play.serial
273 if len(serial_batch_list) == 0:
274 serial_batch_list = [-1]
275
276 cur_item = 0
277 serialized_batches = []
278
279 while len(all_hosts) > 0:
280 # get the serial value from current item in the list
281 serial = pct_to_int(serial_batch_list[cur_item], all_hosts_len)
282
283 # if the serial count was not specified or is invalid, default to
284 # a list of all hosts, otherwise grab a chunk of the hosts equal
285 # to the current serial item size
286 if serial <= 0:
287 serialized_batches.append(all_hosts)
288 break
289 else:
290 play_hosts = []
291 for x in range(serial):
292 if len(all_hosts) > 0:
293 play_hosts.append(all_hosts.pop(0))
294
295 serialized_batches.append(play_hosts)
296
297 # increment the current batch list item number, and if we've hit
298 # the end keep using the last element until we've consumed all of
299 # the hosts in the inventory
300 cur_item += 1
301 if cur_item > len(serial_batch_list) - 1:
302 cur_item = len(serial_batch_list) - 1
303
304 return serialized_batches
305
306 def _generate_retry_inventory(self, retry_path, replay_hosts):
307 """
308 Called when a playbook run fails. It generates an inventory which allows
309 re-running on ONLY the failed hosts. This may duplicate some variable
310 information in group_vars/host_vars but that is ok, and expected.
311 """
312 try:
313 makedirs_safe(os.path.dirname(retry_path))
314 with open(retry_path, 'w') as fd:
315 for x in replay_hosts:
316 fd.write("%s\n" % x)
317 except Exception as e:
318 display.warning("Could not create retry file '%s'.\n\t%s" % (retry_path, to_text(e)))
319 return False
320
321 return True