use of io.opentracing.Tracer 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.Tracer in project hono by eclipse.
the class KafkaBasedCommandSender method sendCommand.
/**
* {@inheritDoc}
*
* <p>
* The replyId is not used in the Kafka based implementation. It can be set to {@code null}.
* If set it will be ignored.
* <p>
* If the timeout duration is {@code null} then the default timeout value of
* {@value DEFAULT_COMMAND_TIMEOUT_IN_MS} ms is used.
*/
@Override
public Future<DownstreamMessage<KafkaMessageContext>> sendCommand(final String tenantId, final String deviceId, final String command, final String contentType, final Buffer data, final String replyId, final Map<String, Object> properties, final Duration timeout, final SpanContext context) {
Objects.requireNonNull(tenantId);
Objects.requireNonNull(deviceId);
Objects.requireNonNull(command);
final long timeoutInMs = Optional.ofNullable(timeout).map(t -> {
if (t.isNegative()) {
throw new IllegalArgumentException("command timeout duration must be >= 0");
}
return t.toMillis();
}).orElse(DEFAULT_COMMAND_TIMEOUT_IN_MS);
final String correlationId = correlationIdSupplier.get();
final Span span = TracingHelper.buildChildSpan(tracer, context, "send command and receive response", getClass().getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenantId).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(TracingHelper.TAG_CORRELATION_ID, correlationId).start();
final ExpiringCommandPromise expiringCommandPromise = new ExpiringCommandPromise(correlationId, timeoutInMs, // Remove the corresponding pending response entry if times out
x -> removePendingCommandResponse(tenantId, correlationId), span);
subscribeForCommandResponse(tenantId, span).compose(ok -> {
// Store the correlation id and the expiring command promise
pendingCommandResponses.computeIfAbsent(tenantId, k -> new ConcurrentHashMap<>()).put(correlationId, expiringCommandPromise);
return sendCommand(tenantId, deviceId, command, contentType, data, correlationId, properties, true, "send command", span.context()).onSuccess(sent -> {
LOGGER.debug("sent command [correlation-id: {}], waiting for response", correlationId);
span.log("sent command, waiting for response");
}).onFailure(error -> {
LOGGER.debug("error sending command", error);
// To ensure that the span is not already finished.
if (!expiringCommandPromise.future().isComplete()) {
TracingHelper.logError(span, "error sending command", error);
}
removePendingCommandResponse(tenantId, correlationId);
expiringCommandPromise.tryCompleteAndCancelTimer(Future.failedFuture(error));
});
});
return expiringCommandPromise.future().onComplete(o -> span.finish());
}
use of io.opentracing.Tracer in project hono by eclipse.
the class ProtonBasedCommandResponseSenderTest method setUp.
/**
* Sets up the fixture.
*/
@BeforeEach
public void setUp() {
span = TracingMockSupport.mockSpan();
final Tracer tracer = TracingMockSupport.mockTracer(span);
final Vertx vertx = mock(Vertx.class);
when(vertx.eventBus()).thenReturn(mock(EventBus.class));
final ClientConfigProperties clientConfigProperties = new ClientConfigProperties();
protonSender = AmqpClientUnitTestHelper.mockProtonSender();
connection = AmqpClientUnitTestHelper.mockHonoConnection(vertx, clientConfigProperties, tracer);
when(connection.isConnected()).thenReturn(Future.succeededFuture());
when(connection.isConnected(anyLong())).thenReturn(Future.succeededFuture());
when(connection.createSender(anyString(), any(), any())).thenReturn(Future.succeededFuture(protonSender));
sender = new ProtonBasedCommandResponseSender(connection, SendMessageSampler.Factory.noop(), false);
}
use of io.opentracing.Tracer in project hono by eclipse.
the class KafkaBasedInternalCommandConsumer method handleCommandMessage.
void handleCommandMessage(final KafkaConsumerRecord<String, Buffer> record) {
// get partition/offset of the command record - related to the tenant-based topic the command was originally received in
final Integer commandPartition = KafkaRecordHelper.getOriginalPartitionHeader(record.headers()).orElse(null);
final Long commandOffset = KafkaRecordHelper.getOriginalOffsetHeader(record.headers()).orElse(null);
if (commandPartition == null || commandOffset == null) {
LOG.warn("command record is invalid - missing required original partition/offset headers");
return;
}
final KafkaBasedCommand command;
try {
command = KafkaBasedCommand.fromRoutedCommandRecord(record);
} catch (final IllegalArgumentException e) {
LOG.warn("command record is invalid [tenant-id: {}, device-id: {}]", KafkaRecordHelper.getTenantId(record.headers()).orElse(null), KafkaRecordHelper.getDeviceId(record.headers()).orElse(null), e);
return;
}
// check whether command has already been received and handled;
// partition index and offset here are related to the *tenant-based* topic the command was originally received in
// therefore they are stored in a map with the tenant as key
final Map<Integer, Long> lastHandledPartitionOffsets = lastHandledPartitionOffsetsPerTenant.computeIfAbsent(command.getTenant(), k -> new HashMap<>());
final Long lastHandledOffset = lastHandledPartitionOffsets.get(commandPartition);
if (lastHandledOffset != null && commandOffset <= lastHandledOffset) {
if (LOG.isDebugEnabled()) {
LOG.debug("ignoring command - record partition offset {} <= last handled offset {} [{}]", commandOffset, lastHandledOffset, command);
}
} else {
lastHandledPartitionOffsets.put(commandPartition, commandOffset);
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 record (by the Command Router) and therefore has to be adopted manually here.
command.setGatewayId(commandHandler.getGatewayId());
}
final SpanContext spanContext = KafkaTracingHelper.extractSpanContext(tracer, record);
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);
KafkaTracingHelper.TAG_OFFSET.set(currentSpan, record.offset());
final var commandContext = new KafkaBasedCommandContext(command, commandResponseSender, currentSpan);
tenantClient.get(command.getTenant(), spanContext).onFailure(t -> {
if (ServiceInvocationException.extractStatusCode(t) == HttpURLConnection.HTTP_NOT_FOUND) {
commandContext.reject(new TenantDisabledOrNotRegisteredException(command.getTenant(), HttpURLConnection.HTTP_NOT_FOUND));
} else {
commandContext.release(new ServerErrorException(command.getTenant(), HttpURLConnection.HTTP_UNAVAILABLE, "error retrieving tenant configuration", t));
}
}).onSuccess(tenantConfig -> {
commandContext.put(CommandContext.KEY_TENANT_CONFIG, tenantConfig);
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"));
}
});
}
}
use of io.opentracing.Tracer in project hono by eclipse.
the class RequestResponseClientTest method setUp.
/**
* Sets up the fixture.
*/
@BeforeEach
public void setUp() {
span = TracingMockSupport.mockSpan();
final Tracer tracer = TracingMockSupport.mockTracer(span);
final EventBus eventBus = mock(EventBus.class);
vertx = mock(Vertx.class);
when(vertx.eventBus()).thenReturn(eventBus);
receiver = AmqpClientUnitTestHelper.mockProtonReceiver();
sender = AmqpClientUnitTestHelper.mockProtonSender();
final SendMessageSampler sampler = mock(SendMessageSampler.class);
sample = mock(SendMessageSampler.Sample.class);
when(sampler.start(anyString())).thenReturn(sample);
clientConfig = new RequestResponseClientConfigProperties();
connection = AmqpClientUnitTestHelper.mockHonoConnection(vertx, clientConfig, tracer);
when(connection.isConnected(anyLong())).thenReturn(Future.succeededFuture());
when(connection.createReceiver(anyString(), any(ProtonQoS.class), any(ProtonMessageHandler.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(receiver));
when(connection.createSender(anyString(), any(ProtonQoS.class), VertxMockSupport.anyHandler())).thenReturn(Future.succeededFuture(sender));
client = RequestResponseClient.forEndpoint(connection, "ep", "tenant", sampler, VertxMockSupport.mockHandler(), VertxMockSupport.mockHandler());
}
Aggregations