Search in sources :

Example 36 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class MongoDbBasedTenantDao method getBySubjectDn.

/**
 * {@inheritDoc}
 */
@Override
public Future<TenantDto> getBySubjectDn(final X500Principal subjectDn, final SpanContext tracingContext) {
    Objects.requireNonNull(subjectDn);
    final String dn = subjectDn.getName(X500Principal.RFC2253);
    final Span span = tracer.buildSpan("get Tenant by subject DN").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_SUBJECT_DN, dn).start();
    return mongoClient.findWithOptions(collectionName, MongoDbDocumentBuilder.builder().withCa(dn).document(), new FindOptions().setLimit(2)).map(matchingDocuments -> {
        if (matchingDocuments.size() == 0) {
            LOG.debug("could not find tenant with matching trust anchor [subject DN: {}]", dn);
            throw new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "no such tenant");
        } else if (matchingDocuments.size() == 1) {
            final JsonObject tenantJsonResult = matchingDocuments.get(0);
            return TenantDto.forRead(tenantJsonResult.getString(Constants.JSON_FIELD_TENANT_ID), tenantJsonResult.getJsonObject(TenantDto.FIELD_TENANT).mapTo(Tenant.class), tenantJsonResult.getInstant(TenantDto.FIELD_CREATED), tenantJsonResult.getInstant(TenantDto.FIELD_UPDATED_ON), tenantJsonResult.getString(TenantDto.FIELD_VERSION));
        } else {
            LOG.debug("found multiple tenants with matching trust anchor [subject DN: {}]", dn);
            throw new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND, "found multiple tenants with matching trust anchor");
        }
    }).onFailure(t -> TracingHelper.logError(span, "error retrieving tenant", t)).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X500Principal(javax.security.auth.x500.X500Principal) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ArrayList(java.util.ArrayList) Status(io.vertx.ext.healthchecks.Status) Sort(org.eclipse.hono.service.management.Sort) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) SearchResult(org.eclipse.hono.service.management.SearchResult) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) FindOptions(io.vertx.ext.mongo.FindOptions) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Example 37 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class MongoDbBasedTenantDao method update.

/**
 * {@inheritDoc}
 */
@Override
public Future<String> update(final TenantDto newTenantConfig, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(newTenantConfig);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("update Tenant").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, newTenantConfig.getTenantId()).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    final JsonObject updateTenantQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(newTenantConfig.getTenantId()).document();
    return validateTrustAnchors(newTenantConfig, span).compose(ok -> mongoClient.findOneAndReplaceWithOptions(collectionName, updateTenantQuery, JsonObject.mapFrom(newTenantConfig), new FindOptions(), new UpdateOptions().setReturningNewDocument(true))).compose(updateResult -> {
        if (updateResult == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(newTenantConfig.getTenantId(), resourceVersion, getById(newTenantConfig.getTenantId(), false, span));
        } else {
            LOG.debug("successfully updated tenant [tenant-id: {}]", newTenantConfig.getTenantId());
            span.log("successfully updated tenant");
            return Future.succeededFuture(updateResult.getString(TenantDto.FIELD_VERSION));
        }
    }).recover(error -> {
        if (MongoDbBasedDao.isDuplicateKeyError(error)) {
            LOG.debug("failed to update tenant [{}], tenant alias already in use", newTenantConfig.getTenantId(), error);
            final var exception = new ClientErrorException(newTenantConfig.getTenantId(), HttpURLConnection.HTTP_CONFLICT, "tenant alias already in use");
            TracingHelper.logError(span, exception);
            return Future.failedFuture(exception);
        } else {
            TracingHelper.logError(span, "error updating tenant", error);
            return mapError(error);
        }
    }).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X500Principal(javax.security.auth.x500.X500Principal) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ArrayList(java.util.ArrayList) Status(io.vertx.ext.healthchecks.Status) Sort(org.eclipse.hono.service.management.Sort) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) SearchResult(org.eclipse.hono.service.management.SearchResult) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) FindOptions(io.vertx.ext.mongo.FindOptions) JsonObject(io.vertx.core.json.JsonObject) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Span(io.opentracing.Span) UpdateOptions(io.vertx.ext.mongo.UpdateOptions)

Example 38 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class MongoDbBasedTenantDao method delete.

/**
 * {@inheritDoc}
 */
@Override
public Future<Void> delete(final String tenantId, final Optional<String> resourceVersion, final SpanContext tracingContext) {
    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(resourceVersion);
    final Span span = tracer.buildSpan("delete Tenant").addReference(References.CHILD_OF, tracingContext).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    resourceVersion.ifPresent(v -> TracingHelper.TAG_RESOURCE_VERSION.set(span, v));
    final JsonObject deleteTenantQuery = MongoDbDocumentBuilder.builder().withVersion(resourceVersion).withTenantId(tenantId).document();
    return mongoClient.findOneAndDelete(collectionName, deleteTenantQuery).compose(deleteResult -> {
        if (deleteResult == null) {
            return MongoDbBasedDao.checkForVersionMismatchAndFail(tenantId, resourceVersion, getById(tenantId, false, span));
        } else {
            LOG.debug("successfully deleted tenant [tenant-id: {}]", tenantId);
            span.log("successfully deleted tenant");
            return Future.succeededFuture((Void) null);
        }
    }).onFailure(t -> TracingHelper.logError(span, "error deleting tenant", t)).recover(this::mapError).onComplete(r -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) X500Principal(javax.security.auth.x500.X500Principal) Filter(org.eclipse.hono.service.management.Filter) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Tenant(org.eclipse.hono.service.management.tenant.Tenant) ArrayList(java.util.ArrayList) Status(io.vertx.ext.healthchecks.Status) Sort(org.eclipse.hono.service.management.Sort) HealthCheckHandler(io.vertx.ext.healthchecks.HealthCheckHandler) HealthCheckProvider(org.eclipse.hono.service.HealthCheckProvider) SearchResult(org.eclipse.hono.service.management.SearchResult) References(io.opentracing.References) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantDto(org.eclipse.hono.service.management.tenant.TenantDto) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Promise(io.vertx.core.Promise) TenantWithId(org.eclipse.hono.service.management.tenant.TenantWithId) MongoClient(io.vertx.ext.mongo.MongoClient) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) SpanContext(io.opentracing.SpanContext) Objects(java.util.Objects) List(java.util.List) IndexOptions(io.vertx.ext.mongo.IndexOptions) Optional(java.util.Optional) Span(io.opentracing.Span) FindOptions(io.vertx.ext.mongo.FindOptions) UpdateOptions(io.vertx.ext.mongo.UpdateOptions) MongoDbDocumentBuilder(org.eclipse.hono.deviceregistry.mongodb.utils.MongoDbDocumentBuilder) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Example 39 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class AbstractJdbcRegistryTest method startDevices.

@BeforeEach
void startDevices(final Vertx vertx) throws IOException, SQLException {
    final var jdbc = resolveJdbcProperties();
    try (var connection = DriverManager.getConnection(jdbc.getUrl(), jdbc.getUsername(), jdbc.getPassword());
        var script = Files.newBufferedReader(EXAMPLE_SQL_BASE.resolve("02-create.devices.sql"))) {
        // pre-create database
        RunScript.execute(connection, script);
    }
    properties = new DeviceServiceProperties();
    this.credentialsAdapter = new CredentialsServiceImpl(DeviceStores.adapterStoreFactory().createTable(vertx, TRACER, jdbc, Optional.empty(), Optional.empty(), Optional.empty()), properties);
    this.registrationAdapter = new RegistrationServiceImpl(DeviceStores.adapterStoreFactory().createTable(vertx, TRACER, jdbc, Optional.empty(), Optional.empty(), Optional.empty()), new NoOpSchemaCreator());
    this.credentialsManagement = new CredentialsManagementServiceImpl(vertx, new SpringBasedHonoPasswordEncoder(properties.getMaxBcryptCostfactor()), DeviceStores.managementStoreFactory().createTable(vertx, TRACER, jdbc, Optional.empty(), Optional.empty(), Optional.empty()), properties);
    this.registrationManagement = new DeviceManagementServiceImpl(vertx, DeviceStores.managementStoreFactory().createTable(vertx, TRACER, jdbc, Optional.empty(), Optional.empty(), Optional.empty()), properties);
    tenantInformationService = mock(TenantInformationService.class);
    when(tenantInformationService.getTenant(anyString(), any())).thenReturn(Future.succeededFuture(new Tenant()));
    when(tenantInformationService.tenantExists(anyString(), any())).thenAnswer(invocation -> {
        return Future.succeededFuture(OperationResult.ok(HttpURLConnection.HTTP_OK, TenantKey.from(invocation.getArgument(0)), Optional.empty(), Optional.empty()));
    });
    registrationManagement.setTenantInformationService(tenantInformationService);
    credentialsManagement.setTenantInformationService(tenantInformationService);
}
Also used : Tenant(org.eclipse.hono.service.management.tenant.Tenant) SpringBasedHonoPasswordEncoder(org.eclipse.hono.auth.SpringBasedHonoPasswordEncoder) TenantInformationService(org.eclipse.hono.deviceregistry.service.tenant.TenantInformationService) DeviceServiceProperties(org.eclipse.hono.deviceregistry.jdbc.config.DeviceServiceProperties) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 40 with Tenant

use of org.eclipse.hono.service.management.tenant.Tenant in project hono by eclipse.

the class ResolveGroupsTest method testResolveGroupsWhenDeleting.

@Test
void testResolveGroupsWhenDeleting(final VertxTestContext context) {
    final var tenantId = UUID.randomUUID().toString();
    Future.succeededFuture().flatMap(x -> this.tenantManagement.createTenant(Optional.of(tenantId), new Tenant(), SPAN)).flatMap(x -> this.registrationManagement.createDevice(tenantId, Optional.of("d1"), new Device().setViaGroups(Collections.singletonList("g1")), SPAN)).flatMap(x -> this.registrationManagement.createDevice(tenantId, Optional.of("gw1"), new Device().setMemberOf(Collections.singletonList("g1")), SPAN)).flatMap(x -> this.registrationManagement.createDevice(tenantId, Optional.of("gw2"), new Device().setMemberOf(Collections.singletonList("g1")), SPAN)).flatMap(x -> this.registrationAdapter.assertRegistration(tenantId, "d1", "gw1").onComplete(context.succeeding(result -> {
        context.verify(() -> {
            assertThat(result.isOk()).isTrue();
            assertThat(result.getPayload()).isNotNull();
            assertThat(result.getPayload().getJsonArray(RegistrationConstants.FIELD_VIA)).containsExactly("gw1", "gw2");
        });
    }))).flatMap(x -> this.registrationManagement.deleteDevice(tenantId, "gw1", Optional.empty(), SPAN)).flatMap(x -> this.registrationAdapter.assertRegistration(tenantId, "d1", "gw2").onComplete(context.succeeding(result -> {
        context.verify(() -> {
            assertThat(result.isOk()).isTrue();
            assertThat(result.getPayload()).isNotNull();
            assertThat(result.getPayload().getJsonArray(RegistrationConstants.FIELD_VIA)).containsExactly("gw2");
        });
    }))).flatMap(x -> this.registrationManagement.deleteDevice(tenantId, "gw2", Optional.empty(), SPAN)).flatMap(x -> this.registrationAdapter.assertRegistration(tenantId, "d1", "gw2").onComplete(context.succeeding(result -> {
        context.verify(() -> {
            assertThat(result.isOk()).isFalse();
        });
    }))).onComplete(context.succeedingThenComplete());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) Arrays(java.util.Arrays) Device(org.eclipse.hono.service.management.device.Device) Set(java.util.Set) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) UUID(java.util.UUID) Truth.assertThat(com.google.common.truth.Truth.assertThat) VertxExtension(io.vertx.junit5.VertxExtension) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) HashSet(java.util.HashSet) Test(org.junit.jupiter.api.Test) CompositeFuture(io.vertx.core.CompositeFuture) List(java.util.List) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Optional(java.util.Optional) OperationResult(org.eclipse.hono.service.management.OperationResult) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Device(org.eclipse.hono.service.management.device.Device) Test(org.junit.jupiter.api.Test)

Aggregations

Tenant (org.eclipse.hono.service.management.tenant.Tenant)165 Test (org.junit.jupiter.api.Test)138 VertxTestContext (io.vertx.junit5.VertxTestContext)137 HttpURLConnection (java.net.HttpURLConnection)122 Truth.assertThat (com.google.common.truth.Truth.assertThat)113 TimeUnit (java.util.concurrent.TimeUnit)109 JsonObject (io.vertx.core.json.JsonObject)108 Future (io.vertx.core.Future)107 Timeout (io.vertx.junit5.Timeout)99 IntegrationTestSupport (org.eclipse.hono.tests.IntegrationTestSupport)98 RegistryManagementConstants (org.eclipse.hono.util.RegistryManagementConstants)97 Constants (org.eclipse.hono.util.Constants)95 Tenants (org.eclipse.hono.tests.Tenants)92 Optional (java.util.Optional)91 Promise (io.vertx.core.Promise)86 Device (org.eclipse.hono.service.management.device.Device)80 Adapter (org.eclipse.hono.util.Adapter)78 VertxExtension (io.vertx.junit5.VertxExtension)77 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)77 Logger (org.slf4j.Logger)74