Search in sources :

Example 16 with Tracer

use of io.opentracing.Tracer in project carbon-apimgt by wso2.

the class ZipkinTracer method getTracer.

@Override
public Tracer getTracer(String serviceName) {
    String hostname = configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_HOST) != null ? configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_HOST) : TracingConstants.ZIPKIN_DEFAULT_HOST;
    int port = configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_PORT) != null ? Integer.parseInt(configuration.getFirstProperty(TracingConstants.ZIPKIN_CONFIG_PORT)) : TracingConstants.ZIPKIN_DEFAULT_PORT;
    boolean tracerLogEnabled = Boolean.parseBoolean(configuration.getFirstProperty(TracingConstants.CONFIG_TRACER_LOG_ENABLED) != null ? configuration.getFirstProperty(TracingConstants.CONFIG_TRACER_LOG_ENABLED) : TracingConstants.DEFAULT_TRACER_LOG_ENABLED);
    OkHttpSender sender = OkHttpSender.create("http://" + hostname + ":" + port + TracingConstants.ZIPKIN_API_CONTEXT);
    Tracer tracer = BraveTracer.create(Tracing.newBuilder().localServiceName(serviceName).spanReporter(AsyncReporter.builder(sender).build()).propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, TracingConstants.REQUEST_ID)).build());
    if (tracerLogEnabled) {
        Reporter reporter = new TracingReporter(LogFactory.getLog(TracingConstants.TRACER));
        Tracer tracerR = new TracerR(tracer, reporter, new ThreadLocalScopeManager());
        GlobalTracer.register(tracerR);
        return tracerR;
    } else {
        GlobalTracer.register(tracer);
        return tracer;
    }
}
Also used : OkHttpSender(zipkin2.reporter.okhttp3.OkHttpSender) ThreadLocalScopeManager(io.opentracing.util.ThreadLocalScopeManager) BraveTracer(brave.opentracing.BraveTracer) Tracer(io.opentracing.Tracer) GlobalTracer(io.opentracing.util.GlobalTracer) Reporter(io.opentracing.contrib.reporter.Reporter) AsyncReporter(zipkin2.reporter.AsyncReporter) TracerR(io.opentracing.contrib.reporter.TracerR)

Example 17 with Tracer

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

the class KafkaBasedCommandResponseSenderTest method testThatNotificationConsumerIsRegistered.

/**
 * Verifies that the sender registers itself for notifications of the type {@link TenantChangeNotification}.
 */
@Test
public void testThatNotificationConsumerIsRegistered() {
    final EventBus eventBus = mock(EventBus.class);
    final Vertx vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    final Span span = TracingMockSupport.mockSpan();
    final Tracer tracer = TracingMockSupport.mockTracer(span);
    final var mockProducer = KafkaClientUnitTestHelper.newMockProducer(true);
    final var factory = CachingKafkaProducerFactory.testFactory(vertx, (n, c) -> KafkaClientUnitTestHelper.newKafkaProducer(mockProducer));
    @SuppressWarnings("unused") final var sender = new KafkaBasedCommandResponseSender(vertx, factory, kafkaProducerConfig, tracer);
    verify(eventBus).consumer(eq(NotificationEventBusSupport.getEventBusAddress(TenantChangeNotification.TYPE)), VertxMockSupport.anyHandler());
    verifyNoMoreInteractions(eventBus);
}
Also used : Tracer(io.opentracing.Tracer) EventBus(io.vertx.core.eventbus.EventBus) Vertx(io.vertx.core.Vertx) Span(io.opentracing.Span) NoopSpan(io.opentracing.noop.NoopSpan) Test(org.junit.jupiter.api.Test)

Example 18 with Tracer

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

the class KafkaBasedCommandResponseSenderTest method testIfValidCommandResponseKafkaRecordIsSent.

@Test
void testIfValidCommandResponseKafkaRecordIsSent(final VertxTestContext ctx, final Vertx vertx) {
    // GIVEN a command response sender
    final String tenantId = "test-tenant";
    final String deviceId = "test-device";
    final String correlationId = UUID.randomUUID().toString();
    final String contentType = "text/plain";
    final String payload = "the-payload";
    final int status = 200;
    final String additionalHeader1Name = "testHeader1";
    final String additionalHeader1Value = "testHeader1Value";
    final String additionalHeader2Name = "testHeader2";
    final String additionalHeader2Value = "testHeader2Value";
    final Map<String, Object> additionalProperties = Map.of(additionalHeader1Name, additionalHeader1Value, additionalHeader2Name, additionalHeader2Value);
    final CommandResponse commandResponse = CommandResponse.fromAddressAndCorrelationId(String.format("%s/%s/%s", CommandConstants.COMMAND_RESPONSE_ENDPOINT, tenantId, Commands.getDeviceFacingReplyToId("", deviceId, MessagingType.kafka)), correlationId, Buffer.buffer(payload), contentType, status);
    commandResponse.setAdditionalProperties(additionalProperties);
    final Span span = TracingMockSupport.mockSpan();
    final Tracer tracer = TracingMockSupport.mockTracer(span);
    final var mockProducer = KafkaClientUnitTestHelper.newMockProducer(true);
    final var factory = CachingKafkaProducerFactory.testFactory(vertx, (n, c) -> KafkaClientUnitTestHelper.newKafkaProducer(mockProducer));
    final var sender = new KafkaBasedCommandResponseSender(vertx, factory, kafkaProducerConfig, tracer);
    final TenantObject tenant = TenantObject.from(tenantId);
    tenant.setResourceLimits(new ResourceLimits().setMaxTtlCommandResponse(10L));
    // WHEN sending a command response
    sender.sendCommandResponse(tenant, new RegistrationAssertion(deviceId), commandResponse, NoopSpan.INSTANCE.context()).onComplete(ctx.succeeding(t -> {
        ctx.verify(() -> {
            // THEN the producer record is created from the given values...
            final ProducerRecord<String, Buffer> record = mockProducer.history().get(0);
            assertThat(record.key()).isEqualTo(deviceId);
            assertThat(record.topic()).isEqualTo(new HonoTopic(HonoTopic.Type.COMMAND_RESPONSE, tenantId).toString());
            assertThat(record.value().toString()).isEqualTo(payload);
            // Verify if the record contains the necessary headers.
            final Headers headers = record.headers();
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.SYS_PROPERTY_CORRELATION_ID, correlationId);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.APP_PROPERTY_STATUS, status);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.SYS_PROPERTY_CONTENT_TYPE, contentType);
            final var creationTimeHeader = headers.headers(MessageHelper.SYS_PROPERTY_CREATION_TIME);
            assertThat(creationTimeHeader).hasSize(1);
            final Long creationTimeMillis = Json.decodeValue(Buffer.buffer(creationTimeHeader.iterator().next().value()), Long.class);
            assertThat(creationTimeMillis).isGreaterThan(0L);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, MessageHelper.SYS_HEADER_PROPERTY_TTL, 10000L);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, additionalHeader1Name, additionalHeader1Value);
            KafkaClientUnitTestHelper.assertUniqueHeaderWithExpectedValue(headers, additionalHeader2Name, additionalHeader2Value);
            verify(span).finish();
        });
        ctx.completeNow();
    }));
}
Also used : VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) Json(io.vertx.core.json.Json) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) MessagingKafkaProducerConfigProperties(org.eclipse.hono.client.kafka.producer.MessagingKafkaProducerConfigProperties) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Headers(org.apache.kafka.common.header.Headers) HashMap(java.util.HashMap) Commands(org.eclipse.hono.client.command.Commands) MessagingType(org.eclipse.hono.util.MessagingType) EventBus(io.vertx.core.eventbus.EventBus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) Map(java.util.Map) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) CommandConstants(org.eclipse.hono.util.CommandConstants) KafkaClientUnitTestHelper(org.eclipse.hono.kafka.test.KafkaClientUnitTestHelper) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) ResourceLimits(org.eclipse.hono.util.ResourceLimits) Tracer(io.opentracing.Tracer) CachingKafkaProducerFactory(org.eclipse.hono.client.kafka.producer.CachingKafkaProducerFactory) Vertx(io.vertx.core.Vertx) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Mockito.verify(org.mockito.Mockito.verify) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) Test(org.junit.jupiter.api.Test) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) NoopSpan(io.opentracing.noop.NoopSpan) Mockito.mock(org.mockito.Mockito.mock) Tracer(io.opentracing.Tracer) Headers(org.apache.kafka.common.header.Headers) CommandResponse(org.eclipse.hono.client.command.CommandResponse) HonoTopic(org.eclipse.hono.client.kafka.HonoTopic) Span(io.opentracing.Span) NoopSpan(io.opentracing.noop.NoopSpan) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ResourceLimits(org.eclipse.hono.util.ResourceLimits) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) TenantObject(org.eclipse.hono.util.TenantObject) Test(org.junit.jupiter.api.Test)

Example 19 with Tracer

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

the class KafkaBasedCommandConsumerFactoryImplIT method getKafkaBasedCommandConsumerFactory.

private KafkaBasedCommandConsumerFactoryImpl getKafkaBasedCommandConsumerFactory(final Supplier<Future<Void>> targetAdapterInstanceGetterCompletionFutureSupplier, final String tenantToHandleCommandsFor) {
    final KafkaProducerFactory<String, Buffer> producerFactory = CachingKafkaProducerFactory.sharedFactory(vertx);
    final TenantClient tenantClient = getTenantClient();
    final CommandTargetMapper commandTargetMapper = new CommandTargetMapper() {

        @Override
        public Future<JsonObject> getTargetGatewayAndAdapterInstance(final String tenantId, final String deviceId, final SpanContext context) {
            final JsonObject jsonObject = new JsonObject();
            jsonObject.put(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID, adapterInstanceId);
            jsonObject.put(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID, deviceId);
            if (!tenantId.equals(tenantToHandleCommandsFor)) {
                return Future.failedFuture("ignoring command for other tenant " + tenantId);
            }
            if (targetAdapterInstanceGetterCompletionFutureSupplier == null) {
                return Future.succeededFuture(jsonObject);
            }
            return targetAdapterInstanceGetterCompletionFutureSupplier.get().map(jsonObject);
        }
    };
    final Span span = TracingMockSupport.mockSpan();
    final Tracer tracer = TracingMockSupport.mockTracer(span);
    final MessagingKafkaConsumerConfigProperties kafkaConsumerConfig = new MessagingKafkaConsumerConfigProperties();
    kafkaConsumerConfig.setConsumerConfig(Map.of(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, IntegrationTestSupport.DOWNSTREAM_BOOTSTRAP_SERVERS));
    final CommandRouterMetrics metrics = mock(CommandRouterMetrics.class);
    when(metrics.startTimer()).thenReturn(Timer.start());
    final var kafkaBasedCommandConsumerFactoryImpl = new KafkaBasedCommandConsumerFactoryImpl(vertx, tenantClient, commandTargetMapper, producerFactory, IntegrationTestSupport.getKafkaProducerConfig(), IntegrationTestSupport.getKafkaProducerConfig(), kafkaConsumerConfig, metrics, NoopKafkaClientMetricsSupport.INSTANCE, tracer, null);
    kafkaBasedCommandConsumerFactoryImpl.setGroupId(commandRouterGroupId);
    componentsToStopAfterTest.add(kafkaBasedCommandConsumerFactoryImpl);
    return kafkaBasedCommandConsumerFactoryImpl;
}
Also used : Buffer(io.vertx.core.buffer.Buffer) KafkaBasedCommandConsumerFactoryImpl(org.eclipse.hono.commandrouter.impl.kafka.KafkaBasedCommandConsumerFactoryImpl) SpanContext(io.opentracing.SpanContext) Tracer(io.opentracing.Tracer) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) CommandRouterMetrics(org.eclipse.hono.commandrouter.CommandRouterMetrics) CommandTargetMapper(org.eclipse.hono.commandrouter.CommandTargetMapper) TenantClient(org.eclipse.hono.client.registry.TenantClient)

Example 20 with Tracer

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

the class SQL method runTransactionally.

/**
 * Run operation transactionally.
 * <p>
 * This function will perform the following operations:
 * <ul>
 *     <li>Open a new connection</li>
 *     <li>Turn off auto-commit mode</li>
 *     <li>Call the provided function</li>
 *     <li>If the provided function failed, perform a <em>Rollback</em> operation</li>
 *     <li>If the provided function succeeded, perform a <em>Commit</em> operation</li>
 *     <li>Close the connection</li>
 * </ul>
 *
 * @param client The client to use.
 * @param tracer The tracer to use.
 * @param function The function to execute while the transaction is open.
 * @param context The span to log to.
 * @param <T> The type of the result.
 * @return A future, tracking the outcome of the operation.
 */
public static <T> Future<T> runTransactionally(final SQLClient client, final Tracer tracer, final SpanContext context, final BiFunction<SQLConnection, SpanContext, Future<T>> function) {
    final Span span = startSqlSpan(tracer, context, "run transactionally", builder -> {
    });
    final Promise<SQLConnection> promise = Promise.promise();
    client.getConnection(promise);
    return promise.future().onSuccess(x -> {
        final Map<String, Object> log = new HashMap<>();
        log.put(Fields.EVENT, "success");
        log.put(Fields.MESSAGE, "connection opened");
        span.log(log);
    }).flatMap(connection -> SQL.setAutoCommit(tracer, span.context(), connection, false).flatMap(y -> function.apply(connection, span.context()).compose(v -> SQL.commit(tracer, span.context(), connection).map(v), x -> SQL.rollback(tracer, span.context(), connection).flatMap(unused -> Future.failedFuture(x)))).onComplete(x -> connection.close())).onComplete(x -> span.finish());
}
Also used : Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) BiFunction(java.util.function.BiFunction) UrlEscapers(com.google.common.net.UrlEscapers) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) Throwables(com.google.common.base.Throwables) HashMap(java.util.HashMap) SpanBuilder(io.opentracing.Tracer.SpanBuilder) Tags(io.opentracing.tag.Tags) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Consumer(java.util.function.Consumer) SQLException(java.sql.SQLException) List(java.util.List) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) Fields(io.opentracing.log.Fields) URI(java.net.URI) TracingHelper(org.eclipse.hono.tracing.TracingHelper) SQLClient(io.vertx.ext.sql.SQLClient) HashMap(java.util.HashMap) SQLConnection(io.vertx.ext.sql.SQLConnection) Span(io.opentracing.Span)

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