Java Code Examples for io.opentracing.Tracer#buildSpan()

The following examples show how to use io.opentracing.Tracer#buildSpan() . 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: OpenTracingHelperTest.java    From java-agent with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTracerWithRulesEnabled() {
    System.setProperty("io.opentracing.contrib.agent.allowInstrumentedTracer", "true");
    try {
        OpenTracingHelper helper = new OpenTracingHelper(null);
        Tracer tracer = helper.getTracer();

        assertNotNull(tracer);

        tracer.buildSpan("test2");
    } catch(DummyTracer.DummyCalled e) {
        assertTrue(e.triggeringEnabled);
        return;
    } finally {
        System.clearProperty("io.opentracing.contrib.agent.allowInstrumentedTracer");
    }
    fail("DummyTracer did not initialize properly");
}
 
Example 2
Source File: Tracing.java    From opentracing-tutorial with Apache License 2.0 6 votes vote down vote up
public static Span startServerSpan(Tracer tracer, javax.ws.rs.core.HttpHeaders httpHeaders, String operationName) {
    // format the headers for extraction
    MultivaluedMap<String, String> rawHeaders = httpHeaders.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<String, String>();
    for (String key : rawHeaders.keySet()) {
        headers.put(key, rawHeaders.get(key).get(0));
    }

    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(headers));
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(operationName);
        } else {
            spanBuilder = tracer.buildSpan(operationName).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(operationName);
    }
    // TODO could add more tags like http.url
    return spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).start();
}
 
Example 3
Source File: OpenTracingFilter.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
private <T extends JFilterContext> void processConsumerTracing(
        Tracer tracer, JRequest request, T filterCtx, JFilterChain next) throws Throwable {
    MessageWrapper msg = request.message();
    Tracer.SpanBuilder spanBuilder = tracer.buildSpan(msg != null ? msg.getOperationName() : "null");
    Span activeSpan = OpenTracingContext.getActiveSpan();
    if (activeSpan != null) {
        spanBuilder.asChildOf(activeSpan);
    }

    Span span = spanBuilder.start();
    try {
        injectContext(tracer, span, request);

        // next filter
        next.doFilter(request, filterCtx);

        span.log("request success.");
    } catch (Throwable t){
        span.log("request fail. " + t.getMessage());
        throw t;
    } finally {
        span.finish();
    }
}
 
Example 4
Source File: OpenTracingHelperTest.java    From java-agent with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTracerResolved() {
    OpenTracingHelper helper = new OpenTracingHelper(null);
    Tracer tracer = helper.getTracer();

    assertNotNull(tracer);

    try {
        tracer.buildSpan("Test");
    } catch (DummyTracer.DummyCalled e) {
        assertFalse(e.triggeringEnabled);
        return;
    }
    fail("DummyTracer did not initialize properly");
}
 
Example 5
Source File: TracingUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a span builder for a tracer with some parent.
 * @param tracer current tracer
 * @param parent parent span the span will eventually attach to. Note: we don't create asChildOf relationship
 *               because we don't want to create an additional child relationship in the case where the parent
 *               span is equivalent to the active span.
 * @param spanName name to be given to span
 * @param tags tags given to span builder
 * @return noop if parent is noop or null. Otherwise, a real span builder.
 */
public static Tracer.SpanBuilder childSpanBuilder(Tracer tracer, Span parent, String spanName, String... tags) {
  Preconditions.checkArgument(tags.length % 2 == 0);
  if (parent == null || parent.equals(NoopSpan.INSTANCE)) {
    return NoopSpanBuilder.INSTANCE;
  }

  Tracer.SpanBuilder builder = tracer.buildSpan(spanName);

  for (int i = 0; i < tags.length; i += 2) {
    builder.withTag(tags[i], tags[i + 1]);
  }
  return builder;
}
 
Example 6
Source File: OpenTracingFilter.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private Span extractContext(Tracer tracer, JRequest request) {
    MessageWrapper msg = request.message();
    Tracer.SpanBuilder spanBuilder = tracer.buildSpan(msg != null ? msg.getOperationName() : "null");
    try {
        SpanContext spanContext = tracer.extract(
                Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(request.getAttachments()));
        if (spanContext != null) {
            spanBuilder.asChildOf(spanContext);
        }
    } catch (Throwable t) {
        spanBuilder.withTag("Error", "extract from request failed: " + t.getMessage());
    }
    return spanBuilder.start();
}
 
Example 7
Source File: TestHttpServerHandler.java    From pampas with Apache License 2.0 4 votes vote down vote up
@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        count.increment();
        System.out.println("server2-count:" + count.sum());

        if (!(msg instanceof FullHttpRequest)) {
            result = "未知请求!";
            send(ctx, result, HttpResponseStatus.BAD_REQUEST);
            return;
        }
        FullHttpRequest httpRequest = (FullHttpRequest) msg;


        Tracer tracer = OpenTracingContext.getTracer();
        Tracer.SpanBuilder spanBuilder = tracer.buildSpan("/server2" + httpRequest.uri());

        SpanContext spanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMap() {
            @Override
            public Iterator<Map.Entry<String, String>> iterator() {
                System.out.println("Trancer iterator...");
                return httpRequest.headers().iteratorAsString();
            }

            @Override
            public void put(String key, String value) {
                System.out.println("XXXXXXXXXXXXXXXXX");
            }
        });
        if (spanCtx != null) {
            spanBuilder.asChildOf(spanCtx);
        }
        Span span = spanBuilder.start();


        try {
            String path = httpRequest.uri();          //获取路径
            String body = getBody(httpRequest);     //获取参数
            HttpMethod method = httpRequest.method();//获取请求方法
            //如果不是这个路径,就直接返回错误
            log.info("请求URI:{},METHOD:{},body:{}", path, method, body);
//            Thread.sleep(10000L);
            result = "非法请求!";
            send(ctx, result, HttpResponseStatus.OK);
            return;

        } catch (Exception e) {
            System.out.println("#server2-处理请求失败!");
            e.printStackTrace();
        } finally {
            //释放请求
            span.finish();
            httpRequest.release();
        }
    }
 
Example 8
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);
  }
}