use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class AbstractVertxBasedHttpProtocolAdapter method doUploadMessage.
private void doUploadMessage(final HttpContext ctx, final String tenant, final String deviceId, final Buffer payload, final String contentType, final MetricsTags.EndpointType endpoint) {
if (!ctx.hasValidQoS()) {
HttpUtils.badRequest(ctx.getRoutingContext(), "unsupported QoS-Level header value");
return;
}
if (!isPayloadOfIndicatedType(payload, contentType)) {
HttpUtils.badRequest(ctx.getRoutingContext(), String.format("content type [%s] does not match payload", contentType));
return;
}
final MetricsTags.QoS qos = getQoSLevel(endpoint, ctx.getRequestedQos());
final Device authenticatedDevice = ctx.getAuthenticatedDevice();
final String gatewayId = authenticatedDevice != null && !deviceId.equals(authenticatedDevice.getDeviceId()) ? authenticatedDevice.getDeviceId() : null;
final Span currentSpan = TracingHelper.buildChildSpan(tracer, TracingHandler.serverSpanContext(ctx.getRoutingContext()), "upload " + endpoint.getCanonicalName(), getTypeName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenant).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null).withTag(TracingHelper.TAG_QOS, qos.name()).start();
final Promise<Void> responseReady = Promise.promise();
final Future<RegistrationAssertion> tokenTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice, currentSpan.context());
final int payloadSize = Optional.ofNullable(payload).map(ok -> payload.length()).orElse(0);
final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, currentSpan.context());
final Future<TenantObject> tenantValidationTracker = tenantTracker.compose(tenantObject -> CompositeFuture.all(isAdapterEnabled(tenantObject), checkMessageLimit(tenantObject, payloadSize, currentSpan.context())).map(success -> tenantObject));
// we only need to consider TTD if the device and tenant are enabled and the adapter
// is enabled for the tenant
final Future<Integer> ttdTracker = CompositeFuture.all(tenantValidationTracker, tokenTracker).compose(ok -> {
final Integer ttdParam = getTimeUntilDisconnectFromRequest(ctx);
return getTimeUntilDisconnect(tenantTracker.result(), ttdParam).map(effectiveTtd -> {
if (effectiveTtd != null) {
currentSpan.setTag(MessageHelper.APP_PROPERTY_DEVICE_TTD, effectiveTtd);
}
return effectiveTtd;
});
});
final Future<CommandConsumer> commandConsumerTracker = ttdTracker.compose(ttd -> createCommandConsumer(ttd, tenantTracker.result(), deviceId, gatewayId, ctx.getRoutingContext(), responseReady, currentSpan));
commandConsumerTracker.compose(ok -> {
final Map<String, Object> props = getDownstreamMessageProperties(ctx);
Optional.ofNullable(commandConsumerTracker.result()).map(c -> ttdTracker.result()).ifPresent(ttd -> props.put(MessageHelper.APP_PROPERTY_DEVICE_TTD, ttd));
props.put(MessageHelper.APP_PROPERTY_QOS, ctx.getRequestedQos().ordinal());
customizeDownstreamMessageProperties(props, ctx);
setTtdRequestConnectionCloseHandler(ctx.getRoutingContext(), commandConsumerTracker.result(), tenant, deviceId, currentSpan);
if (EndpointType.EVENT.equals(endpoint)) {
ctx.getTimeToLive().ifPresent(ttl -> props.put(MessageHelper.SYS_HEADER_PROPERTY_TTL, ttl.toSeconds()));
return CompositeFuture.all(getEventSender(tenantValidationTracker.result()).sendEvent(tenantTracker.result(), tokenTracker.result(), contentType, payload, props, currentSpan.context()), responseReady.future()).map(s -> (Void) null);
} else {
// unsettled
return CompositeFuture.all(getTelemetrySender(tenantValidationTracker.result()).sendTelemetry(tenantTracker.result(), tokenTracker.result(), ctx.getRequestedQos(), contentType, payload, props, currentSpan.context()), responseReady.future()).map(s -> (Void) null);
}
}).compose(proceed -> {
// request and the CommandConsumer from the current request has not been closed yet
return Optional.ofNullable(commandConsumerTracker.result()).map(consumer -> consumer.close(currentSpan.context()).otherwise(thr -> {
TracingHelper.logError(currentSpan, thr);
return (Void) null;
})).orElseGet(Future::succeededFuture);
}).map(proceed -> {
if (ctx.response().closed()) {
log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]: response already closed", endpoint, tenant, deviceId);
TracingHelper.logError(currentSpan, "failed to send HTTP response to device: response already closed");
currentSpan.finish();
// close the response here, ensuring that the TracingHandler bodyEndHandler gets called
ctx.response().end();
} else {
final CommandContext commandContext = ctx.get(CommandContext.KEY_COMMAND_CONTEXT);
setResponsePayload(ctx.response(), commandContext, currentSpan);
ctx.getRoutingContext().addBodyEndHandler(ok -> {
log.trace("successfully processed [{}] message for device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId);
if (commandContext != null) {
commandContext.getTracingSpan().log("forwarded command to device in HTTP response body");
commandContext.accept();
metrics.reportCommand(commandContext.getCommand().isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, commandContext.getCommand().getPayloadSize(), getMicrometerSample(commandContext));
}
metrics.reportTelemetry(endpoint, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, qos, payloadSize, ctx.getTtdStatus(), getMicrometerSample(ctx.getRoutingContext()));
currentSpan.finish();
});
ctx.response().exceptionHandler(t -> {
log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId, t);
if (commandContext != null) {
TracingHelper.logError(commandContext.getTracingSpan(), "failed to forward command to device in HTTP response body", t);
commandContext.release(t);
metrics.reportCommand(commandContext.getCommand().isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), ProcessingOutcome.UNDELIVERABLE, commandContext.getCommand().getPayloadSize(), getMicrometerSample(commandContext));
}
currentSpan.log("failed to send HTTP response to device");
TracingHelper.logError(currentSpan, t);
currentSpan.finish();
});
ctx.response().end();
}
return proceed;
}).recover(t -> {
log.debug("cannot process [{}] message from device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId, t);
final boolean responseClosedPrematurely = ctx.response().closed();
final Future<Void> commandConsumerClosedTracker = Optional.ofNullable(commandConsumerTracker.result()).map(consumer -> consumer.close(currentSpan.context()).onFailure(thr -> TracingHelper.logError(currentSpan, thr))).orElseGet(Future::succeededFuture);
final CommandContext commandContext = ctx.get(CommandContext.KEY_COMMAND_CONTEXT);
if (commandContext != null) {
TracingHelper.logError(commandContext.getTracingSpan(), "command won't be forwarded to device in HTTP response body, HTTP request handling failed", t);
commandContext.release(t);
currentSpan.log("released command for device");
}
final ProcessingOutcome outcome;
if (ClientErrorException.class.isInstance(t)) {
outcome = ProcessingOutcome.UNPROCESSABLE;
ctx.fail(t);
} else {
outcome = ProcessingOutcome.UNDELIVERABLE;
final String errorMessage = t instanceof ServerErrorException ? ((ServerErrorException) t).getClientFacingMessage() : null;
HttpUtils.serviceUnavailable(ctx.getRoutingContext(), 2, Strings.isNullOrEmpty(errorMessage) ? "temporarily unavailable" : errorMessage);
}
if (responseClosedPrematurely) {
log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]: response already closed", endpoint, tenant, deviceId);
TracingHelper.logError(currentSpan, "failed to send HTTP response to device: response already closed");
}
metrics.reportTelemetry(endpoint, tenant, tenantTracker.result(), outcome, qos, payloadSize, ctx.getTtdStatus(), getMicrometerSample(ctx.getRoutingContext()));
TracingHelper.logError(currentSpan, t);
commandConsumerClosedTracker.onComplete(res -> currentSpan.finish());
return Future.failedFuture(t);
});
}
use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class AbstractVertxBasedHttpProtocolAdapter method uploadCommandResponseMessage.
/**
* Uploads a command response message to Hono.
*
* @param ctx The routing context of the HTTP request.
* @param tenant The tenant of the device from which the command response was received.
* @param deviceId The device from which the command response was received.
* @param commandRequestId The id of the command that the response has been sent in reply to.
* @param responseStatus The HTTP status code that the device has provided in its request to indicate
* the outcome of processing the command (may be {@code null}).
* @throws NullPointerException if ctx, tenant or deviceId are {@code null}.
*/
public final void uploadCommandResponseMessage(final HttpContext ctx, final String tenant, final String deviceId, final String commandRequestId, final Integer responseStatus) {
Objects.requireNonNull(ctx);
Objects.requireNonNull(tenant);
Objects.requireNonNull(deviceId);
final Buffer payload = ctx.getRoutingContext().getBody();
final String contentType = ctx.getContentType();
log.debug("processing response to command [tenantId: {}, deviceId: {}, cmd-req-id: {}, status code: {}]", tenant, deviceId, commandRequestId, responseStatus);
final Device authenticatedDevice = ctx.getAuthenticatedDevice();
final Span currentSpan = TracingHelper.buildChildSpan(tracer, TracingHandler.serverSpanContext(ctx.getRoutingContext()), "upload Command response", getTypeName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenant).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(Constants.HEADER_COMMAND_RESPONSE_STATUS, responseStatus).withTag(Constants.HEADER_COMMAND_REQUEST_ID, commandRequestId).withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null).start();
final CommandResponse cmdResponseOrNull = CommandResponse.fromRequestId(commandRequestId, tenant, deviceId, payload, contentType, responseStatus);
final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, currentSpan.context());
final Future<CommandResponse> commandResponseTracker = cmdResponseOrNull != null ? Future.succeededFuture(cmdResponseOrNull) : Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, String.format("command-request-id [%s] or status code [%s] is missing/invalid", commandRequestId, responseStatus)));
final int payloadSize = Optional.ofNullable(payload).map(Buffer::length).orElse(0);
CompositeFuture.all(tenantTracker, commandResponseTracker).compose(commandResponse -> {
final Future<RegistrationAssertion> deviceRegistrationTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice, currentSpan.context());
final Future<Void> tenantValidationTracker = CompositeFuture.all(isAdapterEnabled(tenantTracker.result()), checkMessageLimit(tenantTracker.result(), payloadSize, currentSpan.context())).map(ok -> null);
return CompositeFuture.all(tenantValidationTracker, deviceRegistrationTracker).compose(ok -> sendCommandResponse(tenantTracker.result(), deviceRegistrationTracker.result(), commandResponseTracker.result(), currentSpan.context())).map(delivery -> {
log.trace("delivered command response [command-request-id: {}] to application", commandRequestId);
currentSpan.log("delivered command response to application");
currentSpan.finish();
metrics.reportCommand(Direction.RESPONSE, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, payloadSize, getMicrometerSample(ctx.getRoutingContext()));
ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
ctx.response().end();
return delivery;
});
}).otherwise(t -> {
log.debug("could not send command response [command-request-id: {}] to application", commandRequestId, t);
TracingHelper.logError(currentSpan, t);
currentSpan.finish();
metrics.reportCommand(Direction.RESPONSE, tenant, tenantTracker.result(), ProcessingOutcome.from(t), payloadSize, getMicrometerSample(ctx.getRoutingContext()));
ctx.fail(t);
return null;
});
}
use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class VertxBasedHttpProtocolAdapter method handlePostTelemetry.
void handlePostTelemetry(final RoutingContext ctx) {
if (Device.class.isInstance(ctx.user())) {
final Device device = (Device) ctx.user();
uploadTelemetryMessage(HttpContext.from(ctx), device.getTenantId(), device.getDeviceId());
} else {
handle401(ctx);
}
}
use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class TelemetryResourceTest method testUploadTelemetryWithQoS1.
/**
* Verifies that the adapter waits for a the AMQP Messaging Network to accept a
* forwarded telemetry message that has been published using a CON message,
* before responding with a 2.04 status to the device.
*/
@Test
public void testUploadTelemetryWithQoS1() {
// GIVEN an adapter with a downstream telemetry consumer attached
givenAnAdapter(properties);
final Promise<Void> outcome = Promise.promise();
givenATelemetrySenderForAnyTenant(outcome);
final var resource = givenAResource(adapter);
// WHEN a device publishes an telemetry message with QoS 1
final Buffer payload = Buffer.buffer("some payload");
final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
final Device authenticatedDevice = new Device("tenant", "device");
final CoapContext context = CoapContext.fromRequest(coapExchange, authenticatedDevice, authenticatedDevice, "device", span);
resource.handlePostRequest(context);
// THEN the message is being forwarded downstream
assertTelemetryMessageHasBeenSentDownstream(QoS.AT_LEAST_ONCE, "tenant", "device", "text/plain");
// and the device does not get a response
verify(coapExchange, never()).respond(any(Response.class));
// until the telemetry message has been accepted
outcome.complete();
verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
verify(metrics).reportTelemetry(eq(MetricsTags.EndpointType.TELEMETRY), eq("tenant"), any(), eq(MetricsTags.ProcessingOutcome.FORWARDED), eq(MetricsTags.QoS.AT_LEAST_ONCE), eq(payload.length()), eq(TtdStatus.NONE), any());
}
use of org.eclipse.hono.auth.Device in project hono by eclipse.
the class TelemetryResourceTest method testUploadTelemetryWithOneWayCommand.
/**
* Verifies that the adapter includes a command in the response to a telemetry request.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadTelemetryWithOneWayCommand(final VertxTestContext ctx) {
// GIVEN an adapter with a downstream telemetry consumer attached
givenAnAdapter(properties);
givenATelemetrySenderForAnyTenant();
final var resource = givenAResource(adapter);
// and a commandConsumerFactory that upon creating a consumer will invoke it with a command
final Sample commandTimer = mock(Sample.class);
final CommandContext commandContext = givenAOneWayCommandContext("tenant", "device", "doThis", null, null);
when(commandContext.get(anyString())).thenReturn(commandTimer);
when(commandConsumerFactory.createCommandConsumer(eq("tenant"), eq("device"), VertxMockSupport.anyHandler(), any(), any())).thenAnswer(invocation -> {
final Handler<CommandContext> consumer = invocation.getArgument(2);
consumer.handle(commandContext);
return Future.succeededFuture(commandConsumer);
});
// WHEN a device publishes a telemetry message with a hono-ttd parameter
final Buffer payload = Buffer.buffer("some payload");
final OptionSet options = new OptionSet();
options.addUriQuery(String.format("%s=%d", Constants.HEADER_TIME_TILL_DISCONNECT, 20));
options.setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, options);
final Device authenticatedDevice = new Device("tenant", "device");
final CoapContext context = CoapContext.fromRequest(coapExchange, authenticatedDevice, authenticatedDevice, "device", span);
resource.handlePostRequest(context).onComplete(ctx.succeeding(ok -> {
ctx.verify(() -> {
// THEN the message is being forwarded downstream
assertTelemetryMessageHasBeenSentDownstream(QoS.AT_LEAST_ONCE, "tenant", "device", "text/plain");
// correctly reported
verify(metrics).reportTelemetry(eq(MetricsTags.EndpointType.TELEMETRY), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(MetricsTags.QoS.AT_LEAST_ONCE), eq(payload.length()), eq(TtdStatus.COMMAND), any());
// and the device gets a response which contains a (one-way) command
verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED == res.getCode() && CommandConstants.COMMAND_ENDPOINT.equals(res.getOptions().getLocationPathString()) && res.getOptions().getLocationQueryString().endsWith("=doThis") && res.getPayloadSize() == 0));
verify(metrics).reportCommand(eq(Direction.ONE_WAY), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(0), eq(commandTimer));
});
ctx.completeNow();
}));
}
Aggregations