001package io.prometheus.metrics.tracer.initializer;
002
003import io.prometheus.metrics.tracer.agent.OpenTelemetryAgentSpanContext;
004import io.prometheus.metrics.tracer.common.SpanContext;
005import io.prometheus.metrics.tracer.otel.OpenTelemetrySpanContext;
006import java.util.concurrent.atomic.AtomicReference;
007
008public class SpanContextSupplier {
009
010  private static final AtomicReference<SpanContext> spanContextRef =
011      new AtomicReference<SpanContext>();
012
013  public static void setSpanContext(SpanContext spanContext) {
014    spanContextRef.set(spanContext);
015  }
016
017  public static boolean hasSpanContext() {
018    return getSpanContext() != null;
019  }
020
021  public static SpanContext getSpanContext() {
022    return spanContextRef.get();
023  }
024
025  static {
026    try {
027      if (OpenTelemetrySpanContext.isAvailable()) {
028        spanContextRef.set(new OpenTelemetrySpanContext());
029      }
030    } catch (NoClassDefFoundError ignored) {
031      // tracer_otel dependency not found
032    } catch (UnsupportedClassVersionError ignored) {
033      // OpenTelemetry requires Java 8, but client_java might run on Java 6.
034    }
035    try {
036      if (OpenTelemetryAgentSpanContext.isAvailable()) {
037        spanContextRef.set(new OpenTelemetryAgentSpanContext());
038      }
039    } catch (NoClassDefFoundError ignored) {
040      // tracer_otel_agent dependency not found
041    } catch (UnsupportedClassVersionError ignored) {
042      // OpenTelemetry requires Java 8, but client_java might run on Java 6.
043    }
044  }
045}