diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 332a95242b..287c50b84d 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -39,9 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; -import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; -import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; -import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; +import org.thingsboard.server.service.iot_hub.DevicePackageService; +import org.thingsboard.server.service.iot_hub.DevicePackageRequest; +import org.thingsboard.server.service.iot_hub.DevicePackageResult; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallPlan; @@ -58,7 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService; public class IotHubController extends BaseController { private final IotHubService iotHubService; - private final DevicePackageUpdateService devicePackageUpdateService; + private final DevicePackageService devicePackageService; private final IotHubInstalledItemService iotHubInstalledItemService; private final DeviceConnectivityService deviceConnectivityService; private final SystemSecurityService systemSecurityService; @@ -103,21 +103,29 @@ public class IotHubController extends BaseController { return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/device/install") + @ResponseBody + public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException { + checkAllPermissions(); + return devicePackageService.install(getCurrentUser(), request); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @ResponseBody public List checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); + return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/installedItems/{installedItemId}/deviceUpdate") @ResponseBody - public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, - @RequestBody DeviceUpdateRequest request) throws ThingsboardException { + public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId, + @RequestBody DevicePackageRequest request) throws ThingsboardException { checkAllPermissions(); - return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); + return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java similarity index 72% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java index f4604beea4..ac998aae5a 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java @@ -16,10 +16,13 @@ import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.GroupEntity; +import org.thingsboard.server.common.data.HasCustomerId; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasVersion; @@ -30,14 +33,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.ConverterId; +import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; @@ -66,6 +72,7 @@ import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -86,18 +93,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * Applies an update of an installed device package in one transaction. The install wizard resolves the templates - * of the new version (the same way it installs them) and sends the entity of each step; this service checks the - * plan, saves every entity and the new version of the installed item together, and rolls all of it back on a - * failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a - * rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, - * are written after commit too. + * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the + * templates of the version and sends the entity of each step; this service checks the plan, saves every entity + * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors, + * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control + * and the attributes, which aren't transactional, are written after commit too. */ @Service @TbCoreComponent @Slf4j @RequiredArgsConstructor -public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { +public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService { // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} private static final Map STEP_ALIASES = Map.of( @@ -110,7 +116,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i "DOWNLINK_CONVERTER", "downlinkConverter", "INTEGRATION", "integration"); private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); - private static final String UNEXPECTED_ERROR = "Failed to update the device package"; + private static final String UNEXPECTED_ERROR = "Failed to save the device package"; private final IotHubInstalledItemService installedItemService; private final IotHubRestClient iotHubRestClient; @@ -129,6 +135,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private final AttributesService attributesService; private final TelemetrySubscriptionService telemetryService; private final TransactionTemplate transactionTemplate; + private final ProjectInfo projectInfo; @Override public List check(SecurityUser user, IotHubInstalledItemId installedItemId) { @@ -162,33 +169,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } @Override - public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { + public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Installing device package version {}", tenantId, request.getVersionId()); + DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> { + if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) { + throw new IllegalArgumentException("Invalid install request"); + } + Placement placement = placement(tenantId, request); + JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + // The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation + DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor(); + validateInstallSteps(request); + validate(tenantId, previous, request); + return transactionTemplate.execute(status -> { + Applied applied = applySteps(tenantId, previous, request, null, placement); + IotHubInstalledItem installedItem = new IotHubInstalledItem(); + installedItem.setTenantId(tenantId); + installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText())); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setItemType("DEVICE"); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + reportInstall(user, request.getVersionId()); + log.info("[{}] Installed device package version {}", tenantId, request.getVersionId()); + } + return result; + } + + @Override + public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) { TenantId tenantId = user.getTenantId(); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - Applied applied; - try { + DevicePackageResult result = apply(user, "update of " + installedItemId, () -> { DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { throw new IllegalArgumentException("The version belongs to another item"); } - validatePlan(devicePackage, request); - checkFeatures(tenantId, request); - validateIntegrations(tenantId, request); - applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); + validate(tenantId, devicePackage.descriptor(), request); + return transactionTemplate.execute(status -> { + IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); + Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE); + installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(applied.descriptor()); + installedItemService.save(tenantId, installedItem); + return applied; + }); + }); + if (result.isSuccess()) { + log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); + } + return result; + } + + /** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */ + private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) { + TenantId tenantId = user.getTenantId(); + Applied applied; + try { + applied = change.apply(); } catch (StepFailure e) { - log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); - return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); + log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); + return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey); } catch (RestClientException e) { - log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); - return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); + log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); + return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); } catch (Exception e) { - log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); - return DeviceUpdateResult.error(userMessage(e), null); + log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e); + return DevicePackageResult.error(userMessage(e), null); } afterCommit(user, tenantId, applied); - log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); - return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); + return DevicePackageResult.success(applied.descriptor(), applied.outputs()); + } + + /** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */ + private void reportInstall(SecurityUser user, String versionId) { + TenantId tenantId = user.getTenantId(); + try { + InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(), + projectInfo.getProjectVersion(), projectInfo.getProductType()); + iotHubRestClient.reportVersionInstalled(versionId, report); + } catch (Exception e) { + log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage()); + } + } + + /** + * At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or + * gateway is never overwritten: its credentials are what its firmware uses. + */ + private static void validateInstallSteps(DevicePackageRequest request) { + if (request.getSteps() == null) { + return; + } + for (DevicePackageRequest.Step step : request.getSteps()) { + boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); + if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution())) + || (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) { + throw new IllegalArgumentException("Invalid install step: " + step.getName()); + } + } + } + + /** + * The customer and the device group the install was opened from; each must be the tenant's. The group's own + * permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources. + */ + private Placement placement(TenantId tenantId, DevicePackageRequest request) { + CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId()) + ? new CustomerId(request.getCustomerId()) : null; + if (customerId != null && !isTenantsCustomer(tenantId, customerId)) { + throw new IllegalArgumentException("Invalid install request"); + } + if (request.getEntityGroupId() == null) { + return new Placement(customerId, customerId, null); + } + EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId())); + EntityId owner = group != null ? group.getOwnerId() : null; + boolean tenants = owner != null && (tenantId.equals(owner) + || (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId())))); + if (group == null || group.getType() != EntityType.DEVICE || !tenants) { + throw new IllegalArgumentException("Invalid install request"); + } + // As a device saved into a group: with no customer given, a new one goes to the group's customer + CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId; + return new Placement(customerId, deviceCustomerId, group); + } + + private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) { + Customer customer = customerService.findCustomerById(tenantId, customerId); + return customer != null && tenantId.equals(customer.getTenantId()); + } + + /** + * Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without + * a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale. + */ + private static void assignCustomer(GroupEntity entity, CustomerId customerId, GroupEntity current, DevicePackageRequest.Step step) { + if (customerId != null) { + entity.setOwnerId(customerId); + } + if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) { + throw new IllegalArgumentException(step.getName() + " belongs to another owner"); + } + } + + /** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */ + private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception { + validatePlan(ownedIds(previous), request); + checkFeatures(tenantId, request); + validateIntegrations(tenantId, request); } private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { @@ -201,50 +343,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** - * The update may only change what the package owns, or what the user confirmed. The device and the gateway, + * The device package may only change what it owns, or what the user confirmed. Its own device and gateway, * whose credentials the firmware uses, are never changed. */ - private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { + private void validatePlan(Set ownedIds, DevicePackageRequest request) { if (request.getSteps() == null || request.getSteps().isEmpty()) { - throw new IllegalArgumentException("The update has no steps"); + throw new IllegalArgumentException("The device package has no steps"); } - Set ownedIds = ownedIds(devicePackage.descriptor()); // A form's values are saved under its key too, so an entity step may not share it Set stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { - throw new IllegalArgumentException("Invalid update step: " + step.getName()); + throw new IllegalArgumentException("Invalid step: " + step.getName()); } if (!stateKeys.add(step.stateKey())) { - throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); + throw new IllegalArgumentException("Duplicate step: " + step.stateKey()); } boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); switch (step.getAction()) { case KEEP, OVERWRITE -> { if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { - throw new IllegalArgumentException("No entity for update step: " + step.getName()); + throw new IllegalArgumentException("No entity for step: " + step.getName()); } boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed() && !"GATEWAY_CONNECTOR".equals(step.getType())) { throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); } - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) { throw new IllegalArgumentException("The device and its credentials don't change on update"); } } case CREATE -> { } } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { - throw new IllegalArgumentException("No entity data for update step: " + step.getName()); + if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { + throw new IllegalArgumentException("No entity data for step: " + step.getName()); } } } /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ - private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { - boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP + private void checkFeatures(TenantId tenantId, DevicePackageRequest request) { + boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); if (savesIntegrations) { subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); @@ -252,13 +393,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } /** The configuration of an integration is checked by a remote call, so before the transaction. */ - private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { - for (DeviceUpdateRequest.Step step : request.getSteps()) { - if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { + private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception { + for (DevicePackageRequest.Step step : request.getSteps()) { + if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) { continue; } ObjectNode body = step.getEntity().deepCopy(); - // Converters this update creates have no id yet; the configuration doesn't depend on them + // Converters the request creates have no id yet; the configuration doesn't depend on them body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); Integration integration = JacksonUtil.treeToValue(body, Integration.class); integration.setTenantId(tenantId); @@ -274,9 +415,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { - IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); - DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); + /** + * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the + * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null. + */ + private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId, + Placement placement) { Set ownedIds = ownedIds(previous); Map aliasOutputs = new HashMap<>(); Map outputs = new LinkedHashMap<>(); @@ -291,21 +435,22 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i List stepEntityIds = new ArrayList<>(); Map usedExistingIds = usedExistingIds(previous); List saved = new ArrayList<>(); - List connectorSteps = new ArrayList<>(); + List grouped = new ArrayList<>(); + List connectorSteps = new ArrayList<>(); List attributes = new ArrayList<>(); DashboardId dashboardId = null; - for (DeviceUpdateRequest.Step step : request.getSteps()) { + for (DevicePackageRequest.Step step : request.getSteps()) { try { if ("GATEWAY_CONNECTOR".equals(step.getType())) { // A connector lives in the gateway's attributes, which aren't transactional: saved after commit - if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() != DevicePackageRequest.Action.KEEP) { connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); } continue; } JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; - StepResult result = applyStep(tenantId, step, entity); + StepResult result = applyStep(tenantId, step, entity, placement); ObjectNode output = result.output(); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); outputs.put(step.stateKey(), output); @@ -317,7 +462,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i state.put("resolution", resolution); // A kept entity keeps the checksum of what the package left: the current one would take the // user's changes for the package's, and the next update would overwrite them without a warning - String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); + String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); if (checksum != null) { state.put("checksum", checksum); } @@ -343,8 +488,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if (result.saved() != null) { saved.add(result.saved()); } - if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { - // As at install, the step's attributes go with the entity it saved; written after commit + if (placement.entityGroup() != null && result.saved() != null && result.saved().created() + && result.entityId().getEntityType() == EntityType.DEVICE) { + entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId()); + grouped.add(result.saved()); + } + // The step's attributes go with the entity it saved; at install also onto an entity the user chose to + // use, as the install always did. Written after commit + boolean install = installedVersionId == null; + if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) { attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); } } catch (StepFailure e) { @@ -356,7 +508,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps // it changes: the other steps and the forms keep their install state - if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { + if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) { previous.getInstallState().forEach((key, value) -> { if (value instanceof ObjectNode state) { installState.putIfAbsent(key, state); @@ -376,15 +528,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i carryMetadataStates(previous, tracked, state); descriptor.setInstallState(state); - installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); - installedItem.setItemName(versionInfo.get("name").asText()); - installedItem.setVersion(versionInfo.get("version").asText()); - installedItem.setDescriptor(descriptor); - installedItemService.save(tenantId, installedItem); // Resolved once every entity is saved: attributes may refer to a later step's entity List resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); - return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); + return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped); } /** The checksums the installed device packages recorded, by entity. */ @@ -422,7 +569,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * fails: the plan was made for the version installed before. Without it both would create the new entities. */ - private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { + private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) { IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) @@ -432,11 +579,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return installedItem; } - private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException { return switch (step.getType()) { case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); - case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); - case "DASHBOARD" -> saveDashboard(tenantId, step, entity); + case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement); + case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "INTEGRATION" -> saveIntegration(tenantId, step, entity); @@ -444,16 +591,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i }; } - private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); profile.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(profile, id, current, step); // The tenant's default profile stays the default one @@ -466,31 +613,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; Device device; boolean created = false; - if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { + if (step.getAction() == DevicePackageRequest.Action.CREATE) { Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); template.setId(null); template.setVersion(null); + assignCustomer(template, placement.deviceCustomerId(), null, step); device = deviceService.saveDevice(template); created = true; } else { Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; device = existing(tenantId, current, step); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { - // Another device the user chose to overwrite; the package's own device never changes + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { + // On update, another device the user chose to overwrite; it keeps its credentials. The package's own + // device never changes, and an install never overwrites one Device template = JacksonUtil.treeToValue(entity, Device.class); template.setTenantId(tenantId); prepareOverwrite(template, id, current, step); + assignCustomer(template, placement.customerId(), current, step); device = deviceService.saveDevice(template); created = true; } } DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); - if (created && step.getCredentials() != null && step.getCredentials().isObject()) { + if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) { credentials = applyCredentials(tenantId, credentials, step.getCredentials()); } ObjectNode output = output(device.getId(), device.getName()); @@ -500,7 +650,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i if ("GATEWAY".equals(step.getType())) { output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); } - SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; + SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null; return new StepResult(device.getId(), output, null, saved); } @@ -520,16 +670,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); } - private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) { DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getTitle()); } Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); dashboard.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(dashboard, id, current, step); // The dashboard keeps its owner and the customers it is assigned to @@ -537,25 +687,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i dashboard.setCustomerId(current.getCustomerId()); } dashboard.setAssignedCustomers(current.getAssignedCustomers()); + assignCustomer(dashboard, placement.customerId(), current, step); } else { dashboard.setId(null); dashboard.setVersion(null); + assignCustomer(dashboard, placement.customerId(), null, step); } Dashboard result = dashboardService.saveDashboard(dashboard); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); } - private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { + private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException { RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); ruleChain.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(ruleChain, id, current, step); // A rule chain the tenant made its root one stays the root @@ -578,17 +730,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); return kept(id, current.getName()); } Converter converter = JacksonUtil.treeToValue(entity, Converter.class); converter.setTenantId(tenantId); converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(converter, id, current, step); } else { @@ -599,10 +751,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); } - private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { + private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) { IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; - if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { + if (step.getAction() == DevicePackageRequest.Action.KEEP) { existing(tenantId, current, step); Integration merged = withMergedMetadata(current, step.getMetadata()); if (merged != null) { @@ -613,7 +765,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } Integration integration = JacksonUtil.treeToValue(entity, Integration.class); integration.setTenantId(tenantId); - if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { + if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) { existing(tenantId, current, step); prepareOverwrite(integration, id, current, step); // The devices keep sending to the same endpoint @@ -668,7 +820,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i /** * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. - * A copy: the integration may be the cache's own instance, which a rolled back update must not change. + * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change. */ private static Integration withMergedMetadata(Integration integration, JsonNode entries) { if (entries == null || !entries.isObject() || entries.isEmpty()) { @@ -698,7 +850,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the * user reviewed makes the save fail if someone changed the entity since. */ - private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { + private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) { switch (entity) { case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } @@ -715,9 +867,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i ((HasVersion) entity).setVersion(currentVersion); } - private T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { + private T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) { if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { - throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); + throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again."); } return current; } @@ -745,9 +897,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with * its metadata, which isn't cached. */ - private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { + private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) { String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); - return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); + return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE)); } private static ObjectNode output(EntityId id, String name) { @@ -775,7 +927,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } } - /** Replaces ${.} of entities this update has saved, e.g. the id of a converter it created. */ + /** Replaces ${.} of entities the request has saved, e.g. the id of a converter it created. */ static JsonNode resolvePlaceholders(JsonNode node, Map aliasOutputs) { if (node == null) { return null; @@ -834,17 +986,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; } - /** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ + /** + * What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install + * or update. + */ private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { for (SavedEntity saved : applied.saved()) { try { - logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), + CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null; + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId, saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); if (saved.id().getEntityType() != EntityType.DEVICE) { autoCommit(user, saved.id()); } } catch (Exception e) { - log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); + log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e); + } + } + for (SavedEntity saved : applied.grouped()) { + try { + logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(), + ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName()); + } catch (Exception e) { + log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e); } } for (StepAttributes step : applied.attributes()) { @@ -855,7 +1019,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); } } - for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { + for (DevicePackageRequest.Step step : applied.connectorSteps()) { try { saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); } catch (Exception e) { @@ -905,7 +1069,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i */ static String userMessage(Throwable e) { if (e instanceof EntityVersionMismatchException) { - return "Someone changed it while you were reviewing the update. Check the update again."; + return "Someone changed it meanwhile. Check the package again."; } if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException || e instanceof SubscriptionException) { @@ -961,8 +1125,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i return ids; } - private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { - DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); + private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) { + DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class); if (entity != null) { copy.setEntity(entity); } @@ -972,6 +1136,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { } + @FunctionalInterface + private interface PackageChange { + Applied apply() throws Exception; + } + private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { } @@ -982,8 +1151,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i } private record Applied(DeviceInstalledItemDescriptor descriptor, Map outputs, List saved, - List connectorSteps, List attributes, - Map aliasOutputs) { + List connectorSteps, List attributes, + Map aliasOutputs, EntityGroup entityGroup, List grouped) { + } + + /** + * Where an install opened from a customer's or a device group's page puts its entities. A new device follows the + * group's customer when no customer is given, as a device saved into a group does; an update has none. + */ + private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) { + static final Placement NONE = new Placement(null, null, null); } /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index ddbe8ec5d7..b950ecbd86 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -421,7 +421,7 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); if ("DEVICE".equals(itemType)) { - // Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService + // Updated in one transaction from the install wizard of the new version, see DevicePackageService throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java similarity index 67% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java index a62f556c57..f79f023672 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java @@ -10,28 +10,33 @@ import java.util.Map; import java.util.UUID; /** - * The update of an installed device package as the install wizard planned it: the entity of each install step - * of the new version, already resolved from its template, and what to do with it. The server applies all of it - * in one transaction, together with the new version of the installed item, or nothing. + * The install or update of a device package as the install wizard planned it: the entity of each install step + * of the version being installed, already resolved from its template, and what to do with it. The server applies + * all of it in one transaction, together with the installed item, or nothing. */ @Data -public class DeviceUpdateRequest { +public class DevicePackageRequest { private String versionId; - // The version installed when the wizard planned the update; the update fails if the package changed since + // Update only: the version installed when the wizard planned the update, which fails if the package changed since private UUID fromVersionId; - // The install method of the new version's steps; the installed one when not set + // The install method of the steps; an update without it keeps the installed one private String selectedInstallMethod; // The form values of the install state, by step: the server adds the entities to it private Map installState; + // Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard + // go to, and the group the created device or gateway is added to. An update ignores them + private UUID customerId; + private UUID entityGroupId; private List steps; public enum Action { - // Taken as it is: the new version doesn't change it, or the user kept an entity they had + // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had KEEP, // Takes the entity from the step OVERWRITE, - // A new entity: new in this version, deleted since install, or a copy next to one with the same name + // A new entity: one the package installs, a step new in this version or deleted since install, or a copy + // next to one with the same name CREATE } @@ -51,13 +56,13 @@ public class DeviceUpdateRequest { private Long expectedVersion; // The user confirmed overwriting an entity of another package or one they didn't install with this package private boolean confirmed; - // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity this - // update creates is left for the server, which knows its id only once it is created. + // OVERWRITE and CREATE: the entity resolved from the template. ${.} of an entity the + // request creates is left for the server, which knows its id only once it is created. private JsonNode entity; // DEVICE and GATEWAY: the credentials template, if any private JsonNode credentials; // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, - // they may keep ${.} of an entity this update creates. + // they may keep ${.} of an entity the request creates. private JsonNode serverAttributes; private JsonNode sharedAttributes; // The resolution the install state records for it @@ -65,7 +70,8 @@ public class DeviceUpdateRequest { // INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the // integration, e.g. one the package took as it was; null removes an entry private JsonNode metadata; - // UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check + // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later + // update checks that converter against ThingsBoard's default one private boolean defaultConverter; /** diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java similarity index 70% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java index 5c8ec6e8d7..d07a51d839 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java @@ -17,7 +17,7 @@ import java.util.Map; @Data @NoArgsConstructor @AllArgsConstructor -public class DeviceUpdateResult { +public class DevicePackageResult { private boolean success; private String errorMessage; @@ -26,12 +26,12 @@ public class DeviceUpdateResult { // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; - public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { - return new DeviceUpdateResult(true, null, null, descriptor, outputs); + public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { + return new DevicePackageResult(true, null, null, descriptor, outputs); } - public static DeviceUpdateResult error(String errorMessage, String failedStep) { - return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); + public static DevicePackageResult error(String errorMessage, String failedStep) { + return new DevicePackageResult(false, errorMessage, failedStep, null, null); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java similarity index 59% rename from application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java rename to application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java index 5688056c98..60103c6e01 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java @@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser; import java.util.List; -/** Updates an installed device package to another version of its item. */ -public interface DevicePackageUpdateService { +/** Installs a device package, or updates an installed one to another version of its item. */ +public interface DevicePackageService { /** The package's entities as they are now: whether they still exist, changed since, or are shared. */ List check(SecurityUser user, IotHubInstalledItemId installedItemId); + /** Installs the version in one transaction, together with its installed item, or nothing. */ + DevicePackageResult install(SecurityUser user, DevicePackageRequest request); + /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ - DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); + DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request); } diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java similarity index 60% rename from application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java rename to application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java index 38595a0c71..5a75ddc997 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java @@ -8,6 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -16,12 +17,17 @@ import org.mockito.quality.Strictness; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.client.RestClientException; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.HasName; +import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.AttributeScope; +import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; @@ -30,23 +36,29 @@ import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceProfileId; +import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.id.UserId; +import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.dao.converter.ConverterService; +import org.thingsboard.server.dao.customer.CustomerService; import org.thingsboard.server.dao.dashboard.DashboardService; import org.thingsboard.server.dao.device.DeviceCredentialsService; import org.thingsboard.server.dao.device.DeviceProfileService; import org.thingsboard.server.dao.device.DeviceService; import org.thingsboard.server.dao.entity.EntityService; +import org.thingsboard.server.dao.group.EntityGroupService; import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.subscription.PlatformFeature; @@ -54,6 +66,7 @@ import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.service.entitiy.TbLogEntityActionService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; +import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; @@ -62,20 +75,25 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.ExecutionException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class DefaultDevicePackageUpdateServiceTest { +class DefaultDevicePackageServiceTest { private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); private final SecurityUser user = mock(SecurityUser.class); @@ -119,18 +137,30 @@ class DefaultDevicePackageUpdateServiceTest { private TelemetrySubscriptionService telemetryService; @Mock private IotHubService iotHubService; + @Mock + private ProjectInfo projectInfo; + @Mock + private CustomerService customerService; + @Mock + private EntityGroupService entityGroupService; @InjectMocks - private DefaultDevicePackageUpdateService service; + private DefaultDevicePackageService service; private IotHubInstalledItem installedItem; // Set when the transaction callback threw, so the transaction would roll back private final List rolledBack = new ArrayList<>(); + private boolean inTransaction; + private final List savedInTransaction = new ArrayList<>(); + // What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside + private final List afterCommitCalls = new ArrayList<>(); @BeforeEach void setUp() { ReflectionTestUtils.setField(service, "entityService", entityService); ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); + ReflectionTestUtils.setField(service, "customerService", customerService); + ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService); when(user.getTenantId()).thenReturn(tenantId); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -158,11 +188,14 @@ class DefaultDevicePackageUpdateServiceTest { when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + inTransaction = true; try { return invocation.>getArgument(0).doInTransaction(null); } catch (RuntimeException e) { rolledBack.add(e); throw e; + } finally { + inTransaction = false; } }); when(packageEntities.checksum(any(), any())).thenReturn("checksum"); @@ -184,7 +217,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), keep("AM308", "DEVICE", deviceId), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); @@ -218,10 +251,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); + DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -237,10 +270,10 @@ class DefaultDevicePackageUpdateServiceTest { dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); overview.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(overview)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -256,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -266,10 +299,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void useExistingOfAPackageEntity_staysThePackages() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -282,10 +315,10 @@ class DefaultDevicePackageUpdateServiceTest { // At install the user picked their own dashboard: the install adds it to createdEntityIds too ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -295,9 +328,9 @@ class DefaultDevicePackageUpdateServiceTest { @Test void overwritingAnEntityUsedAtInstall_needsAConfirmation() { ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -327,10 +360,10 @@ class DefaultDevicePackageUpdateServiceTest { // v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setResolution("use-existing"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -343,9 +376,9 @@ class DefaultDevicePackageUpdateServiceTest { DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); installed.setUsedExistingEntityIds(List.of(dashboardId)); installed.setInstallState(Map.of()); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -358,7 +391,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); @@ -377,13 +410,13 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setResolution("use-existing"); ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); entries.putNull("profile.milesight-iot-am308"); step.setMetadata(entries); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(Integration.class); @@ -411,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest { integration.setId(integrationId); when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -438,11 +471,11 @@ class DefaultDevicePackageUpdateServiceTest { current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current); when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId); step.setResolution("use-existing"); step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); @@ -465,10 +498,10 @@ class DefaultDevicePackageUpdateServiceTest { configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); current.setConfiguration(configuration); when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); - DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); + DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId); step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); verify(integrationService, never()).saveIntegration(any()); @@ -476,12 +509,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsWithOneKey_areRejected() { - DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); + DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); first.setId("main-dashboard"); - DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); + DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId); second.setId("main-dashboard"); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second)); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -489,25 +522,25 @@ class DefaultDevicePackageUpdateServiceTest { @Test void twoStepsOfOneTypeAndName_areRejected() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard"); verify(transactionTemplate, never()).execute(any()); } @Test void stepWithTheKeyOfAForm_isRejected() { - DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); + DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); step.setId("Settings"); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10)))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); - assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings"); + assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings"); verify(transactionTemplate, never()).execute(any()); } @@ -532,14 +565,14 @@ class DefaultDevicePackageUpdateServiceTest { legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"), "Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app")))); - DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); + DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId); uplink.setDefaultConverter(true); - DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); + DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId); ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308")); - DeviceUpdateRequest request = request(uplink, ttn); + DevicePackageRequest request = request(uplink, ttn); request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration"))); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -563,7 +596,7 @@ class DefaultDevicePackageUpdateServiceTest { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); @@ -580,12 +613,12 @@ class DefaultDevicePackageUpdateServiceTest { void entityChangedSinceTheCheck_isAVersionConflict() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); - assertThat(result.getErrorMessage()).contains("Check the update again"); + assertThat(result.getErrorMessage()).contains("Check the package again"); verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); } @@ -608,7 +641,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); @@ -640,12 +673,12 @@ class DefaultDevicePackageUpdateServiceTest { IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); when(installedItemService.findByTenantId(any(), any(), any(), any())) .thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); - DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setConfirmed(true); step.setDefaultConverter(true); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(step)); assertThat(result.isSuccess()).isTrue(); JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink"); @@ -672,14 +705,14 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0"); when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo); // ThingsBoard's default converter changed: only the converter step is sent - DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, + DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L, JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); step.setId("uplink"); step.setDefaultConverter(true); - DeviceUpdateRequest request = request(step); + DevicePackageRequest request = request(step); request.setVersionId(installedVersionId.toString()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isTrue(); Map state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState(); @@ -697,7 +730,7 @@ class DefaultDevicePackageUpdateServiceTest { void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); assertThat(result.isSuccess()).isTrue(); assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard"); @@ -707,7 +740,7 @@ class DefaultDevicePackageUpdateServiceTest { void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { DashboardId foreign = new DashboardId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -716,7 +749,7 @@ class DefaultDevicePackageUpdateServiceTest { @Test void theDeviceIsNeverOverwritten() { - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); assertThat(result.isSuccess()).isFalse(); @@ -729,7 +762,7 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); assertThat(result.isSuccess()).isFalse(); verify(transactionTemplate, never()).execute(any()); @@ -743,7 +776,7 @@ class DefaultDevicePackageUpdateServiceTest { updated.setItemVersionId(UUID.fromString(versionId)); when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -754,10 +787,10 @@ class DefaultDevicePackageUpdateServiceTest { @Test void planOfAnotherInstalledVersion_isRejected() { - DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); + DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId)); request.setFromVersionId(UUID.randomUUID()); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); + DevicePackageResult result = service.update(user, installedItem.getId(), request); assertThat(result.isSuccess()).isFalse(); verify(installedItemService, never()).save(any(), any()); @@ -768,7 +801,7 @@ class DefaultDevicePackageUpdateServiceTest { doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) .when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( + DevicePackageResult result = service.update(user, installedItem.getId(), request( create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); assertThat(result.isSuccess()).isFalse(); @@ -780,10 +813,10 @@ class DefaultDevicePackageUpdateServiceTest { void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); - DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); + DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); - DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); assertThat(result.isSuccess()).isTrue(); ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); @@ -829,12 +862,12 @@ class DefaultDevicePackageUpdateServiceTest { @Test void userMessage_showsValidationMessagesAndHidesInternalOnes() { - assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) + assertThat(DefaultDevicePackageService.userMessage(new DataValidationException("Rule chains limit reached"))) .isEqualTo("Rule chains limit reached"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) - .contains("Check the update again"); - assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) - .isEqualTo("Failed to update the device package"); + assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) + .contains("Check the package again"); + assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) + .isEqualTo("Failed to save the device package"); } @Test @@ -842,12 +875,431 @@ class DefaultDevicePackageUpdateServiceTest { ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); - ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); + ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device)); assertThat(resolved.get("a").asText()).isEqualTo("123"); assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); } + @Test + void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("use-existing"); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + integrationStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + verify(transactionTemplate).execute(any()); + assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM"); + ArgumentCaptor saved = ArgumentCaptor.forClass(IotHubInstalledItem.class); + verify(installedItemService).save(eq(tenantId), saved.capture()); + IotHubInstalledItem item = saved.getValue(); + assertThat(item.getTenantId()).isEqualTo(tenantId); + assertThat(item.getItemId()).isEqualTo(itemId); + assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(item.getVersion()).isEqualTo("1.0.1"); + assertThat(item.getItemName()).isEqualTo("AM308"); + assertThat(item.getItemType()).isEqualTo("DEVICE"); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor(); + assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId); + assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId); + assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId); + Map state = descriptor.getInstallState(); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString()); + assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue(); + assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString()); + assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue(); + assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString()); + assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing"); + assertThat(result.getDescriptor()).isSameAs(descriptor); + assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard"); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installFailureOnALaterStepSavesNothing() { + mockInstall(); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); + + DevicePackageResult result = service.install(user, request( + create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard"); + assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); + assertThat(rolledBack).hasSize(1); + verify(installedItemService, never()).save(any(), any()); + verifyNoInteractions(logEntityActionService, telemetryService); + verify(iotHubRestClient, never()).reportVersionInstalled(any(), any()); + } + + @Test + void installOverwriteOfAnExistingEntityNeedsAConfirmation() { + mockInstall(); + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + + DevicePackageResult result = service.install(user, request( + overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard"); + verify(transactionTemplate, never()).execute(any()); + verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWithBadIntegrationCredentialsSavesNothing() throws Exception { + mockInstall(); + doThrow(new ExecutionException(new IllegalStateException("Wrong API key"))) + .when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any()); + + DevicePackageResult result = service.install(user, request( + create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN"); + assertThat(result.getErrorMessage()).isEqualTo("Wrong API key"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWhenHubIsUnavailableSavesNothing() { + mockInstall(); + when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused")); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later."); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() { + mockInstall(); + doAnswer(i -> { + recordAfterCommit("REPORT"); + throw new RestClientException("Connection refused"); + }).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + + DevicePackageResult result = service.install(user, request( + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient); + order.verify(installedItemService).save(eq(tenantId), any()); + order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user)); + order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any()); + assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT"); + } + + @Test + void installRejectsAFromVersion() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setFromVersionId(installedVersionId); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installKeepStepMustUseExisting() { + mockInstall(); + DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId); + integrationStep.setResolution("created"); + + DevicePackageResult result = service.install(user, request(integrationStep)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installRejectsAMalformedVersionId() { + mockInstall(); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setVersionId("not-a-uuid"); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(iotHubRestClient, never()).getVersionInfo(any()); + verify(transactionTemplate, never()).execute(any()); + } + + @Test + void installAssignsTheCustomerToTheDeviceAndTheDashboard() { + mockInstall(); + CustomerId customerId = customerOf(tenantId); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(customerId); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId); + } + + @Test + void installAddsTheDeviceToTheEntityGroup() { + mockInstall(); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Warehouse sensors"); + group.setOwnerId(tenantId); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId)); + assertThat(savedInTransaction).contains("ENTITY_GROUP"); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP), + eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors")); + assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT"); + } + + @Test + void installRejectsACustomerOfAnotherTenant() { + mockInstall(); + CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID())); + DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(customerId.getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install request"); + verify(transactionTemplate, never()).execute(any()); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateIgnoresCustomerAndEntityGroup() { + when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); + DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))); + request.setCustomerId(UUID.randomUUID()); + request.setEntityGroupId(UUID.randomUUID()); + + DevicePackageResult result = service.update(user, installedItem.getId(), request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getCustomerId()).isNull(); + verifyNoInteractions(customerService, entityGroupService); + } + + @Test + void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + current.setCustomerId(customerOf(tenantId)); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare"); + assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner"); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void updateOverwriteOfAnotherDeviceKeepsItsCredentials() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + Device current = new Device(otherId); + current.setTenantId(tenantId); + current.setName("AM308 spare"); + when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0)); + DeviceCredentials credentials = new DeviceCredentials(); + credentials.setDeviceId(otherId); + credentials.setCredentialsId("existing-token"); + when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials); + DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare")); + step.setConfirmed(true); + step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token")); + + DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); + + assertThat(result.isSuccess()).isTrue(); + verify(deviceService).saveDevice(any(Device.class)); + verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any()); + assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token"); + } + + @Test + void installRejectsAnOverwriteOfADeviceOrGateway() { + mockInstall(); + for (String type : new String[]{"DEVICE", "GATEWAY"}) { + DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308")); + step.setConfirmed(true); + + DevicePackageResult result = service.install(user, request(step)); + + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308"); + } + verify(transactionTemplate, never()).execute(any()); + verify(deviceService, never()).saveDevice(any(Device.class)); + verify(installedItemService, never()).save(any(), any()); + } + + @Test + void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() { + mockInstall(); + DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId); + deviceStep.setResolution("use-existing"); + deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308")); + deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); + + DevicePackageResult result = service.install(user, request(deviceStep, + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")))); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); + verify(telemetryService, times(2)).saveAttributes(saved.capture()); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId); + assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE); + assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308"); + assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); + // The kept device isn't saved, so only the dashboard is audited + assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT"); + } + + @Test + void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() { + mockInstall(); + CustomerId groupCustomer = customerOf(tenantId); + EntityGroup group = new EntityGroup(); + group.setId(new EntityGroupId(UUID.randomUUID())); + group.setType(EntityType.DEVICE); + group.setName("Customer sensors"); + group.setOwnerId(groupCustomer); + when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group); + DevicePackageRequest request = request( + create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")), + create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))); + request.setEntityGroupId(group.getId().getId()); + + DevicePackageResult result = service.install(user, request); + + assertThat(result.isSuccess()).isTrue(); + ArgumentCaptor device = ArgumentCaptor.forClass(Device.class); + verify(deviceService).saveDevice(device.capture()); + assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer); + ArgumentCaptor dashboard = ArgumentCaptor.forClass(Dashboard.class); + verify(dashboardService).saveDashboard(dashboard.capture()); + assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId); + verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId); + verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user)); + } + + private CustomerId customerOf(TenantId owner) { + Customer customer = new Customer(new CustomerId(UUID.randomUUID())); + customer.setTenantId(owner); + when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer); + return customer.getId(); + } + + /** The new entities get these ids; each save records that it ran inside the transaction. */ + private void mockInstall() { + when(user.getId()).thenReturn(new UserId(UUID.randomUUID())); + when(projectInfo.getProjectVersion()).thenReturn("4.4.1"); + when(projectInfo.getProductType()).thenReturn("PE"); + when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> { + recordSave("DEVICE_PROFILE"); + DeviceProfile profile = i.getArgument(0); + profile.setId(profileId); + return profile; + }); + when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> { + recordSave("DASHBOARD"); + Dashboard dashboard = i.getArgument(0); + dashboard.setId(dashboardId); + return dashboard; + }); + when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> { + recordSave("DEVICE"); + Device device = i.getArgument(0); + device.setId(deviceId); + return device; + }); + doAnswer(i -> { + recordSave("ENTITY_GROUP"); + return null; + }).when(entityGroupService).addEntityToEntityGroup(any(), any(), any()); + when(installedItemService.save(any(), any())).thenAnswer(i -> { + recordSave("INSTALLED_ITEM"); + return i.getArgument(1); + }); + Integration integration = new Integration(); + integration.setId(integrationId); + integration.setTenantId(tenantId); + integration.setName("TTN my-app"); + when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration); + doAnswer(i -> { + recordAfterCommit("AUDIT"); + return null; + }).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class), + any(ActionType.class), any(User.class), any(Object[].class)); + doAnswer(i -> { + recordAfterCommit("REPORT"); + return null; + }).when(iotHubRestClient).reportVersionInstalled(any(), any()); + doAnswer(i -> { + recordAfterCommit("ATTRIBUTES"); + return null; + }).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class)); + } + + private void recordSave(String what) { + if (inTransaction) { + savedInTransaction.add(what); + } + } + + private void recordAfterCommit(String what) { + afterCommitCalls.add(inTransaction ? what + " in transaction" : what); + } + private IotHubInstalledItem otherPackage(Map installState) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setInstallState(installState); @@ -875,35 +1327,35 @@ class DefaultDevicePackageUpdateServiceTest { return dashboard; } - private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { - DeviceUpdateRequest request = new DeviceUpdateRequest(); + private DevicePackageRequest request(DevicePackageRequest.Step... steps) { + DevicePackageRequest request = new DevicePackageRequest(); request.setVersionId(versionId); request.setSteps(List.of(steps)); return request; } - private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); + private static DevicePackageRequest.Step keep(String name, String type, EntityId id) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.KEEP); step.setEntityId(id.getId()); return step; } - private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); + private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.OVERWRITE); step.setEntityId(id.getId()); step.setExpectedVersion(version); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { - DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); + private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) { + DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.Action.CREATE); step.setEntity(entity); return step; } - private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { - DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); + private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) { + DevicePackageRequest.Step step = new DevicePackageRequest.Step(); step.setName(name); step.setType(type); step.setAction(action); diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index e162ba1357..b9af2299f2 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -14,7 +14,7 @@ import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; -import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; +import { DevicePackageEntityState, DevicePackageRequest, DevicePackageResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorConfig } from '@core/interceptors/interceptor-config'; @@ -180,18 +180,6 @@ export class IotHubApiService { ); } - public registerDeviceInstall( - versionId: string, - descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig - ): Observable { - return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, - { type: 'DEVICE', ...descriptor }, - { params: this.buildParams(config) } - ); - } - public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable { return this.http.post( `/api/iot-hub/versions/${versionId}/install`, @@ -287,14 +275,23 @@ export class IotHubApiService { } /** Applies a device package update in one transaction: all of it, or nothing. */ - public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable { - return this.http.post( + public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`, request, { params: this.buildParams(config) } ); } + /** Installs a device package in one transaction: all of its entities and the installed item, or nothing. */ + public installDevicePackage(request: DevicePackageRequest, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/device/install`, + request, + { params: this.buildParams(config) } + ); + } + public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable { return this.http.get( `/api/iot-hub/installedItems/${installedItemId}/keptEntities`, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index 23578f5490..cf6e9d0cca 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -62,93 +62,7 @@ } @case ('progress') { - @if (data.update) { - - } @else { -
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { - @if (i > 0) { -
- } - @if (ep.status === 'conflict' || ep.status === 'error') { -
-
-
- warning -
-
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - @if (ep.status === 'conflict') { - - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} - - } - @if (ep.status === 'error' && ep.errorMessage) { - {{ ep.errorMessage }} - } -
-
-
- @if (ep.status === 'conflict') { - @if (ep.conflictType === 'use-or-overwrite') { - - - } @else { - - - } - } - @if (ep.status === 'error') { - - } -
-
- } @else { -
-
- @switch (ep.status) { - @case ('pending') { -
{{ i + 1 }}
- } - @case ('running') { - - } - @case ('success') { - check_circle - } - } -
- - {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - - - @if (ep.status === 'success') { - {{ 'iot-hub.done' | translate }} - } - @if (ep.status === 'running') { - {{ 'iot-hub.in-progress' | translate }} - } - -
- } - } -
- } + } } @@ -156,18 +70,17 @@ - @let hint = textWithLink('iot-hub.device-update-modified'); - {{ hint.before }}{{ hint.link }}{{ hint.after }} + {{ modifiedHintText.before }}{{ modifiedHintText.link }}{{ modifiedHintText.after }} - - + +
- @for (ep of ws.entitySteps; track ep.step.name; let i = $index) { + @for (ep of ws.entitySteps; track ep.step; let i = $index) { @if (i > 0) {
} - @let plan = updatePlanOf(ep); + @let plan = planOf(ep); @let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name); @if (ws.reviewing && plan && !plan.confirmed) {
@@ -182,7 +95,7 @@ } @if (plan.existing) { - {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }} + {{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate), name: plan.existing.name } }} } @if (plan.shared) { @@ -198,19 +111,21 @@
@if (plan.existing) { @if (ep.step.type === 'DASHBOARD') { - } @else { - } - + @if (canOverwriteExisting(ep)) { + + } } @else { - } @@ -237,7 +152,7 @@ } @case ('success') { - check_circle + check_circle } @default {
{{ i + 1 }}
@@ -249,7 +164,8 @@ {{ label }} - @if (plan?.action === 'create' && plan.resolution !== 'use-existing') { + + @if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') { {{ 'iot-hub.device-update-new' | translate }} }
@@ -274,10 +190,10 @@ {{ 'iot-hub.in-progress' | translate }} } @case ('success') { - {{ updateOutcomeOf(plan) | translate }} + {{ appliedOutcomeOf(plan) | translate }} } @case ('skipped') { - {{ 'iot-hub.device-update-skipped' | translate }} + {{ 'iot-hub.device-package-skipped' | translate }} } @default { @@ -335,7 +251,7 @@
- @for (ws of wizardSteps; track ws.label) { + @for (ws of wizardSteps; track ws) { @@ -359,8 +275,8 @@ done - @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -378,24 +294,24 @@ } - @if (data.update && currentWizardStep?.type === 'progress') { + @if (currentWizardStep?.type === 'progress') { @let step = currentWizardStep; - @if (hasUpdateError(step)) { -
+ @if (hasPackageError(step)) { +
error {{ step.progressError }}
- } @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) { -
+ } @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) { +
warning - {{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }} + {{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}
} } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -432,13 +348,13 @@ } @case ('progress') { - @if (data.update && (step.reviewing || step.updating || step.progressError)) { - @if (step.progressError && !step.updating) { - - + - } @else if (step.updating) { + } @else if (step.applying) { } - } @else if (step.progressError) { - - } @else if (step.progressDone && isLastWizardStep) { - } @else if (!step.progressError) { + } @else {