use of org.eclipse.hono.client.command.Command in project hono by eclipse.
the class ProtonBasedInternalCommandSender method sendCommand.
@Override
public Future<Void> sendCommand(final CommandContext commandContext, final String adapterInstanceId) {
Objects.requireNonNull(commandContext);
Objects.requireNonNull(adapterInstanceId);
return getOrCreateSenderLink(getTargetAddress(adapterInstanceId)).recover(thr -> Future.failedFuture(StatusCodeMapper.toServerError(thr))).compose(sender -> {
final Span span = newChildSpan(commandContext.getTracingContext(), "delegate Command request");
final Command command = commandContext.getCommand();
final Message message = adoptOrCreateMessage(command);
TracingHelper.setDeviceTags(span, command.getTenant(), command.getDeviceId());
if (command.isTargetedAtGateway()) {
MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_CMD_VIA, command.getGatewayId());
TracingHelper.TAG_GATEWAY_ID.set(span, command.getGatewayId());
}
return sender.sendAndWaitForRawOutcome(message, span);
}).map(delivery -> {
final DeliveryState remoteState = delivery.getRemoteState();
LOG.trace("command [{}] sent to downstream peer; remote state of delivery: {}", commandContext.getCommand(), remoteState);
if (Accepted.class.isInstance(remoteState)) {
commandContext.accept();
} else if (Rejected.class.isInstance(remoteState)) {
final Rejected rejected = (Rejected) remoteState;
commandContext.reject(Optional.ofNullable(rejected.getError()).map(ErrorCondition::getDescription).orElse(null));
} else if (Released.class.isInstance(remoteState)) {
commandContext.release();
} else if (Modified.class.isInstance(remoteState)) {
final Modified modified = (Modified) remoteState;
commandContext.modify(modified.getDeliveryFailed(), modified.getUndeliverableHere());
}
return (Void) null;
}).onFailure(thr -> {
LOG.debug("failed to send command [{}] to downstream peer", commandContext.getCommand(), thr);
if (thr instanceof NoConsumerException) {
TracingHelper.logError(commandContext.getTracingSpan(), "no credit - target adapter instance '" + adapterInstanceId + "' may be offline in which case the device hasn't subscribed again yet");
}
commandContext.release(thr);
});
}
use of org.eclipse.hono.client.command.Command in project hono by eclipse.
the class KafkaBasedInternalCommandSender method sendCommand.
@Override
public Future<Void> sendCommand(final CommandContext commandContext, final String adapterInstanceId) {
Objects.requireNonNull(commandContext);
Objects.requireNonNull(adapterInstanceId);
final Command command = commandContext.getCommand();
if (!(command instanceof KafkaBasedCommand)) {
commandContext.release();
log.error("command is not an instance of KafkaBasedCommand");
throw new IllegalArgumentException("command is not an instance of KafkaBasedCommand");
}
final String topicName = getInternalCommandTopic(adapterInstanceId);
final Span currentSpan = startChildSpan("delegate Command request", topicName, command.getTenant(), command.getDeviceId(), commandContext.getTracingContext());
return sendAndWaitForOutcome(topicName, command.getTenant(), command.getDeviceId(), command.getPayload(), getHeaders((KafkaBasedCommand) command), currentSpan).onSuccess(v -> commandContext.accept()).onFailure(thr -> commandContext.release(new ServerErrorException(command.getTenant(), HttpURLConnection.HTTP_UNAVAILABLE, "failed to publish command message on internal command topic", thr))).onComplete(ar -> currentSpan.finish());
}
use of org.eclipse.hono.client.command.Command in project hono by eclipse.
the class ProtocolAdapterMockSupport method newRequestResponseCommand.
private Command newRequestResponseCommand(final String tenantId, final String deviceId, final String name, final String replyToId, final String contentType, final Buffer payload, final MessagingType messagingType) {
final Command command = newOneWayCommand(tenantId, deviceId, name, contentType, payload);
when(command.isOneWay()).thenReturn(false);
when(command.getRequestId()).thenReturn(Commands.encodeRequestIdParameters("correlation-id", replyToId, deviceId, messagingType));
return command;
}
use of org.eclipse.hono.client.command.Command in project hono by eclipse.
the class VertxBasedAmqpProtocolAdapter method doUploadCommandResponseMessage.
private Future<Void> doUploadCommandResponseMessage(final AmqpContext context, final ResourceIdentifier resource, final Span currentSpan) {
final Future<CommandResponse> responseTracker = Optional.ofNullable(getCommandResponse(context.getMessage())).map(Future::succeededFuture).orElseGet(() -> {
TracingHelper.logError(currentSpan, String.format("invalid message (correlationId: %s, address: %s, status: %s)", context.getMessage().getCorrelationId(), context.getMessage().getAddress(), MessageHelper.getStatus(context.getMessage())));
return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed command response message"));
});
final Future<TenantObject> tenantTracker = getTenantConfiguration(resource.getTenantId(), currentSpan.context());
return CompositeFuture.all(tenantTracker, responseTracker).compose(ok -> {
final CommandResponse commandResponse = responseTracker.result();
log.trace("sending command response [device-id: {}, status: {}, correlation-id: {}, reply-to: {}]", resource.getResourceId(), commandResponse.getStatus(), commandResponse.getCorrelationId(), commandResponse.getReplyToId());
final Map<String, Object> items = new HashMap<>(3);
items.put(Fields.EVENT, "sending command response");
items.put(TracingHelper.TAG_CORRELATION_ID.getKey(), commandResponse.getCorrelationId());
items.put(MessageHelper.APP_PROPERTY_STATUS, commandResponse.getStatus());
currentSpan.log(items);
final Future<RegistrationAssertion> tokenFuture = getRegistrationAssertion(resource.getTenantId(), resource.getResourceId(), context.getAuthenticatedDevice(), currentSpan.context());
final Future<TenantObject> tenantValidationTracker = CompositeFuture.all(isAdapterEnabled(tenantTracker.result()), checkMessageLimit(tenantTracker.result(), context.getPayloadSize(), currentSpan.context())).map(success -> tenantTracker.result());
return CompositeFuture.all(tenantValidationTracker, tokenFuture).compose(success -> sendCommandResponse(tenantTracker.result(), tokenFuture.result(), commandResponse, currentSpan.context()));
}).map(delivery -> {
log.trace("forwarded command response from device [tenant: {}, device-id: {}]", resource.getTenantId(), resource.getResourceId());
metrics.reportCommand(Direction.RESPONSE, resource.getTenantId(), tenantTracker.result(), ProcessingOutcome.FORWARDED, context.getPayloadSize(), context.getTimer());
return delivery;
}).recover(t -> {
log.debug("cannot process command response from device [tenant: {}, device-id: {}]", resource.getTenantId(), resource.getResourceId(), t);
metrics.reportCommand(Direction.RESPONSE, resource.getTenantId(), tenantTracker.result(), ProcessingOutcome.from(t), context.getPayloadSize(), context.getTimer());
return Future.failedFuture(t);
});
}
use of org.eclipse.hono.client.command.Command in project hono by eclipse.
the class AbstractHonoResource method addCommandToResponse.
/**
* Adds a command to a CoAP response.
* <p>
* This default implementation adds the command name, content format and response URI to the
* CoAP response options and puts the command's input data (if any) to the response body.
*
* @param response The CoAP response.
* @param commandContext The context containing the command to add.
* @param currentSpan The Open Tracing span used for tracking the CoAP request.
*/
protected void addCommandToResponse(final Response response, final CommandContext commandContext, final Span currentSpan) {
final Command command = commandContext.getCommand();
final OptionSet options = response.getOptions();
options.addLocationQuery(Constants.HEADER_COMMAND + "=" + command.getName());
if (command.isOneWay()) {
options.setLocationPath(CommandConstants.COMMAND_ENDPOINT);
} else {
options.setLocationPath(CommandConstants.COMMAND_RESPONSE_ENDPOINT);
}
currentSpan.setTag(Constants.HEADER_COMMAND, command.getName());
LOG.debug("adding command [name: {}, request-id: {}] to response for device [tenant-id: {}, device-id: {}]", command.getName(), command.getRequestId(), command.getTenant(), command.getGatewayOrDeviceId());
commandContext.getTracingSpan().log("forwarding command to device in CoAP response");
if (command.isTargetedAtGateway()) {
options.addLocationPath(command.getTenant());
options.addLocationPath(command.getDeviceId());
currentSpan.setTag(Constants.HEADER_COMMAND_TARGET_DEVICE, command.getDeviceId());
}
if (!command.isOneWay()) {
options.addLocationPath(command.getRequestId());
currentSpan.setTag(Constants.HEADER_COMMAND_REQUEST_ID, command.getRequestId());
}
final int formatCode = MediaTypeRegistry.parse(command.getContentType());
if (formatCode != MediaTypeRegistry.UNDEFINED) {
options.setContentFormat(formatCode);
} else {
currentSpan.log("ignoring unknown content type [" + command.getContentType() + "] of command");
}
Optional.ofNullable(command.getPayload()).ifPresent(b -> response.setPayload(b.getBytes()));
}
Aggregations