Search in sources :

Example 1 with DeviceKey

use of org.eclipse.hono.deviceregistry.service.device.DeviceKey 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 2 with DeviceKey

use of org.eclipse.hono.deviceregistry.service.device.DeviceKey in project hono by eclipse.

the class TableManagementStore method deleteDevice.

/**
 * Delete a single device.
 * <p>
 * This will execute the {@code delete} or {@code deleteVersioned} SQL statement and provide
 * the named parameters {@code tenant_id}, {@code device_id}, and {@code expected_version} (if set).
 * It will return the plain update result of the operation.
 *
 * @param key The key of the device to delete.
 * @param resourceVersion An optional resource version.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<UpdateResult> deleteDevice(final DeviceKey key, final Optional<String> resourceVersion, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "delete 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 Statement statement;
    if (resourceVersion.isPresent()) {
        statement = this.deleteVersionedStatement;
    } else {
        statement = this.deleteStatement;
    }
    final var expanded = statement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
        resourceVersion.ifPresent(version -> map.put("expected_version", version));
    });
    log.debug("delete - statement: {}", expanded);
    final var result = expanded.trace(this.tracer, span.context()).update(this.client);
    return checkOptimisticLock(result, span, resourceVersion, checkSpan -> readDevice(this.client, key, checkSpan)).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) Statement(org.eclipse.hono.service.base.jdbc.store.Statement) Span(io.opentracing.Span)

Example 3 with DeviceKey

use of org.eclipse.hono.deviceregistry.service.device.DeviceKey in project hono by eclipse.

the class MongoDbBasedRegistrationService method getRegistrationInformation.

/**
 * {@inheritDoc}
 */
@Override
protected Future<RegistrationResult> getRegistrationInformation(final DeviceKey deviceKey, final Span span) {
    Objects.requireNonNull(deviceKey);
    Objects.requireNonNull(span);
    return dao.getById(deviceKey.getTenantId(), deviceKey.getDeviceId(), span.context()).map(dto -> RegistrationResult.from(HttpURLConnection.HTTP_OK, new JsonObject().put(RegistrationConstants.FIELD_PAYLOAD_DEVICE_ID, deviceKey.getDeviceId()).put(RegistrationConstants.FIELD_DATA, JsonObject.mapFrom(dto.getData())))).otherwise(t -> RegistrationResult.from(ServiceInvocationException.extractStatusCode(t)));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Objects(java.util.Objects) DeviceDao(org.eclipse.hono.deviceregistry.mongodb.model.DeviceDao) RegistrationResult(org.eclipse.hono.util.RegistrationResult) Set(java.util.Set) DeviceKey(org.eclipse.hono.deviceregistry.service.device.DeviceKey) Span(io.opentracing.Span) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) JsonObject(io.vertx.core.json.JsonObject) ServiceInvocationException(org.eclipse.hono.client.ServiceInvocationException) Future(io.vertx.core.Future) AbstractRegistrationService(org.eclipse.hono.deviceregistry.service.device.AbstractRegistrationService) JsonObject(io.vertx.core.json.JsonObject)

Example 4 with DeviceKey

use of org.eclipse.hono.deviceregistry.service.device.DeviceKey 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 DeviceKey

use of org.eclipse.hono.deviceregistry.service.device.DeviceKey in project hono by eclipse.

the class TableManagementStore method getCredentials.

/**
 * Get all credentials for a device.
 * <p>
 * This gets the credentials of a device. If the device cannot be found, the
 * result must be empty. If no credentials could be found for an existing device,
 * the result must not be empty, but provide an empty {@link CredentialsReadResult}.
 *
 * @param key The key of the device.
 * @param spanContext The span to contribute to.
 * @return A future, tracking the outcome of the operation.
 */
public Future<Optional<CredentialsReadResult>> getCredentials(final DeviceKey key, final SpanContext spanContext) {
    final Span span = TracingHelper.buildChildSpan(this.tracer, spanContext, "get credentials", getClass().getSimpleName()).withTag(TracingHelper.TAG_TENANT_ID, key.getTenantId()).withTag(TracingHelper.TAG_DEVICE_ID, key.getDeviceId()).start();
    final var expanded = this.readCredentialsStatement.expand(map -> {
        map.put("tenant_id", key.getTenantId());
        map.put("device_id", key.getDeviceId());
    });
    final Promise<SQLConnection> promise = Promise.promise();
    this.client.getConnection(promise);
    return promise.future().compose(connection -> readDevice(connection, key, span).compose(result -> extractVersionForUpdate(result, Optional.empty())).compose(version -> expanded.trace(this.tracer, span.context()).query(connection).compose(r -> {
        span.log(Map.of(Fields.EVENT, "read result", "rows", r.getNumRows()));
        final var credentials = parseCredentials(r);
        log.debug("Credentials: {}", credentials);
        return Future.succeededFuture(Optional.of(new CredentialsReadResult(key.getDeviceId(), credentials, Optional.ofNullable(version))));
    })).onComplete(x -> connection.close())).recover(err -> recoverNotFound(span, err, Optional::empty)).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) Optional(java.util.Optional) SQLConnection(io.vertx.ext.sql.SQLConnection) Span(io.opentracing.Span)

Aggregations

Span (io.opentracing.Span)6 Future (io.vertx.core.Future)6 JsonObject (io.vertx.core.json.JsonObject)6 Objects (java.util.Objects)6 Set (java.util.Set)6 DeviceKey (org.eclipse.hono.deviceregistry.service.device.DeviceKey)6 SpanContext (io.opentracing.SpanContext)5 Tracer (io.opentracing.Tracer)5 Fields (io.opentracing.log.Fields)5 CompositeFuture (io.vertx.core.CompositeFuture)5 Promise (io.vertx.core.Promise)5 Json (io.vertx.core.json.Json)5 JDBCClient (io.vertx.ext.jdbc.JDBCClient)5 ResultSet (io.vertx.ext.sql.ResultSet)5 SQLConnection (io.vertx.ext.sql.SQLConnection)5 UpdateResult (io.vertx.ext.sql.UpdateResult)5 Timestamp (java.sql.Timestamp)5 Collections (java.util.Collections)5 HashSet (java.util.HashSet)5 List (java.util.List)5