Debian Codegraph @

ansible_collections/community/general/plugins/callback/counter_enabled.py

raw
1 # Copyright (c) 2018, Ivan Aragones Muniesa <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 """
5 Counter enabled Ansible callback plugin (See DOCUMENTATION for more information)
6 """
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 author: Unknown (!UNKNOWN)
12 name: counter_enabled
13 type: stdout
14 short_description: Adds counters to the output items (tasks and hosts/task)
15 description:
16 - Use this callback when you need a kind of progress bar on a large environments.
17 - You can see how many tasks has the playbook to run, and which one is actually running.
18 - You can see how many hosts may run a task, and which of them is actually running.
19 extends_documentation_fragment:
20 - ansible.builtin.default_callback
21 requirements:
22 - set as stdout callback in C(ansible.cfg) (C(stdout_callback = counter_enabled))
23 """
24
25 from ansible import constants as C
26 from ansible.playbook.task_include import TaskInclude
27 from ansible.plugins.callback import CallbackBase
28 from ansible.utils.color import colorize, hostcolor
29
30
31 class CallbackModule(CallbackBase):
32 """
33 This is the default callback interface, which simply prints messages
34 to stdout when new callback events are received.
35 """
36
37 CALLBACK_VERSION = 2.0
38 CALLBACK_TYPE = "stdout"
39 CALLBACK_NAME = "community.general.counter_enabled"
40
41 _task_counter = 1
42 _task_total = 0
43 _host_counter = 1
44 _host_total = 0
45 _current_batch_total = 0
46 _previous_batch_total = 0
47
48 def __init__(self):
49 super().__init__()
50
51 self._playbook = ""
52 self._play = ""
53
54 def _all_vars(self, host=None, task=None):
55 # host and task need to be specified in case 'magic variables' (host vars, group vars, etc)
56 # need to be loaded as well
57 return self._play.get_variable_manager().get_vars(play=self._play, host=host, task=task)
58
59 def v2_playbook_on_start(self, playbook):
60 self._playbook = playbook
61
62 def v2_playbook_on_play_start(self, play):
63 name = play.get_name().strip()
64 if not name:
65 msg = "play"
66 else:
67 msg = f"PLAY [{name}]"
68
69 self._play = play
70
71 self._display.banner(msg)
72 self._play = play
73
74 self._previous_batch_total = self._current_batch_total
75 self._current_batch_total = self._previous_batch_total + len(self._all_vars()["vars"]["ansible_play_batch"])
76 self._host_total = len(self._all_vars()["vars"]["ansible_play_hosts_all"])
77 self._task_total = len(self._play.get_tasks()[0])
78 self._task_counter = 1
79
80 def v2_playbook_on_stats(self, stats):
81 self._display.banner("PLAY RECAP")
82
83 hosts = sorted(stats.processed.keys())
84 for host in hosts:
85 stat = stats.summarize(host)
86
87 self._display.display(
88 f"{hostcolor(host, stat)} : {colorize('ok', stat['ok'], C.COLOR_OK)} {colorize('changed', stat['changed'], C.COLOR_CHANGED)} "
89 f"{colorize('unreachable', stat['unreachable'], C.COLOR_UNREACHABLE)} {colorize('failed', stat['failures'], C.COLOR_ERROR)} "
90 f"{colorize('rescued', stat['rescued'], C.COLOR_OK)} {colorize('ignored', stat['ignored'], C.COLOR_WARN)}",
91 screen_only=True,
92 )
93
94 self._display.display(
95 f"{hostcolor(host, stat, False)} : {colorize('ok', stat['ok'], None)} {colorize('changed', stat['changed'], None)} "
96 f"{colorize('unreachable', stat['unreachable'], None)} {colorize('failed', stat['failures'], None)} "
97 f"{colorize('rescued', stat['rescued'], None)} {colorize('ignored', stat['ignored'], None)}",
98 log_only=True,
99 )
100
101 self._display.display("", screen_only=True)
102
103 # print custom stats
104 if self._plugin_options.get("show_custom_stats", C.SHOW_CUSTOM_STATS) and stats.custom:
105 # fallback on constants for inherited plugins missing docs
106 self._display.banner("CUSTOM STATS: ")
107 # per host
108 # TODO: come up with 'pretty format'
109 for k in sorted(stats.custom.keys()):
110 if k == "_run":
111 continue
112 _custom_stats = self._dump_results(stats.custom[k], indent=1).replace("\n", "")
113 self._display.display(f"\t{k}: {_custom_stats}")
114
115 # print per run custom stats
116 if "_run" in stats.custom:
117 self._display.display("", screen_only=True)
118 _custom_stats_run = self._dump_results(stats.custom["_run"], indent=1).replace("\n", "")
119 self._display.display(f"\tRUN: {_custom_stats_run}")
120 self._display.display("", screen_only=True)
121
122 def v2_playbook_on_task_start(self, task, is_conditional):
123 args = ""
124 # args can be specified as no_log in several places: in the task or in
125 # the argument spec. We can check whether the task is no_log but the
126 # argument spec can't be because that is only run on the target
127 # machine and we haven't run it there yet at this time.
128 #
129 # So we give people a config option to affect display of the args so
130 # that they can secure this if they feel that their stdout is insecure
131 # (shoulder surfing, logging stdout straight to a file, etc).
132 if not task.no_log and C.DISPLAY_ARGS_TO_STDOUT:
133 args = ", ".join(("{k}={v}" for k, v in task.args.items()))
134 args = f" {args}"
135 self._display.banner(f"TASK {self._task_counter}/{self._task_total} [{task.get_name().strip()}{args}]")
136 if self._display.verbosity >= 2:
137 path = task.get_path()
138 if path:
139 self._display.display(f"task path: {path}", color=C.COLOR_DEBUG)
140 self._host_counter = self._previous_batch_total
141 self._task_counter += 1
142
143 def v2_runner_on_ok(self, result):
144 self._host_counter += 1
145
146 delegated_vars = result._result.get("_ansible_delegated_vars", None)
147
148 if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
149 self._print_task_banner(result._task)
150
151 if isinstance(result._task, TaskInclude):
152 return
153 elif result._result.get("changed", False):
154 if delegated_vars:
155 msg = f"changed: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> {delegated_vars['ansible_host']}]"
156 else:
157 msg = f"changed: {self._host_counter}/{self._host_total} [{result._host.get_name()}]"
158 color = C.COLOR_CHANGED
159 else:
160 if not self._plugin_options.get("display_ok_hosts", True):
161 return
162 if delegated_vars:
163 msg = f"ok: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> {delegated_vars['ansible_host']}]"
164 else:
165 msg = f"ok: {self._host_counter}/{self._host_total} [{result._host.get_name()}]"
166 color = C.COLOR_OK
167
168 self._handle_warnings(result._result)
169
170 if result._task.loop and "results" in result._result:
171 self._process_items(result)
172 else:
173 self._clean_results(result._result, result._task.action)
174
175 if self._run_is_verbose(result):
176 msg += f" => {self._dump_results(result._result)}"
177 self._display.display(msg, color=color)
178
179 def v2_runner_on_failed(self, result, ignore_errors=False):
180 self._host_counter += 1
181
182 delegated_vars = result._result.get("_ansible_delegated_vars", None)
183 self._clean_results(result._result, result._task.action)
184
185 if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
186 self._print_task_banner(result._task)
187
188 self._handle_exception(result._result)
189 self._handle_warnings(result._result)
190
191 if result._task.loop and "results" in result._result:
192 self._process_items(result)
193
194 else:
195 if delegated_vars:
196 self._display.display(
197 f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> "
198 f"{delegated_vars['ansible_host']}]: FAILED! => {self._dump_results(result._result)}",
199 color=C.COLOR_ERROR,
200 )
201 else:
202 self._display.display(
203 f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()}]: FAILED! => {self._dump_results(result._result)}",
204 color=C.COLOR_ERROR,
205 )
206
207 if ignore_errors:
208 self._display.display("...ignoring", color=C.COLOR_SKIP)
209
210 def v2_runner_on_skipped(self, result):
211 self._host_counter += 1
212
213 if self._plugin_options.get(
214 "show_skipped_hosts", C.DISPLAY_SKIPPED_HOSTS
215 ): # fallback on constants for inherited plugins missing docs
216 self._clean_results(result._result, result._task.action)
217
218 if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
219 self._print_task_banner(result._task)
220
221 if result._task.loop and "results" in result._result:
222 self._process_items(result)
223 else:
224 msg = f"skipping: {self._host_counter}/{self._host_total} [{result._host.get_name()}]"
225 if self._run_is_verbose(result):
226 msg += f" => {self._dump_results(result._result)}"
227 self._display.display(msg, color=C.COLOR_SKIP)
228
229 def v2_runner_on_unreachable(self, result):
230 self._host_counter += 1
231
232 if self._play.strategy == "free" and self._last_task_banner != result._task._uuid:
233 self._print_task_banner(result._task)
234
235 delegated_vars = result._result.get("_ansible_delegated_vars", None)
236 if delegated_vars:
237 self._display.display(
238 f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()} -> "
239 f"{delegated_vars['ansible_host']}]: UNREACHABLE! => {self._dump_results(result._result)}",
240 color=C.COLOR_UNREACHABLE,
241 )
242 else:
243 self._display.display(
244 f"fatal: {self._host_counter}/{self._host_total} [{result._host.get_name()}]: UNREACHABLE! => {self._dump_results(result._result)}",
245 color=C.COLOR_UNREACHABLE,
246 )