Search in sources :

Example 1 with Versioned

use of org.eclipse.hono.deviceregistry.util.Versioned in project hono by eclipse.

the class ManagementStore method create.

/**
 * Create a new tenant.
 * <p>
 * The operation may fail with a {@link org.eclipse.hono.service.base.jdbc.store.DuplicateKeyException} if a
 * tenant with the ID or trust anchor already exists.
 *
 * @param tenantId The ID of the new tenant.
 * @param tenant The tenant information.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Void>> create(final String tenantId, final Tenant tenant, final SpanContext spanContext) {
    final var json = tenantToJson(tenant);
    final var version = UUID.randomUUID().toString();
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "create tenant", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> {
        final var expanded = this.createStatement.expand(params -> {
            params.put("tenant_id", tenantId);
            params.put("version", version);
            params.put("data", json);
        });
        log.debug("create - statement: {}", expanded);
        return expanded.trace(this.tracer, span.context()).update(this.client).recover(SQL::translateException).flatMap(r -> insertAllTrustAnchors(connection, tenantId, tenant, span));
    }).map(new Versioned<Void>(version, null)).onComplete(x -> span.finish());
}
Also used : Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Span(io.opentracing.Span)

Example 2 with Versioned

use of org.eclipse.hono.deviceregistry.util.Versioned in project hono by eclipse.

the class ManagementStore method update.

/**
 * Create a new tenant.
 * <p>
 * The operation may fail with a {@link org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException} if the
 * specified tenant does not exist.
 * <p>
 * The operation may fail with a {@link org.eclipse.hono.service.base.jdbc.store.DuplicateKeyException} if a
 * tenant with the ID or trust anchor already exists.
 * <p>
 * The operation may fail with an {@link org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException} if
 * an expected resource version was provided, but the current version did not match.
 *
 * @param tenantId The ID of the new tenant.
 * @param tenant The tenant information.
 * @param resourceVersion An optional resource version.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Void>> update(final String tenantId, final Tenant tenant, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final var json = tenantToJson(tenant);
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "update tenant", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, tenantId).start();
    final var nextVersion = UUID.randomUUID().toString();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final Statement statement = resourceVersion.isPresent() ? this.updateVersionedStatement : this.updateStatement;
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> updateJsonField(connection, tenantId, statement, json, resourceVersion, nextVersion, span).flatMap(r -> {
        if (r.getUpdated() <= 0) {
            return Future.failedFuture(new EntityNotFoundException());
        } else {
            return Future.succeededFuture();
        }
    }).flatMap(x -> deleteAllTrustAnchors(connection, tenantId, span)).flatMap(r -> insertAllTrustAnchors(connection, tenantId, tenant, span))).map(new Versioned<Void>(nextVersion, null)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) TenantConstants(org.eclipse.hono.util.TenantConstants) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Future(io.vertx.core.Future) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) SpanContext(io.opentracing.SpanContext) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JDBCClient(io.vertx.ext.jdbc.JDBCClient) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) SQLOperations(io.vertx.ext.sql.SQLOperations) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) Span(io.opentracing.Span)

Example 3 with Versioned

use of org.eclipse.hono.deviceregistry.util.Versioned in project hono by eclipse.

the class TableManagementStore method updateDevice.

/**
 * Update device registration information.
 * <p>
 * This called the {@link #updateJsonField(DeviceKey, Statement, String, Optional, String, Span)} method
 * with either the {@code updateRegistration} or {@code updateRegistrationVersioned}
 * statement.
 *
 * @param key The key of the device to update.
 * @param device The device data to store.
 * @param resourceVersion The optional resource version.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Void>> updateDevice(final DeviceKey key, final Device device, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "update device", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, key.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, key.getDeviceId()).start();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final var memberOf = Optional.ofNullable(device.getMemberOf()).<Set<String>>map(HashSet::new).orElse(Collections.emptySet());
    final JdbcBasedDeviceDto deviceDto = JdbcBasedDeviceDto.forUpdate(key, device, DeviceRegistryUtils.getUniqueIdentifier());
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> readDeviceForUpdate(connection, key, context).compose(result -> extractVersionForUpdate(result, resourceVersion)).compose(version -> deleteGroups(connection, key, context).map(version)).compose(version -> createGroups(connection, key, memberOf, context).map(version)).compose(version -> this.updateRegistrationVersionedStatement.expand(map -> {
        map.put("tenant_id", deviceDto.getTenantId());
        map.put("device_id", deviceDto.getDeviceId());
        map.put("data", deviceDto.getDeviceJson());
        map.put("expected_version", version);
        map.put("next_version", deviceDto.getVersion());
        map.put("updated_on", Timestamp.from(deviceDto.getUpdatedOn()));
        map.put("auto_provisioning_notification_sent", deviceDto.isAutoProvisioningNotificationSent());
    }).trace(this.tracer, span.context()).update(connection).compose(TableManagementStore::checkUpdateOutcome).map(version))).map(x -> new Versioned<Void>(deviceDto.getVersion(), null)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Json(io.vertx.core.json.Json) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) LoggerFactory(org.slf4j.LoggerFactory) Supplier(java.util.function.Supplier) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Map(java.util.Map) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Timestamp(java.sql.Timestamp) Promise(io.vertx.core.Promise) Set(java.util.Set) DeviceKey(org.eclipse.hono.deviceregistry.service.device.DeviceKey) OptimisticLockingException(org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException) 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) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JDBCClient(io.vertx.ext.jdbc.JDBCClient) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) ResultSet(io.vertx.ext.sql.ResultSet) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Collections(java.util.Collections) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) Span(io.opentracing.Span)

Example 4 with Versioned

use of org.eclipse.hono.deviceregistry.util.Versioned in project hono by eclipse.

the class TableManagementStore method setCredentials.

/**
 * Set all credentials for a device.
 * <p>
 * This will set/update all credentials of the device. If the device does not exist, the result
 * will be {@code false}. If the update was successful, then the result will be {@code true}.
 * If the resource version was provided, but the provided version was no longer the current version,
 * then the future will fail with a {@link OptimisticLockingException}.
 *
 * @param key The key of the device to update.
 * @param credentials The credentials to set.
 * @param resourceVersion The optional resource version to update.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Boolean>> setCredentials(final DeviceKey key, final List<CommonCredential> credentials, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "set credentials", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, key.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, key.getDeviceId()).withTag("num_credentials", credentials.size()).start();
    resourceVersion.ifPresent(version -> span.setTag("version", version));
    final String nextVersion = UUID.randomUUID().toString();
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> readDeviceForUpdate(connection, key, context).compose(result -> extractVersionForUpdate(result, resourceVersion)).compose(version -> Future.succeededFuture().compose(x -> {
        final Promise<CredentialsDto> result = Promise.promise();
        final var updatedCredentialsDto = CredentialsDto.forUpdate(key.getTenantId(), key.getDeviceId(), credentials, nextVersion);
        if (updatedCredentialsDto.requiresMerging()) {
            getCredentialsDto(key, connection, span).map(updatedCredentialsDto::merge).onComplete(result);
        } else {
            // simply replace the existing credentials with the
            // updated ones provided by the client
            result.complete(updatedCredentialsDto);
        }
        return result.future();
    }).compose(updatedCredentials -> this.deleteAllCredentialsStatement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
    }).trace(this.tracer, span.context()).update(connection).map(updatedCredentials)).compose(updatedCredentials -> {
        updatedCredentials.createMissingSecretIds();
        return CompositeFuture.all(updatedCredentials.getData().stream().map(JsonObject::mapFrom).filter(c -> c.containsKey("type") && c.containsKey("auth-id")).map(c -> this.insertCredentialEntryStatement.expand(map -> {
            map.put("tenant_id", key.getTenantId());
            map.put("device_id", key.getDeviceId());
            map.put("type", c.getString("type"));
            map.put("auth_id", c.getString("auth-id"));
            map.put("data", c.toString());
        }).trace(this.tracer, span.context()).update(connection)).collect(Collectors.toList())).mapEmpty();
    }).compose(x -> this.updateDeviceVersionStatement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
        map.put("expected_version", version);
        map.put("next_version", nextVersion);
    }).trace(this.tracer, span.context()).update(connection).compose(TableManagementStore::checkUpdateOutcome)).map(true))).recover(err -> recoverNotFound(span, err, () -> false)).map(ok -> new Versioned<>(nextVersion, ok)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Json(io.vertx.core.json.Json) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) LoggerFactory(org.slf4j.LoggerFactory) Supplier(java.util.function.Supplier) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Map(java.util.Map) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Timestamp(java.sql.Timestamp) Promise(io.vertx.core.Promise) Set(java.util.Set) DeviceKey(org.eclipse.hono.deviceregistry.service.device.DeviceKey) OptimisticLockingException(org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException) 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) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JDBCClient(io.vertx.ext.jdbc.JDBCClient) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) ResultSet(io.vertx.ext.sql.ResultSet) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Collections(java.util.Collections) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Promise(io.vertx.core.Promise) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JsonObject(io.vertx.core.json.JsonObject) Span(io.opentracing.Span)

Example 5 with Versioned

use of org.eclipse.hono.deviceregistry.util.Versioned in project hono by eclipse.

the class TableManagementStore method createDevice.

/**
 * Creates a new device.
 * <p>
 * This method executes the {@code create} statement, providing the named parameters
 * {@code tenant_id}, {@code device_id}, {@code version}, and {@code data}.
 * <p>
 * It returns the plain update result. In case a device with the same ID already
 * exists, the underlying database must throw an {@link java.sql.SQLException}, indicating
 * a duplicate entity or constraint violation. This will be translated into a
 * failed future with an {@link org.eclipse.hono.service.base.jdbc.store.DuplicateKeyException}.
 *
 * @param key The key of the device to create.
 * @param device The device data.
 * @param tenant The configuration of the tenant that the device belongs to.
 * @param globalDevicesPerTenantLimit The globally defined maximum number of devices per tenant. A value
 *                                    &lt;= 0 will be interpreted as no limit being defined.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Versioned<Void>> createDevice(final DeviceKey key, final Device device, final Tenant tenant, final int globalDevicesPerTenantLimit, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "create device", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, key.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, key.getDeviceId()).start();
    final JdbcBasedDeviceDto deviceDto = JdbcBasedDeviceDto.forCreation(key, device, DeviceRegistryUtils.getUniqueIdentifier());
    return SQL.runTransactionally(this.client, this.tracer, span.context(), (connection, context) -> {
        final var expanded = this.createStatement.expand(params -> {
            params.put("tenant_id", deviceDto.getTenantId());
            params.put("device_id", deviceDto.getDeviceId());
            params.put("version", deviceDto.getVersion());
            params.put("data", deviceDto.getDeviceJson());
            params.put("created", Timestamp.from(deviceDto.getCreationTime()));
            params.put("auto_provisioned", deviceDto.isAutoProvisioned());
        });
        log.debug("createDevice - statement: {}", expanded);
        return getDeviceCount(key.getTenantId(), span.context()).compose(currentDeviceCount -> tenant.checkDeviceLimitReached(key.getTenantId(), currentDeviceCount, globalDevicesPerTenantLimit)).compose(ok -> expanded.trace(this.tracer, context).update(this.client).recover(SQL::translateException)).compose(x -> createGroups(connection, key, new HashSet<>(device.getMemberOf()), context));
    }).map(new Versioned<Void>(deviceDto.getVersion(), null)).onComplete(x -> span.finish());
}
Also used : SQL(org.eclipse.hono.service.base.jdbc.store.SQL) Json(io.vertx.core.json.Json) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) LoggerFactory(org.slf4j.LoggerFactory) Supplier(java.util.function.Supplier) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) Map(java.util.Map) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) Device(org.eclipse.hono.service.management.device.Device) Logger(org.slf4j.Logger) Tracer(io.opentracing.Tracer) Timestamp(java.sql.Timestamp) Promise(io.vertx.core.Promise) Set(java.util.Set) DeviceKey(org.eclipse.hono.deviceregistry.service.device.DeviceKey) OptimisticLockingException(org.eclipse.hono.service.base.jdbc.store.OptimisticLockingException) 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) CommonCredential(org.eclipse.hono.service.management.credentials.CommonCredential) JDBCClient(io.vertx.ext.jdbc.JDBCClient) CredentialsDto(org.eclipse.hono.service.management.credentials.CredentialsDto) UpdateResult(io.vertx.ext.sql.UpdateResult) EntityNotFoundException(org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException) ResultSet(io.vertx.ext.sql.ResultSet) SQLConnection(io.vertx.ext.sql.SQLConnection) Optional(java.util.Optional) Span(io.opentracing.Span) DeviceRegistryUtils(org.eclipse.hono.deviceregistry.util.DeviceRegistryUtils) Collections(java.util.Collections) StatementConfiguration(org.eclipse.hono.service.base.jdbc.store.StatementConfiguration) Versioned(org.eclipse.hono.deviceregistry.util.Versioned) JdbcBasedDeviceDto(org.eclipse.hono.service.base.jdbc.store.model.JdbcBasedDeviceDto) Span(io.opentracing.Span) SQL(org.eclipse.hono.service.base.jdbc.store.SQL) HashSet(java.util.HashSet)

Aggregations

Span (io.opentracing.Span)5 Versioned (org.eclipse.hono.deviceregistry.util.Versioned)5 SpanContext (io.opentracing.SpanContext)4 Tracer (io.opentracing.Tracer)4 CompositeFuture (io.vertx.core.CompositeFuture)4 Future (io.vertx.core.Future)4 JsonObject (io.vertx.core.json.JsonObject)4 JDBCClient (io.vertx.ext.jdbc.JDBCClient)4 SQLConnection (io.vertx.ext.sql.SQLConnection)4 UpdateResult (io.vertx.ext.sql.UpdateResult)4 Optional (java.util.Optional)4 UUID (java.util.UUID)4 Collectors (java.util.stream.Collectors)4 EntityNotFoundException (org.eclipse.hono.service.base.jdbc.store.EntityNotFoundException)4 SQL (org.eclipse.hono.service.base.jdbc.store.SQL)4 Statement (org.eclipse.hono.service.base.jdbc.store.Statement)4 StatementConfiguration (org.eclipse.hono.service.base.jdbc.store.StatementConfiguration)4 Tenant (org.eclipse.hono.service.management.tenant.Tenant)4 TracingHelper (org.eclipse.hono.tracing.TracingHelper)4 Logger (org.slf4j.Logger)4