Search in sources :

Example 86 with Tracer

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

the class TenantServiceBasedX509Authentication method validateClientCertificate.

/**
 * Validates a certificate path using a trust anchor retrieved from
 * the Tenant service.
 * <p>
 * This method uses the tenant client to determine the tenant that the client belongs to.
 * <p>
 * First, the {@link TenantClient#get(X500Principal, SpanContext)} method is invoked with the
 * the issuer DN of the first element of the certificate path.
 * <p>
 * If that fails, then the {@link TenantClient#get(String, SpanContext)} method is invoked with
 * the first label of the first requested host name.
 *
 * @param path The certificate path to validate.
 * @param requestedHostNames The host names conveyed by the client in a TLS SNI extension.
 * @param spanContext The <em>OpenTracing</em> context in which the
 *                    validation should be executed, or {@code null}
 *                    if no context exists (yet).
 * @return A future indicating the outcome of the validation.
 *         <p>
 *         The future will be failed with a {@link org.eclipse.hono.client.ServiceInvocationException}
 *         if the certificate path could not be validated.
 *         <p>
 *         Otherwise, the future will be succeeded with a JSON object having
 *         the following properties:
 *         <pre>
 *         {
 *           "subject-dn": [RFC 2253 formatted subject DN of the client's end certificate],
 *           "tenant-id": [identifier of the tenant that the device belongs to]
 *         }
 *         </pre>
 *
 *         If auto-provisioning is enabled for the trust anchor being used, the JSON object may optionally contain
 *         the DER encoding of the (validated) client certificate as a Base64 encoded byte array in the
 *         client-certificate property.
 * @throws NullPointerException if certificate path is {@code null}.
 */
@Override
public Future<JsonObject> validateClientCertificate(final Certificate[] path, final List<String> requestedHostNames, final SpanContext spanContext) {
    Objects.requireNonNull(path);
    final Span span = TracingHelper.buildChildSpan(tracer, spanContext, "validate device certificate", getClass().getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start();
    return getX509CertificatePath(path).compose(x509chain -> {
        final X509Certificate deviceCert = x509chain.get(0);
        final Map<String, String> detail = new HashMap<>(4);
        detail.put("subject DN", deviceCert.getSubjectX500Principal().getName(X500Principal.RFC2253));
        detail.put("issuer DN", deviceCert.getIssuerX500Principal().getName(X500Principal.RFC2253));
        detail.put("not before", deviceCert.getNotBefore().toString());
        detail.put("not after", deviceCert.getNotAfter().toString());
        span.log(detail);
        final Future<TenantObject> tenantTracker = getTenant(deviceCert, requestedHostNames, span);
        return tenantTracker.compose(tenant -> {
            final Set<TrustAnchor> trustAnchors = tenant.getTrustAnchors();
            if (trustAnchors.isEmpty()) {
                return Future.failedFuture(new ClientErrorException(tenant.getTenantId(), HttpURLConnection.HTTP_UNAUTHORIZED, "no valid trust anchors defined for tenant"));
            } else {
                if (log.isTraceEnabled()) {
                    final var b = new StringBuilder("found tenant [tenant-id: ").append(tenant.getTenantId()).append("]").append(" for client certificate [subject-dn: ").append(deviceCert.getSubjectX500Principal().getName(X500Principal.RFC2253)).append(", issuer-dn: ").append(deviceCert.getIssuerX500Principal().getName(X500Principal.RFC2253)).append("]").append(System.lineSeparator()).append("with trust anchors:").append(System.lineSeparator());
                    trustAnchors.stream().forEach(ta -> {
                        b.append("Trust Anchor [subject-dn: ").append(ta.getCAName()).append("]");
                    });
                    log.trace(b.toString());
                }
                final List<X509Certificate> chainToValidate = List.of(deviceCert);
                return certPathValidator.validate(chainToValidate, trustAnchors).recover(t -> Future.failedFuture(new ClientErrorException(tenant.getTenantId(), HttpURLConnection.HTTP_UNAUTHORIZED, t.getMessage(), t)));
            }
        }).compose(ok -> getCredentials(x509chain, tenantTracker.result()));
    }).onSuccess(authInfo -> span.log("certificate validated successfully")).onFailure(t -> {
        log.debug("validation of client certificate failed", t);
        TracingHelper.logError(span, t);
    }).onComplete(ar -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) X500Principal(javax.security.auth.x500.X500Principal) X509CertificateChainValidator(org.eclipse.hono.service.auth.X509CertificateChainValidator) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) Map(java.util.Map) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) LinkedList(java.util.LinkedList) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) NoopTracerFactory(io.opentracing.noop.NoopTracerFactory) Set(java.util.Set) TenantClient(org.eclipse.hono.client.registry.TenantClient) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) Certificate(java.security.cert.Certificate) Span(io.opentracing.Span) CertificateEncodingException(java.security.cert.CertificateEncodingException) TrustAnchor(java.security.cert.TrustAnchor) Future(io.vertx.core.Future) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TrustAnchor(java.security.cert.TrustAnchor) Span(io.opentracing.Span) HashMap(java.util.HashMap) Map(java.util.Map) X509Certificate(java.security.cert.X509Certificate)

Example 87 with Tracer

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

the class AbstractProtocolAdapterApplication method prometheusResourceLimitChecks.

/**
 * Creates resource limit checks based on data retrieved from a Prometheus server
 * via its HTTP API.
 *
 * @param config The configuration properties.
 * @param tenantClient The client to use for retrieving tenant configuration data.
 * @throws NullPointerException if any of the parameters are {@code null}-
 * @return The checks.
 */
protected ResourceLimitChecks prometheusResourceLimitChecks(final PrometheusBasedResourceLimitChecksConfig config, final TenantClient tenantClient) {
    Objects.requireNonNull(config);
    Objects.requireNonNull(tenantClient);
    if (config.isHostConfigured()) {
        final WebClientOptions webClientOptions = new WebClientOptions();
        webClientOptions.setConnectTimeout(config.getConnectTimeout());
        webClientOptions.setDefaultHost(config.getHost());
        webClientOptions.setDefaultPort(config.getPort());
        webClientOptions.setTrustOptions(config.getTrustOptions());
        webClientOptions.setKeyCertOptions(config.getKeyCertOptions());
        webClientOptions.setSsl(config.isTlsEnabled());
        final var webClient = WebClient.create(vertx, webClientOptions);
        final var cacheTimeout = Duration.ofSeconds(config.getCacheTimeout());
        final Caffeine<Object, Object> builder = Caffeine.newBuilder().executor(Executors.newSingleThreadExecutor(r -> {
            final var t = new Thread(r);
            t.setDaemon(true);
            return t;
        })).initialCapacity(config.getCacheMinSize()).maximumSize(config.getCacheMaxSize()).expireAfterWrite(cacheTimeout).refreshAfterWrite(cacheTimeout.dividedBy(2));
        return new PrometheusBasedResourceLimitChecks(builder.buildAsync(new ConnectedDevicesAsyncCacheLoader(webClient, config, tracer)), builder.buildAsync(new ConnectionDurationAsyncCacheLoader(webClient, config, tracer)), builder.buildAsync(new DataVolumeAsyncCacheLoader(webClient, config, tracer)), tenantClient, tracer);
    } else {
        return new NoopResourceLimitChecks();
    }
}
Also used : WebClientOptions(io.vertx.ext.web.client.WebClientOptions) MessagingKafkaConsumerConfigProperties(org.eclipse.hono.client.kafka.consumer.MessagingKafkaConsumerConfigProperties) MessagingKafkaProducerConfigProperties(org.eclipse.hono.client.kafka.producer.MessagingKafkaProducerConfigProperties) ProtonBasedDeviceRegistrationClient(org.eclipse.hono.client.registry.amqp.ProtonBasedDeviceRegistrationClient) KafkaBasedEventSender(org.eclipse.hono.client.telemetry.kafka.KafkaBasedEventSender) KafkaBasedCommandResponseSender(org.eclipse.hono.client.command.kafka.KafkaBasedCommandResponseSender) LoggerFactory(org.slf4j.LoggerFactory) LoggingConnectionEventProducer(org.eclipse.hono.adapter.monitoring.LoggingConnectionEventProducer) CommandRouterCommandConsumerFactory(org.eclipse.hono.client.command.CommandRouterCommandConsumerFactory) PrometheusBasedResourceLimitChecksConfig(org.eclipse.hono.adapter.resourcelimits.PrometheusBasedResourceLimitChecksConfig) KafkaAdminClientOptions(org.eclipse.hono.client.kafka.KafkaAdminClientOptions) NoopResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.NoopResourceLimitChecks) AbstractServiceApplication(org.eclipse.hono.service.quarkus.AbstractServiceApplication) TelemetrySender(org.eclipse.hono.client.telemetry.TelemetrySender) ProtonBasedInternalCommandConsumer(org.eclipse.hono.client.command.amqp.ProtonBasedInternalCommandConsumer) MessagingType(org.eclipse.hono.util.MessagingType) Duration(java.time.Duration) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) RegistrationResult(org.eclipse.hono.util.RegistrationResult) DataVolumeAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.DataVolumeAsyncCacheLoader) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) ProtonBasedCredentialsClient(org.eclipse.hono.client.registry.amqp.ProtonBasedCredentialsClient) KafkaConsumerOptions(org.eclipse.hono.client.kafka.consumer.KafkaConsumerOptions) NotificationConstants(org.eclipse.hono.notification.NotificationConstants) ConnectionEventProducerConfig(org.eclipse.hono.adapter.monitoring.ConnectionEventProducerConfig) MessagingClientProviders(org.eclipse.hono.adapter.MessagingClientProviders) EventSender(org.eclipse.hono.client.telemetry.EventSender) CredentialsResult(org.eclipse.hono.util.CredentialsResult) ProtonBasedNotificationReceiver(org.eclipse.hono.client.notification.amqp.ProtonBasedNotificationReceiver) CachingKafkaProducerFactory(org.eclipse.hono.client.kafka.producer.CachingKafkaProducerFactory) TenantClient(org.eclipse.hono.client.registry.TenantClient) Caches(org.eclipse.hono.service.cache.Caches) Future(io.vertx.core.Future) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) ConfigMapping(io.smallrye.config.ConfigMapping) List(java.util.List) KafkaProducerFactory(org.eclipse.hono.client.kafka.producer.KafkaProducerFactory) ConnectionDurationAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.ConnectionDurationAsyncCacheLoader) Buffer(io.vertx.core.buffer.Buffer) CommandRouterClient(org.eclipse.hono.client.command.CommandRouterClient) Optional(java.util.Optional) MicrometerKafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.MicrometerKafkaClientMetricsSupport) ConnectionEventProducerOptions(org.eclipse.hono.adapter.monitoring.ConnectionEventProducerOptions) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) KafkaBasedTelemetrySender(org.eclipse.hono.client.telemetry.kafka.KafkaBasedTelemetrySender) WebClient(io.vertx.ext.web.client.WebClient) ProtonBasedCommandResponseSender(org.eclipse.hono.client.command.amqp.ProtonBasedCommandResponseSender) ProtonBasedTenantClient(org.eclipse.hono.client.registry.amqp.ProtonBasedTenantClient) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) ClientOptions(org.eclipse.hono.config.quarkus.ClientOptions) Cache(com.github.benmanes.caffeine.cache.Cache) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) Inject(javax.inject.Inject) CompositeFuture(io.vertx.core.CompositeFuture) CommonKafkaClientOptions(org.eclipse.hono.client.kafka.CommonKafkaClientOptions) KafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.KafkaClientMetricsSupport) KafkaBasedInternalCommandConsumer(org.eclipse.hono.client.command.kafka.KafkaBasedInternalCommandConsumer) KafkaMetricsOptions(org.eclipse.hono.client.kafka.metrics.KafkaMetricsOptions) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) PrometheusBasedResourceLimitCheckOptions(org.eclipse.hono.adapter.resourcelimits.PrometheusBasedResourceLimitCheckOptions) KafkaAdminClientConfigProperties(org.eclipse.hono.client.kafka.KafkaAdminClientConfigProperties) PrometheusBasedResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.PrometheusBasedResourceLimitChecks) WrappedLifecycleComponentVerticle(org.eclipse.hono.util.WrappedLifecycleComponentVerticle) HonoConnection(org.eclipse.hono.client.HonoConnection) ProtonBasedCommandRouterClient(org.eclipse.hono.client.command.amqp.ProtonBasedCommandRouterClient) RequestResponseClientConfigProperties(org.eclipse.hono.client.RequestResponseClientConfigProperties) NotificationReceiver(org.eclipse.hono.notification.NotificationReceiver) NotificationKafkaConsumerConfigProperties(org.eclipse.hono.client.notification.kafka.NotificationKafkaConsumerConfigProperties) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) TenantResult(org.eclipse.hono.util.TenantResult) Caffeine(com.github.benmanes.caffeine.cache.Caffeine) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) MessagingClientProvider(org.eclipse.hono.client.util.MessagingClientProvider) KafkaBasedNotificationReceiver(org.eclipse.hono.client.notification.kafka.KafkaBasedNotificationReceiver) KafkaProducerOptions(org.eclipse.hono.client.kafka.producer.KafkaProducerOptions) RequestResponseClientOptions(org.eclipse.hono.client.RequestResponseClientOptions) TenantObject(org.eclipse.hono.util.TenantObject) NoopKafkaClientMetricsSupport(org.eclipse.hono.client.kafka.metrics.NoopKafkaClientMetricsSupport) DeploymentOptions(io.vertx.core.DeploymentOptions) ProtonBasedDownstreamSender(org.eclipse.hono.client.telemetry.amqp.ProtonBasedDownstreamSender) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) ConnectedDevicesAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.ConnectedDevicesAsyncCacheLoader) SendMessageSampler(org.eclipse.hono.client.SendMessageSampler) HonoEventConnectionEventProducer(org.eclipse.hono.adapter.monitoring.HonoEventConnectionEventProducer) CredentialsObject(org.eclipse.hono.util.CredentialsObject) WebClientOptions(io.vertx.ext.web.client.WebClientOptions) PrometheusBasedResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.PrometheusBasedResourceLimitChecks) ConnectionDurationAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.ConnectionDurationAsyncCacheLoader) ConnectedDevicesAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.ConnectedDevicesAsyncCacheLoader) DataVolumeAsyncCacheLoader(org.eclipse.hono.adapter.resourcelimits.DataVolumeAsyncCacheLoader) TenantObject(org.eclipse.hono.util.TenantObject) CredentialsObject(org.eclipse.hono.util.CredentialsObject) NoopResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.NoopResourceLimitChecks)

Example 88 with Tracer

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

the class LoraProtocolAdapterTest method setUp.

/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {
    vertx = mock(Vertx.class);
    final Context context = VertxMockSupport.mockContext(vertx);
    webClient = mock(WebClient.class);
    this.properties = givenDefaultConfigurationProperties();
    createClients();
    prepareClients();
    processMessageSpan = mock(Span.class);
    when(processMessageSpan.context()).thenReturn(mock(SpanContext.class));
    final Span otherSpan = mock(Span.class);
    when(otherSpan.context()).thenReturn(mock(SpanContext.class));
    final SpanBuilder processMessageSpanBuilder = mock(SpanBuilder.class, withSettings().defaultAnswer(RETURNS_SELF));
    when(processMessageSpanBuilder.start()).thenReturn(processMessageSpan);
    final SpanBuilder otherSpanBuilder = mock(SpanBuilder.class, withSettings().defaultAnswer(RETURNS_SELF));
    when(otherSpanBuilder.start()).thenReturn(otherSpan);
    final Tracer tracer = mock(Tracer.class);
    when(tracer.buildSpan(eq(LoraProtocolAdapter.SPAN_NAME_PROCESS_MESSAGE))).thenReturn(processMessageSpanBuilder);
    when(tracer.buildSpan(argThat(opName -> !opName.equals(LoraProtocolAdapter.SPAN_NAME_PROCESS_MESSAGE)))).thenReturn(otherSpanBuilder);
    final HttpAdapterMetrics metrics = mock(HttpAdapterMetrics.class);
    when(metrics.startTimer()).thenReturn(mock(Sample.class));
    adapter = new LoraProtocolAdapter(webClient);
    adapter.setConfig(properties);
    adapter.setTracer(tracer);
    adapter.init(vertx, context);
    adapter.setMetrics(metrics);
    setServiceClients(adapter);
}
Also used : RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) CommandContext(org.eclipse.hono.client.command.CommandContext) HttpContext(org.eclipse.hono.service.http.HttpContext) SpanContext(io.opentracing.SpanContext) HttpURLConnection(java.net.HttpURLConnection) BeforeEach(org.junit.jupiter.api.BeforeEach) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) LoraProviderMalformedPayloadException(org.eclipse.hono.adapter.lora.providers.LoraProviderMalformedPayloadException) RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.vertx.core.Context) RETURNS_SELF(org.mockito.Mockito.RETURNS_SELF) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) CommandContext(org.eclipse.hono.client.command.CommandContext) Set(java.util.Set) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Span(io.opentracing.Span) Mockito.withSettings(org.mockito.Mockito.withSettings) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpAdapterMetrics(org.eclipse.hono.adapter.http.HttpAdapterMetrics) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpContext(org.eclipse.hono.service.http.HttpContext) HttpServerRequest(io.vertx.core.http.HttpServerRequest) HttpResponse(io.vertx.ext.web.client.HttpResponse) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) SpanBuilder(io.opentracing.Tracer.SpanBuilder) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) TracingHandler(org.eclipse.hono.service.http.TracingHandler) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ArgumentMatchers.isNull(org.mockito.ArgumentMatchers.isNull) Tracer(io.opentracing.Tracer) Vertx(io.vertx.core.Vertx) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Sample(io.micrometer.core.instrument.Timer.Sample) Mockito.verify(org.mockito.Mockito.verify) SpanContext(io.opentracing.SpanContext) HttpRequest(io.vertx.ext.web.client.HttpRequest) HttpProtocolAdapterProperties(org.eclipse.hono.adapter.http.HttpProtocolAdapterProperties) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) SpanBuilder(io.opentracing.Tracer.SpanBuilder) SpanContext(io.opentracing.SpanContext) Tracer(io.opentracing.Tracer) Sample(io.micrometer.core.instrument.Timer.Sample) Vertx(io.vertx.core.Vertx) WebClient(io.vertx.ext.web.client.WebClient) Span(io.opentracing.Span) HttpAdapterMetrics(org.eclipse.hono.adapter.http.HttpAdapterMetrics) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 89 with Tracer

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

the class AmqpAdapterClientSenderTestBase method setUp.

/**
 * Sets up fixture.
 */
@BeforeEach
public void setUp() {
    sender = AmqpClientUnitTestHelper.mockProtonSender();
    protonDelivery = mock(ProtonDelivery.class);
    when(protonDelivery.remotelySettled()).thenReturn(true);
    final Accepted deliveryState = new Accepted();
    when(protonDelivery.getRemoteState()).thenReturn(deliveryState);
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenReturn(protonDelivery);
    final Span span = TracingMockSupport.mockSpan();
    spanBuilder = TracingMockSupport.mockSpanBuilder(span);
    final Tracer tracer = TracingMockSupport.mockTracer(spanBuilder);
    connection = AmqpClientUnitTestHelper.mockHonoConnection(mock(Vertx.class));
    when(connection.getTracer()).thenReturn(tracer);
    when(connection.createSender(any(), any(), any())).thenReturn(Future.succeededFuture(sender));
}
Also used : ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) Tracer(io.opentracing.Tracer) Span(io.opentracing.Span) Accepted(org.apache.qpid.proton.amqp.messaging.Accepted) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 90 with Tracer

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

the class CommandContext method createSpan.

/**
 * Creates and starts an <em>OpenTracing</em> span for the command handling operation.
 *
 * @param tracer The tracer to use.
 * @param command The command for which the span should be started.
 * @param parentSpanContext The context of the span to reference as parent span.
 * @param followsFromSpanContext A span context for which to add a <em>follows-from</em> reference,
 *                               e.g. the span context for the operation to create the command consumer.
 * @param componentName The component to set for the span.
 * @return The created span.
 * @throws NullPointerException if tracer or command is {@code null}.
 */
static Span createSpan(final Tracer tracer, final Command command, final SpanContext parentSpanContext, final SpanContext followsFromSpanContext, final String componentName) {
    Objects.requireNonNull(tracer);
    Objects.requireNonNull(command);
    // we set the component tag to the class name because we have no access to
    // the name of the enclosing component we are running in
    final Tracer.SpanBuilder spanBuilder = TracingHelper.buildChildSpan(tracer, parentSpanContext, "handle command", componentName).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER).withTag(TracingHelper.TAG_TENANT_ID, command.getTenant()).withTag(TracingHelper.TAG_DEVICE_ID, command.getDeviceId());
    if (command.getGatewayId() != null) {
        spanBuilder.withTag(MessageHelper.APP_PROPERTY_GATEWAY_ID, command.getGatewayId());
    }
    spanBuilder.addReference(References.FOLLOWS_FROM, followsFromSpanContext);
    final Span currentSpan = spanBuilder.start();
    command.logToSpan(currentSpan);
    return currentSpan;
}
Also used : Tracer(io.opentracing.Tracer) 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