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      return true;
019    } catch (LinkageError ignored) {
020      // NoClassDefFoundError:
021      //   Either OpenTelemetry is not present, or it is version 0.9.1 or older when io.opentelemetry.api.trace.Span did not exist.
022      // IncompatibleClassChangeError:
023      //   The application uses an OpenTelemetry version between 0.10.0 and 0.15.0 when SpanContext was a class, and not an interface.
024      return false;
025    }
026  }
027
028  @Override
029  public String getTraceId() {
030    String traceId = Span.current().getSpanContext().getTraceId();
031    return TraceId.isValid(traceId) ? traceId : null;
032  }
033
034  @Override
035  public String getSpanId() {
036    String spanId = Span.current().getSpanContext().getSpanId();
037    return SpanId.isValid(spanId) ? spanId : null;
038  }
039}