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

The following examples show how to use io.opentracing.Tracer#inject() . 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: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static Object requestStart(final Object arg0) {
  if (LocalSpanContext.get(COMPONENT_NAME_CLIENT) != null) {
    LocalSpanContext.get(COMPONENT_NAME_CLIENT).increment();
    return arg0;
  }

  final HttpRequest request = (HttpRequest)arg0;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(request.method().value())
    .withTag(Tags.COMPONENT, COMPONENT_NAME_CLIENT)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_METHOD, request.method().value())
    .withTag(Tags.HTTP_URL, request.getUri().toString())
    .withTag(Tags.PEER_HOSTNAME, request.getUri().host().address())
    .withTag(Tags.PEER_PORT, request.getUri().port())
    .start();

  final HttpHeadersInjectAdapter injectAdapter = new HttpHeadersInjectAdapter(request);
  tracer.inject(span.context(), Builtin.HTTP_HEADERS, injectAdapter);

  LocalSpanContext.set(COMPONENT_NAME_CLIENT, span, tracer.activateSpan(span));

  return injectAdapter.getHttpRequest();
}
 
Example 2
Source File: Http2Client.java    From light-4j with Apache License 2.0 6 votes vote down vote up
/**
 * Add Authorization Code grant token the caller app gets from OAuth2 server and inject OpenTracing context
 *
 * This is the method called from client like web server that want to have Tracer context pass through.
 *
 * @param request the http request
 * @param token the bearer token
 * @param tracer the OpenTracing tracer
 */
public void addAuthTokenTrace(ClientRequest request, String token, Tracer tracer) {
    if(token != null && !token.startsWith("Bearer ")) {
        if(token.toUpperCase().startsWith("BEARER ")) {
            // other cases of Bearer
            token = "Bearer " + token.substring(7);
        } else {
            token = "Bearer " + token;
        }
    }
    request.getRequestHeaders().put(Headers.AUTHORIZATION, token);
    if(tracer != null && tracer.activeSpan() != null) {
        Tags.SPAN_KIND.set(tracer.activeSpan(), Tags.SPAN_KIND_CLIENT);
        Tags.HTTP_METHOD.set(tracer.activeSpan(), request.getMethod().toString());
        Tags.HTTP_URL.set(tracer.activeSpan(), request.getPath());
        tracer.inject(tracer.activeSpan().context(), Format.Builtin.HTTP_HEADERS, new ClientRequestCarrier(request));
    }
}
 
Example 3
Source File: PulsarClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void internalSendAsyncEnter(final Object thiz, final Object arg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final MessageImpl<?> message = (MessageImpl<?>)arg;
  final Producer<?> producer = (Producer<?>)thiz;

  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan("send")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_PRODUCER)
    .withTag(Tags.MESSAGE_BUS_DESTINATION, producer.getTopic())
    .withTag(Tags.PEER_SERVICE, "pulsar")
    .start();

  message.getProperties();

  tracer.inject(span.context(), Builtin.TEXT_MAP, new PropertiesMapInjectAdapter(message.getMessageBuilder()));

  final Scope scope = tracer.activateSpan(span);
  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 4
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Injects a {@code SpanContext} into the headers of vert.x {@code DeliveryOptions}.
 *
 * @param tracer The Tracer to use for injecting the context.
 * @param spanContext The context to inject or {@code null} if no context is available.
 * @param deliveryOptions The delivery options to inject the context into.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public static void injectSpanContext(final Tracer tracer, final SpanContext spanContext, final DeliveryOptions deliveryOptions) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(deliveryOptions);

    if (spanContext != null && !(spanContext instanceof NoopSpanContext)) {
        final MultiMap headers = Optional.of(deliveryOptions)
                .map(options -> options.getHeaders())
                .orElseGet(() -> {
                    final MultiMap newHeaders = MultiMap.caseInsensitiveMultiMap();
                    deliveryOptions.setHeaders(newHeaders);
                    return newHeaders;
                });
        tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new MultiMapInjectAdapter(headers));
    }
}
 
Example 5
Source File: AsyncHttpClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static Object enter(final Object request, final Object handler) {
  final Request req = (Request)request;
  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer
    .buildSpan(req.getMethod())
    .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
    .withTag(Tags.HTTP_METHOD.getKey(), req.getMethod())
    .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_URL.getKey(), req.getUrl()).start();

  tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new TextMap() {
    @Override
    public Iterator<Entry<String,String>> iterator() {
      throw new UnsupportedOperationException("iterator not supported with Tracer.inject()");
    }

    @Override
    public void put(final String key, final String value) {
      req.getHeaders().add(key, value);
    }
  });

  return WrapperProxy.wrap(handler, new TracingAsyncHandler(tracer, (AsyncHandler<?>)handler, span));
}
 
Example 6
Source File: SpringWebSocketAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void sendEnter(final Object arg) {
  final Tracer tracer = GlobalTracer.get();
  final StompHeaders headers = (StompHeaders)arg;
  final Span span = tracer.buildSpan(headers.getDestination())
    .withTag(Tags.COMPONENT, "stomp-session")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .start();

  tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new StompHeadersInjectAdapter(headers));
  spanHolder.set(span);
}
 
Example 7
Source File: HttpURLConnectionAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void enter(final Object thiz, final boolean connected) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  if (connected)
    return;

  final HttpURLConnection connection = (HttpURLConnection)thiz;
  final Tracer tracer = GlobalTracer.get();
  final SpanContext spanContext = tracer.extract(Builtin.HTTP_HEADERS, new HttpURLConnectionExtractAdapter(connection));

  if (spanContext != null)
    return;

  final Span span = tracer.buildSpan(connection.getRequestMethod())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.HTTP_METHOD, connection.getRequestMethod())
    .withTag(Tags.HTTP_URL, connection.getURL().toString())
    .withTag(Tags.PEER_PORT, getPort(connection))
    .withTag(Tags.PEER_HOSTNAME, connection.getURL().getHost()).start();

  final Scope scope = tracer.activateSpan(span);
  tracer.inject(span.context(), Builtin.HTTP_HEADERS, new HttpURLConnectionInjectAdapter(connection));

  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 8
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Injects a {@code SpanContext} into a JSON object.
 * <p>
 * The span context will be injected into a new JSON object under key <em>span-context</em>.
 *
 * @param tracer The Tracer to use for injecting the context.
 * @param spanContext The context to inject.
 * @param jsonObject The JSON object to inject the context into.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public static void injectSpanContext(final Tracer tracer, final SpanContext spanContext, final JsonObject jsonObject) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(spanContext);
    Objects.requireNonNull(jsonObject);

    final JsonObject spanContextJson = new JsonObject();
    jsonObject.put(JSON_KEY_SPAN_CONTEXT, spanContextJson);
    tracer.inject(spanContext, Format.Builtin.TEXT_MAP, new JsonObjectInjectAdapter(spanContextJson));
}
 
Example 9
Source File: PlayWSAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object executeStart(final Object arg0, final Object arg1) {
  final Request request = (Request)arg0;
  final AsyncHandler<?> asyncHandler = (AsyncHandler<?>)arg1;

  final Tracer tracer = GlobalTracer.get();
  final Span span = tracer.buildSpan(request.getMethod())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_METHOD, request.getMethod())
    .withTag(Tags.HTTP_URL, request.getUrl())
    .start();

  tracer.inject(span.context(), Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(request.getHeaders()));
  return WrapperProxy.wrap(asyncHandler, new TracingAsyncHandler(asyncHandler, span));
}
 
Example 10
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 11
Source File: OpenTracingFilter.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
private void injectContext(Tracer tracer, Span span, final JRequest request) {
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, new TextMap() {

        @Override
        public Iterator<Map.Entry<String, String>> iterator() {
            throw new UnsupportedOperationException("iterator");
        }

        @Override
        public void put(String key, String value) {
            request.putAttachment(key, value);
        }
    });
}
 
Example 12
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 13
Source File: FeignAgentIntercept.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
private static Request inject(final Tracer tracer, final SpanContext spanContext, final Request request) {
  final HashMap<String,Collection<String>> headersWithTracingContext = new HashMap<>(request.headers());
  tracer.inject(spanContext, Format.Builtin.HTTP_HEADERS, new HttpHeadersInjectAdapter(headersWithTracingContext));
  return Request.create(request.method(), request.url(), headersWithTracingContext, request.body(), request.charset());
}
 
Example 14
Source File: HttpKafkaProducer.java    From client-examples with Apache License 2.0 4 votes vote down vote up
private Future <List<OffsetRecordSent>> send(String topic, Span span) {
    Future<List<OffsetRecordSent>> fut = Future.future();        

    JsonObject records = new JsonObject();
    records.put("records", new JsonArray().add(new JsonObject().put("value", "message-" + this.messagesSent++)));

    HttpRequest<Buffer> httpRequest = this.client.post(this.config.getEndpointPrefix() + "/topics/" + topic);

    Tracer tracer = GlobalTracer.get();
    tracer.inject(span.context(), Format.Builtin.HTTP_HEADERS, new TextMap() {
        @Override
        public Iterator<Map.Entry<String, String>> iterator() {
            throw new UnsupportedOperationException("TextMapInjectAdapter should only be used with Tracer.inject()");
        }

        @Override
        public void put(String key, String value) {
            httpRequest.putHeader(key, value);
        }
    });

    httpRequest
            .putHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), String.valueOf(records.toBuffer().length()))
            .putHeader(HttpHeaderNames.CONTENT_TYPE.toString(), "application/vnd.kafka.json.v2+json")
            .as(BodyCodec.jsonObject())
            .sendJsonObject(records, ar -> {
                if (ar.succeeded()) {
                    HttpResponse<JsonObject> response = ar.result();
                    if (response.statusCode() == HttpResponseStatus.OK.code()) {
                        List<OffsetRecordSent> list = new ArrayList<>();
                        response.body().getJsonArray("offsets").forEach(obj -> {
                            JsonObject json = (JsonObject) obj;
                            list.add(new OffsetRecordSent(
                                json.getInteger("partition"),
                                json.getLong("offset"))
                                );
                        });
                        fut.complete(list);
                    } else {
                        fut.fail(new RuntimeException("Got HTTP status code " + response.statusCode()));
                    }
                } else {
                    fut.fail(ar.cause());
                }

                if (this.config.getMessageCount().isPresent() &&
                    this.messagesSent >= this.config.getMessageCount().get()) {
                        this.vertx.close(done -> System.exit(0));
                }
            });
    return fut;
}
 
Example 15
Source File: TraceUtil.java    From qmq with Apache License 2.0 4 votes vote down vote up
public static void inject(Message message, Tracer tracer) {
    Scope scope = tracer.scopeManager().active();
    if (scope == null) return;
    tracer.inject(scope.span().context(), Format.Builtin.TEXT_MAP, new QmqMessageInjectAdapter(message));
}
 
Example 16
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 17
Source File: InjectionTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, String> injectTextMap(final Tracer unit) {
    final SpanContext context = newSpan(unit).context();
    final Map<String, String> map = new HashMap<>();
    unit.inject(context, TEXT_MAP, new TextMapAdapter(map));
    return map;
}
 
Example 18
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 19
Source File: SolrCmdDistributor.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private void submit(final Req req, boolean isCommit) throws IOException {
  // Copy user principal from the original request to the new update request, for later authentication interceptor use
  if (SolrRequestInfo.getRequestInfo() != null) {
    req.uReq.setUserPrincipal(SolrRequestInfo.getRequestInfo().getReq().getUserPrincipal());
  }

  Tracer tracer = GlobalTracer.getTracer();
  Span parentSpan = tracer.activeSpan();
  if (parentSpan != null) {
    tracer.inject(parentSpan.context(), Format.Builtin.HTTP_HEADERS,
        new SolrRequestCarrier(req.uReq));
  }

  if (req.synchronous) {
    blockAndDoRetries();

    try {
      req.uReq.setBasePath(req.node.getUrl());
      clients.getHttpClient().request(req.uReq);
    } catch (Exception e) {
      SolrException.log(log, e);
      Error error = new Error();
      error.e = e;
      error.req = req;
      if (e instanceof SolrException) {
        error.statusCode = ((SolrException) e).code();
      }
      errors.add(error);
    }
    
    return;
  }
  
  if (log.isDebugEnabled()) {
    log.debug("sending update to {} retry: {} {} params {}"
        , req.node.getUrl(), req.retries, req.cmd, req.uReq.getParams());
  }
  
  if (isCommit) {
    // a commit using ConncurrentUpdateSolrServer is not async,
    // so we make it async to prevent commits from happening
    // serially across multiple nodes
    pending.add(completionService.submit(() -> {
      doRequest(req);
      return null;
    }));
  } else {
    doRequest(req);
  }
}
 
Example 20
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Injects a {@code SpanContext} into an AMQP {@code Message}.
 * <p>
 * The span context will be written to the message annotations of the given message.
 *
 * @param tracer The Tracer to use for injecting the context.
 * @param spanContext The context to inject.
 * @param message The AMQP {@code Message} object to inject the context into.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public static void injectSpanContext(final Tracer tracer, final SpanContext spanContext, final Message message) {

    Objects.requireNonNull(tracer);
    Objects.requireNonNull(spanContext);
    Objects.requireNonNull(message);

    tracer.inject(spanContext, Format.Builtin.TEXT_MAP,
            new MessageAnnotationsInjectAdapter(message, AMQP_ANNOTATION_NAME_TRACE_CONTEXT));
}