io.opentracing.propagation.TextMapInjectAdapter Java Examples

The following examples show how to use io.opentracing.propagation.TextMapInjectAdapter. 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: Client.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
public void send() throws InterruptedException {
  Message message = new Message();

  Span span =
      tracer
          .buildSpan("send")
          .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
          .withTag(Tags.COMPONENT.getKey(), "example-client")
          .start();
  try (Scope scope = tracer.activateSpan(span)) {
    tracer.inject(span.context(), Builtin.TEXT_MAP_INJECT, new TextMapInjectAdapter(message));
    queue.put(message);
  } finally {
    span.finish();
  }
}
 
Example #2
Source File: AsyncService.java    From hawkular-apm with Apache License 2.0 6 votes vote down vote up
public void callService(Span span, Handler handler) {
    Span clientSpan = getTracer().buildSpan("Client")
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/outbound")
            .withTag(Constants.PROP_TRANSACTION_NAME, "AnotherTxnName")     // Should not overwrite the existing name
            .asChildOf(span).start();
    Message mesg = createMessage();
    getTracer().inject(clientSpan.context(), Format.Builtin.TEXT_MAP,
            new TextMapInjectAdapter(mesg.getHeaders()));

    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(() -> {
        delay(500);

        // Explicit finish
        clientSpan.finish();

        handler.handle("My Response");
    });
}
 
Example #3
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    SpanContext spanContext,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  this.rootSpan = null;

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name).asChildOf(spanContext);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace(
        "Created span [{}], with name [{}], child of [{}]",
        this.span,
        name,
        spanContext.toString());
  }

  this.context = ctx.put(Span.class, this.span);
}
 
Example #4
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 5 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    SpanContext spanContext,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  this.rootSpan = null;

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name).asChildOf(spanContext);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace(
        "Created span [{}], with name [{}], child of [{}]",
        this.span,
        name,
        spanContext.toString());
  }

  this.context = ctx.put(Span.class, this.span);
}
 
Example #5
Source File: SyncService.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
public void callService(Span span) {
    try (Span clientSpan = getTracer().buildSpan("Client")
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/outbound")
            .withTag(Constants.PROP_TRANSACTION_NAME, SYNC_TXN_NAME_2)
            .asChildOf(span).start()) {
        Message mesg = createMessage();
        getTracer().inject(clientSpan.context(), Format.Builtin.TEXT_MAP,
                new TextMapInjectAdapter(mesg.getHeaders()));

        delay(500);

        // Explicit finish
        clientSpan.finish();
    }
}
 
Example #6
Source File: SpawnService.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
public void callService(Span span) {
    try (Span clientSpan = getTracer().buildSpan("Client")
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/outbound")
            .withTag(Constants.PROP_TRANSACTION_NAME, "AnotherTxnName")     // Should not overwrite the existing name
            .asChildOf(span).start()) {
        Message mesg = createMessage();
        getTracer().inject(clientSpan.context(), Format.Builtin.TEXT_MAP,
                new TextMapInjectAdapter(mesg.getHeaders()));

        delay(500);

        // Explicit finish
        clientSpan.finish();
    }
}
 
Example #7
Source File: ClientService.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
public void callService(Span span) {
    try (Span clientSpan = getTracer().buildSpan("Client")
            .withTag(Constants.ZIPKIN_BIN_ANNOTATION_HTTP_URL, "http://localhost:8080/outbound")
            .withTag("myTag", myTag)
            .asChildOf(span).start()) {
        Message mesg = createMessage();
        getTracer().inject(clientSpan.context(), Format.Builtin.TEXT_MAP,
                new TextMapInjectAdapter(mesg.getHeaders()));

        delay(500);
    }
}
 
Example #8
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 #9
Source File: Client.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
public void send() throws InterruptedException {
    Message message = new Message();

    Span span = tracer.buildSpan("send")
        .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
        .withTag(Tags.COMPONENT.getKey(), "example-client")
        .start();
    try (Scope scope = tracer.activateSpan(span)) {
        tracer.inject(span.context(), Builtin.TEXT_MAP_INJECT, new TextMapInjectAdapter(message));
        queue.put(message);
    } finally {
        span.finish();
    }
}
 
Example #10
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Inject tracer specific information to tracerSpecificCarrier
 *
 * @param span
 * @param tracer
 * @param tracerSpecificCarrier
 * */
public static void inject(TracingSpan span, TracingTracer tracer, Map<String, String> tracerSpecificCarrier) {
    Object sp = span.getSpan();
    if (sp instanceof Span) {
        tracer.getTracingTracer().inject(((Span) sp).context(), Format.Builtin.HTTP_HEADERS,
                new TextMapInjectAdapter(tracerSpecificCarrier));
    } else if (sp instanceof SpanContext) {
        tracer.getTracingTracer().inject((SpanContext) sp, Format.Builtin.HTTP_HEADERS,
                new TextMapInjectAdapter(tracerSpecificCarrier));
    }
}
 
Example #11
Source File: TraceClientFilter.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void doFilter(Request request, Response response, FilterChain chain) throws Throwable {
	if (!isTrace) {
		chain.doFilter(request, response);
		return;
	}
	if (!(request instanceof TarsServantRequest) || !TraceUtil.checkServant(((TarsServantRequest)request).getServantName())) {
		chain.doFilter(request, response);
		return;
	}
	ServerConfig config = ConfigurationManager.getInstance().getServerConfig();
	DistributedContext context = DistributedContextManager.getDistributedContext();
	String servantName = context.get(TraceManager.INTERNAL_SERVANT_NAME);
	Tracer tracer = TraceContext.getInstance().getCurrentTracer();
	
       if (tracer == null) {
       	chain.doFilter(request, response);
       } else {
       	TarsServantRequest tarsServantRequest = (TarsServantRequest)request;
       	boolean isSync = tarsServantRequest.getInvokeStatus() == InvokeStatus.SYNC_CALL 
       			|| tarsServantRequest.getInvokeStatus() == InvokeStatus.FUTURE_CALL;
       	
       	String protocol = Constants.TARS_PROTOCOL;
       	Map<String, String> requestContext = tarsServantRequest.getContext();
       	if (requestContext != null && !requestContext.isEmpty()) {
       		protocol = requestContext.get(TraceManager.PROTOCOL);
       		requestContext.remove(TraceManager.PROTOCOL);
       	}
       	try(Scope scope = tracer.buildSpan(tarsServantRequest.getFunctionName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).startActive(isSync)) {
       		Map<String, String> status = tarsServantRequest.getStatus();
       		if (status == null) {
       			tarsServantRequest.setStatus(new HashMap<String, String>());
       			status = tarsServantRequest.getStatus();
       		}
       		tracer.inject(scope.span().context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(status));
       		scope.span().setTag("client.ipv4", config.getLocalIP());
       		scope.span().setTag("client.port", config.getServantAdapterConfMap().get(servantName).getEndpoint().port());
       		scope.span().setTag("tars.interface", getObjName(servantName));
       		scope.span().setTag("tars.method", tarsServantRequest.getFunctionName());
       		scope.span().setTag("tars.protocol", protocol);
       		scope.span().setTag("tars.client.version", ClientVersion.getVersion());
       		
       		
       		TarsServantResponse tarsServantResponse = (TarsServantResponse)response;
       		try {
       			chain.doFilter(request, response);
       			if (isSync) {
           			scope.span().setTag("tars.retcode", Integer.toString(tarsServantResponse.getRet()));
           		} else {
           			TraceManager.getInstance().putSpan(request.getTicketNumber(), tracer, scope.span());
           		}
       		} catch (Exception e) {
       			scope.span().log(e.getMessage());
       			throw e;
       		}
       		
       		
       	}
       }
}
 
Example #12
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  Span root = ctx.getOrDefault(Span.class, this.tracer.activeSpan());
  if (log.isTraceEnabled()) {
    log.trace("Span from context [{}]", root);
  }
  this.rootSpan = root;
  if (log.isTraceEnabled()) {
    log.trace("Stored context root span [{}]", this.rootSpan);
  }

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  if (root != null) {
    spanBuilder.asChildOf(root);
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace("Created span [{}], with name [{}]", this.span, name);
  }
  this.context = ctx.put(Span.class, this.span);
}
 
Example #13
Source File: SpanSubscriber.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
SpanSubscriber(
    Subscriber<? super T> subscriber,
    Context ctx,
    Tracer tracer,
    Map<String, String> tracingMetadata,
    String name,
    Tag... tags) {
  this.subscriber = subscriber;
  this.tracer = tracer;
  Span root = ctx.getOrDefault(Span.class, this.tracer.activeSpan());
  if (log.isTraceEnabled()) {
    log.trace("Span from context [{}]", root);
  }
  this.rootSpan = root;
  if (log.isTraceEnabled()) {
    log.trace("Stored context root span [{}]", this.rootSpan);
  }

  Tracer.SpanBuilder spanBuilder = this.tracer.buildSpan(name);
  if (tags != null && tags.length > 0) {
    for (Tag tag : tags) {
      spanBuilder.withTag(tag.getKey(), tag.getValue());
    }
  }

  if (root != null) {
    spanBuilder.asChildOf(root);
  }

  this.span = spanBuilder.start();

  if (tracingMetadata != null) {
    TextMapInjectAdapter adapter = new TextMapInjectAdapter(tracingMetadata);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, adapter);
  }

  if (log.isTraceEnabled()) {
    log.trace("Created span [{}], with name [{}]", this.span, name);
  }
  this.context = ctx.put(Span.class, this.span);
}
 
Example #14
Source File: SamplingTest.java    From hawkular-apm with Apache License 2.0 4 votes vote down vote up
@Test
public void testSamplingPriorityChangedToZero() {
    APMTracerTest.TestTraceRecorder traceRecorder = new APMTracerTest.TestTraceRecorder();
    Tracer tracer = new APMTracer(traceRecorder, Sampler.ALWAYS_SAMPLE);

    Span rootSpan = tracer.buildSpan("foo")
            .asChildOf(extractedTraceState(tracer, ReportingLevel.All))
            .start();

    Span descendant = tracer.buildSpan("foo")
            .asChildOf(rootSpan)
            .start();

    Map<String, String> carrier = new HashMap<>();
    tracer.inject(descendant.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.All.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    Span descendantZeroSampling = tracer.buildSpan("foo")
            .asChildOf(rootSpan)
            .start();

    descendantZeroSampling.setTag(Tags.SAMPLING_PRIORITY.getKey(), 0);
    carrier.clear();
    tracer.inject(descendantZeroSampling.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.None.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    descendantZeroSampling.finish();
    descendant.finish();
    rootSpan.finish();

    Assert.assertEquals(1, traceRecorder.getTraces().size());
    traceRecorder.clear();

    Span descendantDescendantZeroSampling = tracer.buildSpan("foo")
            .addReference(References.FOLLOWS_FROM, descendantZeroSampling.context())
            .start();

    carrier.clear();
    tracer.inject(descendantDescendantZeroSampling.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.None.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    descendantDescendantZeroSampling.finish();
    Assert.assertEquals(0, traceRecorder.getTraces().size());
}
 
Example #15
Source File: SamplingTest.java    From hawkular-apm with Apache License 2.0 4 votes vote down vote up
@Test
public void testSamplingPriorityChangedToOne() {
    APMTracerTest.TestTraceRecorder traceRecorder = new APMTracerTest.TestTraceRecorder();
    Tracer tracer = new APMTracer(traceRecorder, Sampler.ALWAYS_SAMPLE);

    Span rootSpan = tracer.buildSpan("foo")
            .asChildOf(extractedTraceState(tracer, ReportingLevel.None))
            .start();

    Span descendant = tracer.buildSpan("foo")
            .asChildOf(rootSpan)
            .start();

    Map<String, String> carrier = new HashMap<>();
    tracer.inject(descendant.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.None.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    Span descendantOneSampling = tracer.buildSpan("foo")
            .asChildOf(rootSpan)
            .start();

    descendantOneSampling.setTag(Tags.SAMPLING_PRIORITY.getKey(), 1);
    carrier.clear();
    tracer.inject(descendantOneSampling.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.All.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    descendantOneSampling.finish();
    descendant.finish();
    rootSpan.finish();

    Span descendantDescendantOneSampling = tracer.buildSpan("foo")
            .addReference(References.FOLLOWS_FROM, descendantOneSampling.context())
            .start();

    carrier.clear();
    tracer.inject(descendantDescendantOneSampling.context(), Format.Builtin.TEXT_MAP, new TextMapInjectAdapter(carrier));
    Assert.assertEquals(ReportingLevel.All.name(), carrier.get(Constants.HAWKULAR_APM_LEVEL));

    descendantDescendantOneSampling.finish();
    Assert.assertEquals(2, traceRecorder.getTraces().size());
}
 
Example #16
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();
    }
}