Search in sources :

Example 1 with DeviceDisabledOrNotRegisteredException

use of org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException in project hono by eclipse.

the class AbstractProtocolAdapterBase method getRegistrationAssertion.

@Override
public final Future<RegistrationAssertion> getRegistrationAssertion(final String tenantId, final String deviceId, final Device authenticatedDevice, final SpanContext context) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    final Future<String> gatewayId = getGatewayId(tenantId, deviceId, authenticatedDevice);
    return gatewayId.compose(gwId -> getRegistrationClient().assertRegistration(tenantId, deviceId, gwId, context)).onSuccess(assertion -> {
        // the updateLastGateway invocation shouldn't delay or possibly fail the surrounding operation
        // so don't wait for the outcome here
        updateLastGateway(assertion, tenantId, deviceId, authenticatedDevice, context).onFailure(t -> {
            log.warn("failed to update last gateway [tenantId: {}, deviceId: {}]", tenantId, deviceId, t);
        });
    }).recover(error -> {
        final int errorCode = ServiceInvocationException.extractStatusCode(error);
        if (errorCode == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(new DeviceDisabledOrNotRegisteredException(tenantId, errorCode));
        } else if (errorCode == HttpURLConnection.HTTP_FORBIDDEN) {
            return Future.failedFuture(new GatewayDisabledOrNotRegisteredException(tenantId, errorCode));
        } else {
            return Future.failedFuture(error);
        }
    });
}
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) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) GatewayDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.GatewayDisabledOrNotRegisteredException)

Example 2 with DeviceDisabledOrNotRegisteredException

use of org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException in project hono by eclipse.

the class AbstractMappingAndDelegatingCommandHandler method mapAndDelegateIncomingCommand.

/**
 * Delegates an incoming command to the protocol adapter instance that the target
 * device is connected to.
 * <p>
 * Determines the target gateway (if applicable) and protocol adapter instance for an incoming command
 * and delegates the command to the resulting protocol adapter instance.
 *
 * @param commandContext The context of the command to send.
 * @param timer The timer indicating the amount of time used for processing the command message.
 * @return A future indicating the outcome of the operation.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
protected final Future<Void> mapAndDelegateIncomingCommand(final CommandContext commandContext, final Timer.Sample timer) {
    Objects.requireNonNull(commandContext);
    Objects.requireNonNull(timer);
    final Command command = commandContext.getCommand();
    // determine last used gateway device id
    if (log.isTraceEnabled()) {
        log.trace("determine command target gateway/adapter for [{}]", command);
    }
    final Future<TenantObject> tenantObjectFuture = tenantClient.get(command.getTenant(), commandContext.getTracingContext());
    return tenantObjectFuture.compose(tenantObject -> {
        TenantTraceSamplingHelper.applyTraceSamplingPriority(tenantObject, null, commandContext.getTracingSpan());
        commandContext.put(CommandContext.KEY_TENANT_CONFIG, tenantObject);
        // check whether the handler messaging type is equal to the messaging type of the tenant (if set)
        final MessagingType tenantMessagingType = Optional.ofNullable(tenantObject.getProperty(TenantConstants.FIELD_EXT, JsonObject.class)).map(ext -> ext.getString(TenantConstants.FIELD_EXT_MESSAGING_TYPE)).map(MessagingType::valueOf).orElse(null);
        if (tenantMessagingType != null && getMessagingType() != tenantMessagingType) {
            log.info("command received via {} but tenant is configured to use {} [{}]", getMessagingType(), tenantMessagingType, commandContext.getCommand());
            commandContext.getTracingSpan().log(String.format("command received via %s but tenant is configured to use %s", getMessagingType(), tenantMessagingType));
        }
        return commandTargetMapper.getTargetGatewayAndAdapterInstance(command.getTenant(), command.getDeviceId(), commandContext.getTracingContext());
    }).recover(cause -> {
        final Throwable error;
        if (tenantObjectFuture.failed() && ServiceInvocationException.extractStatusCode(cause) == HttpURLConnection.HTTP_NOT_FOUND) {
            error = new TenantDisabledOrNotRegisteredException(command.getTenant(), HttpURLConnection.HTTP_NOT_FOUND);
        } else if (cause instanceof DeviceDisabledOrNotRegisteredException) {
            error = cause;
        } else if (ServiceInvocationException.extractStatusCode(cause) == HttpURLConnection.HTTP_NOT_FOUND) {
            log.debug("no target adapter instance found for command with device id " + command.getDeviceId(), cause);
            error = new NoConsumerException("no target adapter instance found");
        } else {
            log.debug("error getting target gateway and adapter instance for command with device id " + command.getDeviceId(), cause);
            error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "error getting target gateway and adapter instance", cause);
        }
        if (error instanceof ClientErrorException) {
            commandContext.reject(error);
        } else {
            commandContext.release(error);
        }
        reportCommandProcessingError(command, tenantObjectFuture.result(), error, timer);
        return Future.failedFuture(cause);
    }).compose(result -> {
        final String targetAdapterInstanceId = result.getString(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID);
        final String targetDeviceId = result.getString(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID);
        final String targetGatewayId = targetDeviceId.equals(command.getDeviceId()) ? null : targetDeviceId;
        if (Objects.isNull(targetGatewayId)) {
            log.trace("determined target adapter instance [{}] for [{}] (command not mapped to gateway)", targetAdapterInstanceId, command);
        } else {
            command.setGatewayId(targetGatewayId);
            log.trace("determined target gateway [{}] and adapter instance [{}] for [{}]", targetGatewayId, targetAdapterInstanceId, command);
            commandContext.getTracingSpan().log("determined target gateway [" + targetGatewayId + "]");
        }
        return sendCommand(commandContext, targetAdapterInstanceId, tenantObjectFuture.result(), timer);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InternalCommandSender(org.eclipse.hono.client.command.InternalCommandSender) Command(org.eclipse.hono.client.command.Command) TenantConstants(org.eclipse.hono.util.TenantConstants) Lifecycle(org.eclipse.hono.util.Lifecycle) LoggerFactory(org.slf4j.LoggerFactory) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) NoConsumerException(org.eclipse.hono.client.NoConsumerException) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) MessagingType(org.eclipse.hono.util.MessagingType) Timer(io.micrometer.core.instrument.Timer) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) DeviceConnectionConstants(org.eclipse.hono.util.DeviceConnectionConstants) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) ServerErrorException(org.eclipse.hono.client.ServerErrorException) CommandTargetMapper(org.eclipse.hono.commandrouter.CommandTargetMapper) TenantClient(org.eclipse.hono.client.registry.TenantClient) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) CommandRouterMetrics(org.eclipse.hono.commandrouter.CommandRouterMetrics) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) Optional(java.util.Optional) Span(io.opentracing.Span) TenantObject(org.eclipse.hono.util.TenantObject) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) Command(org.eclipse.hono.client.command.Command) NoConsumerException(org.eclipse.hono.client.NoConsumerException) MessagingType(org.eclipse.hono.util.MessagingType) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 3 with DeviceDisabledOrNotRegisteredException

use of org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException in project hono by eclipse.

the class CommandTargetMapperImpl method getTargetGatewayAndAdapterInstance.

@Override
public final Future<JsonObject> getTargetGatewayAndAdapterInstance(final String tenantId, final String deviceId, final SpanContext context) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    final Span span = TracingHelper.buildChildSpan(tracer, context, "get target gateway and adapter instance", CommandTargetMapper.class.getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER).withTag(TracingHelper.TAG_TENANT_ID, tenantId).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).start();
    return registrationClient.assertRegistration(tenantId, deviceId, null, span.context()).map(RegistrationAssertion::getAuthorizedGateways).recover(t -> {
        LOG.debug("Error retrieving gateways authorized to act on behalf of device [tenant-id: {}, device-id: {}]", tenantId, deviceId, t);
        return Future.failedFuture(ServiceInvocationException.extractStatusCode(t) == HttpURLConnection.HTTP_NOT_FOUND ? new DeviceDisabledOrNotRegisteredException(tenantId, HttpURLConnection.HTTP_NOT_FOUND) : t);
    }).compose(viaGateways -> {
        return deviceConnectionInfo.getCommandHandlingAdapterInstances(tenantId, deviceId, new HashSet<>(viaGateways), span).compose(resultJson -> determineTargetInstanceJson(resultJson, deviceId, viaGateways, span));
    }).onFailure(t -> {
        LOG.debug("Error getting target gateway and adapter instance", t);
        TracingHelper.logError(span, t);
        Tags.HTTP_STATUS.set(span, ServiceInvocationException.extractStatusCode(t));
    }).onComplete(ar -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) DeviceConnectionConstants(org.eclipse.hono.util.DeviceConnectionConstants) LoggerFactory(org.slf4j.LoggerFactory) ServerErrorException(org.eclipse.hono.client.ServerErrorException) CommandTargetMapper(org.eclipse.hono.commandrouter.CommandTargetMapper) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) MessageHelper(org.eclipse.hono.util.MessageHelper) Tags(io.opentracing.tag.Tags) Future(io.vertx.core.Future) DeviceConnectionInfo(org.eclipse.hono.deviceconnection.infinispan.client.DeviceConnectionInfo) SpanContext(io.opentracing.SpanContext) HashSet(java.util.HashSet) Objects(java.util.Objects) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) DeviceRegistrationClient(org.eclipse.hono.client.registry.DeviceRegistrationClient) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) CommandTargetMapper(org.eclipse.hono.commandrouter.CommandTargetMapper) DeviceDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Span(io.opentracing.Span) HashSet(java.util.HashSet)

Aggregations

SpanContext (io.opentracing.SpanContext)3 Future (io.vertx.core.Future)3 JsonObject (io.vertx.core.json.JsonObject)3 HttpURLConnection (java.net.HttpURLConnection)3 Objects (java.util.Objects)3 ServiceInvocationException (org.eclipse.hono.client.ServiceInvocationException)3 DeviceDisabledOrNotRegisteredException (org.eclipse.hono.client.registry.DeviceDisabledOrNotRegisteredException)3 Span (io.opentracing.Span)2 Tracer (io.opentracing.Tracer)2 Tags (io.opentracing.tag.Tags)2 List (java.util.List)2 Optional (java.util.Optional)2 ClientErrorException (org.eclipse.hono.client.ClientErrorException)2 ServerErrorException (org.eclipse.hono.client.ServerErrorException)2 CommandContext (org.eclipse.hono.client.command.CommandContext)2 DeviceRegistrationClient (org.eclipse.hono.client.registry.DeviceRegistrationClient)2 TenantClient (org.eclipse.hono.client.registry.TenantClient)2 TenantDisabledOrNotRegisteredException (org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException)2 CommandTargetMapper (org.eclipse.hono.commandrouter.CommandTargetMapper)2 TracingHelper (org.eclipse.hono.tracing.TracingHelper)2