Search in sources :

Example 61 with SpanContext

use of io.opentracing.SpanContext in project Payara by payara.

the class ContextSetupProviderImpl method startConcurrentContextSpan.

private void startConcurrentContextSpan(ComponentInvocation invocation, InvocationContext handle) {
    Tracer tracer = openTracing.getTracer(openTracing.getApplicationName(Globals.getDefaultBaseServiceLocator().getService(InvocationManager.class)));
    // Start a trace in the request tracing system
    SpanBuilder builder = tracer.buildSpan("executeConcurrentContext");
    // Check for propagated span
    if (handle.getSpanContextMap() != null) {
        @SuppressWarnings("unchecked") SpanContext spanContext = tracer.extract(Format.Builtin.TEXT_MAP, new MapToTextMap(handle.getSpanContextMap()));
        if (spanContext != null) {
            builder.asChildOf(spanContext);
            // Check for the presence of a propagated parent operation name
            try {
                String operationName = ((RequestTraceSpanContext) spanContext).getBaggageItems().get("operation.name");
                if (operationName != null) {
                    builder.withTag("Parent Operation Name", operationName);
                }
            } catch (ClassCastException cce) {
                logger.log(Level.FINE, "ClassCastException caught converting Span Context", cce);
            }
        }
    }
    if (invocation != null) {
        builder = builder.withTag("App Name", invocation.getAppName()).withTag("Component ID", invocation.getComponentId()).withTag("Module Name", invocation.getModuleName());
        Object instance = invocation.getInstance();
        if (instance != null) {
            builder.withTag("Class Name", instance.getClass().getName());
        }
    }
    builder.withTag("Thread Name", Thread.currentThread().getName());
    tracer.activateSpan(builder.start());
}
Also used : SpanBuilder(io.opentracing.Tracer.SpanBuilder) RequestTraceSpanContext(fish.payara.notification.requesttracing.RequestTraceSpanContext) SpanContext(io.opentracing.SpanContext) Tracer(io.opentracing.Tracer) MapToTextMap(fish.payara.opentracing.propagation.MapToTextMap)

Example 62 with SpanContext

use of io.opentracing.SpanContext in project Payara by payara.

the class OpenTracingIiopServerInterceptor method receive_request.

@Override
public void receive_request(ServerRequestInfo serverRequestInfo) throws ForwardRequest {
    // Double check we have a tracer
    if (!tracerAvailable()) {
        return;
    }
    ServiceContext serviceContext = serverRequestInfo.get_request_service_context(OPENTRACING_IIOP_ID);
    if (serviceContext == null) {
        return;
    }
    OpenTracingIiopTextMap openTracingIiopTextMap = null;
    try (ByteArrayInputStream bis = new ByteArrayInputStream(serviceContext.context_data);
        ObjectInput in = new OpenTracingIiopObjectInputStream(bis)) {
        openTracingIiopTextMap = (OpenTracingIiopTextMap) in.readObject();
    } catch (IOException | ClassNotFoundException exception) {
        throw new ForwardRequest(exception.getMessage(), serverRequestInfo);
    }
    Tracer.SpanBuilder spanBuilder = tracer.buildSpan("rmi").withTag(Tags.COMPONENT.getKey(), "ejb");
    if (openTracingIiopTextMap != null) {
        SpanContext spanContext = tracer.extract(Format.Builtin.TEXT_MAP, openTracingIiopTextMap);
        // Add the propagated span as a parent
        spanBuilder.asChildOf(spanContext);
    }
    // Start the span and mark it as active
    tracer.activateSpan(spanBuilder.start());
}
Also used : ForwardRequest(org.omg.PortableInterceptor.ForwardRequest) SpanContext(io.opentracing.SpanContext) ByteArrayInputStream(java.io.ByteArrayInputStream) ServiceContext(org.omg.IOP.ServiceContext) Tracer(io.opentracing.Tracer) ObjectInput(java.io.ObjectInput) IOException(java.io.IOException)

Example 63 with SpanContext

use of io.opentracing.SpanContext 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 64 with SpanContext

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

the class AbstractProtocolAdapterBase method sendTtdEvent.

@Override
public final Future<Void> sendTtdEvent(final String tenant, final String deviceId, final Device authenticatedDevice, final Integer ttd, final SpanContext context) {
    Objects.requireNonNull(tenant);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(ttd);
    final Future<RegistrationAssertion> tokenTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice, context);
    final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant, context);
    return CompositeFuture.all(tokenTracker, tenantConfigTracker).compose(ok -> {
        if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {
            final Map<String, Object> props = new HashMap<>();
            props.put(MessageHelper.APP_PROPERTY_ORIG_ADAPTER, getTypeName());
            props.put(MessageHelper.APP_PROPERTY_QOS, QoS.AT_LEAST_ONCE.ordinal());
            props.put(MessageHelper.APP_PROPERTY_DEVICE_TTD, ttd);
            return getEventSender(tenantConfigTracker.result()).sendEvent(tenantConfigTracker.result(), tokenTracker.result(), EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION, null, props, context).onSuccess(s -> log.debug("successfully sent TTD notification [tenant: {}, device-id: {}, TTD: {}]", tenant, deviceId, ttd)).onFailure(t -> log.debug("failed to send TTD notification [tenant: {}, device-id: {}, TTD: {}]", tenant, deviceId, ttd, t));
        } else {
            // this adapter is not enabled for the tenant
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) DecodeException(io.vertx.core.json.DecodeException) Context(io.vertx.core.Context) NoopResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.NoopResourceLimitChecks) TelemetrySender(org.eclipse.hono.client.telemetry.TelemetrySender) MessagingType(org.eclipse.hono.util.MessagingType) Map(java.util.Map) CredentialsClient(org.eclipse.hono.client.registry.CredentialsClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) EventSender(org.eclipse.hono.client.telemetry.EventSender) CommandContext(org.eclipse.hono.client.command.CommandContext) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) TenantClient(org.eclipse.hono.client.registry.TenantClient) MessageHelper(org.eclipse.hono.util.MessageHelper) ServiceBaseUtils(org.eclipse.hono.service.util.ServiceBaseUtils) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) TrustOptions(io.vertx.core.net.TrustOptions) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CommandRouterClient(org.eclipse.hono.client.command.CommandRouterClient) Optional(java.util.Optional) QoS(org.eclipse.hono.util.QoS) ConnectionLimitManager(org.eclipse.hono.adapter.limiting.ConnectionLimitManager) Lifecycle(org.eclipse.hono.util.Lifecycle) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ConnectionEventProducer(org.eclipse.hono.adapter.monitoring.ConnectionEventProducer) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) CommandResponseSender(org.eclipse.hono.client.command.CommandResponseSender) ArrayList(java.util.ArrayList) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) CompositeFuture(io.vertx.core.CompositeFuture) Status(io.vertx.ext.healthchecks.Status) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) GatewayDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.GatewayDisabledOrNotRegisteredException) TelemetryExecutionContext(org.eclipse.hono.util.TelemetryExecutionContext) Strings(org.eclipse.hono.util.Strings) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Sample(io.micrometer.core.instrument.Timer.Sample) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) CommandConsumerFactory(org.eclipse.hono.client.command.CommandConsumerFactory) ValidityBasedTrustOptions(org.eclipse.hono.service.auth.ValidityBasedTrustOptions) ServiceClient(org.eclipse.hono.client.util.ServiceClient) ConnectionAttemptOutcome(org.eclipse.hono.service.metric.MetricsTags.ConnectionAttemptOutcome) AbstractServiceBase(org.eclipse.hono.service.AbstractServiceBase) ResourceLimitChecks(org.eclipse.hono.adapter.resourcelimits.ResourceLimitChecks) TenantObject(org.eclipse.hono.util.TenantObject) HashMap(java.util.HashMap) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject) TenantObject(org.eclipse.hono.util.TenantObject)

Example 65 with SpanContext

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

the class ProtonBasedInternalCommandConsumer method handleCommandMessage.

void handleCommandMessage(final ProtonDelivery delivery, final Message msg) {
    final ProtonBasedCommand command;
    try {
        command = ProtonBasedCommand.fromRoutedCommandMessage(msg);
    } catch (final IllegalArgumentException e) {
        log.debug("address of command message is invalid: {}", msg.getAddress());
        final Rejected rejected = new Rejected();
        rejected.setError(new ErrorCondition(Constants.AMQP_BAD_REQUEST, "invalid command target address"));
        delivery.disposition(rejected, true);
        return;
    }
    final CommandHandlerWrapper commandHandler = commandHandlers.getCommandHandler(command.getTenant(), command.getGatewayOrDeviceId());
    if (commandHandler != null && commandHandler.getGatewayId() != null) {
        // Gateway information set in command handler means a gateway has subscribed for commands for a specific device.
        // This information isn't getting set in the message (by the Command Router) and therefore has to be adopted manually here.
        command.setGatewayId(commandHandler.getGatewayId());
    }
    final SpanContext spanContext = TracingHelper.extractSpanContext(tracer, msg);
    final SpanContext followsFromSpanContext = commandHandler != null ? commandHandler.getConsumerCreationSpanContext() : null;
    final Span currentSpan = CommandContext.createSpan(tracer, command, spanContext, followsFromSpanContext, getClass().getSimpleName());
    currentSpan.setTag(MessageHelper.APP_PROPERTY_ADAPTER_INSTANCE_ID, adapterInstanceId);
    final CommandContext commandContext = new ProtonBasedCommandContext(command, delivery, currentSpan);
    if (commandHandler != null) {
        log.trace("using [{}] for received command [{}]", commandHandler, command);
        // command.isValid() check not done here - it is to be done in the command handler
        commandHandler.handleCommand(commandContext);
    } else {
        log.info("no command handler found for command [{}]", command);
        commandContext.release(new NoConsumerException("no command handler found for command"));
    }
}
Also used : SpanContext(io.opentracing.SpanContext) CommandContext(org.eclipse.hono.client.command.CommandContext) CommandHandlerWrapper(org.eclipse.hono.client.command.CommandHandlerWrapper) ErrorCondition(org.apache.qpid.proton.amqp.transport.ErrorCondition) NoConsumerException(org.eclipse.hono.client.NoConsumerException) Rejected(org.apache.qpid.proton.amqp.messaging.Rejected) Span(io.opentracing.Span)

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