Search in sources :

Example 56 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class ProtonBasedCommandRouterClient method enableCommandRouting.

@Override
public Future<Void> enableCommandRouting(final List<String> tenantIds, final SpanContext context) {
    Objects.requireNonNull(tenantIds);
    if (tenantIds.isEmpty()) {
        return Future.succeededFuture();
    }
    final Span currentSpan = newChildSpan(context, "enable command routing");
    currentSpan.log(Map.of("no_of_tenants", tenantIds.size()));
    final JsonArray payload = new JsonArray(tenantIds);
    final Future<RequestResponseResult<JsonObject>> resultTracker = getOrCreateClient(tenantIds.get(0)).compose(client -> client.createAndSendRequest(CommandRouterConstants.CommandRouterAction.ENABLE_COMMAND_ROUTING.getSubject(), null, payload.toBuffer(), MessageHelper.CONTENT_TYPE_APPLICATION_JSON, this::getRequestResponseResult, currentSpan));
    return mapResultAndFinishSpan(resultTracker, result -> {
        switch(result.getStatus()) {
            case HttpURLConnection.HTTP_NO_CONTENT:
                log.info("successfully enabled routing of commands for {} tenants in Command Router", tenantIds.size());
                return null;
            default:
                final ServiceInvocationException e = StatusCodeMapper.from(result);
                log.info("failed to enable routing of commands in Command Router", e);
                throw e;
        }
    }, currentSpan).mapEmpty();
}
Also used : JsonArray(io.vertx.core.json.JsonArray) HttpURLConnection(java.net.HttpURLConnection) CacheDirective(org.eclipse.hono.util.CacheDirective) DecodeException(io.vertx.core.json.DecodeException) LoggerFactory(org.slf4j.LoggerFactory) CommandRouterConstants(org.eclipse.hono.util.CommandRouterConstants) HashMap(java.util.HashMap) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Constants(org.eclipse.hono.util.Constants) Tags(io.opentracing.tag.Tags) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) CompositeFuture(io.vertx.core.CompositeFuture) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) Duration(java.time.Duration) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) HonoConnection(org.eclipse.hono.client.HonoConnection) AbstractRequestResponseServiceClient(org.eclipse.hono.client.amqp.AbstractRequestResponseServiceClient) Logger(org.slf4j.Logger) RequestResponseResult(org.eclipse.hono.util.RequestResponseResult) RequestResponseClient(org.eclipse.hono.client.amqp.RequestResponseClient) CachingClientFactory(org.eclipse.hono.client.impl.CachingClientFactory) Set(java.util.Set) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) ApplicationProperties(org.apache.qpid.proton.amqp.messaging.ApplicationProperties) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CommandRouterClient(org.eclipse.hono.client.command.CommandRouterClient) Clock(java.time.Clock) Optional(java.util.Optional) Span(io.opentracing.Span) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) RequestResponseResult(org.eclipse.hono.util.RequestResponseResult) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Span(io.opentracing.Span)

Example 57 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class TelemetrySenderTest method testSendAndWaitForOutcomeWithTracing.

/**
 * Verifies that {@link TraceableTelemetrySender#sendAndWaitForOutcome(String, byte[], String, java.util.Map, SpanContext)}
 * uses the given SpanContext.
 *
 * @param ctx The test context to use for running asynchronous tests.
 */
@Test
public void testSendAndWaitForOutcomeWithTracing(final VertxTestContext ctx) {
    // GIVEN a TraceableTelemetrySender instance
    final TraceableTelemetrySender telemetrySender = ((TraceableTelemetrySender) createTelemetrySender());
    // WHEN sending a message using the API...
    final SpanContext spanContext = mock(SpanContext.class);
    final Future<ProtonDelivery> deliveryFuture = telemetrySender.sendAndWaitForOutcome(DEVICE_ID, PAYLOAD, CONTENT_TYPE, APPLICATION_PROPERTIES, spanContext);
    // ...AND WHEN the disposition is updated by the peer
    updateDisposition();
    deliveryFuture.onComplete(ctx.succeeding(delivery -> {
        // THEN the given SpanContext is used
        ctx.verify(() -> {
            verify(spanBuilder).addReference(any(), eq(spanContext));
            assertMessageConformsAmqpAdapterSpec(ADDRESS);
        });
        ctx.completeNow();
    }));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) AmqpAdapterClientTelemetrySenderImpl(org.eclipse.hono.client.device.amqp.impl.AmqpAdapterClientTelemetrySenderImpl) ProtonDelivery(io.vertx.proton.ProtonDelivery) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) Mockito.verify(org.mockito.Mockito.verify) SpanContext(io.opentracing.SpanContext) Test(org.junit.jupiter.api.Test) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.mock(org.mockito.Mockito.mock) SpanContext(io.opentracing.SpanContext) ProtonDelivery(io.vertx.proton.ProtonDelivery) Test(org.junit.jupiter.api.Test)

Example 58 with SpanContext

use of io.opentracing.SpanContext in project hono by eclipse.

the class CommandRouterCommandConsumerFactory method doCreateCommandConsumer.

private Future<CommandConsumer> doCreateCommandConsumer(final String tenantId, final String deviceId, final String gatewayId, final Handler<CommandContext> commandHandler, final Duration lifespan, final SpanContext context) {
    // lifespan greater than what can be expressed in nanoseconds (i.e. 292 years) is considered unlimited, preventing ArithmeticExceptions down the road
    final Duration sanitizedLifespan = lifespan == null || lifespan.isNegative() || lifespan.getSeconds() > (Long.MAX_VALUE / 1000_000_000L) ? Duration.ofSeconds(-1) : lifespan;
    LOG.trace("create command consumer [tenant-id: {}, device-id: {}, gateway-id: {}]", tenantId, deviceId, gatewayId);
    // register the command handler
    // for short-lived command consumers, let the consumer creation span context be used as reference in the command span
    final SpanContext consumerCreationContextToUse = !sanitizedLifespan.isNegative() && sanitizedLifespan.toSeconds() <= TenantConstants.DEFAULT_MAX_TTD ? context : null;
    final CommandHandlerWrapper commandHandlerWrapper = new CommandHandlerWrapper(tenantId, deviceId, gatewayId, commandHandler, Vertx.currentContext(), consumerCreationContextToUse);
    commandHandlers.putCommandHandler(commandHandlerWrapper);
    final Instant lifespanStart = Instant.now();
    return commandRouterClient.registerCommandConsumer(tenantId, deviceId, adapterInstanceId, sanitizedLifespan, context).onFailure(thr -> {
        LOG.info("error registering consumer with the command router service [tenant: {}, device: {}]", tenantId, deviceId, thr);
        // handler association failed - unregister the handler
        commandHandlers.removeCommandHandler(tenantId, deviceId);
    }).map(v -> {
        return new CommandConsumer() {

            @Override
            public Future<Void> close(final SpanContext spanContext) {
                return removeCommandConsumer(commandHandlerWrapper, sanitizedLifespan, lifespanStart, spanContext);
            }
        };
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) BiFunction(java.util.function.BiFunction) TenantConstants(org.eclipse.hono.util.TenantConstants) Lifecycle(org.eclipse.hono.util.Lifecycle) LoggerFactory(org.slf4j.LoggerFactory) Vertx(io.vertx.core.Vertx) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Instant(java.time.Instant) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) ArrayList(java.util.ArrayList) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CompositeFuture(io.vertx.core.CompositeFuture) List(java.util.List) ServiceClient(org.eclipse.hono.client.util.ServiceClient) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) CommandConstants(org.eclipse.hono.util.CommandConstants) Handler(io.vertx.core.Handler) ConnectionLifecycle(org.eclipse.hono.client.ConnectionLifecycle) SpanContext(io.opentracing.SpanContext) Instant(java.time.Instant) Duration(java.time.Duration)

Example 59 with SpanContext

use of io.opentracing.SpanContext in project cxf by apache.

the class AbstractOpenTracingProvider method startTraceSpan.

protected TraceScopeHolder<TraceScope> startTraceSpan(final Map<String, List<String>> requestHeaders, URI uri, String method) {
    SpanContext parent = tracer.extract(Builtin.HTTP_HEADERS, new TextMapAdapter(requestHeaders.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, this::getFirstValueOrEmpty))));
    final Span activeSpan;
    final Scope scope;
    if (parent == null) {
        activeSpan = tracer.buildSpan(buildSpanDescription(uri.getPath(), method)).start();
        scope = tracer.scopeManager().activate(activeSpan);
    } else {
        activeSpan = tracer.buildSpan(buildSpanDescription(uri.getPath(), method)).asChildOf(parent).start();
        scope = tracer.scopeManager().activate(activeSpan);
    }
    // Set additional tags
    activeSpan.setTag(Tags.HTTP_METHOD.getKey(), method);
    activeSpan.setTag(Tags.HTTP_URL.getKey(), uri.toString());
    // If the service resource is using asynchronous processing mode, the trace
    // scope will be closed in another thread and as such should be detached.
    Span span = null;
    if (isAsyncResponse()) {
        // Do not modify the current context span
        span = activeSpan;
        propagateContinuationSpan(span);
        scope.close();
    }
    return new TraceScopeHolder<TraceScope>(new TraceScope(activeSpan, scope), span != null);
}
Also used : SpanContext(io.opentracing.SpanContext) Scope(io.opentracing.Scope) TextMapAdapter(io.opentracing.propagation.TextMapAdapter) Map(java.util.Map) Span(io.opentracing.Span)

Example 60 with SpanContext

use of io.opentracing.SpanContext in project jaeger-client-java by jaegertracing.

the class FilterIntegrationTest method testExtractorReturnsNullWhenTracerStateHeaderIsMissing.

/*
   * This test exists because opentracing's convention around missing tracer
   * state headers may change to stop supporting the automatic creation of
   * building a span.
   */
@Test
public void testExtractorReturnsNullWhenTracerStateHeaderIsMissing() {
    ContainerRequestContext reqContext = mock(ContainerRequestContext.class);
    given(reqContext.getHeaders()).willReturn(new MultivaluedHashMap<String, String>());
    ServerRequestCarrier carrier = new ServerRequestCarrier(reqContext);
    SpanContext spanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
    assertNull(spanCtx);
}
Also used : SpanContext(io.opentracing.SpanContext) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) ServerRequestCarrier(com.uber.jaeger.filters.jaxrs2.ServerRequestCarrier) Test(org.junit.Test)

Aggregations

SpanContext (io.opentracing.SpanContext)118 Span (io.opentracing.Span)81 Future (io.vertx.core.Future)70 Tracer (io.opentracing.Tracer)60 Objects (java.util.Objects)57 HttpURLConnection (java.net.HttpURLConnection)56 JsonObject (io.vertx.core.json.JsonObject)55 TracingHelper (org.eclipse.hono.tracing.TracingHelper)55 Logger (org.slf4j.Logger)54 LoggerFactory (org.slf4j.LoggerFactory)54 List (java.util.List)51 Promise (io.vertx.core.Promise)45 Optional (java.util.Optional)45 Map (java.util.Map)40 ClientErrorException (org.eclipse.hono.client.ClientErrorException)39 MessageHelper (org.eclipse.hono.util.MessageHelper)33 UUID (java.util.UUID)31 Collectors (java.util.stream.Collectors)31 HashMap (java.util.HashMap)25 Vertx (io.vertx.core.Vertx)24