Search in sources :

Example 6 with Result

use of org.eclipse.hono.service.management.Result in project hono by eclipse.

the class AbstractDeviceManagementService method deleteDevice.

@Override
public final Future<Result<Void>> deleteDevice(final String tenantId, final String deviceId, final Optional<String> resourceVersion, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(resourceVersion);
    Objects.requireNonNull(span);
    return this.tenantInformationService.tenantExists(tenantId, span).otherwise(t -> Result.from(ServiceInvocationException.extractStatusCode(t))).compose(result -> {
        switch(result.getStatus()) {
            case HttpURLConnection.HTTP_OK:
                break;
            case HttpURLConnection.HTTP_NOT_FOUND:
                span.log("tenant does not exist (anymore)");
                LOG.info("trying to delete device of non-existing tenant [tenant-id: {}, device-id: {}]", tenantId, deviceId);
                break;
            default:
                span.log(Map.of(Fields.EVENT, "could not determine tenant status", Tags.HTTP_STATUS.getKey(), result.getStatus()));
                LOG.info("could not determine tenant status [tenant-id: {}, code: {}]", tenantId, result.getStatus());
        }
        return processDeleteDevice(DeviceKey.from(tenantId, deviceId), resourceVersion, span);
    }).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new DeviceChangeNotification(LifecycleChange.DELETE, tenantId, deviceId, Instant.now(), false))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) DeviceManagementService(org.eclipse.hono.service.management.device.DeviceManagementService) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) Map(java.util.Map) Fields(io.opentracing.log.Fields) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) NoopTenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.NoopTenantInformationService) Device(org.eclipse.hono.service.management.device.Device) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) UUID(java.util.UUID) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification)

Example 7 with Result

use of org.eclipse.hono.service.management.Result in project hono by eclipse.

the class AbstractDeviceManagementService method createDevice.

@Override
public final Future<OperationResult<Id>> createDevice(final String tenantId, final Optional<String> deviceId, final Device device, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(device);
    Objects.requireNonNull(span);
    final String deviceIdValue = deviceId.orElseGet(() -> generateDeviceId(tenantId));
    return this.tenantInformationService.tenantExists(tenantId, span).compose(result -> result.isError() ? Future.failedFuture(ServiceInvocationException.create(tenantId, result.getStatus(), "tenant does not exist", null)) : processCreateDevice(DeviceKey.from(result.getPayload(), deviceIdValue), device, span)).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new DeviceChangeNotification(LifecycleChange.CREATE, tenantId, deviceIdValue, Instant.now(), device.isEnabled()))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Tags(io.opentracing.tag.Tags) DeviceManagementService(org.eclipse.hono.service.management.device.DeviceManagementService) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) Map(java.util.Map) Fields(io.opentracing.log.Fields) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) AllDevicesOfTenantDeletedNotification(org.eclipse.hono.notification.deviceregistry.AllDevicesOfTenantDeletedNotification) NoopTenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.NoopTenantInformationService) Device(org.eclipse.hono.service.management.device.Device) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) UUID(java.util.UUID) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) DeviceChangeNotification(org.eclipse.hono.notification.deviceregistry.DeviceChangeNotification)

Example 8 with Result

use of org.eclipse.hono.service.management.Result in project hono by eclipse.

the class AbstractTenantManagementService method updateTenant.

@Override
public final Future<OperationResult<Void>> updateTenant(final String tenantId, final Tenant tenantObj, final Optional<String> resourceVersion, final Span span) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantObj);
    Objects.requireNonNull(resourceVersion);
    Objects.requireNonNull(span);
    final Promise<Void> tenantCheck = Promise.promise();
    try {
        tenantObj.assertTrustAnchorIdUniquenessAndCreateMissingIds();
        tenantCheck.complete();
    } catch (final IllegalStateException e) {
        log.debug("error updating tenant", e);
        TracingHelper.logError(span, e);
        tenantCheck.fail(new ClientErrorException(tenantId, HttpURLConnection.HTTP_BAD_REQUEST, e.getMessage()));
    }
    return tenantCheck.future().compose(ok -> processUpdateTenant(tenantId, tenantObj, resourceVersion, span)).onSuccess(result -> NotificationEventBusSupport.sendNotification(vertx, new TenantChangeNotification(LifecycleChange.UPDATE, tenantId, Instant.now(), tenantObj.isEnabled()))).recover(t -> DeviceRegistryUtils.mapError(t, tenantId));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LifecycleChange(org.eclipse.hono.notification.deviceregistry.LifecycleChange) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Sort(org.eclipse.hono.service.management.Sort) SearchResult(org.eclipse.hono.service.management.SearchResult) TenantManagementService(org.eclipse.hono.service.management.tenant.TenantManagementService) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Instant(java.time.Instant) Result(org.eclipse.hono.service.management.Result) Future(io.vertx.core.Future) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Span(io.opentracing.Span) NotificationEventBusSupport(org.eclipse.hono.notification.NotificationEventBusSupport) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Id(org.eclipse.hono.service.management.Id) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantChangeNotification(org.eclipse.hono.notification.deviceregistry.TenantChangeNotification)

Example 9 with Result

use of org.eclipse.hono.service.management.Result in project hono by eclipse.

the class DeviceAndGatewayAutoProvisionerTest method testProvisionFailsWhenEventNotificationFails.

@SuppressWarnings("unchecked")
private void testProvisionFailsWhenEventNotificationFails(final VertxTestContext ctx, final boolean isGateway, final String expectedDeviceId) throws CertificateEncodingException {
    configureTenant(isGateway, null);
    final JsonObject clientContext = new JsonObject().put(CredentialsConstants.FIELD_CLIENT_CERT, cert.getEncoded());
    when(deviceManagementService.createDevice(eq(tenantId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.ok(HttpURLConnection.HTTP_CREATED, Id.of(deviceId), Optional.empty(), Optional.empty())));
    when(deviceManagementService.updateDevice(eq(tenantId), eq(expectedDeviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_NO_CONTENT)));
    when(credentialsManagementService.updateCredentials(eq(tenantId), eq(expectedDeviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_NO_CONTENT)));
    // WHEN sending an auto-provisioning event fails
    when(sender.sendEvent(any(TenantObject.class), any(RegistrationAssertion.class), anyString(), any(), any(Map.class), any())).thenReturn(Future.failedFuture(ServiceInvocationException.create(HttpURLConnection.HTTP_INTERNAL_ERROR, "error sending event")));
    // WHEN provisioning a device/gateway from a certificate
    deviceAndGatewayAutoProvisioner.provisionIfEnabled(tenantId, tenant, subjectDn, clientContext, NoopSpan.INSTANCE).onComplete(ctx.succeeding(result -> {
        // VERIFY that the status code corresponds to an error.
        assertThat(result.isError()).isTrue();
        assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR);
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) BeforeEach(org.junit.jupiter.api.BeforeEach) CredentialsManagementService(org.eclipse.hono.service.management.credentials.CredentialsManagementService) CertificateFactory(java.security.cert.CertificateFactory) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Tenant(org.eclipse.hono.service.management.tenant.Tenant) GeneralSecurityException(java.security.GeneralSecurityException) MessagingType(org.eclipse.hono.util.MessagingType) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TrustedCertificateAuthority(org.eclipse.hono.service.management.tenant.TrustedCertificateAuthority) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) EventSender(org.eclipse.hono.client.telemetry.EventSender) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) UUID(java.util.UUID) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Id(org.eclipse.hono.service.management.Id) Mockito.mock(org.mockito.Mockito.mock) CertificateEncodingException(java.security.cert.CertificateEncodingException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) X500Principal(javax.security.auth.x500.X500Principal) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ArgumentCaptor(org.mockito.ArgumentCaptor) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MessagingClientProvider(org.eclipse.hono.client.util.MessagingClientProvider) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) FileInputStream(java.io.FileInputStream) Truth.assertThat(com.google.common.truth.Truth.assertThat) Result(org.eclipse.hono.service.management.Result) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Mockito.verify(org.mockito.Mockito.verify) TenantObject(org.eclipse.hono.util.TenantObject) Mockito.never(org.mockito.Mockito.never) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) NoopSpan(io.opentracing.noop.NoopSpan) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) JsonObject(io.vertx.core.json.JsonObject) Map(java.util.Map)

Example 10 with Result

use of org.eclipse.hono.service.management.Result in project hono by eclipse.

the class DeviceAndGatewayAutoProvisionerTest method testDeviceRegistrationIsRemovedWhenAutoProvisionFails.

/**
 * Verifies that if auto-provisioning fails, then the device registered during auto-provisioning process is removed.
 *
 * @param ctx The vert.x test context.
 * @throws CertificateEncodingException if the certificate cannot be encoded.
 */
@Test
public void testDeviceRegistrationIsRemovedWhenAutoProvisionFails(final VertxTestContext ctx) throws CertificateEncodingException {
    // GIVEN a tenant CA with auto-provisioning enabled
    tenant.getTrustedCertificateAuthorities().get(0).setAutoProvisioningEnabled(true);
    final JsonObject clientContext = new JsonObject().put(CredentialsConstants.FIELD_CLIENT_CERT, cert.getEncoded());
    when(deviceManagementService.createDevice(eq(tenantId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.ok(HttpURLConnection.HTTP_CREATED, Id.of(deviceId), Optional.empty(), Optional.empty())));
    when(credentialsManagementService.updateCredentials(eq(tenantId), eq(deviceId), any(), any(), any())).thenReturn(Future.succeededFuture(OperationResult.empty(HttpURLConnection.HTTP_INTERNAL_ERROR)));
    when(deviceManagementService.deleteDevice(eq(tenantId), eq(deviceId), any(), any())).thenReturn(Future.succeededFuture(Result.from(HttpURLConnection.HTTP_NO_CONTENT)));
    // WHEN provisioning a device from a certificate
    deviceAndGatewayAutoProvisioner.provisionIfEnabled(tenantId, tenant, subjectDn, clientContext, NoopSpan.INSTANCE).onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // THEN the device is registered
            verify(deviceManagementService).createDevice(eq(tenantId), any(), any(), any());
            // WHEN update credentials fails
            verify(credentialsManagementService).updateCredentials(eq(tenantId), eq(deviceId), any(), any(), any());
            // THEN the device registration is deleted
            verify(deviceManagementService).deleteDevice(eq(tenantId), eq(deviceId), any(), any());
            assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_INTERNAL_ERROR);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X509Certificate(java.security.cert.X509Certificate) BeforeEach(org.junit.jupiter.api.BeforeEach) CredentialsManagementService(org.eclipse.hono.service.management.credentials.CredentialsManagementService) CertificateFactory(java.security.cert.CertificateFactory) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Tenant(org.eclipse.hono.service.management.tenant.Tenant) GeneralSecurityException(java.security.GeneralSecurityException) MessagingType(org.eclipse.hono.util.MessagingType) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TrustedCertificateAuthority(org.eclipse.hono.service.management.tenant.TrustedCertificateAuthority) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) EventSender(org.eclipse.hono.client.telemetry.EventSender) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) UUID(java.util.UUID) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) Id(org.eclipse.hono.service.management.Id) Mockito.mock(org.mockito.Mockito.mock) CertificateEncodingException(java.security.cert.CertificateEncodingException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) X500Principal(javax.security.auth.x500.X500Principal) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) ArgumentCaptor(org.mockito.ArgumentCaptor) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) MessagingClientProvider(org.eclipse.hono.client.util.MessagingClientProvider) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) FileInputStream(java.io.FileInputStream) Truth.assertThat(com.google.common.truth.Truth.assertThat) Result(org.eclipse.hono.service.management.Result) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Mockito.verify(org.mockito.Mockito.verify) TenantObject(org.eclipse.hono.util.TenantObject) Mockito.never(org.mockito.Mockito.never) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) NoopSpan(io.opentracing.noop.NoopSpan) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Aggregations

Future (io.vertx.core.Future)18 HttpURLConnection (java.net.HttpURLConnection)18 Optional (java.util.Optional)18 OperationResult (org.eclipse.hono.service.management.OperationResult)18 Result (org.eclipse.hono.service.management.Result)18 Vertx (io.vertx.core.Vertx)17 Id (org.eclipse.hono.service.management.Id)17 Span (io.opentracing.Span)15 NotificationEventBusSupport (org.eclipse.hono.notification.NotificationEventBusSupport)14 LifecycleChange (org.eclipse.hono.notification.deviceregistry.LifecycleChange)14 Truth.assertThat (com.google.common.truth.Truth.assertThat)11 VertxExtension (io.vertx.junit5.VertxExtension)11 VertxTestContext (io.vertx.junit5.VertxTestContext)11 List (java.util.List)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 Test (org.junit.jupiter.api.Test)11 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)11 ArgumentCaptor (org.mockito.ArgumentCaptor)11 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)11 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)11