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

The following examples show how to use io.opentracing.Tracer.SpanBuilder#start() . 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: SQL.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Start a new span for an SQL operation.
 *
 * @param tracer The tracer to use.
 * @param context The current span context.
 * @param operationName The name of the operation.
 * @param customizer An optional customizer.
 * @return The newly created span. The caller is required to finish the span.
 */
public static Span startSqlSpan(final Tracer tracer, final SpanContext context, final String operationName, final Consumer<Tracer.SpanBuilder> customizer) {

    if (tracer == null || context == null) {
        return null;
    }

    final SpanBuilder builder = TracingHelper
            .buildChildSpan(tracer, context, operationName, SQL.class.getSimpleName())
            .withTag(Tags.DB_TYPE.getKey(), "sql");

    if (customizer != null) {
        customizer.accept(builder);
    }

    return builder.start();

}
 
Example 2
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 3
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 4
Source File: SQL.java    From enmasse with Apache License 2.0 6 votes vote down vote up
public static Span startSqlSpan(final Tracer tracer, final SpanContext context, final String operationName, final Consumer<Tracer.SpanBuilder> customizer) {

        if (tracer == null || context == null) {
            return null;
        }

        final SpanBuilder builder = TracingHelper
                .buildChildSpan(tracer, context, operationName, SQL.class.getSimpleName())
                .withTag(Tags.DB_TYPE.getKey(), "sql");

        if (customizer != null) {
            customizer.accept(builder);
        }

        return builder.start();

    }
 
Example 5
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 6
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 7
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 8
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 9
Source File: SpymemcachedAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Object get(final Object key, final Object callback) {
  final SpanBuilder spanBuilder = spanBuilder("get");
  if (key instanceof Collection) {
    final Iterator<? extends CharSequence> iterator = ((Collection<? extends CharSequence>)key).iterator();
    final StringBuilder builder = new StringBuilder();
    for (int i = 0; iterator.hasNext(); ++i) {
      if (i > 0)
        builder.append(',');

      builder.append(iterator.next());
    }

    spanBuilder.withTag("keys", builder.toString());
  }
  else {
    spanBuilder.withTag("key", key.toString()).start();
  }

  final Span span = spanBuilder.start();
  return WrapperProxy.wrap(callback, new TracingGetOperationCallback((GetOperation.Callback)callback, span));
}
 
Example 10
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 11
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 12
Source File: SpymemcachedAgentIntercept.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static Object tracingCallback(final String operation, final Object key, final Object callback) {
  final SpanBuilder spanBuilder = spanBuilder(operation);
  if (key != null)
    spanBuilder.withTag("key", key.toString());

  final Span span = spanBuilder.start();
  return WrapperProxy.wrap(callback, new TracingOperationCallback((OperationCallback)callback, span));
}
 
Example 13
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 14
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 15
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 16
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void doFullRegisterOrderAndRemove() throws InterruptedException, ExecutionException {
	SpanBuilder spanBuilder = getTracer().buildSpan("fullSystemTest");
	final Span span = spanBuilder.start();
	try {
		SpanContext parentContext = span.context();

		// Register 
		CompletableFuture<Customer> newCustomer = CompletableFuture
				.supplyAsync(() -> registerRandomCustomer(parentContext));
		// Maybe not get the types and colors over and over. Looks pretty in the traces though...
		CompletableFuture<RobotType[]> availableTypes = CompletableFuture
				.supplyAsync(() -> getAllTypes(parentContext));
		CompletableFuture<Color[]> availableColors = CompletableFuture
				.supplyAsync(() -> getAllColors(parentContext));
		CompletableFuture.allOf(newCustomer, availableTypes, availableColors);

		Customer customer = newCustomer.get();

		// First completion stage done. Now we can create the order
		List<RobotOrderLineItem> lineItems = createRandomOrder(availableTypes.get(), availableColors.get());
		CompletableFuture<RobotOrder> robotOrderCompletable = CompletableFuture
				.supplyAsync(() -> postOrder(customer, lineItems, parentContext));

		// Rest will happen asynchrously when data is available...
		CompletableFuture<RealizedOrder> realizedOrderFuture = new CompletableFuture<RealizedOrder>();
		// When we have the order, we schedule the polling for an available order...
		robotOrderCompletable
				.thenAccept((order) -> awaitOrderCompletion(order, realizedOrderFuture, parentContext));
		// Once the order is realized, we will remove the customer.
		realizedOrderFuture.thenApply((realizedOrder) -> removeOwner(realizedOrder, parentContext))
				.thenAccept((customerId) -> span.finish());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
		throw t;
	}
}
 
Example 17
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;
}
 
Example 18
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 19
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 20
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;
}