Search in sources :

Example 91 with Tracer

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

the class ProtonBasedDeviceRegistrationClientTest method setUp.

/**
 * Sets up the fixture.
 */
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
    span = TracingMockSupport.mockSpan();
    final Tracer tracer = TracingMockSupport.mockTracer(span);
    eventBus = mock(EventBus.class);
    vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    VertxMockSupport.executeBlockingCodeImmediately(vertx);
    receiver = AmqpClientUnitTestHelper.mockProtonReceiver();
    sender = AmqpClientUnitTestHelper.mockProtonSender();
    final RequestResponseClientConfigProperties config = new RequestResponseClientConfigProperties();
    connection = AmqpClientUnitTestHelper.mockHonoConnection(vertx, config, tracer);
    when(connection.connect()).thenReturn(Future.succeededFuture());
    when(connection.isConnected(anyLong())).thenReturn(Future.succeededFuture());
    when(connection.createReceiver(anyString(), any(ProtonQoS.class), any(ProtonMessageHandler.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(receiver));
    when(connection.createSender(anyString(), any(ProtonQoS.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(sender));
    cache = mock(Cache.class);
    when(cache.asMap()).thenReturn(cacheBackingMap);
}
Also used : ProtonQoS(io.vertx.proton.ProtonQoS) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Tracer(io.opentracing.Tracer) EventBus(io.vertx.core.eventbus.EventBus) Vertx(io.vertx.core.Vertx) Cache(com.github.benmanes.caffeine.cache.Cache) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 92 with Tracer

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

the class ProtonBasedCredentialsClientTest method setUp.

/**
 * Sets up the fixture.
 */
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
    span = TracingMockSupport.mockSpan();
    final Tracer tracer = TracingMockSupport.mockTracer(span);
    eventBus = mock(EventBus.class);
    vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    VertxMockSupport.executeBlockingCodeImmediately(vertx);
    receiver = AmqpClientUnitTestHelper.mockProtonReceiver();
    sender = AmqpClientUnitTestHelper.mockProtonSender();
    final RequestResponseClientConfigProperties config = new RequestResponseClientConfigProperties();
    connection = AmqpClientUnitTestHelper.mockHonoConnection(vertx, config, tracer);
    when(connection.connect()).thenReturn(Future.succeededFuture());
    when(connection.isConnected(anyLong())).thenReturn(Future.succeededFuture());
    when(connection.createReceiver(anyString(), any(ProtonQoS.class), any(ProtonMessageHandler.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(receiver));
    when(connection.createSender(anyString(), any(ProtonQoS.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(sender));
    cache = mock(Cache.class);
    when(cache.asMap()).thenReturn(cacheBackingMap);
}
Also used : ProtonQoS(io.vertx.proton.ProtonQoS) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) Tracer(io.opentracing.Tracer) EventBus(io.vertx.core.eventbus.EventBus) Vertx(io.vertx.core.Vertx) Cache(com.github.benmanes.caffeine.cache.Cache) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 93 with Tracer

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

the class KafkaBasedMappingAndDelegatingCommandHandler method mapAndDelegateIncomingCommandMessage.

/**
 * Delegates an incoming command to the protocol adapter instance that the target
 * device is connected to.
 * <p>
 * Determines the target gateway (if applicable) and protocol adapter instance for an incoming command
 * and delegates the command to the resulting protocol adapter instance.
 *
 * @param consumerRecord The consumer record corresponding to the command.
 * @return A future indicating the outcome of the operation.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public Future<Void> mapAndDelegateIncomingCommandMessage(final KafkaConsumerRecord<String, Buffer> consumerRecord) {
    Objects.requireNonNull(consumerRecord);
    final Timer.Sample timer = getMetrics().startTimer();
    final KafkaBasedCommand command;
    try {
        command = KafkaBasedCommand.from(consumerRecord);
    } catch (final IllegalArgumentException exception) {
        log.debug("command record is invalid", exception);
        return Future.failedFuture("command record is invalid");
    }
    final SpanContext spanContext = KafkaTracingHelper.extractSpanContext(tracer, consumerRecord);
    final Span currentSpan = createSpan(command.getTenant(), command.getDeviceId(), spanContext);
    KafkaTracingHelper.setRecordTags(currentSpan, consumerRecord);
    final KafkaBasedCommandContext commandContext = new KafkaBasedCommandContext(command, kafkaBasedCommandResponseSender, currentSpan);
    command.logToSpan(currentSpan);
    if (!command.isValid()) {
        log.debug("received invalid command record [{}]", command);
        return tenantClient.get(command.getTenant(), currentSpan.context()).compose(tenantConfig -> {
            commandContext.put(CommandContext.KEY_TENANT_CONFIG, tenantConfig);
            return Future.failedFuture("command is invalid");
        }).onComplete(ar -> {
            commandContext.reject("malformed command message");
            reportInvalidCommand(commandContext, timer);
        }).mapEmpty();
    }
    log.trace("received valid command record [{}]", command);
    commandQueue.add(commandContext);
    final Promise<Void> resultPromise = Promise.promise();
    final long timerId = vertx.setTimer(PROCESSING_TIMEOUT.toMillis(), tid -> {
        if (commandQueue.remove(commandContext) || !commandContext.isCompleted()) {
            log.info("command processing timed out after {}s [{}]", PROCESSING_TIMEOUT.toSeconds(), commandContext.getCommand());
            TracingHelper.logError(commandContext.getTracingSpan(), String.format("command processing timed out after %ds", PROCESSING_TIMEOUT.toSeconds()));
            final ServerErrorException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "command processing timed out");
            commandContext.release(error);
            resultPromise.tryFail(error);
        }
    });
    mapAndDelegateIncomingCommand(commandContext, timer).onComplete(ar -> {
        vertx.cancelTimer(timerId);
        if (ar.failed()) {
            commandQueue.remove(commandContext);
        }
        Futures.tryHandleResult(resultPromise, ar);
    });
    return resultPromise.future();
}
Also used : HttpURLConnection(java.net.HttpURLConnection) KafkaBasedCommandResponseSender(org.eclipse.hono.client.command.kafka.KafkaBasedCommandResponseSender) AbstractMappingAndDelegatingCommandHandler(org.eclipse.hono.commandrouter.impl.AbstractMappingAndDelegatingCommandHandler) MessagingType(org.eclipse.hono.util.MessagingType) Timer(io.micrometer.core.instrument.Timer) KafkaBasedInternalCommandSender(org.eclipse.hono.client.command.kafka.KafkaBasedInternalCommandSender) Duration(java.time.Duration) TracingHelper(org.eclipse.hono.tracing.TracingHelper) KafkaTracingHelper(org.eclipse.hono.client.kafka.tracing.KafkaTracingHelper) Futures(org.eclipse.hono.util.Futures) Tracer(io.opentracing.Tracer) KafkaBasedCommand(org.eclipse.hono.client.command.kafka.KafkaBasedCommand) Promise(io.vertx.core.Promise) CommandContext(org.eclipse.hono.client.command.CommandContext) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) CommandTargetMapper(org.eclipse.hono.commandrouter.CommandTargetMapper) TenantClient(org.eclipse.hono.client.registry.TenantClient) Future(io.vertx.core.Future) KafkaBasedCommandContext(org.eclipse.hono.client.command.kafka.KafkaBasedCommandContext) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) CommandRouterMetrics(org.eclipse.hono.commandrouter.CommandRouterMetrics) Buffer(io.vertx.core.buffer.Buffer) KafkaConsumerRecord(io.vertx.kafka.client.consumer.KafkaConsumerRecord) Span(io.opentracing.Span) SpanContext(io.opentracing.SpanContext) Timer(io.micrometer.core.instrument.Timer) KafkaBasedCommand(org.eclipse.hono.client.command.kafka.KafkaBasedCommand) ServerErrorException(org.eclipse.hono.client.ServerErrorException) KafkaBasedCommandContext(org.eclipse.hono.client.command.kafka.KafkaBasedCommandContext) Span(io.opentracing.Span)

Example 94 with Tracer

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

the class OpenTracingTracingTest method testThatNewSpansAreCreatedWhenNotProvidedUsingMultipleClients.

@Test
public void testThatNewSpansAreCreatedWhenNotProvidedUsingMultipleClients() throws Exception {
    final WebClient client = createWebClient("/bookstore/books", new OpenTracingClientProvider(tracer));
    // The intention is to make a calls one after another, not in parallel, to ensure the
    // thread have trace contexts cleared out.
    IntStream.range(0, 4).mapToObj(index -> client.get()).forEach(r -> assertEquals(Status.OK.getStatusCode(), r.getStatus()));
    assertEquals(REPORTER.getSpans().toString(), 12, REPORTER.getSpans().size());
    IntStream.range(0, 4).map(index -> index * 3).forEach(index -> {
        assertThat(REPORTER.getSpans().get(index).getOperationName(), equalTo("Get Books"));
        assertThat(REPORTER.getSpans().get(index + 1).getOperationName(), equalTo("GET /bookstore/books"));
        assertThat(REPORTER.getSpans().get(index + 2).getOperationName(), equalTo("GET " + client.getCurrentURI()));
    });
}
Also used : Arrays(java.util.Arrays) IsLogContaining.hasItem(org.apache.cxf.systest.jaxrs.tracing.opentracing.IsLogContaining.hasItem) TimeoutException(java.util.concurrent.TimeoutException) Builtin(io.opentracing.propagation.Format.Builtin) AbstractClientServerTestBase(org.apache.cxf.testutil.common.AbstractClientServerTestBase) AbstractTestServerBase(org.apache.cxf.testutil.common.AbstractTestServerBase) Tags(io.opentracing.tag.Tags) Future(java.util.concurrent.Future) MediaType(javax.ws.rs.core.MediaType) Duration(java.time.Duration) NullPointerExceptionMapper(org.apache.cxf.systest.jaxrs.tracing.NullPointerExceptionMapper) After(org.junit.After) ConstSampler(io.jaegertracing.internal.samplers.ConstSampler) IsTagContaining.hasItem(org.apache.cxf.systest.jaxrs.tracing.opentracing.IsTagContaining.hasItem) OpenTracingFeature(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingFeature) JaegerSpanContext(io.jaegertracing.internal.JaegerSpanContext) Awaitility.await(org.awaitility.Awaitility.await) Response(javax.ws.rs.core.Response) TextMap(io.opentracing.propagation.TextMap) HasSpan.hasSpan(org.apache.cxf.systest.jaxrs.tracing.opentracing.HasSpan.hasSpan) Entry(java.util.Map.Entry) ProcessingException(javax.ws.rs.ProcessingException) Span(io.opentracing.Span) Scope(io.opentracing.Scope) JaegerTracer(io.jaegertracing.internal.JaegerTracer) IntStream(java.util.stream.IntStream) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) OpenTracingClientProvider(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingClientProvider) BeforeClass(org.junit.BeforeClass) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CoreMatchers.not(org.hamcrest.CoreMatchers.not) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) BookStore(org.apache.cxf.systest.jaxrs.tracing.BookStore) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Status(javax.ws.rs.core.Response.Status) ExpectedException(org.junit.rules.ExpectedException) Matchers.empty(org.hamcrest.Matchers.empty) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) Iterator(java.util.Iterator) Tracer(io.opentracing.Tracer) MalformedURLException(java.net.MalformedURLException) OpenTracingClientFeature(org.apache.cxf.tracing.opentracing.OpenTracingClientFeature) WebClient(org.apache.cxf.jaxrs.client.WebClient) Assert.assertTrue(org.junit.Assert.assertTrue) InMemoryReporter(io.jaegertracing.internal.reporters.InMemoryReporter) Test(org.junit.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractResourceInfo(org.apache.cxf.jaxrs.model.AbstractResourceInfo) Rule(org.junit.Rule) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) OpenTracingClientProvider(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingClientProvider) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Example 95 with Tracer

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

the class OpenTracingTracingTest method testThatNewSpansAreCreatedWhenNotProvidedUsingMultipleAsyncClients.

@Test
public void testThatNewSpansAreCreatedWhenNotProvidedUsingMultipleAsyncClients() throws Exception {
    final WebClient client = createWebClient("/bookstore/books", new OpenTracingClientProvider(tracer));
    // The intention is to make a calls one after another, not in parallel, to ensure the
    // thread have trace contexts cleared out.
    IntStream.range(0, 4).mapToObj(index -> client.async().get()).map(this::get).forEach(r -> assertEquals(Status.OK.getStatusCode(), r.getStatus()));
    assertThat(REPORTER.getSpans().size(), equalTo(12));
    IntStream.range(0, 4).map(index -> index * 3).forEach(index -> {
        assertThat(REPORTER.getSpans().get(index).getOperationName(), equalTo("Get Books"));
        assertThat(REPORTER.getSpans().get(index + 1).getOperationName(), equalTo("GET /bookstore/books"));
        assertThat(REPORTER.getSpans().get(index + 2).getOperationName(), equalTo("GET " + client.getCurrentURI()));
    });
}
Also used : Arrays(java.util.Arrays) IsLogContaining.hasItem(org.apache.cxf.systest.jaxrs.tracing.opentracing.IsLogContaining.hasItem) TimeoutException(java.util.concurrent.TimeoutException) Builtin(io.opentracing.propagation.Format.Builtin) AbstractClientServerTestBase(org.apache.cxf.testutil.common.AbstractClientServerTestBase) AbstractTestServerBase(org.apache.cxf.testutil.common.AbstractTestServerBase) Tags(io.opentracing.tag.Tags) Future(java.util.concurrent.Future) MediaType(javax.ws.rs.core.MediaType) Duration(java.time.Duration) NullPointerExceptionMapper(org.apache.cxf.systest.jaxrs.tracing.NullPointerExceptionMapper) After(org.junit.After) ConstSampler(io.jaegertracing.internal.samplers.ConstSampler) IsTagContaining.hasItem(org.apache.cxf.systest.jaxrs.tracing.opentracing.IsTagContaining.hasItem) OpenTracingFeature(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingFeature) JaegerSpanContext(io.jaegertracing.internal.JaegerSpanContext) Awaitility.await(org.awaitility.Awaitility.await) Response(javax.ws.rs.core.Response) TextMap(io.opentracing.propagation.TextMap) HasSpan.hasSpan(org.apache.cxf.systest.jaxrs.tracing.opentracing.HasSpan.hasSpan) Entry(java.util.Map.Entry) ProcessingException(javax.ws.rs.ProcessingException) Span(io.opentracing.Span) Scope(io.opentracing.Scope) JaegerTracer(io.jaegertracing.internal.JaegerTracer) IntStream(java.util.stream.IntStream) SingletonResourceProvider(org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider) OpenTracingClientProvider(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingClientProvider) BeforeClass(org.junit.BeforeClass) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) CoreMatchers.not(org.hamcrest.CoreMatchers.not) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) BookStore(org.apache.cxf.systest.jaxrs.tracing.BookStore) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Status(javax.ws.rs.core.Response.Status) ExpectedException(org.junit.rules.ExpectedException) Matchers.empty(org.hamcrest.Matchers.empty) JAXRSServerFactoryBean(org.apache.cxf.jaxrs.JAXRSServerFactoryBean) Iterator(java.util.Iterator) Tracer(io.opentracing.Tracer) MalformedURLException(java.net.MalformedURLException) OpenTracingClientFeature(org.apache.cxf.tracing.opentracing.OpenTracingClientFeature) WebClient(org.apache.cxf.jaxrs.client.WebClient) Assert.assertTrue(org.junit.Assert.assertTrue) InMemoryReporter(io.jaegertracing.internal.reporters.InMemoryReporter) Test(org.junit.Test) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) AbstractResourceInfo(org.apache.cxf.jaxrs.model.AbstractResourceInfo) Rule(org.junit.Rule) HTTPClientPolicy(org.apache.cxf.transports.http.configuration.HTTPClientPolicy) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) OpenTracingClientProvider(org.apache.cxf.tracing.opentracing.jaxrs.OpenTracingClientProvider) WebClient(org.apache.cxf.jaxrs.client.WebClient) Test(org.junit.Test)

Aggregations

Tracer (io.opentracing.Tracer)104 Span (io.opentracing.Span)49 SpanContext (io.opentracing.SpanContext)30 Map (java.util.Map)21 Vertx (io.vertx.core.Vertx)19 HashMap (java.util.HashMap)19 Test (org.junit.Test)19 BeforeEach (org.junit.jupiter.api.BeforeEach)19 Test (org.junit.jupiter.api.Test)19 Future (io.vertx.core.Future)18 Buffer (io.vertx.core.buffer.Buffer)16 HttpURLConnection (java.net.HttpURLConnection)14 EventBus (io.vertx.core.eventbus.EventBus)13 JsonObject (io.vertx.core.json.JsonObject)12 Objects (java.util.Objects)12 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 Tags (io.opentracing.tag.Tags)9 Scope (io.opentracing.Scope)8 GlobalTracer (io.opentracing.util.GlobalTracer)8