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

The following examples show how to use io.opentracing.Tracer.SpanBuilder#asChildOf() . 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: TracingChannelInterceptor.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Message<?> preSendServerSpan(final Message<?> message) {
  final String destination = (String)message.getHeaders().get(SIMP_DESTINATION);
  final SpanBuilder spanBuilder = tracer
    .buildSpan(destination != null ? destination : UNKNOWN_DESTINATION)
    .withTag(Tags.SPAN_KIND.getKey(), spanKind)
    .withTag(Tags.COMPONENT.getKey(), WEBSOCKET);

  final Map<String,List<String>> nativeHeaders = (Map<String,List<String>>)message.getHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
  SpanContext spanContext = null;
  if (nativeHeaders != null)
    spanContext = tracer.extract(Builtin.TEXT_MAP, new NativeHeadersExtractAdapter(nativeHeaders));

  if (spanContext == null)
    spanContext = tracer.extract(Format.Builtin.TEXT_MAP, new TextMapExtractAdapter(message.getHeaders()));

  if (spanContext != null)
    spanBuilder.asChildOf(spanContext);

  final Span span = spanBuilder.start();
  return MessageBuilder.fromMessage(message).setHeader(OPENTRACING_SPAN, span).build();
}
 
Example 2
Source File: PlayAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void applyStart(final Object arg0) {
  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Request<?> request = (Request<?>)arg0;
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder spanBuilder = tracer.buildSpan(request.method())
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER)
    .withTag(Tags.HTTP_METHOD, request.method())
    .withTag(Tags.HTTP_URL, (request.secure() ? "https://" : "http://") + request.host() + request.uri());

  final SpanContext parent = tracer.extract(Builtin.HTTP_HEADERS, new HttpHeadersExtractAdapter(request.headers()));
  if (parent != null)
    spanBuilder.asChildOf(parent);

  final Span span = spanBuilder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 3
Source File: RequestHandler.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
public void beforeRequest(Object request, Context context) {
  logger.info("before send {}", request);

  // we cannot use active span because we don't know in which thread it is executed
  // and we cannot therefore activate span. thread can come from common thread pool.
  SpanBuilder spanBuilder =
      tracer
          .buildSpan(OPERATION_NAME)
          .ignoreActiveSpan()
          .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);

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

  context.put("span", spanBuilder.start());
}
 
Example 4
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Customer registerRandomCustomer(SpanContext parent) {
	String newCustomerJSon = getNewCustomerJSonString();
	RequestBody body = RequestBody.create(JSON, newCustomerJSon);
	Request request = new Request.Builder().url(urlCustomer + "/customers").put(body).build();

	SpanBuilder spanBuilder = getTracer().buildSpan("Create random user");
	spanBuilder.asChildOf(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 create customer " + newCustomerJSon);
			return null;
		}
		return Customer.fromJSon(response.body().string());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example 5
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RobotOrder postOrder(Customer c, List<RobotOrderLineItem> lineItems, SpanContext parent) {
	String url = urlOrder + "/orders/new";
	JsonObjectBuilder jsonBodyBuilder = Json.createObjectBuilder();
	jsonBodyBuilder.add(Customer.KEY_CUSTOMER_ID, String.valueOf(c.getId()));

	JsonArrayBuilder lineItemBuilder = Json.createArrayBuilder();
	for (RobotOrderLineItem lineItem : lineItems) {
		lineItemBuilder.add(lineItem.toJSon());
	}

	jsonBodyBuilder.add(RobotOrder.KEY_LINE_ITEMS, lineItemBuilder);
	String bodyStr = jsonBodyBuilder.build().toString();
	RequestBody body = RequestBody.create(JSON, bodyStr);

	Request request = new Request.Builder().url(url).post(body).build();

	SpanBuilder spanBuilder = getTracer().buildSpan("POST: " + url);
	spanBuilder.asChildOf(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 POST:" + url);
			Logger.log("Response: " + response.body().string());
			return null;
		}
		return RobotOrder.fromJSon(response.body().string());
	} catch (IOException e) {
		span.log(OpenTracingUtil.getSpanLogMap(e));
	} finally {
		span.finish();
	}
	return null;
}
 
Example 6
Source File: RequestHandler.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
public void beforeRequest(Object request, Context context) {
    logger.info("before send {}", request);

    // we cannot use active span because we don't know in which thread it is executed
    // and we cannot therefore activate span. thread can come from common thread pool.
    SpanBuilder spanBuilder = tracer.buildSpan(OPERATION_NAME)
            .ignoreActiveSpan()
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT);

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

    context.put("span", spanBuilder.start());
}
 
Example 7
Source File: OpenTracingManager.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
protected void doStartSpanWithParent(SpanBuilder spanBuilder, String id) {
    Span parentSpan = getSpan();

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

    doStartSpan(spanBuilder, id);
}
 
Example 8
Source File: OrderManager.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Long get() {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("buildRobotRequest");
	spanBuilder.withTag(RobotType.KEY_ROBOT_TYPE, lineItem.getRobotTypeId());
	spanBuilder.withTag(Robot.KEY_COLOR, lineItem.getColor().toString());
	spanBuilder.asChildOf(parent);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		FormBody.Builder formBuilder = new FormBody.Builder();
		formBuilder.add(RobotType.KEY_ROBOT_TYPE, lineItem.getRobotTypeId());
		formBuilder.add(Robot.KEY_COLOR, lineItem.getColor().toString());

		Request req = new Request.Builder().url(FACTORY_SERVICE_LOCATION + "/factory/buildrobot")
				.post(formBuilder.build()).build();

		try {
			Response response = httpClient.newCall(req).execute();
			return parseSerial(response.body().string());
		} catch (Throwable e) {
			span.log(OpenTracingUtil.getSpanLogMap(e));
		}
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return -1L;
}
 
Example 9
Source File: OrderManager.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 spanBuilder = GlobalTracer.get().buildSpan("pickupFromFactoryAttempt");
	spanBuilder.withTag(Robot.KEY_SERIAL_NUMBER, String.valueOf(serial));
	spanBuilder.asChildOf(parent);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		okhttp3.HttpUrl.Builder httpBuilder = HttpUrl.parse(FACTORY_SERVICE_LOCATION + "/factory/pickup")
				.newBuilder();
		httpBuilder.addQueryParameter(Robot.KEY_SERIAL_NUMBER, String.valueOf(serial));
		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;
				Robot robot = Robot.fromJSon(body);
				future.complete(robot);
				scheduledFuture.cancel(false);
			}
		} catch (IOException e) {
			span.log(OpenTracingUtil.getSpanLogMap(e));
			scheduledFuture.cancel(false);
		}
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		throw t;
	} finally {
		span.finish();
	}
}
 
Example 10
Source File: Factory.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Robot createChassis(long serialNumber, String robotTypeId, SpanContext spanContext) {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("creatingChassis");
	spanBuilder.asChildOf(spanContext);
	spanBuilder.withTag(RobotType.KEY_ROBOT_TYPE, robotTypeId);
	try (Scope scope = spanBuilder.startActive(true)) {
		Logger.log("Creating robot chassis!");
		// Takes 70 ms to create a robot chassis. Yep, it's a kick ass robot factory.
		Utils.sleep(70);
		return new Robot(serialNumber, robotTypeId, null);
	}
}
 
Example 11
Source File: Factory.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static Robot paintRobot(Robot robotToPaint, Color paint, SpanContext spanContext) {
	SpanBuilder spanBuilder = GlobalTracer.get().buildSpan("paintingRobot");
	spanBuilder.asChildOf(spanContext);
	spanBuilder.withTag(Robot.KEY_COLOR, paint.toString());
	try (Scope scope = spanBuilder.startActive(true)) {
		Logger.log("Painting robot!");
		// Takes 50 ms to paint a robot. Yep, it's a kick ass robot factory.
		Utils.sleep(50);
		return new Robot(robotToPaint.getSerialNumber(), robotToPaint.getRobotType(), paint);
	}
}
 
Example 12
Source File: KafkaStreamsAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void onNextRecordExit(final Object record) {
  if (record == null)
    return;

  if (LocalSpanContext.get(COMPONENT_NAME) != null) {
    LocalSpanContext.get(COMPONENT_NAME).increment();
    return;
  }

  final Tracer tracer = GlobalTracer.get();
  final StampedRecord stampedRecord = (StampedRecord)record;
  final SpanBuilder spanBuilder = tracer.buildSpan("consume")
    .withTag(Tags.COMPONENT, COMPONENT_NAME)
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CONSUMER)
    .withTag(Tags.PEER_SERVICE, "kafka")
    .withTag("partition", stampedRecord.partition())
    .withTag("offset", stampedRecord.offset());

  if (stampedRecord.topic() != null)
    spanBuilder.withTag(Tags.MESSAGE_BUS_DESTINATION, stampedRecord.topic());

  final SpanContext parentContext = TracingKafkaUtils.extractSpanContext(stampedRecord.value.headers(), tracer);
  if (parentContext != null)
    spanBuilder.asChildOf(parentContext);

  final Span span = spanBuilder.start();
  LocalSpanContext.set(COMPONENT_NAME, span, tracer.activateSpan(span));
}
 
Example 13
Source File: TracingServerChannelInboundHandlerAdapter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(final ChannelHandlerContext handlerContext, final Object message) {
  if (!(message instanceof HttpRequest)) {
    handlerContext.fireChannelRead(message);
    return;
  }

  final HttpRequest request = (HttpRequest)message;
  final Tracer tracer = GlobalTracer.get();

  final SpanBuilder spanBuilder = tracer.buildSpan(request.method().name())
    .withTag(Tags.COMPONENT, "netty")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_SERVER)
    .withTag(Tags.HTTP_METHOD, request.method().name())
    .withTag(Tags.HTTP_URL, request.uri());

  final SpanContext spanContext = tracer.extract(Builtin.HTTP_HEADERS, new NettyExtractAdapter(request.headers()));
  if (spanContext != null)
    spanBuilder.asChildOf(spanContext);

  final Span span = spanBuilder.start();
  try (final Scope scope = tracer.activateSpan(span)) {
    handlerContext.channel().attr(SERVER_ATTRIBUTE_KEY).set(span);

    try {
      handlerContext.fireChannelRead(message);
    }
    catch (final Throwable t) {
      OpenTracingApiUtil.setErrorTag(span, t);
      span.finish();
      throw t;
    }
  }
}
 
Example 14
Source File: TracingClientChannelOutboundHandlerAdapter.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise promise) {
  if (!(message instanceof HttpRequest)) {
    context.write(message, promise);
    return;
  }

  final HttpRequest request = (HttpRequest)message;
  final Tracer tracer = GlobalTracer.get();
  final SpanBuilder builder = tracer
    .buildSpan(request.method().name())
    .withTag(Tags.COMPONENT, "netty")
    .withTag(Tags.SPAN_KIND, Tags.SPAN_KIND_CLIENT)
    .withTag(Tags.HTTP_METHOD, request.method().name())
    .withTag(Tags.HTTP_URL, request.uri());

  final SpanContext parentContext = tracer.extract(Builtin.HTTP_HEADERS, new NettyExtractAdapter(request.headers()));

  if (parentContext != null)
    builder.asChildOf(parentContext);

  final Span span = builder.start();
  try (final Scope scope = tracer.activateSpan(span)) {
    // AWS calls are often signed, so we can't add headers without breaking
    // the signature.
    if (!request.headers().contains("amz-sdk-invocation-id")) {
      tracer.inject(span.context(), Builtin.HTTP_HEADERS, new NettyInjectAdapter(request.headers()));
    }

    context.channel().attr(TracingClientChannelInboundHandlerAdapter.CLIENT_ATTRIBUTE_KEY).set(span);
    try {
      context.write(message, promise);
    }
    catch (final Throwable t) {
      OpenTracingApiUtil.setErrorTag(span, t);
      span.finish();
      throw t;
    }
  }
}
 
Example 15
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 16
Source File: TracingHttpRequesterFilter.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private ScopeTracker newTracker(final HttpRequestMetaData request) {
    SpanBuilder spanBuilder = tracer.buildSpan(componentName)
            .withTag(SPAN_KIND.getKey(), SPAN_KIND_CLIENT)
            .withTag(HTTP_METHOD.getKey(), request.method().name())
            .withTag(HTTP_URL.getKey(), request.path());
    final Span activeSpan = tracer.activeSpan();
    if (activeSpan != null) {
        spanBuilder = spanBuilder.asChildOf(activeSpan);
    }
    Scope scope = spanBuilder.startActive(true);
    tracer.inject(scope.span().context(), formatter, request.headers());
    return new ScopeTracker(scope);
}
 
Example 17
Source File: OpenTracingFilter.java    From flower with Apache License 2.0 4 votes vote down vote up
@Override
public Object doFilter(Object message, ServiceContext context, FilterChain chain) {
  String spanName = context.getFlowName() + "." + context.getCurrentServiceName();
  SpanBuilder spanBuilder = getTracer().buildSpan(spanName);
  SpanContext spanContext = null;
  Map<String, String> headerMap = getMap(context);
  if (headerMap != null) {
    spanContext = getTracer().extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(headerMap));
    if (spanContext != null) {
      spanBuilder.asChildOf(spanContext);
    }
  }


  Span span = spanBuilder.start();
  span.log("Flower Trace start.");

  span.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
  Scope scope = tracer.scopeManager().activate(span);
  addAttachements(context, span);

  span.setTag("id", context.getId());
  span.setTag("sync", context.isSync());
  span.setTag("codec", context.getCodec());
  span.setTag("flowName", context.getFlowName());
  span.setTag("serviceName", context.getCurrentServiceName());
  span.setTag("flowMessage.transactionId", context.getFlowMessage().getTransactionId());
  span.setTag("flowMessage.messageType", context.getFlowMessage().getMessageType());

  try {
    return chain.doFilter(message, context);
  } catch (Exception ex) {
    Tags.ERROR.set(span, true);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(Fields.EVENT, "error");
    map.put(Fields.ERROR_OBJECT, ex);
    map.put(Fields.MESSAGE, ex.getMessage());
    span.log(map);
    throw new FlowException(ex);
  } finally {
    span.log("Flower Trace end.");
    scope.close();
    span.finish();
  }

}
 
Example 18
Source File: OpenTracingManager.java    From hawkular-apm with Apache License 2.0 3 votes vote down vote up
/**
 * This is a convenience method for situations where we don't know
 * if a parent span is available. If we try to add a childOf relationship
 * to a null parent, it would cause a null pointer exception.
 *
 * The optional id is associated with the started span.
 *
 * @param spanBuilder The span builder
 * @param parent The parent span
 * @param id The optional id to associate with the span
 */
public void startSpanWithParent(SpanBuilder spanBuilder, Span parent, String id) {
    if (parent != null) {
        spanBuilder.asChildOf(parent.context());
    }

    doStartSpan(spanBuilder, id);
}
 
Example 19
Source File: OpenTracingManager.java    From hawkular-apm with Apache License 2.0 3 votes vote down vote up
/**
 * This is a convenience method for situations where we don't know
 * if a parent span is available. If we try to add a childOf relationship
 * to a null context, it would cause a null pointer exception.
 *
 * The optional id is associated with the started span.
 *
 * @param spanBuilder The span builder
 * @param context The span context
 * @param id The optional id to associate with the span
 */
public void startSpanWithContext(SpanBuilder spanBuilder, SpanContext context, String id) {
    if (context != null) {
        spanBuilder.asChildOf(context);
    }

    doStartSpan(spanBuilder, id);
}