001package io.prometheus.client.exemplars.tracer.otel_agent;
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
008/**
009 * This is exactly the same as the {@code OpenTelemetrySpanContextSupplier}.
010 * However, the {@code io.opentelemetry.api} package is relocated to
011 * {@code io.opentelemetry.javaagent.shaded.io.opentelemetry.api} in the OpenTelemetry agent.
012 */
013public class OpenTelemetryAgentSpanContextSupplier implements SpanContextSupplier {
014
015  public static boolean isAvailable() {
016    try {
017      if ("inactive".equalsIgnoreCase(System.getProperties().getProperty("io.prometheus.otelExemplars"))) {
018        return false;
019      }
020      OpenTelemetryAgentSpanContextSupplier test = new OpenTelemetryAgentSpanContextSupplier();
021      test.getSpanId();
022      test.getTraceId();
023      return true;
024    } catch (LinkageError ignored) {
025      // NoClassDefFoundError:
026      //   Either OpenTelemetry is not present, or it is version 0.9.1 or older when io.opentelemetry.api.trace.Span did not exist.
027      // IncompatibleClassChangeError:
028      //   The application uses an OpenTelemetry version between 0.10.0 and 0.15.0 when SpanContext was a class, and not an interface.
029      return false;
030    }
031  }
032
033  @Override
034  public String getTraceId() {
035    String traceId = Span.current().getSpanContext().getTraceId();
036    return TraceId.isValid(traceId) ? traceId : null;
037  }
038
039  @Override
040  public String getSpanId() {
041    String spanId = Span.current().getSpanContext().getSpanId();
042    return SpanId.isValid(spanId) ? spanId : null;
043  }
044}