Java Code Examples for io.opentracing.Tracer.SpanBuilder#addReference()

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

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  if (record instanceof ConsumerRecord) {
    final ConsumerRecord<?,?> consumerRecord = (ConsumerRecord<?,?>)record;
    final SpanContext spanContext = TracingKafkaUtils.extractSpanContext(consumerRecord.headers(), tracer);
    if (spanContext != null)
      builder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 2
Source File: SpringRabbitMQAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void onMessageEnter(final Object msg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  final Message message = (Message)msg;
  if (message.getMessageProperties() != null) {
    final Map<String,Object> headers = message.getMessageProperties().getHeaders();
    final SpanContext spanContext = tracer.extract(Builtin.TEXT_MAP, new HeadersMapExtractAdapter(headers));
    if (spanContext != null)
      builder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 3
Source File: PulsarFunctionsAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void handleMessageEnter(final Object function, final Object contextArg, final Object arg0) {
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer
    .buildSpan(getFunctionName(function, contextArg))
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER);

  if (arg0 != null) {
    final Record<?> record = (Record<?>)arg0;
    final SpanContext spanContext = tracer.extract(Builtin.TEXT_MAP, new TextMapExtractAdapter(record.getProperties()));
    if (spanContext != null)
      spanBuilder.addReference(References.FOLLOWS_FROM, spanContext);
  }

  final Span span = spanBuilder.start();
  final Scope scope = tracer.activateSpan(span);

  LocalSpanContext.set(COMPONENT_NAME, span, scope);
}
 
Example 4
Source File: PulsarClientAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
private static void buildConsumerSpan(final Consumer<?> consumer, final Message<?> message) {
  final Tracer tracer = GlobalTracer.get();
  final SpanContext parentContext = tracer.extract(Builtin.TEXT_MAP, new TextMapAdapter(message.getProperties()));

  final SpanBuilder spanBuilder = tracer
    .buildSpan("receive")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER)
    .withTag("topic", consumer.getTopic())
    .withTag("subscription", consumer.getSubscription())
    .withTag(Tags.PEER_SERVICE, "pulsar");

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

  spanBuilder.start().finish();
}
 
Example 5
Source File: SpringJmsAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void onMessageEnter(final Object msg) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan("onMessage")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  SpanContext spanContext = null;
  if (msg instanceof SpanContextContainer)
    spanContext = ((SpanContextContainer)msg).getSpanContext();

  if (spanContext == null)
    spanContext = TracingMessageUtils.extract((Message)msg, tracer);

  if (spanContext != null)
    builder.addReference(References.FOLLOWS_FROM, spanContext);

  final Span span = builder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 6
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String doGeneralGetCall(String url, SpanContext parent, String kindOfSpanReference) {
	Request request = new Request.Builder().url(url).get().build();

	SpanBuilder spanBuilder = getTracer().buildSpan("GET: " + url);
	spanBuilder.addReference(kindOfSpanReference, parent);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Response response = httpClient.newCall(request).execute();
		if (!response.isSuccessful()) {
			Logger.log("Failed to call GET:" + url);
			return null;
		}
		return response.body().string();
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example 7
Source File: Factory.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("inProduction");
	spanBuilder.addReference(References.FOLLOWS_FROM, parent.context());
	Span span = spanBuilder.start();
	span.setTag(Robot.KEY_SERIAL_NUMBER, String.valueOf(serialNumber));
	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Robot chassis = createChassis(serialNumber, robotTypeId, scope.span().context());
		// Takes some time to roll the robot over to the painting
		Utils.sleep(10);
		Robot paintedRobot = paintRobot(chassis, paint, scope.span().context());
		completedRobots.put(paintedRobot.getSerialNumber(), paintedRobot);
		jobsInProduction.remove(serialNumber);
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		throw t;
	} finally {
		span.finish();
		parent.finish();
	}
}
 
Example 8
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("orderJob");
	spanBuilder.withTag(RobotOrder.KEY_ORDER_ID, String.valueOf(order.getOrderId()));
	spanBuilder.addReference(References.FOLLOWS_FROM, parent.context());
	Span span = spanBuilder.start();
	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Customer customer = validateUser(order.getCustomerId(), scope.span().context());
		Collection<CompletableFuture<Robot>> robots = dispatch(order.getLineItems(), scope.span().context());
		CompletableFuture<Void> allOf = CompletableFuture.allOf(robots.toArray(new CompletableFuture[0]));
		allOf.get();
		List<Robot> collect = robots.stream().map((robot) -> get(robot)).collect(Collectors.toList());

		// TODO verify that all list items got realized - otherwise add errors for the ones missing etc
		completedOrders.put(order.getOrderId(),
				new RealizedOrder(order, customer, collect.toArray(new Robot[0]), null));
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		completedOrders.put(order.getOrderId(), new RealizedOrder(order, null, null, t));
	} finally {
		span.finish();
		parent.finish();
	}
	orderQueue.remove(order.getOrderId());
}
 
Example 9
Source File: OpenTracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
  log.trace("Processing message before sending it to the channel");
  boolean isConsumer = message.getHeaders().containsKey(Headers.MESSAGE_SENT_FROM_CLIENT);

  SpanBuilder spanBuilder = tracer.buildSpan(getOperationName(channel, isConsumer))
      .withTag(Tags.SPAN_KIND.getKey(), isConsumer ? Tags.SPAN_KIND_CONSUMER : Tags.SPAN_KIND_PRODUCER)
      .withTag(Tags.COMPONENT.getKey(), COMPONENT_NAME)
      .withTag(Tags.MESSAGE_BUS_DESTINATION.getKey(), getChannelName(channel));

  MessageTextMap<?> carrier = new MessageTextMap<>(message, isKafkaBinder);
  SpanContext extractedContext = tracer.extract(Format.Builtin.TEXT_MAP, carrier);
  if (isConsumer) {
    spanBuilder.addReference(References.FOLLOWS_FROM, extractedContext);
  } else if (tracer.activeSpan() == null) {
    // it's a client but active span is null
    // This is a fallback we try to add extractedContext in case there is something
    spanBuilder.asChildOf(extractedContext);
  }

  Span span = spanBuilder.startActive(true).span();

  if (isConsumer) {
    log.trace("Adding 'messageConsumed' header");
    carrier.put(Headers.MESSAGE_CONSUMED, "true");
    // TODO maybe we should remove Headers.MESSAGE_SENT_FROM_CLIENT header here?
  } else {
    log.trace("Adding 'messageSent' header");
    carrier.put(Headers.MESSAGE_SENT_FROM_CLIENT, "true");
  }

  tracer.inject(span.context(), Format.Builtin.TEXT_MAP, carrier);
  return carrier.getMessage();
}
 
Example 10
Source File: AkkaAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object aroundReceiveStart(final Object thiz, final Object message) {
  if (!(message instanceof TracedMessage) && LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return message;
  }

  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer
    .buildSpan("receive")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER);

  final TracedMessage<?> tracedMessage;
  if (message instanceof TracedMessage) {
    tracedMessage = (TracedMessage<?>)message;
    spanBuilder.addReference(References.FOLLOWS_FROM, tracedMessage.spanContext(tracer));
  }
  else {
    tracedMessage = null;
    spanBuilder.withTag(Tags.MESSAGE_BUS_DESTINATION, ((AbstractActor)thiz).getSelf().path().toString());
  }

  final Span span = spanBuilder.start();
  final Scope scope = tracer.activateSpan(span);

  LocalSpanContext.set(COMPONENT_NAME, span, scope);

  return tracedMessage != null ? tracedMessage.getMessage() : message;
}
 
Example 11
Source File: AkkaHttpSyncHandler.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
static Span buildSpan(final HttpRequest request) {
  final SpanBuilder spanBuilder = GlobalTracer.get().buildSpan(request.method().value())
    .withTag(Tags.COMPONENT, COMPONENT_NAME_SERVER)
    .withTag(Tags.HTTP_URL, request.getUri().toString())
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER);

  final SpanContext context = GlobalTracer.get().extract(Builtin.HTTP_HEADERS, new HttpHeadersExtractAdapter(request));
  if (context != null)
    spanBuilder.addReference(References.FOLLOWS_FROM, context);

  return spanBuilder.start();
}
 
Example 12
Source File: OrderCompletionMonitor.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void run() {
	if (isDone) {
		scheduledFuture.cancel(false);
		return;
	}

	SpanBuilder buildSpan = GlobalTracer.get().buildSpan("pickupOrderAttempt");
	buildSpan.withTag(RobotOrder.KEY_ORDER_ID, String.valueOf(order.getOrderId()));
	buildSpan.addReference(References.FOLLOWS_FROM, parent);

	try (Scope scope = buildSpan.startActive(true)) {
		okhttp3.HttpUrl.Builder httpBuilder = HttpUrl.parse(pickupLocation).newBuilder();
		httpBuilder.addQueryParameter(RobotOrder.KEY_ORDER_ID, String.valueOf(order.getOrderId()));
		Request request = new Request.Builder().url(httpBuilder.build()).build();
		try {
			Response response = httpClient.newCall(request).execute();
			String body = response.body().string();
			if (response.isSuccessful() && !body.isEmpty()) {
				isDone = true;
				RealizedOrder realizedOrder = RealizedOrder.fromJSon(body);
				future.complete(realizedOrder);
				scheduledFuture.cancel(false);
			}
		} catch (IOException e) {
			e.printStackTrace();
			scheduledFuture.cancel(false);
		}
	}
}
 
Example 13
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String removeOwner(RealizedOrder realizedOrder, SpanContext ctx) {
	System.out.println("User " + realizedOrder.getCustomer() + " picked up order #"
			+ realizedOrder.getOrder().getOrderId() + ". Now removing customer.");

	Customer customer = realizedOrder.getCustomer();
	String url = urlCustomer + "/customers/" + customer.getId();
	Request request = new Request.Builder().url(url).delete().build();

	SpanBuilder spanBuilder = getTracer().buildSpan("DELETE: " + url);
	spanBuilder.addReference(References.FOLLOWS_FROM, ctx);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Response response = httpClient.newCall(request).execute();
		if (!response.isSuccessful()) {
			Logger.log("Failed to call DELETE:" + url);
			return null;
		}
		System.out.println("User " + realizedOrder.getCustomer() + " removed.");
		// FIXME: Get from return value
		return String.valueOf(customer.getId());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}