Java Code Examples for io.opentracing.Tracer#SpanBuilder

The following examples show how to use io.opentracing.Tracer#SpanBuilder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdbcTracingUtils.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
static Span buildSpan(String operationName,
    String sql,
    ConnectionInfo connectionInfo,
    boolean withActiveSpanOnly,
    Set<String> ignoredStatements,
    Tracer tracer) {
  if (!TracingDriver.isTraceEnabled() || (withActiveSpanOnly && tracer.activeSpan() == null)) {
    return NoopSpan.INSTANCE;
  } else if (ignoredStatements != null && ignoredStatements.contains(sql)) {
    return NoopSpan.INSTANCE;
  }

  Tracer.SpanBuilder spanBuilder = tracer.buildSpan(operationName)
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);

  Span span = spanBuilder.start();
  decorate(span, sql, connectionInfo);

  return span;
}
 
Example 2
Source File: TracingKafkaUtils.java    From java-kafka-client with Apache License 2.0 6 votes vote down vote up
static <K, V> void buildAndFinishChildSpan(ConsumerRecord<K, V> record, Tracer tracer,
    BiFunction<String, ConsumerRecord, String> consumerSpanNameProvider,
    Collection<SpanDecorator> spanDecorators) {
  SpanContext parentContext = TracingKafkaUtils.extractSpanContext(record.headers(), tracer);
  String consumerOper =
      FROM_PREFIX + record.topic(); // <====== It provides better readability in the UI
  Tracer.SpanBuilder spanBuilder = tracer
      .buildSpan(consumerSpanNameProvider.apply(consumerOper, record))
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER);

  if (parentContext != null) {
    spanBuilder.addReference(References.FOLLOWS_FROM, parentContext);
  }

  Span span = spanBuilder.start();

  for (SpanDecorator decorator : spanDecorators) {
    decorator.onResponse(record, span);
  }

  span.finish();

  // Inject created span context into record headers for extraction by client to continue span chain
  inject(span.context(), record.headers(), tracer);
}
 
Example 3
Source File: RabbitMqTracingUtils.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
static Scope buildSendSpan(Tracer tracer, MessageProperties messageProperties) {
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(RabbitMqTracingTags.SPAN_KIND_PRODUCER)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), RabbitMqTracingTags.SPAN_KIND_PRODUCER);

  ScopeManager scopeManager = tracer.scopeManager();
  Optional<SpanContext> existingSpanContext = Optional.ofNullable(scopeManager)
      .map(ScopeManager::activeSpan)
      .map(Span::context);

  existingSpanContext.ifPresent(spanBuilder::asChildOf);

  if (messageProperties.getHeaders() != null) {
    Optional<SpanContext> messageParentContext = findParent(messageProperties, tracer);
    messageParentContext.ifPresent(spanBuilder::asChildOf);
  }
  Span span = spanBuilder.start();
  return scopeManager.activate(span);
}
 
Example 4
Source File: MockTracerTest.java    From opentracing-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartTimestamp() throws InterruptedException {
    MockTracer tracer = new MockTracer();
    long startMicros;
    {
        Tracer.SpanBuilder fooSpan = tracer.buildSpan("foo");
        Thread.sleep(2);
        startMicros = System.currentTimeMillis() * 1000;
        fooSpan.start().finish();
    }
    List<MockSpan> finishedSpans = tracer.finishedSpans();

    Assert.assertEquals(1, finishedSpans.size());
    MockSpan span = finishedSpans.get(0);
    Assert.assertTrue(startMicros <= span.startMicros());
    Assert.assertTrue(System.currentTimeMillis() * 1000 >= span.finishMicros());
}
 
Example 5
Source File: SofaTracer.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public Tracer.SpanBuilder asChildOf(Span parentSpan) {
    if (parentSpan == null) {
        return this;
    }
    return addReference(References.CHILD_OF, parentSpan.context());
}
 
Example 6
Source File: HttpClientTracingDispatch.java    From xio with Apache License 2.0 5 votes vote down vote up
public void onRequest(ChannelHandlerContext ctx, Request request) {
  String requestorIpAddress = remoteIp(ctx);
  if (request.headers().get("x-remote-ip") != null) {
    requestorIpAddress = request.headers().get("x-remote-ip");
  }
  request.headers().set("x-remote-ip", requestorIpAddress);

  String httpType = request.streamId() == Message.H1_STREAM_ID_NONE ? "http1.1" : "h2";
  Tracer.SpanBuilder spanBuilder =
      tracer
          .buildSpan(name + ".client")
          .withTag(Tags.HTTP_METHOD.getKey(), request.method().toString())
          .withTag(Tags.HTTP_URL.getKey(), request.path())
          .withTag("http.request.type", httpType)
          .withTag("http.request.streamId", request.streamId())
          .withTag("http.request.source-ip-address", localIp(ctx))
          .withTag("http.request.originating-ip-address", requestorIpAddress);

  StreamSupport.stream(request.headers().spliterator(), false)
      .forEach(
          (entry) -> {
            spanBuilder.withTag(
                "http.request.headers." + entry.getKey().toString(), entry.getValue().toString());
          });

  Optional<Span> parentSpan = request.httpTraceInfo().getSpan();
  parentSpan.ifPresent(spanBuilder::asChildOf);

  try (Scope scope = spanBuilder.startActive(false)) {
    tracer.inject(
        scope.span().context(),
        Format.Builtin.HTTP_HEADERS,
        new HttpHeadersInjectAdapter(request));
    request.httpTraceInfo().setSpan(scope.span());
    setSpan(ctx, request.streamId(), scope.span());
  }
}
 
Example 7
Source File: TagListenerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldDelegateSpanBuilderStringTag() {
    final Tracer.SpanBuilder builder = unit.buildSpan("test")
            .withTag("k1", "v");

    verify(listener).onTag(eq(builder), tag("k1"), eq("v"));
}
 
Example 8
Source File: GlobalTracerTest.java    From opentracing-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testNoopTracerByDefault() {
    Tracer.SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("my-operation");
    assertThat(spanBuilder, is(instanceOf(NoopSpanBuilder.class)));
}
 
Example 9
Source File: RewritableSpanBuilder.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer.SpanBuilder withTag(final String key, final String value) {
  onTag(key, value);
  return this;
}
 
Example 10
Source File: MockTracer.java    From opentracing-java with Apache License 2.0 4 votes vote down vote up
@Override
public <T> Tracer.SpanBuilder withTag(Tag<T> tag, T value) {
    this.initialTags.put(tag.getKey(), value);
    return this;
}
 
Example 11
Source File: SolrDispatchFilter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
public void doFilter(ServletRequest _request, ServletResponse _response, FilterChain chain, boolean retry) throws IOException, ServletException {
  if (!(_request instanceof HttpServletRequest)) return;
  HttpServletRequest request = closeShield((HttpServletRequest)_request, retry);
  HttpServletResponse response = closeShield((HttpServletResponse)_response, retry);
  Scope scope = null;
  Span span = null;
  try {

    if (cores == null || cores.isShutDown()) {
      try {
        init.await();
      } catch (InterruptedException e) { //well, no wait then
      }
      final String msg = "Error processing the request. CoreContainer is either not initialized or shutting down.";
      if (cores == null || cores.isShutDown()) {
        log.error(msg);
        throw new UnavailableException(msg);
      }
    }

    String requestPath = ServletUtils.getPathAfterContext(request);
    // No need to even create the HttpSolrCall object if this path is excluded.
    if (excludePatterns != null) {
      for (Pattern p : excludePatterns) {
        Matcher matcher = p.matcher(requestPath);
        if (matcher.lookingAt()) {
          chain.doFilter(request, response);
          return;
        }
      }
    }

    SpanContext parentSpan = GlobalTracer.get().extract(request);
    Tracer tracer = GlobalTracer.getTracer();

    Tracer.SpanBuilder spanBuilder = null;
    String hostAndPort = request.getServerName() + "_" + request.getServerPort();
    if (parentSpan == null) {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort);
    } else {
      spanBuilder = tracer.buildSpan(request.getMethod() + ":" + hostAndPort)
          .asChildOf(parentSpan);
    }

    spanBuilder
        .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
        .withTag(Tags.HTTP_URL.getKey(), request.getRequestURL().toString());
    span = spanBuilder.start();
    scope = tracer.scopeManager().activate(span);

    AtomicReference<HttpServletRequest> wrappedRequest = new AtomicReference<>();
    if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been sent
      return;
    }
    if (wrappedRequest.get() != null) {
      request = wrappedRequest.get();
    }

    if (cores.getAuthenticationPlugin() != null) {
      if (log.isDebugEnabled()) {
        log.debug("User principal: {}", request.getUserPrincipal());
      }
    }

    HttpSolrCall call = getHttpSolrCall(request, response, retry);
    ExecutorUtil.setServerThreadFlag(Boolean.TRUE);
    try {
      Action result = call.call();
      switch (result) {
        case PASSTHROUGH:
          chain.doFilter(request, response);
          break;
        case RETRY:
          doFilter(request, response, chain, true); // RECURSION
          break;
        case FORWARD:
          request.getRequestDispatcher(call.getPath()).forward(request, response);
          break;
        case ADMIN:
        case PROCESS:
        case REMOTEQUERY:
        case RETURN:
          break;
      }
    } finally {
      call.destroy();
      ExecutorUtil.setServerThreadFlag(null);
    }
  } finally {
    if (span != null) span.finish();
    if (scope != null) scope.close();

    GlobalTracer.get().clearContext();
    consumeInputFully(request, response);
    SolrRequestInfo.reset();
    SolrRequestParsers.cleanupMultipartFiles(request);
  }
}
 
Example 12
Source File: RewritableSpanBuilder.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer.SpanBuilder asChildOf(final Span parent) {
  target.asChildOf(parent);
  return this;
}
 
Example 13
Source File: SofaTracer.java    From sofa-tracer with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer.SpanBuilder withTag(String key, Number value) {
    this.tags.put(key, value);
    return this;
}
 
Example 14
Source File: SofaTracer.java    From sofa-tracer with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer.SpanBuilder withTag(String key, boolean value) {
    this.tags.put(key, value);
    return this;
}
 
Example 15
Source File: JaegerHandler.java    From light-4j with Apache License 2.0 4 votes vote down vote up
/**
 * Extract the context, start and stop the span here.
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // get the path and method to construct the endpoint for the operation of tracing.
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    String endpoint = null;
    if(auditInfo != null) {
        endpoint = (String)auditInfo.get(Constants.ENDPOINT_STRING);
    } else {
        endpoint = exchange.getRequestPath() + "@" + exchange.getRequestMethod();
    }

    HeaderMap headerMap = exchange.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<>();
    for(HttpString key : headerMap.getHeaderNames()) {
        headers.put(key.toString(), headerMap.getFirst(key));
    }
    TextMap carrier = new TextMapAdapter(headers);

    // start the server span.
    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(endpoint);
        } else {
            spanBuilder = tracer.buildSpan(endpoint).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(endpoint);
    }
    Span rootSpan = spanBuilder
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .withTag(Tags.PEER_HOSTNAME.getKey(), NetUtils.getLocalAddressByDatagram())
            .withTag(Tags.PEER_PORT.getKey(), Server.config.getHttpsPort())
            .start();
    tracer.activateSpan(rootSpan);
    // This can be retrieved in the business handler to add tags and logs for tracing.
    exchange.putAttachment(ROOT_SPAN, rootSpan);
    // The client module can use this to inject tracer.
    exchange.putAttachment(EXCHANGE_TRACER, tracer);

    // add an exchange complete listener to close the Root Span for the request.
    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        Span span = exchange1.getAttachment(ROOT_SPAN);
        if(span != null) {
            span.finish();
        }
        nextListener.proceed();
    });

    Handler.next(exchange, next);
}
 
Example 16
Source File: SofaTracer.java    From sofa-tracer with Apache License 2.0 4 votes vote down vote up
@Override
public Tracer.SpanBuilder asChildOf(SpanContext parent) {
    return addReference(References.CHILD_OF, parent);
}
 
Example 17
Source File: TracingInterceptor.java    From java-jaxrs with Apache License 2.0 3 votes vote down vote up
/**
 * Client requests :
 * <ul>
 * <li>Serialization of request body happens between the tracing filter invocation so we can use child_of.</li>
 * <li>Deserialization happens after the request is processed by the client filter therefore we can use follows_from only.</li>
 * </ul>
 * Server requests :
 * <ul>
 * <li>Deserialization happens between the span in the server filter is started and finished so we can use child_of.</li>
 * <li>Serialization of response entity happens after the server span if finished so we can use only follows_from.</li>
 * </ul>
 * @param context Used to retrieve the current span wrapper created by the jax-rs request filter.
 * @param operationName "serialize" or "deserialize" depending on the context
 * @return a noop span is no span context is registered in the context. Otherwise a new span related to the current on retrieved from the context.
 */
private Span buildSpan(InterceptorContext context, String operationName) {
    final SpanWrapper spanWrapper = findSpan(context);
    if(spanWrapper == null) {
        return NoopSpan.INSTANCE;
    }
    final Tracer.SpanBuilder spanBuilder = tracer.buildSpan(operationName);
    if(spanWrapper.isFinished()) {
        spanBuilder.addReference(References.FOLLOWS_FROM, spanWrapper.get().context());
    } else {
        spanBuilder.asChildOf(spanWrapper.get());
    }
    return spanBuilder.start();
}
 
Example 18
Source File: TracingUtils.java    From dremio-oss with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a builder for a child span with spanName and tags.
 * @param tracer current tracer
 * @param spanName the desired name of the child span
 * @param tags an even length list of tags on the span.
 * @return A noop builder if there is no traced active span. Otherwise, a real span builder.
 */
public static Tracer.SpanBuilder childSpanBuilder(Tracer tracer, String spanName, String... tags) {
  return childSpanBuilder(tracer, tracer.activeSpan(), spanName, tags);
}
 
Example 19
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates a span builder that is initialized with the given operation name and a follows-from reference to the
 * given span context (if set).
 * <p>
 * If the given span context contains a "sampling.priority" baggage item, it is set as a tag in the returned span
 * builder.
 *
 * @param tracer The Tracer to use.
 * @param spanContext The span context that the span being build shall have a follows-from reference to and that is
 *            used to derive the sampling priority from (may be null).
 * @param operationName The operation name to set for the span.
 * @return The span builder.
 * @throws NullPointerException if tracer or operationName is {@code null}.
 */
public static Tracer.SpanBuilder buildFollowsFromSpan(final Tracer tracer, final SpanContext spanContext,
        final String operationName) {
    return buildSpan(tracer, spanContext, operationName, References.FOLLOWS_FROM);
}
 
Example 20
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates a span builder that is initialized with the given operation name and a child-of reference to the given
 * span context (if set).
 * <p>
 * If the given span context contains a "sampling.priority" baggage item, it is set as a tag in the returned span
 * builder. Additionally, it is configured to ignore the active span and set kind tag to server.
 *
 * @param tracer The Tracer to use.
 * @param spanContext The span context that shall be the parent of the Span being built and that is used to derive
 *            the sampling priority from (may be null).
 * @param operationName The operation name to set for the span.
 * @param component The component to set for the span.
 * @return The span builder.
 * @throws NullPointerException if tracer or operationName is {@code null}.
 */
public static Tracer.SpanBuilder buildServerChildSpan(final Tracer tracer, final SpanContext spanContext,
        final String operationName, final String component) {
    return buildChildSpan(tracer, spanContext, operationName, component)
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
}