Debian Codegraph @

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

raw
1 # Copyright (c) 2021, Victor Martinez <[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 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 author: Victor Martinez (@v1v) <[email protected]>
9 name: elastic
10 type: notification
11 short_description: Create distributed traces for each Ansible task in Elastic APM
12 version_added: 3.8.0
13 description:
14 - This callback creates distributed traces for each Ansible task in Elastic APM.
15 - You can configure the plugin with environment variables.
16 - See U(https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html).
17 options:
18 hide_task_arguments:
19 default: false
20 type: bool
21 description:
22 - Hide the arguments for a task.
23 env:
24 - name: ANSIBLE_OPENTELEMETRY_HIDE_TASK_ARGUMENTS
25 apm_service_name:
26 default: ansible
27 type: str
28 description:
29 - The service name resource attribute.
30 env:
31 - name: ELASTIC_APM_SERVICE_NAME
32 apm_server_url:
33 type: str
34 description:
35 - Use the APM server and its environment variables.
36 env:
37 - name: ELASTIC_APM_SERVER_URL
38 apm_secret_token:
39 type: str
40 description:
41 - Use the APM server token.
42 env:
43 - name: ELASTIC_APM_SECRET_TOKEN
44 apm_api_key:
45 type: str
46 description:
47 - Use the APM API key.
48 env:
49 - name: ELASTIC_APM_API_KEY
50 apm_verify_server_cert:
51 default: true
52 type: bool
53 description:
54 - Verifies the SSL certificate if an HTTPS connection.
55 env:
56 - name: ELASTIC_APM_VERIFY_SERVER_CERT
57 traceparent:
58 type: str
59 description:
60 - The L(W3C Trace Context header traceparent,https://www.w3.org/TR/trace-context-1/#traceparent-header).
61 env:
62 - name: TRACEPARENT
63 requirements:
64 - elastic-apm (Python library)
65 """
66
67
68 EXAMPLES = r"""
69 examples: |-
70 Enable the plugin in ansible.cfg:
71 [defaults]
72 callbacks_enabled = community.general.elastic
73
74 Set the environment variable:
75 export ELASTIC_APM_SERVER_URL=<your APM server URL)>
76 export ELASTIC_APM_SERVICE_NAME=your_service_name
77 export ELASTIC_APM_API_KEY=your_APM_API_KEY
78 """
79
80 import getpass
81 import socket
82 import time
83 import uuid
84 from collections import OrderedDict
85 from contextlib import closing
86 from os.path import basename
87
88 from ansible.errors import AnsibleError, AnsibleRuntimeError
89 from ansible.module_utils.ansible_release import __version__ as ansible_version
90 from ansible.plugins.callback import CallbackBase
91
92 ELASTIC_LIBRARY_IMPORT_ERROR: ImportError | None
93 try:
94 from elasticapm import Client, capture_span, instrument, label, trace_parent_from_string
95 except ImportError as imp_exc:
96 ELASTIC_LIBRARY_IMPORT_ERROR = imp_exc
97 else:
98 ELASTIC_LIBRARY_IMPORT_ERROR = None
99
100
101 class TaskData:
102 """
103 Data about an individual task.
104 """
105
106 def __init__(self, uuid, name, path, play, action, args):
107 self.uuid = uuid
108 self.name = name
109 self.path = path
110 self.play = play
111 self.host_data = OrderedDict()
112 self.start = time.time()
113 self.action = action
114 self.args = args
115
116 def add_host(self, host):
117 if host.uuid in self.host_data:
118 if host.status == "included":
119 # concatenate task include output from multiple items
120 host.result = f"{self.host_data[host.uuid].result}\n{host.result}"
121 else:
122 return
123
124 self.host_data[host.uuid] = host
125
126
127 class HostData:
128 """
129 Data about an individual host.
130 """
131
132 def __init__(self, uuid, name, status, result):
133 self.uuid = uuid
134 self.name = name
135 self.status = status
136 self.result = result
137 self.finish = time.time()
138
139
140 class ElasticSource:
141 def __init__(self, display):
142 self.ansible_playbook = ""
143 self.session = str(uuid.uuid4())
144 self.host = socket.gethostname()
145 try:
146 self.ip_address = socket.gethostbyname(socket.gethostname())
147 except Exception:
148 self.ip_address = None
149 self.user = getpass.getuser()
150
151 self._display = display
152
153 def start_task(self, tasks_data, hide_task_arguments, play_name, task):
154 """record the start of a task for one or more hosts"""
155
156 uuid = task._uuid
157
158 if uuid in tasks_data:
159 return
160
161 name = task.get_name().strip()
162 path = task.get_path()
163 action = task.action
164 args = None
165
166 if not task.no_log and not hide_task_arguments:
167 args = ", ".join((f"{k}={v}" for k, v in task.args.items()))
168
169 tasks_data[uuid] = TaskData(uuid, name, path, play_name, action, args)
170
171 def finish_task(self, tasks_data, status, result):
172 """record the results of a task for a single host"""
173
174 task_uuid = result._task._uuid
175
176 if hasattr(result, "_host") and result._host is not None:
177 host_uuid = result._host._uuid
178 host_name = result._host.name
179 else:
180 host_uuid = "include"
181 host_name = "include"
182
183 task = tasks_data[task_uuid]
184
185 task.add_host(HostData(host_uuid, host_name, status, result))
186
187 def generate_distributed_traces(
188 self,
189 tasks_data,
190 status,
191 end_time,
192 traceparent,
193 apm_service_name,
194 apm_server_url,
195 apm_verify_server_cert,
196 apm_secret_token,
197 apm_api_key,
198 ):
199 """generate distributed traces from the collected TaskData and HostData"""
200
201 tasks = []
202 parent_start_time = None
203 for task in tasks_data.values():
204 if parent_start_time is None:
205 parent_start_time = task.start
206 tasks.append(task)
207
208 apm_cli = self.init_apm_client(
209 apm_server_url, apm_service_name, apm_verify_server_cert, apm_secret_token, apm_api_key
210 )
211 if apm_cli:
212 with closing(apm_cli):
213 instrument() # Only call this once, as early as possible.
214 if traceparent:
215 parent = trace_parent_from_string(traceparent)
216 apm_cli.begin_transaction("Session", trace_parent=parent, start=parent_start_time)
217 else:
218 apm_cli.begin_transaction("Session", start=parent_start_time)
219 # Populate trace metadata attributes
220 label(ansible_version=ansible_version)
221 label(ansible_session=self.session, ansible_host_name=self.host, ansible_host_user=self.user)
222 if self.ip_address is not None:
223 label(ansible_host_ip=self.ip_address)
224
225 for task_data in tasks:
226 for host_data in task_data.host_data.values():
227 self.create_span_data(apm_cli, task_data, host_data)
228
229 apm_cli.end_transaction(name=__name__, result=status, duration=end_time - parent_start_time)
230
231 def create_span_data(self, apm_cli, task_data, host_data):
232 """create the span with the given TaskData and HostData"""
233
234 name = f"[{host_data.name}] {task_data.play}: {task_data.name}"
235
236 message = "success"
237 status = "success"
238 enriched_error_message = None
239 if host_data.status == "included":
240 rc = 0
241 else:
242 res = host_data.result._result
243 rc = res.get("rc", 0)
244 if host_data.status == "failed":
245 message = self.get_error_message(res)
246 enriched_error_message = self.enrich_error_message(res)
247 status = "failure"
248 elif host_data.status == "skipped":
249 if "skip_reason" in res:
250 message = res["skip_reason"]
251 else:
252 message = "skipped"
253 status = "unknown"
254
255 with capture_span(
256 task_data.name,
257 start=task_data.start,
258 span_type="ansible.task.run",
259 duration=host_data.finish - task_data.start,
260 labels={
261 "ansible.task.args": task_data.args,
262 "ansible.task.message": message,
263 "ansible.task.module": task_data.action,
264 "ansible.task.name": name,
265 "ansible.task.result": rc,
266 "ansible.task.host.name": host_data.name,
267 "ansible.task.host.status": host_data.status,
268 },
269 ) as span:
270 span.outcome = status
271 if "failure" in status:
272 exception = AnsibleRuntimeError(
273 message=f"{task_data.action}: {name} failed with error message {enriched_error_message}"
274 )
275 apm_cli.capture_exception(exc_info=(type(exception), exception, exception.__traceback__), handled=True)
276
277 def init_apm_client(self, apm_server_url, apm_service_name, apm_verify_server_cert, apm_secret_token, apm_api_key):
278 if apm_server_url:
279 return Client(
280 service_name=apm_service_name,
281 server_url=apm_server_url,
282 verify_server_cert=False,
283 secret_token=apm_secret_token,
284 api_key=apm_api_key,
285 use_elastic_traceparent_header=True,
286 debug=True,
287 )
288
289 @staticmethod
290 def get_error_message(result):
291 if result.get("exception") is not None:
292 return ElasticSource._last_line(result["exception"])
293 return result.get("msg", "failed")
294
295 @staticmethod
296 def _last_line(text):
297 lines = text.strip().split("\n")
298 return lines[-1]
299
300 @staticmethod
301 def enrich_error_message(result):
302 message = result.get("msg", "failed")
303 exception = result.get("exception")
304 stderr = result.get("stderr")
305 return f'message: "{message}"\nexception: "{exception}"\nstderr: "{stderr}"'
306
307
308 class CallbackModule(CallbackBase):
309 """
310 This callback creates distributed traces with Elastic APM.
311 """
312
313 CALLBACK_VERSION = 2.0
314 CALLBACK_TYPE = "notification"
315 CALLBACK_NAME = "community.general.elastic"
316 CALLBACK_NEEDS_ENABLED = True
317
318 def __init__(self, display=None):
319 super().__init__(display=display)
320 self.hide_task_arguments = None
321 self.apm_service_name = None
322 self.ansible_playbook = None
323 self.traceparent = False
324 self.play_name = None
325 self.tasks_data = None
326 self.errors = 0
327 self.disabled = False
328
329 if ELASTIC_LIBRARY_IMPORT_ERROR:
330 raise AnsibleError(
331 "The `elastic-apm` must be installed to use this plugin"
332 ) from ELASTIC_LIBRARY_IMPORT_ERROR
333
334 self.tasks_data = OrderedDict()
335
336 self.elastic = ElasticSource(display=self._display)
337
338 def set_options(self, task_keys=None, var_options=None, direct=None):
339 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
340
341 self.hide_task_arguments = self.get_option("hide_task_arguments")
342
343 self.apm_service_name = self.get_option("apm_service_name")
344 if not self.apm_service_name:
345 self.apm_service_name = "ansible"
346
347 self.apm_server_url = self.get_option("apm_server_url")
348 self.apm_secret_token = self.get_option("apm_secret_token")
349 self.apm_api_key = self.get_option("apm_api_key")
350 self.apm_verify_server_cert = self.get_option("apm_verify_server_cert")
351 self.traceparent = self.get_option("traceparent")
352
353 def v2_playbook_on_start(self, playbook):
354 self.ansible_playbook = basename(playbook._file_name)
355
356 def v2_playbook_on_play_start(self, play):
357 self.play_name = play.get_name()
358
359 def v2_runner_on_no_hosts(self, task):
360 self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
361
362 def v2_playbook_on_task_start(self, task, is_conditional):
363 self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
364
365 def v2_playbook_on_cleanup_task_start(self, task):
366 self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
367
368 def v2_playbook_on_handler_task_start(self, task):
369 self.elastic.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task)
370
371 def v2_runner_on_failed(self, result, ignore_errors=False):
372 self.errors += 1
373 self.elastic.finish_task(self.tasks_data, "failed", result)
374
375 def v2_runner_on_ok(self, result):
376 self.elastic.finish_task(self.tasks_data, "ok", result)
377
378 def v2_runner_on_skipped(self, result):
379 self.elastic.finish_task(self.tasks_data, "skipped", result)
380
381 def v2_playbook_on_include(self, included_file):
382 self.elastic.finish_task(self.tasks_data, "included", included_file)
383
384 def v2_playbook_on_stats(self, stats):
385 if self.errors == 0:
386 status = "success"
387 else:
388 status = "failure"
389 self.elastic.generate_distributed_traces(
390 self.tasks_data,
391 status,
392 time.time(),
393 self.traceparent,
394 self.apm_service_name,
395 self.apm_server_url,
396 self.apm_verify_server_cert,
397 self.apm_secret_token,
398 self.apm_api_key,
399 )
400
401 def v2_runner_on_async_failed(self, result, **kwargs):
402 self.errors += 1