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());
}
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());
}
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());
}
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));
}
});
}
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"));
}
}
Aggregations