Search in sources :

Example 21 with Tracer

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

the class CredentialsApiAuthProvider method authenticate.

@Override
public final void authenticate(final T deviceCredentials, final SpanContext spanContext, final Handler<AsyncResult<DeviceUser>> resultHandler) {
    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    final Span currentSpan = TracingHelper.buildServerChildSpan(tracer, spanContext, "authenticate device", getClass().getSimpleName()).withTag(MessageHelper.APP_PROPERTY_TENANT_ID, deviceCredentials.getTenantId()).withTag(TracingHelper.TAG_AUTH_ID.getKey(), deviceCredentials.getAuthId()).start();
    getCredentialsForDevice(deviceCredentials, currentSpan.context()).recover(t -> Future.failedFuture(mapNotFoundToBadCredentialsException(t))).compose(credentialsOnRecord -> validateCredentials(deviceCredentials, credentialsOnRecord, currentSpan.context())).map(device -> new DeviceUser(device.getTenantId(), device.getDeviceId())).onComplete(authAttempt -> {
        if (authAttempt.succeeded()) {
            currentSpan.log("successfully authenticated device");
        } else {
            currentSpan.log("authentication of device failed");
            TracingHelper.logError(currentSpan, authAttempt.cause());
        }
        currentSpan.finish();
        resultHandler.handle(authAttempt);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) User(io.vertx.ext.auth.User) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) Span(io.opentracing.Span)

Example 22 with Tracer

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

the class CredentialsApiAuthProvider method validateCredentials.

/**
 * Verifies that the credentials provided by a device during the authentication
 * process match the credentials on record for that device.
 *
 * @param deviceCredentials The credentials provided by the device.
 * @param credentialsOnRecord The credentials to match against.
 * @param spanContext The OpenTracing context to use for tracking the operation.
 * @return A future that is succeeded with the authenticated device if the
 *         credentials have been validated successfully. Otherwise, the
 *         future is failed with a {@link ServiceInvocationException}.
 */
private Future<Device> validateCredentials(final T deviceCredentials, final CredentialsObject credentialsOnRecord, final SpanContext spanContext) {
    final Span currentSpan = TracingHelper.buildServerChildSpan(tracer, spanContext, "validate credentials", getClass().getSimpleName()).withTag(MessageHelper.APP_PROPERTY_TENANT_ID, deviceCredentials.getTenantId()).withTag(TracingHelper.TAG_AUTH_ID.getKey(), deviceCredentials.getAuthId()).withTag(TracingHelper.TAG_CREDENTIALS_TYPE.getKey(), deviceCredentials.getType()).start();
    final Promise<Device> result = Promise.promise();
    if (!deviceCredentials.getAuthId().equals(credentialsOnRecord.getAuthId())) {
        currentSpan.log(String.format("Credentials service returned wrong credentials-on-record [auth-id: %s]", credentialsOnRecord.getAuthId()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!deviceCredentials.getType().equals(credentialsOnRecord.getType())) {
        currentSpan.log(String.format("Credentials service returned wrong credentials-on-record [type: %s]", credentialsOnRecord.getType()));
        result.fail(new ServerErrorException(HttpURLConnection.HTTP_INTERNAL_ERROR));
    } else if (!credentialsOnRecord.isEnabled()) {
        currentSpan.log("credentials-on-record are disabled");
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED));
    } else {
        doValidateCredentials(deviceCredentials, credentialsOnRecord).onComplete(result);
    }
    return result.future().map(device -> {
        currentSpan.log("validation of credentials succeeded");
        currentSpan.finish();
        return device;
    }).recover(t -> {
        currentSpan.log("validation of credentials failed");
        TracingHelper.logError(currentSpan, t);
        currentSpan.finish();
        return Future.failedFuture(t);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) LoggerFactory(org.slf4j.LoggerFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) User(io.vertx.ext.auth.User) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) CredentialsObject(org.eclipse.hono.util.CredentialsObject) Device(org.eclipse.hono.auth.Device) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Span(io.opentracing.Span)

Example 23 with Tracer

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

the class KafkaHeadersInjectExtractAdapterTest method testJaegerTracerCanUseAdapter.

/**
 * Verifies that the Jaeger tracer implementation can successfully use the adapters to inject and extract
 * a SpanContext.
 */
@Test
public void testJaegerTracerCanUseAdapter() {
    final Configuration config = new Configuration("test");
    final Tracer tracer = config.getTracer();
    final Span span = tracer.buildSpan("do").start();
    final List<KafkaHeader> headers = new ArrayList<>();
    final KafkaHeadersInjectAdapter injectAdapter = new KafkaHeadersInjectAdapter(headers);
    tracer.inject(span.context(), Format.Builtin.TEXT_MAP, injectAdapter);
    final SpanContext context = tracer.extract(Format.Builtin.TEXT_MAP, new KafkaHeadersExtractAdapter(headers));
    assertThat(context.toSpanId()).isEqualTo(span.context().toSpanId());
}
Also used : SpanContext(io.opentracing.SpanContext) Configuration(io.jaegertracing.Configuration) Tracer(io.opentracing.Tracer) ArrayList(java.util.ArrayList) Span(io.opentracing.Span) KafkaHeader(io.vertx.kafka.client.producer.KafkaHeader) Test(org.junit.jupiter.api.Test)

Example 24 with Tracer

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

the class ProtonBasedNotificationReceiverTest method setUp.

/**
 * Sets up the fixture.
 */
@BeforeEach
public void setUp() {
    final Tracer tracer = TracingMockSupport.mockTracer(TracingMockSupport.mockSpan());
    final EventBus eventBus = mock(EventBus.class);
    final Vertx vertx = mock(Vertx.class);
    when(vertx.eventBus()).thenReturn(eventBus);
    final RequestResponseClientConfigProperties config = new RequestResponseClientConfigProperties();
    // don't let requestTimeout timer be started
    config.setRequestTimeout(0);
    connection = AmqpClientUnitTestHelper.mockHonoConnection(vertx, config, tracer);
    when(connection.connect()).thenReturn(Future.succeededFuture(connection));
    final ProtonReceiver receiver = AmqpClientUnitTestHelper.mockProtonReceiver();
    when(connection.createReceiver(anyString(), any(ProtonQoS.class), any(ProtonMessageHandler.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(receiver));
    client = new ProtonBasedNotificationReceiver(connection);
}
Also used : ProtonReceiver(io.vertx.proton.ProtonReceiver) 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) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 25 with Tracer

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

the class AbstractKafkaBasedMessageSender method sendAndWaitForOutcome.

/**
 * Sends a message to a Kafka broker and waits for the outcome.
 *
 * @param topic The topic to send the message to.
 * @param tenantId The tenant that the device belongs to.
 * @param deviceId The device identifier.
 * @param payload The data to send or {@code null} if the message has no payload.
 * @param headers Additional meta data that should be included in the message.
 * @param currentSpan The <em>OpenTracing</em> span used to use for tracking the sending of the message.
 *             The span will <em>not</em> be finished by this method.
 * @return A future indicating the outcome of the operation.
 *         <p>
 *         The future will be succeeded if the message has been sent.
 *         <p>
 *         The future will be failed with a {@link org.eclipse.hono.client.ServerErrorException} if the data could
 *         not be sent. The error code contained in the exception indicates the cause of the failure.
 * @throws NullPointerException if topic, tenantId, deviceId, headers or span are {@code null}.
 */
protected final Future<Void> sendAndWaitForOutcome(final String topic, final String tenantId, final String deviceId, final Buffer payload, final List<KafkaHeader> headers, final Span currentSpan) {
    Objects.requireNonNull(topic);
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(headers);
    Objects.requireNonNull(currentSpan);
    if (stopped) {
        return Future.failedFuture(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "sender already stopped"));
    }
    final KafkaProducerRecord<String, Buffer> record = KafkaProducerRecord.create(topic, deviceId, payload);
    log.trace("sending message to Kafka [topic: {}, tenantId: {}, deviceId: {}]", topic, tenantId, deviceId);
    record.addHeaders(headers);
    KafkaTracingHelper.injectSpanContext(tracer, record, currentSpan.context());
    logProducerRecord(currentSpan, record);
    return getOrCreateProducer().send(record).onSuccess(recordMetadata -> logRecordMetadata(currentSpan, deviceId, recordMetadata)).otherwise(t -> {
        logError(currentSpan, topic, tenantId, deviceId, t);
        throw new ServerErrorException(tenantId, getErrorCode(t), t);
    }).mapEmpty();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) Json(io.vertx.core.json.Json) RecordMetadata(io.vertx.kafka.client.producer.RecordMetadata) Lifecycle(org.eclipse.hono.util.Lifecycle) LoggerFactory(org.slf4j.LoggerFactory) KafkaClientFactory(org.eclipse.hono.client.kafka.KafkaClientFactory) Tags(io.opentracing.tag.Tags) KafkaProducer(io.vertx.kafka.client.producer.KafkaProducer) ArrayList(java.util.ArrayList) Status(io.vertx.ext.healthchecks.Status) MessagingType(org.eclipse.hono.util.MessagingType) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) References(io.opentracing.References) Map(java.util.Map) TracingHelper(org.eclipse.hono.tracing.TracingHelper) MessagingClient(org.eclipse.hono.util.MessagingClient) Strings(org.eclipse.hono.util.Strings) KafkaTracingHelper(org.eclipse.hono.client.kafka.tracing.KafkaTracingHelper) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) ServerErrorException(org.eclipse.hono.client.ServerErrorException) UUID(java.util.UUID) KafkaRecordHelper(org.eclipse.hono.client.kafka.KafkaRecordHelper) Instant(java.time.Instant) MessageHelper(org.eclipse.hono.util.MessageHelper) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) ServiceClient(org.eclipse.hono.client.util.ServiceClient) Buffer(io.vertx.core.buffer.Buffer) EncodeException(io.vertx.core.json.EncodeException) Span(io.opentracing.Span) KafkaHeader(io.vertx.kafka.client.producer.KafkaHeader) KafkaProducerRecord(io.vertx.kafka.client.producer.KafkaProducerRecord) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

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