Debian Codegraph @

ansible_collections/community/general/plugins/callback/opentelemetry.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: opentelemetry
10 type: notification
11 short_description: Create distributed traces with OpenTelemetry
12 version_added: 3.7.0
13 description:
14 - This callback creates distributed traces for each Ansible task with OpenTelemetry.
15 - You can configure the OpenTelemetry exporter and SDK with environment variables.
16 - See U(https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html).
17 - See
18 U(https://opentelemetry-python.readthedocs.io/en/latest/sdk/environment_variables.html#opentelemetry-sdk-environment-variables).
19 options:
20 hide_task_arguments:
21 default: false
22 type: bool
23 description:
24 - Hide the arguments for a task.
25 env:
26 - name: ANSIBLE_OPENTELEMETRY_HIDE_TASK_ARGUMENTS
27 ini:
28 - section: callback_opentelemetry
29 key: hide_task_arguments
30 version_added: 5.3.0
31 enable_from_environment:
32 type: str
33 description:
34 - Whether to enable this callback only if the given environment variable exists and it is set to V(true).
35 - This is handy when you use Configuration as Code and want to send distributed traces if running in the CI rather when
36 running Ansible locally.
37 - For such, it evaluates the given O(enable_from_environment) value as environment variable and if set to V(true) this
38 plugin is enabled.
39 env:
40 - name: ANSIBLE_OPENTELEMETRY_ENABLE_FROM_ENVIRONMENT
41 ini:
42 - section: callback_opentelemetry
43 key: enable_from_environment
44 version_added: 5.3.0
45 version_added: 3.8.0
46 otel_service_name:
47 default: ansible
48 type: str
49 description:
50 - The service name resource attribute.
51 env:
52 - name: OTEL_SERVICE_NAME
53 ini:
54 - section: callback_opentelemetry
55 key: otel_service_name
56 version_added: 5.3.0
57 traceparent:
58 default: None
59 type: str
60 description:
61 - The L(W3C Trace Context header traceparent,https://www.w3.org/TR/trace-context-1/#traceparent-header).
62 env:
63 - name: TRACEPARENT
64 disable_logs:
65 default: false
66 type: bool
67 description:
68 - Disable sending logs.
69 env:
70 - name: ANSIBLE_OPENTELEMETRY_DISABLE_LOGS
71 ini:
72 - section: callback_opentelemetry
73 key: disable_logs
74 version_added: 5.8.0
75 disable_attributes_in_logs:
76 default: false
77 type: bool
78 description:
79 - Disable populating span attributes to the logs.
80 env:
81 - name: ANSIBLE_OPENTELEMETRY_DISABLE_ATTRIBUTES_IN_LOGS
82 ini:
83 - section: callback_opentelemetry
84 key: disable_attributes_in_logs
85 version_added: 7.1.0
86 store_spans_in_file:
87 type: str
88 description:
89 - It stores the exported spans in the given file.
90 env:
91 - name: ANSIBLE_OPENTELEMETRY_STORE_SPANS_IN_FILE
92 ini:
93 - section: callback_opentelemetry
94 key: store_spans_in_file
95 version_added: 9.0.0
96 otel_exporter_otlp_traces_protocol:
97 type: str
98 description:
99 - E(OTEL_EXPORTER_OTLP_TRACES_PROTOCOL) represents the transport protocol for spans.
100 - See
101 U(https://opentelemetry-python.readthedocs.io/en/latest/sdk/environment_variables.html#envvar-OTEL_EXPORTER_OTLP_TRACES_PROTOCOL).
102 default: grpc
103 choices:
104 - grpc
105 - http/protobuf
106 env:
107 - name: OTEL_EXPORTER_OTLP_TRACES_PROTOCOL
108 ini:
109 - section: callback_opentelemetry
110 key: otel_exporter_otlp_traces_protocol
111 version_added: 9.0.0
112 requirements:
113 - opentelemetry-api (Python library)
114 - opentelemetry-exporter-otlp (Python library)
115 - opentelemetry-sdk (Python library)
116 """
117
118
119 EXAMPLES = r"""
120 examples: |-
121 Enable the plugin in ansible.cfg:
122 [defaults]
123 callbacks_enabled = community.general.opentelemetry
124 [callback_opentelemetry]
125 enable_from_environment = ANSIBLE_OPENTELEMETRY_ENABLED
126
127 Set the environment variable:
128 export OTEL_EXPORTER_OTLP_ENDPOINT=<your endpoint (OTLP/HTTP)>
129 export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer your_otel_token"
130 export OTEL_SERVICE_NAME=your_service_name
131 export ANSIBLE_OPENTELEMETRY_ENABLED=true
132 """
133
134 import getpass
135 import json
136 import os
137 import socket
138 import uuid
139 from collections import OrderedDict
140 from os.path import basename
141 from time import time_ns
142 from urllib.parse import urlparse
143
144 from ansible.errors import AnsibleError
145 from ansible.module_utils.ansible_release import __version__ as ansible_version
146 from ansible.plugins.callback import CallbackBase
147
148 OTEL_LIBRARY_IMPORT_ERROR: ImportError | None
149 try:
150 from opentelemetry import trace
151 from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter as GRPCOTLPSpanExporter
152 from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter as HTTPOTLPSpanExporter
153 from opentelemetry.sdk.resources import SERVICE_NAME, Resource
154 from opentelemetry.sdk.trace import TracerProvider
155 from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcessor
156 from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
157 from opentelemetry.trace import SpanKind
158 from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
159 from opentelemetry.trace.status import Status, StatusCode
160 except ImportError as imp_exc:
161 OTEL_LIBRARY_IMPORT_ERROR = imp_exc
162 else:
163 OTEL_LIBRARY_IMPORT_ERROR = None
164
165
166 class TaskData:
167 """
168 Data about an individual task.
169 """
170
171 def __init__(self, uuid, name, path, play, action, args):
172 self.uuid = uuid
173 self.name = name
174 self.path = path
175 self.play = play
176 self.host_data = OrderedDict()
177 self.start = time_ns()
178 self.action = action
179 self.args = args
180 self.dump = None
181
182 def add_host(self, host):
183 if host.uuid in self.host_data:
184 if host.status == "included":
185 # concatenate task include output from multiple items
186 host.result = f"{self.host_data[host.uuid].result}\n{host.result}"
187 else:
188 self.host_data[host.uuid].update(host.status, host.result)
189 return
190
191 self.host_data[host.uuid] = host
192
193
194 class HostData:
195 """
196 Data about an individual host.
197 """
198
199 def __init__(self, uuid, name, status, result=None):
200 self.uuid = uuid
201 self.name = name
202 self.status = status
203 self.result = result
204 self.finish = None
205 self.start = time_ns()
206
207 def update(self, status, result):
208 self.status = status
209 self.result = result
210 self.finish = time_ns()
211
212
213 class OpenTelemetrySource:
214 def __init__(self, display):
215 self.ansible_playbook = ""
216 self.session = str(uuid.uuid4())
217 self.host = socket.gethostname()
218 try:
219 self.ip_address = socket.gethostbyname(socket.gethostname())
220 except Exception:
221 self.ip_address = None
222 self.user = getpass.getuser()
223
224 self._display = display
225
226 def traceparent_context(self, traceparent):
227 carrier = dict()
228 carrier["traceparent"] = traceparent
229 return TraceContextTextMapPropagator().extract(carrier=carrier)
230
231 def start_task(self, tasks_data, hide_task_arguments, play_name, task, host):
232 """record the start of a task for one or more hosts"""
233
234 uuid = task._uuid
235
236 if uuid in tasks_data:
237 tasks_data[uuid].add_host(HostData(host._uuid, host.name, "started"))
238 return
239
240 name = task.get_name().strip()
241 path = task.get_path()
242 action = task.action
243 args = None
244
245 if not task.no_log and not hide_task_arguments:
246 args = task.args
247
248 tasks_data[uuid] = TaskData(uuid, name, path, play_name, action, args)
249 tasks_data[uuid].add_host(HostData(host._uuid, host.name, "started"))
250
251 def finish_task(self, tasks_data, status, result, dump):
252 """record the results of a task for a single host"""
253
254 task_uuid = result._task._uuid
255
256 if hasattr(result, "_host") and result._host is not None:
257 host_uuid = result._host._uuid
258 host_name = result._host.name
259 else:
260 host_uuid = "include"
261 host_name = "include"
262
263 task = tasks_data[task_uuid]
264
265 task.dump = dump
266 task.add_host(HostData(host_uuid, host_name, status, result))
267
268 def generate_distributed_traces(
269 self,
270 otel_service_name,
271 ansible_playbook,
272 tasks_data,
273 status,
274 traceparent,
275 disable_logs,
276 disable_attributes_in_logs,
277 otel_exporter_otlp_traces_protocol,
278 store_spans_in_file,
279 ):
280 """generate distributed traces from the collected TaskData and HostData"""
281
282 tasks = []
283 parent_start_time = None
284 for task in tasks_data.values():
285 if parent_start_time is None:
286 parent_start_time = task.start
287 tasks.append(task)
288
289 trace.set_tracer_provider(TracerProvider(resource=Resource.create({SERVICE_NAME: otel_service_name})))
290
291 otel_exporter = None
292 if store_spans_in_file:
293 otel_exporter = InMemorySpanExporter()
294 processor = SimpleSpanProcessor(otel_exporter)
295 else:
296 if otel_exporter_otlp_traces_protocol == "grpc":
297 otel_exporter = GRPCOTLPSpanExporter()
298 else:
299 otel_exporter = HTTPOTLPSpanExporter()
300 processor = BatchSpanProcessor(otel_exporter)
301
302 trace.get_tracer_provider().add_span_processor(processor)
303
304 tracer = trace.get_tracer(__name__)
305
306 with tracer.start_as_current_span(
307 ansible_playbook,
308 context=self.traceparent_context(traceparent),
309 start_time=parent_start_time,
310 kind=SpanKind.SERVER,
311 ) as parent:
312 parent.set_status(status)
313 # Populate trace metadata attributes
314 parent.set_attribute("ansible.version", ansible_version)
315 parent.set_attribute("ansible.session", self.session)
316 parent.set_attribute("ansible.host.name", self.host)
317 if self.ip_address is not None:
318 parent.set_attribute("ansible.host.ip", self.ip_address)
319 parent.set_attribute("ansible.host.user", self.user)
320 for task in tasks:
321 for host_data in task.host_data.values():
322 start = host_data.start or task.start
323 with tracer.start_as_current_span(task.name, start_time=start, end_on_exit=False) as span:
324 self.update_span_data(task, host_data, span, disable_logs, disable_attributes_in_logs)
325
326 return otel_exporter
327
328 def update_span_data(self, task_data, host_data, span, disable_logs, disable_attributes_in_logs):
329 """update the span with the given TaskData and HostData"""
330
331 name = f"[{host_data.name}] {task_data.play}: {task_data.name}"
332
333 message = "success"
334 res = {}
335 rc = 0
336 status = Status(status_code=StatusCode.OK)
337 if host_data.status != "included":
338 # Support loops
339 enriched_error_message = None
340 if host_data.result and "results" in host_data.result._result:
341 if host_data.status == "failed":
342 message = self.get_error_message_from_results(host_data.result._result["results"], task_data.action)
343 enriched_error_message = self.enrich_error_message_from_results(
344 host_data.result._result["results"], task_data.action
345 )
346 elif host_data.result:
347 res = host_data.result._result
348 rc = res.get("rc", 0)
349 if host_data.status == "failed":
350 message = self.get_error_message(res)
351 enriched_error_message = self.enrich_error_message(res)
352
353 if host_data.status == "failed":
354 status = Status(status_code=StatusCode.ERROR, description=message)
355 # Record an exception with the task message
356 span.record_exception(BaseException(enriched_error_message))
357 elif host_data.status == "skipped":
358 message = res["skip_reason"] if "skip_reason" in res else "skipped"
359 status = Status(status_code=StatusCode.UNSET)
360 elif host_data.status == "ignored":
361 status = Status(status_code=StatusCode.UNSET)
362
363 span.set_status(status)
364
365 # Create the span and log attributes
366 attributes = {
367 "ansible.task.module": task_data.action,
368 "ansible.task.message": message,
369 "ansible.task.name": name,
370 "ansible.task.result": rc,
371 "ansible.task.host.name": host_data.name,
372 "ansible.task.host.status": host_data.status,
373 }
374 if isinstance(task_data.args, dict) and "gather_facts" not in task_data.action:
375 names = tuple(self.transform_ansible_unicode_to_str(k) for k in task_data.args.keys())
376 values = tuple(self.transform_ansible_unicode_to_str(k) for k in task_data.args.values())
377 attributes[("ansible.task.args.name")] = names
378 attributes[("ansible.task.args.value")] = values
379
380 self.set_span_attributes(span, attributes)
381
382 # This will allow to enrich the service map
383 self.add_attributes_for_service_map_if_possible(span, task_data)
384 # Send logs
385 if not disable_logs:
386 # This will avoid populating span attributes to the logs
387 span.add_event(task_data.dump, attributes={} if disable_attributes_in_logs else attributes)
388 # Close span always
389 span.end(end_time=host_data.finish)
390
391 def set_span_attributes(self, span, attributes):
392 """update the span attributes with the given attributes if not None"""
393
394 if span is None and self._display is not None:
395 self._display.warning("span object is None. Please double check if that is expected.")
396 else:
397 if attributes is not None:
398 span.set_attributes(attributes)
399
400 def add_attributes_for_service_map_if_possible(self, span, task_data):
401 """Update the span attributes with the service that the task interacted with, if possible."""
402
403 redacted_url = self.parse_and_redact_url_if_possible(task_data.args)
404 if redacted_url:
405 span.set_attribute("http.url", redacted_url.geturl())
406
407 @staticmethod
408 def parse_and_redact_url_if_possible(args):
409 """Parse and redact the url, if possible."""
410
411 try:
412 parsed_url = urlparse(OpenTelemetrySource.url_from_args(args))
413 except ValueError:
414 return None
415
416 if OpenTelemetrySource.is_valid_url(parsed_url):
417 return OpenTelemetrySource.redact_user_password(parsed_url)
418 return None
419
420 @staticmethod
421 def url_from_args(args):
422 # the order matters
423 url_args = (
424 "url",
425 "api_url",
426 "baseurl",
427 "repo",
428 "server_url",
429 "chart_repo_url",
430 "registry_url",
431 "endpoint",
432 "uri",
433 "updates_url",
434 )
435 for arg in url_args:
436 if args is not None and args.get(arg):
437 return args.get(arg)
438 return ""
439
440 @staticmethod
441 def redact_user_password(url):
442 return url._replace(netloc=url.hostname) if url.password else url
443
444 @staticmethod
445 def is_valid_url(url):
446 if all([url.scheme, url.netloc, url.hostname]):
447 return "{{" not in url.hostname
448 return False
449
450 @staticmethod
451 def transform_ansible_unicode_to_str(value):
452 parsed_url = urlparse(str(value))
453 if OpenTelemetrySource.is_valid_url(parsed_url):
454 return OpenTelemetrySource.redact_user_password(parsed_url).geturl()
455 return str(value)
456
457 @staticmethod
458 def get_error_message(result):
459 if result.get("exception") is not None:
460 return OpenTelemetrySource._last_line(result["exception"])
461 return result.get("msg", "failed")
462
463 @staticmethod
464 def get_error_message_from_results(results, action):
465 for result in results:
466 if result.get("failed", False):
467 return f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.get_error_message(result)}"
468
469 @staticmethod
470 def _last_line(text):
471 lines = text.strip().split("\n")
472 return lines[-1]
473
474 @staticmethod
475 def enrich_error_message(result):
476 message = result.get("msg", "failed")
477 exception = result.get("exception")
478 stderr = result.get("stderr")
479 return f'message: "{message}"\nexception: "{exception}"\nstderr: "{stderr}"'
480
481 @staticmethod
482 def enrich_error_message_from_results(results, action):
483 message = ""
484 for result in results:
485 if result.get("failed", False):
486 message = f"{action}({result.get('item', 'none')}) - {OpenTelemetrySource.enrich_error_message(result)}\n{message}"
487 return message
488
489
490 class CallbackModule(CallbackBase):
491 """
492 This callback creates distributed traces.
493 """
494
495 CALLBACK_VERSION = 2.0
496 CALLBACK_TYPE = "notification"
497 CALLBACK_NAME = "community.general.opentelemetry"
498 CALLBACK_NEEDS_ENABLED = True
499
500 def __init__(self, display=None):
501 super().__init__(display=display)
502 self.hide_task_arguments = None
503 self.disable_attributes_in_logs = None
504 self.disable_logs = None
505 self.otel_service_name = None
506 self.ansible_playbook = None
507 self.play_name = None
508 self.tasks_data = None
509 self.errors = 0
510 self.disabled = False
511 self.traceparent = False
512 self.store_spans_in_file = False
513 self.otel_exporter_otlp_traces_protocol = None
514
515 if OTEL_LIBRARY_IMPORT_ERROR:
516 raise AnsibleError(
517 "The `opentelemetry-api`, `opentelemetry-exporter-otlp` or `opentelemetry-sdk` must be installed to use this plugin"
518 ) from OTEL_LIBRARY_IMPORT_ERROR
519
520 self.tasks_data = OrderedDict()
521
522 self.opentelemetry = OpenTelemetrySource(display=self._display)
523
524 def set_options(self, task_keys=None, var_options=None, direct=None):
525 super().set_options(task_keys=task_keys, var_options=var_options, direct=direct)
526
527 environment_variable = self.get_option("enable_from_environment")
528 if environment_variable is not None and os.environ.get(environment_variable, "false").lower() != "true":
529 self.disabled = True
530 self._display.warning(
531 f"The `enable_from_environment` option has been set and {environment_variable} is not enabled. Disabling the `opentelemetry` callback plugin."
532 )
533
534 self.hide_task_arguments = self.get_option("hide_task_arguments")
535
536 self.disable_attributes_in_logs = self.get_option("disable_attributes_in_logs")
537
538 self.disable_logs = self.get_option("disable_logs")
539
540 self.store_spans_in_file = self.get_option("store_spans_in_file")
541
542 self.otel_service_name = self.get_option("otel_service_name")
543
544 if not self.otel_service_name:
545 self.otel_service_name = "ansible"
546
547 # See https://github.com/open-telemetry/opentelemetry-specification/issues/740
548 self.traceparent = self.get_option("traceparent")
549
550 self.otel_exporter_otlp_traces_protocol = self.get_option("otel_exporter_otlp_traces_protocol")
551
552 def dump_results(self, task, result):
553 """dump the results if disable_logs is not enabled"""
554 if self.disable_logs:
555 return ""
556 # ansible.builtin.uri contains the response in the json field
557 save = dict(result._result)
558
559 if "json" in save and task.action in ("ansible.builtin.uri", "ansible.legacy.uri", "uri"):
560 save.pop("json")
561 # ansible.builtin.slurp contains the response in the content field
562 if "content" in save and task.action in ("ansible.builtin.slurp", "ansible.legacy.slurp", "slurp"):
563 save.pop("content")
564 return self._dump_results(save)
565
566 def v2_playbook_on_start(self, playbook):
567 self.ansible_playbook = basename(playbook._file_name)
568
569 def v2_playbook_on_play_start(self, play):
570 self.play_name = play.get_name()
571
572 def v2_runner_on_start(self, host, task):
573 self.opentelemetry.start_task(self.tasks_data, self.hide_task_arguments, self.play_name, task, host)
574
575 def v2_runner_on_failed(self, result, ignore_errors=False):
576 if ignore_errors:
577 status = "ignored"
578 else:
579 status = "failed"
580 self.errors += 1
581
582 self.opentelemetry.finish_task(
583 self.tasks_data, status, result, self.dump_results(self.tasks_data[result._task._uuid], result)
584 )
585
586 def v2_runner_on_ok(self, result):
587 self.opentelemetry.finish_task(
588 self.tasks_data, "ok", result, self.dump_results(self.tasks_data[result._task._uuid], result)
589 )
590
591 def v2_runner_on_skipped(self, result):
592 self.opentelemetry.finish_task(
593 self.tasks_data, "skipped", result, self.dump_results(self.tasks_data[result._task._uuid], result)
594 )
595
596 def v2_runner_on_unreachable(self, result):
597 self.errors += 1
598 self.opentelemetry.finish_task(
599 self.tasks_data, "failed", result, self.dump_results(self.tasks_data[result._task._uuid], result)
600 )
601
602 def v2_playbook_on_include(self, included_file):
603 self.opentelemetry.finish_task(self.tasks_data, "included", included_file, "")
604
605 def v2_playbook_on_stats(self, stats):
606 if self.errors == 0:
607 status = Status(status_code=StatusCode.OK)
608 else:
609 status = Status(status_code=StatusCode.ERROR)
610 otel_exporter = self.opentelemetry.generate_distributed_traces(
611 self.otel_service_name,
612 self.ansible_playbook,
613 self.tasks_data,
614 status,
615 self.traceparent,
616 self.disable_logs,
617 self.disable_attributes_in_logs,
618 self.otel_exporter_otlp_traces_protocol,
619 self.store_spans_in_file,
620 )
621
622 if self.store_spans_in_file:
623 spans = [json.loads(span.to_json()) for span in otel_exporter.get_finished_spans()]
624 with open(self.store_spans_in_file, "w", encoding="utf-8") as output:
625 json.dump({"spans": spans}, output, indent=4)
626
627 def v2_runner_on_async_failed(self, result, **kwargs):
628 self.errors += 1