From e5bb639bcb4eff7d4498f4d156d5a58488a5f04b Mon Sep 17 00:00:00 2001 From: Gabriel Buica Date: Thu, 16 May 2024 13:58:56 +0100 Subject: [PATCH] CP-48995: Instrument `XenAPI.py` to submit traceparent Instrument `XenAPI.py` to submit the current traceparent back into xapi if it can import `opentelemetry`. Currently, we don't see the traces of `sm` calling back to `xapi` using `XenAPI.py`. This will instrument `XenAPI.py` to pass a traceparent into `xapi` when opentelemetry is available. Signed-off-by: Gabriel Buica --- python3/packages/observer.py | 5 +++++ scripts/examples/python/XenAPI/XenAPI.py | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/python3/packages/observer.py b/python3/packages/observer.py index 076fa986a9a..ad41b89848f 100644 --- a/python3/packages/observer.py +++ b/python3/packages/observer.py @@ -371,6 +371,11 @@ def _patch_module(module_name): # If there are no configs, or an exception is raised, span and patch_module # are not overridden and will be the defined no-op functions. span, patch_module = _init_tracing(observer_configs, observer_config_dir) + + # If tracing is now operational, explicity set "OTEL_SDK_DISABLED" to "false". + # In our case, different from the standard, we want the tracing disabled by + # default, so if the env variable is not set the noop implementation is used. + os.environ["OTEL_SDK_DISABLED"] = "false" except Exception as exc: syslog.error("Exception while setting up tracing, running script untraced: %s", exc) span, patch_module = _span_noop, _patch_module_noop diff --git a/scripts/examples/python/XenAPI/XenAPI.py b/scripts/examples/python/XenAPI/XenAPI.py index ab868e92188..0211fe5e9c8 100644 --- a/scripts/examples/python/XenAPI/XenAPI.py +++ b/scripts/examples/python/XenAPI/XenAPI.py @@ -55,6 +55,7 @@ # -------------------------------------------------------------------- import gettext +import os import socket import sys @@ -65,6 +66,15 @@ import http.client as httplib import xmlrpc.client as xmlrpclib +otel = False +try: + if os.environ["OTEL_SDK_DISABLED"] == "false": + from opentelemetry import propagate + from opentelemetry.trace.propagation import set_span_in_context, get_current_span + otel = True + +except Exception: + pass translation = gettext.translation('xen-xm', fallback = True) @@ -101,7 +111,19 @@ def connect(self): class UDSTransport(xmlrpclib.Transport): def add_extra_header(self, key, value): self._extra_headers += [ (key,value) ] + def with_tracecontext(self): + if otel: + headers = {} + # pylint: disable=possibly-used-before-assignment + ctx = set_span_in_context(get_current_span()) + # pylint: disable=possibly-used-before-assignment + propagators = propagate.get_global_textmap() + propagators.inject(headers, ctx) + self._extra_headers = [] + for k, v in headers.items(): + self.add_extra_header(k, v) def make_connection(self, host): + self.with_tracecontext() return UDSHTTPConnection(host) def notimplemented(name, *args, **kwargs):