001package io.prometheus.client.exemplars.tracer.otel;
002
003import io.opentelemetry.api.trace.Span;
004import io.opentelemetry.api.trace.SpanId;
005import io.opentelemetry.api.trace.TraceId;
006import io.prometheus.client.exemplars.tracer.common.SpanContextSupplier;
007
008public class OpenTelemetrySpanContextSupplier implements SpanContextSupplier {
009
010        public static boolean isAvailable() {
011    try {
012      if ("inactive".equalsIgnoreCase(System.getProperties().getProperty("io.prometheus.otelExemplars"))) {
013        return false;
014      }
015      OpenTelemetrySpanContextSupplier test = new OpenTelemetrySpanContextSupplier();
016      test.getSpanId();
017      test.getTraceId();
018      test.isSampled();
019      return true;
020    } catch (LinkageError ignored) {
021      // NoClassDefFoundError:
022      //   Either OpenTelemetry is not present, or it is version 0.9.1 or older when io.opentelemetry.api.trace.Span did not exist.
023      // IncompatibleClassChangeError:
024      //   The application uses an OpenTelemetry version between 0.10.0 and 0.15.0 when SpanContext was a class, and not an interface.
025      return false;
026    }
027  }
028
029        @Override
030        public String getTraceId() {
031                String traceId = Span.current().getSpanContext().getTraceId();
032                return TraceId.isValid(traceId) ? traceId : null;
033        }
034
035        @Override
036        public String getSpanId() {
037                String spanId = Span.current().getSpanContext().getSpanId();
038                return SpanId.isValid(spanId) ? spanId : null;
039        }
040
041        @Override
042        public boolean isSampled() {
043                return Span.current().getSpanContext().isSampled();
044        }
045}