io.opentracing.propagation.TextMapExtractAdapter Java Examples

The following examples show how to use io.opentracing.propagation.TextMapExtractAdapter. 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: Server.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
private void process(Message message) {
  SpanContext context =
      tracer.extract(Builtin.TEXT_MAP_EXTRACT, new TextMapExtractAdapter(message));
  Span span =
      tracer
          .buildSpan("receive")
          .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
          .withTag(Tags.COMPONENT.getKey(), "example-server")
          .asChildOf(context)
          .start();

  try (Scope scope = tracer.activateSpan(span)) {
    // Simulate work.
  } finally {
    span.finish();
  }
}
 
Example #2
Source File: RpcHandler.java    From ja-micro with Apache License 2.0 6 votes vote down vote up
protected Span getSpan(String methodName, Map<String, String> headers, OrangeContext context) {
    Span span = null;
    if (tracer != null) {
        SpanContext spanContext = tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapExtractAdapter(headers));
        if (spanContext != null) {
            span = tracer.buildSpan(methodName).asChildOf(spanContext).start();
        } else {
            span = tracer.buildSpan(methodName).start();
        }
        span.setTag("correlation_id", context.getCorrelationId());
        span.setTag("rpc.call", methodName);
        Tags.SPAN_KIND.set(span, Tags.SPAN_KIND_SERVER);
        Tags.PEER_SERVICE.set(span, context.getRpcOriginService());
        context.setTracingContext(span.context());
    }
    return span;
}
 
Example #3
Source File: SyncService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void handle1(Message message) {
    SpanContext spanCtx = getTracer().extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(message.getHeaders()));

    // Top level, so create Tracer and root span
    Span serverSpan = getTracer().buildSpan("Server")
            .asChildOf(spanCtx)
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/inbound?orderId=123&verbose=true")
            .withTag(Constants.PROP_TRANSACTION_NAME, SYNC_TXN_NAME_1)
            .withTag(ORDER_ID_NAME, ORDER_ID_VALUE)
            .start();

    delay(500);

    component(serverSpan);

    serverSpan.setTag("fault", MY_FAULT);

    delay(500);

    serverSpan.finish();

    serverSpan.close();
}
 
Example #4
Source File: SyncService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void handle2(Message message) {
    SpanContext spanCtx = getTracer().extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(message.getHeaders()));

    // Top level, so create Tracer and root span
    Span serverSpan = getTracer().buildSpan("Server")
            .asChildOf(spanCtx)
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/inbound?orderId=123&verbose=true")
            .withTag(ORDER_ID_NAME, ORDER_ID_VALUE)
            .start();

    delay(500);

    component(serverSpan);

    serverSpan.setTag("fault", MY_FAULT);

    delay(500);

    serverSpan.finish();

    serverSpan.close();
}
 
Example #5
Source File: SpawnService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void handle(Message message) {
    SpanContext spanCtx = getTracer().extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(message.getHeaders()));

    // Top level, so create Tracer and root span
    Span serverSpan = getTracer().buildSpan("Server")
            .asChildOf(spanCtx)
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/inbound?orderId=123&verbose=true")
            .withTag("orderId", "1243343456455")
            .start();

    delay(500);

    component1(serverSpan);

    serverSpan.finish();

    serverSpan.close();
}
 
Example #6
Source File: ForkJoinService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void handle(Message message) {
    SpanContext spanCtx = getTracer().extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(message.getHeaders()));

    // Top level, so create Tracer and root span
    Span serverSpan = getTracer().buildSpan("Server")
            .asChildOf(spanCtx)
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/inbound?orderId=123&verbose=true")
            .withTag("orderId", "1243343456455")
            .start();

    delay(500);

    ForkJoinPool pool = new ForkJoinPool();
    for (int i = 0; i < 5; i++) {
        int pos = i;
        pool.execute(() -> component(serverSpan, pos));
    }

    pool.awaitQuiescence(5, TimeUnit.SECONDS);

    serverSpan.finish();

    serverSpan.close();
}
 
Example #7
Source File: AsyncService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void handle(Message message, Handler handler) {
    SpanContext spanCtx = getTracer().extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(message.getHeaders()));

    // Top level, so create Tracer and root span
    Span serverSpan = getTracer().buildSpan("Server")
            .asChildOf(spanCtx)
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL,
                    "http://localhost:8080/inbound?orderId=123&verbose=true")
            .withTag("orderId", "1243343456455")
            .start();

    delay(500);

    callService(serverSpan, obj -> {

        serverSpan.finish();

        handler.handle(obj);
    });
}
 
Example #8
Source File: UsersHandler.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/user")
public Response hello(@Context HttpHeaders headers, @Context UriInfo uriInfo) {
    SpanContext spanContext =
            tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(Utils.extractHeaders(headers)));

    Span span = tracer.buildSpan("get_user")
            .asChildOf(spanContext)
            .withTag("http.url", uriInfo.getRequestUri().toString())
            .start();

    /**
     * Some business logic
     */
    span.close();

    return Response.ok("{name: \"admin\"}").build();
}
 
Example #9
Source File: HelloHandler.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/hello")
public Response hello(@Context HttpHeaders headers) {
    SpanContext spanContext =
            tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(Utils.extractHeaders(headers)));

    Span span = tracer.buildSpan("hello")
            .asChildOf(spanContext)
            .start();
    /**
     * Some business logic
     */
    span.close();

    return Response.ok("Hello from WildFly Swarm! [java]").build();
}
 
Example #10
Source File: TraceServerFilter.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void doFilter(Request request, Response response, FilterChain chain)
		throws Throwable {
	if (!isTrace || !(request instanceof TarsServantRequest)) {
		chain.doFilter(request, response);
	} else {
		
		TarsServantRequest tarsServantRequest = (TarsServantRequest)request;
		
		try(TraceContext traceContext = TraceContext.getInstance().initCurrentTrace(tarsServantRequest.getServantName())) {
			Tracer tracer = TraceContext.getInstance().getCurrentTracer();
			Map<String, String> status = tarsServantRequest.getStatus();
			if (tracer == null || status == null || status.isEmpty()) {
				chain.doFilter(request, response);
				return;
			} 
			try (Scope scope = tracer.buildSpan(tarsServantRequest.getFunctionName())
					.asChildOf(tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(status)))
					.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).startActive(true)) {
				Endpoint endpoint = ConfigurationManager.getInstance().getServerConfig().getServantAdapterConfMap().get(tarsServantRequest.getServantName()).getEndpoint();
				scope.span().setTag("server.ipv4", ConfigurationManager.getInstance().getServerConfig().getLocalIP());
				if (endpoint != null) {
					scope.span().setTag("server.port", endpoint.port());
					if (StringUtils.isNotEmpty(endpoint.setDivision())) {
						scope.span().setTag("tars.set_division", endpoint.setDivision());
					}
					scope.span().setTag("tars.server.version", ClientVersion.getVersion());
				}
				chain.doFilter(request, response);
				TarsServantResponse tarsServantResponse = (TarsServantResponse)response;
				if (response != null && tarsServantResponse.getCause() != null && tarsServantResponse.getCause().getMessage() != null) {
					scope.span().log(tarsServantResponse.getCause().getMessage());
				}
				
			}
		}
	}

}
 
Example #11
Source File: LogCorrelationTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
private SpanContext context(final String key, final String value) {
    return unit.extract(TEXT_MAP_EXTRACT,
            new TextMapExtractAdapter(ImmutableMap.of(
                    "traceid", "1",
                    "spanid", "1",
                    "baggage-" + key, value
            )));
}
 
Example #12
Source File: AutoTaggingTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
private SpanContext context(final String baggageKey) {
    return unit.extract(TEXT_MAP_EXTRACT,
            new TextMapExtractAdapter(ImmutableMap.of(
                    "traceid", "1",
                    "spanid", "1",
                    "baggage-" + baggageKey, "yes"
            )));
}
 
Example #13
Source File: Server.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
private void process(Message message) {
    SpanContext context = tracer.extract(Builtin.TEXT_MAP_EXTRACT, new TextMapExtractAdapter(message));
    Span span = tracer.buildSpan("receive")
      .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
      .withTag(Tags.COMPONENT.getKey(), "example-server")
      .asChildOf(context)
      .start();

    try (Scope scope = tracer.activateSpan(span)) {
    } finally {
        span.finish();
    }
}
 
Example #14
Source File: MockTracerTest.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testTextMapPropagatorTextMap() {
    MockTracer tracer = new MockTracer(MockTracer.Propagator.TEXT_MAP);
    HashMap<String, String> injectMap = new HashMap<>();
    injectMap.put("foobag", "donttouch");
    {
        Span parentSpan = tracer.buildSpan("foo")
                .start();
        parentSpan.setBaggageItem("foobag", "fooitem");
        parentSpan.finish();

        tracer.inject(parentSpan.context(), Format.Builtin.TEXT_MAP_INJECT,
                new TextMapInjectAdapter(injectMap));

        SpanContext extract = tracer.extract(Format.Builtin.TEXT_MAP_EXTRACT, new TextMapExtractAdapter(injectMap));

        Span childSpan = tracer.buildSpan("bar")
                .asChildOf(extract)
                .start();
        childSpan.setBaggageItem("barbag", "baritem");
        childSpan.finish();
    }
    List<MockSpan> finishedSpans = tracer.finishedSpans();

    Assert.assertEquals(2, finishedSpans.size());
    Assert.assertEquals(finishedSpans.get(0).context().traceId(), finishedSpans.get(1).context().traceId());
    Assert.assertEquals(finishedSpans.get(0).context().spanId(), finishedSpans.get(1).parentId());
    Assert.assertEquals("fooitem", finishedSpans.get(0).getBaggageItem("foobag"));
    Assert.assertNull(finishedSpans.get(0).getBaggageItem("barbag"));
    Assert.assertEquals("fooitem", finishedSpans.get(1).getBaggageItem("foobag"));
    Assert.assertEquals("baritem", finishedSpans.get(1).getBaggageItem("barbag"));
    Assert.assertEquals("donttouch", injectMap.get("foobag"));
}
 
Example #15
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 #16
Source File: APMSpanTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
protected SpanContext extractSpanContext(Tracer tracer, String id) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID);
    headers.put(Constants.HAWKULAR_APM_ID, id);
    headers.put(Constants.HAWKULAR_APM_TXN, TEST_TXN);

    return tracer.extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(headers));
}
 
Example #17
Source File: SamplingTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
private SpanContext extractedTraceState(Tracer tracer, ReportingLevel reportingLevel) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, "foo");
    headers.put(Constants.HAWKULAR_APM_ID, "foo");
    headers.put(Constants.HAWKULAR_APM_LEVEL, reportingLevel.toString());

    return tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(headers));
}
 
Example #18
Source File: APMTracerReferenceTest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
protected SpanContext extractedTraceState(Tracer tracer, String id) {
    Map<String, String> headers = new HashMap<>();
    headers.put(Constants.HAWKULAR_APM_TRACEID, TEST_APM_TRACEID);
    headers.put(Constants.HAWKULAR_APM_ID, id);
    headers.put(Constants.HAWKULAR_APM_TXN, TEST_TXN);

    return tracer.extract(Format.Builtin.TEXT_MAP,
            new TextMapExtractAdapter(headers));
}
 
Example #19
Source File: Tracing.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to extract and build the active span out of Map containing the
 * processed headers.
 *
 * @param headers is the Map of the processed headers
 * @return Scope containing the extracted span marked as active. Can be used
 *         with try-with-resource construct
 */
private static Scope buildSpanFromHeaders(Map<String, String> headers) {
  Tracer.SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("op");
  try {
    SpanContext parentSpanCtx = GlobalTracer.get().extract(Format.Builtin.HTTP_HEADERS,
        new TextMapExtractAdapter(headers));
    if (parentSpanCtx != null) {
      spanBuilder = spanBuilder.asChildOf(parentSpanCtx);
    }
  } catch (IllegalArgumentException e) {
    e.printStackTrace();
  }
  return spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).startActive(true);
}
 
Example #20
Source File: TracingFilter.java    From nakadi with MIT License 4 votes vote down vote up
@Override
protected void doFilterInternal(final HttpServletRequest request,
                                final HttpServletResponse response, final FilterChain filterChain)
        throws IOException, ServletException {
    final Long startTime = System.currentTimeMillis();
    final Map<String, String> requestHeaders = Collections.list(request.getHeaderNames())
            .stream()
            .collect(Collectors.toMap(h -> h, request::getHeader));

    final SpanContext spanContext = GlobalTracer.get()
            .extract(HTTP_HEADERS, new TextMapExtractAdapter(requestHeaders));
    final Span baseSpan;
    if (spanContext != null) {
        if (isCommitRequest(request.getRequestURI(), request.getMethod())) {
            baseSpan = TracingService.getNewSpanWithReference("commit_events",
                    startTime, spanContext);
        } else {
            baseSpan = TracingService.getNewSpanWithParent("all_requests",
                    startTime, spanContext);
        }
    } else {
        baseSpan = TracingService.getNewSpan("all_requests", startTime);
    }

    try {
        baseSpan
                .setTag("client_id", authorizationService.getSubject().map(Subject::getName).orElse("-"))
                .setTag("http.url", request.getRequestURI() +
                        Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""))
                .setTag("http.header.content_encoding",
                        Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""))
                .setTag("http.header.accept_encoding",
                        Optional.ofNullable(request.getQueryString()).map(q -> "?" + q).orElse(""))
                .setTag("http.header.user_agent",
                        Optional.ofNullable(request.getHeader("User-Agent")).orElse("-"));
        request.setAttribute("span", baseSpan);
        //execute request
        filterChain.doFilter(request, response);
        if (request.isAsyncStarted()) {
            final String flowId = FlowIdUtils.peek();
            request.getAsyncContext().addListener(new AsyncRequestListener(request, response, flowId, baseSpan));
        }
    } finally {
        if (!request.isAsyncStarted()) {
            traceRequest(request.getContentLength(), response.getStatus(), baseSpan);
        }
        final Map<String, String> spanContextToInject = new HashMap<>();
        GlobalTracer.get().inject(baseSpan.context(),
                HTTP_HEADERS, new TextMapInjectAdapter(spanContextToInject));
        response.setHeader(SPAN_CONTEXT, spanContextToInject.toString());
        baseSpan.finish();
    }
}
 
Example #21
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
public static SpanContext deserializeTracingMetadata(
    Tracer tracer, Map<String, String> metadata) {
  TextMapExtractAdapter adapter = new TextMapExtractAdapter(metadata);
  return tracer.extract(Format.Builtin.TEXT_MAP, adapter);
}
 
Example #22
Source File: Tracing.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
public static SpanContext deserializeTracingMetadata(
    Tracer tracer, Map<String, String> metadata) {
  TextMapExtractAdapter adapter = new TextMapExtractAdapter(metadata);
  return tracer.extract(Format.Builtin.TEXT_MAP, adapter);
}
 
Example #23
Source File: Util.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
 * Extract the tracer specific information from headerMap
 *
 * @param tracer
 * @param headerMap
 * @return a TracingSpan object
 * */
public static TracingSpan extract(TracingTracer tracer, Map<String, String> headerMap) {
    return new TracingSpan(tracer.getTracingTracer().extract(Format.Builtin.HTTP_HEADERS,
            new TextMapExtractAdapter(headerMap)));
}