Browse Source

Merge pull request #16466 from pinkevmladchy/fix/iot-hub-device-update-in-place-lts-4.4

IoT Hub: update a device package in place instead of deleting its device
pull/16536/head
Shvaika Dmytro 1 month ago
committed by GitHub
parent
commit
912c90bfb6
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 12
      application/src/main/java/org/thingsboard/server/controller/IntegrationController.java
  2. 22
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  3. 18
      application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java
  4. 9
      application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java
  5. 947
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java
  6. 47
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  7. 119
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java
  8. 27
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java
  9. 19
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java
  10. 71
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java
  11. 37
      application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java
  12. 116
      application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java
  13. 4
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  14. 29
      application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java
  15. 748
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  16. 52
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  17. 2
      common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java
  18. 3
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java
  19. 3
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java
  20. 5
      dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java
  21. 3
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java
  22. 5
      dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java
  23. 21
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  24. 195
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  25. 84
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  26. 1246
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  27. 28
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html
  28. 19
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss
  29. 18
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts
  30. 28
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  31. 84
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  32. 6
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  33. 39
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html
  34. 33
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss
  35. 82
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  36. 12
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  37. 56
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  38. 12
      ui-ngx/src/assets/converters/js-tti-decoder.raw
  39. 12
      ui-ngx/src/assets/converters/js-ttn-decoder.raw
  40. 12
      ui-ngx/src/assets/converters/tbel-tti-decoder.raw
  41. 12
      ui-ngx/src/assets/converters/tbel-ttn-decoder.raw
  42. 21
      ui-ngx/src/assets/locale/locale.constant-en_US.json

12
application/src/main/java/org/thingsboard/server/controller/IntegrationController.java

@ -142,14 +142,10 @@ public class IntegrationController extends AutoCommitController {
checkEntity(integration.getId(), integration, Resource.INTEGRATION); checkEntity(integration.getId(), integration, Resource.INTEGRATION);
if (!integration.isEdgeTemplate()) { try {
try { tbIntegrationService.validateIntegrationConfiguration(tenantId, integration);
Integration copy = new Integration(integration); } catch (ExecutionException e) {
secretConfigurationService.replaceSecretUsages(tenantId, copy.getConfiguration()); throwRealCause(e);
integrationManagerService.validateIntegrationConfiguration(copy).get(20, TimeUnit.SECONDS);
} catch (ExecutionException e) {
throwRealCause(e);
}
} }
Integration result = checkNotNull(integrationService.saveIntegration(integration)); Integration result = checkNotNull(integrationService.saveIntegration(integration));

22
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -38,6 +38,10 @@ import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService; 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.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan; import org.thingsboard.server.service.iot_hub.InstallPlan;
@ -54,6 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController { public class IotHubController extends BaseController {
private final IotHubService iotHubService; private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService;
private final IotHubInstalledItemService iotHubInstalledItemService; private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService; private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -98,6 +103,23 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody
public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.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 {
checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/update/{versionId}") @PostMapping("/installedItems/{installedItemId}/update/{versionId}")
@ResponseBody @ResponseBody

18
application/src/main/java/org/thingsboard/server/service/entitiy/integration/DefaultTbIntegrationService.java

@ -15,21 +15,27 @@ import org.thingsboard.server.common.data.LibraryConvertersInfo;
import org.thingsboard.server.common.data.converter.ConverterType; import org.thingsboard.server.common.data.converter.ConverterType;
import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationInfo; import org.thingsboard.server.common.data.integration.IntegrationInfo;
import org.thingsboard.server.common.data.integration.IntegrationType; import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.converter.ConverterService; import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.integration.IntegrationService; import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.secret.SecretConfigurationService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.converter.ConverterLibraryService; import org.thingsboard.server.service.converter.ConverterLibraryService;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.integration.IntegrationManagerService;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Slf4j @Slf4j
@Service @Service
@ -40,6 +46,8 @@ public class DefaultTbIntegrationService extends AbstractTbEntityService impleme
private final IntegrationService integrationService; private final IntegrationService integrationService;
private final ConverterLibraryService converterLibraryService; private final ConverterLibraryService converterLibraryService;
private final ConverterService converterService; private final ConverterService converterService;
private final IntegrationManagerService integrationManagerService;
private final SecretConfigurationService secretConfigurationService;
@Override @Override
public PageData<IntegrationInfo> findTenantIntegrationInfos(TenantId tenantId, PageLink pageLink, boolean isEdgeTemplate) { public PageData<IntegrationInfo> findTenantIntegrationInfos(TenantId tenantId, PageLink pageLink, boolean isEdgeTemplate) {
@ -94,4 +102,14 @@ public class DefaultTbIntegrationService extends AbstractTbEntityService impleme
return result; return result;
} }
@Override
public void validateIntegrationConfiguration(TenantId tenantId, Integration integration) throws ExecutionException, InterruptedException, TimeoutException {
if (integration.isEdgeTemplate()) {
return;
}
Integration copy = new Integration(integration);
secretConfigurationService.replaceSecretUsages(tenantId, copy.getConfiguration());
integrationManagerService.validateIntegrationConfiguration(copy).get(20, TimeUnit.SECONDS);
}
} }

9
application/src/main/java/org/thingsboard/server/service/entitiy/integration/TbIntegrationService.java

@ -5,12 +5,15 @@ package org.thingsboard.server.service.entitiy.integration;
import org.thingsboard.server.common.data.IntegrationConvertersInfo; import org.thingsboard.server.common.data.IntegrationConvertersInfo;
import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EdgeId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.integration.IntegrationInfo; import org.thingsboard.server.common.data.integration.IntegrationInfo;
import org.thingsboard.server.common.data.integration.IntegrationType; import org.thingsboard.server.common.data.integration.IntegrationType;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public interface TbIntegrationService { public interface TbIntegrationService {
@ -19,4 +22,10 @@ public interface TbIntegrationService {
PageData<IntegrationInfo> findIntegrationInfosByTenantIdAndEdgeId(TenantId tenantId, EdgeId edgeId, PageLink pageLink); PageData<IntegrationInfo> findIntegrationInfosByTenantIdAndEdgeId(TenantId tenantId, EdgeId edgeId, PageLink pageLink);
Map<IntegrationType, IntegrationConvertersInfo> getIntegrationsConvertersInfo(TenantId tenantId); Map<IntegrationType, IntegrationConvertersInfo> getIntegrationsConvertersInfo(TenantId tenantId);
/**
* The check before an integration is saved: its configuration, with the secrets it uses, is validated by its type.
* An edge template isn't validated. An invalid configuration fails with an {@link ExecutionException}.
*/
void validateIntegrationConfiguration(TenantId tenantId, Integration integration) throws ExecutionException, InterruptedException, TimeoutException;
} }

947
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java

@ -0,0 +1,947 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import com.google.gson.JsonParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestClientException;
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.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.HasTenantId;
import org.thingsboard.server.common.data.HasVersion;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.converter.ConverterType;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
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.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
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.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.rule.RuleChainMetaData;
import org.thingsboard.server.common.data.security.DeviceCredentials;
import org.thingsboard.server.common.data.security.DeviceCredentialsType;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.dao.attributes.AttributesService;
import org.thingsboard.server.dao.converter.ConverterService;
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.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException;
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.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
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.
*/
@Service
@TbCoreComponent
@Slf4j
@RequiredArgsConstructor
public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService {
// Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id}
private static final Map<String, String> STEP_ALIASES = Map.of(
"DEVICE_PROFILE", "deviceProfile",
"DEVICE", "device",
"GATEWAY", "gateway",
"DASHBOARD", "dashboard",
"RULE_CHAIN", "ruleChain",
"UPLINK_CONVERTER", "uplinkConverter",
"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 final IotHubInstalledItemService installedItemService;
private final IotHubRestClient iotHubRestClient;
private final IotHubService iotHubService;
private final DevicePackageEntities packageEntities;
private final DeviceProfileService deviceProfileService;
private final DeviceService deviceService;
private final DeviceCredentialsService deviceCredentialsService;
private final DashboardService dashboardService;
private final RuleChainService ruleChainService;
private final TbRuleChainService tbRuleChainService;
private final ConverterService converterService;
private final IntegrationService integrationService;
private final TbIntegrationService tbIntegrationService;
private final SubscriptionService subscriptionService;
private final AttributesService attributesService;
private final TelemetrySubscriptionService telemetryService;
private final TransactionTemplate transactionTemplate;
@Override
public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) {
TenantId tenantId = user.getTenantId();
DeviceInstalledItemDescriptor descriptor = findDevicePackage(tenantId, installedItemId).descriptor();
Set<UUID> sharedIds = new HashSet<>();
iotHubService.findKeptEntities(tenantId, installedItemId).getEntities().forEach(e -> sharedIds.add(e.getEntityId().getId()));
Map<UUID, EntityId> createdIds = createdIds(descriptor);
Map<UUID, Set<String>> recordedChecksums = recordedChecksums(tenantId);
List<DevicePackageEntityState> states = new ArrayList<>();
if (descriptor.getInstallState() == null) {
return states;
}
descriptor.getInstallState().forEach((stepName, state) -> {
EntityId entityId = DevicePackageEntities.entityIdOf(state, createdIds);
if (entityId == null || !DevicePackageEntities.CHECKSUM_TYPES.contains(entityId.getEntityType())) {
return;
}
DevicePackageEntities.Snapshot snapshot = packageEntities.load(tenantId, entityId);
JsonNode storedChecksum = state.get("checksum");
// Changed by someone else only when no installed package recorded the current checksum: an update of another
// package that shares the entity, e.g. a converter, records it only in its own row
Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null :
!storedChecksum.asText().equals(snapshot.checksum())
&& !recordedChecksums.getOrDefault(entityId.getId(), Set.of()).contains(snapshot.checksum());
states.add(new DevicePackageEntityState(stepName, entityId, snapshot != null,
snapshot != null ? snapshot.version() : null, modified, sharedIds.contains(entityId.getId())));
});
return states;
}
@Override
public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId());
Applied applied;
try {
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));
} catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName);
} 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);
} catch (Exception e) {
log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e);
return DeviceUpdateResult.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());
}
private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) {
IotHubInstalledItem installedItem = installedItemService.findById(tenantId, installedItemId);
if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())
|| !(installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor)) {
throw new IllegalArgumentException("Installed device package not found");
}
return new DevicePackage(installedItem, descriptor);
}
/**
* The update may only change what the package owns, or what the user confirmed. The device and the gateway,
* whose credentials the firmware uses, are never changed.
*/
private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) {
if (request.getSteps() == null || request.getSteps().isEmpty()) {
throw new IllegalArgumentException("The update has no steps");
}
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor());
Set<String> stateKeys = new HashSet<>();
for (DeviceUpdateRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
throw new IllegalArgumentException("Invalid update step: " + step.getName());
}
// The key of the step's install state
if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) {
throw new IllegalArgumentException("Duplicate update step: " + step.getName());
}
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());
}
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId());
if (step.getAction() == DeviceUpdateRequest.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) {
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());
}
}
}
/** 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
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER")));
if (savesIntegrations) {
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
}
}
/** 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) {
continue;
}
ObjectNode body = step.getEntity().deepCopy();
// Converters this update 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);
try {
tbIntegrationService.validateIntegrationConfiguration(tenantId, integration);
} catch (ExecutionException e) {
// What the integration reports, e.g. wrong credentials, is what the user has to fix
Throwable cause = e.getCause() != null ? e.getCause() : e;
throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause));
} catch (TimeoutException e) {
throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration"));
}
}
}
private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) {
IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
DeviceInstalledItemDescriptor previous = devicePackage.descriptor();
Set<UUID> ownedIds = ownedIds(previous);
Map<String, ObjectNode> aliasOutputs = new HashMap<>();
Map<String, ObjectNode> outputs = new LinkedHashMap<>();
Map<String, ObjectNode> installState = new LinkedHashMap<>();
if (request.getInstallState() != null) {
request.getInstallState().forEach((key, value) -> {
if (value != null && value.has("formValues")) {
installState.put(key, JacksonUtil.newObjectNode().set("formValues", value.get("formValues")));
}
});
}
List<EntityId> stepEntityIds = new ArrayList<>();
Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous);
List<SavedEntity> saved = new ArrayList<>();
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>();
List<StepAttributes> attributes = new ArrayList<>();
// The checksums of the entities this update overwrote, which other packages may record too
DashboardId dashboardId = null;
for (DeviceUpdateRequest.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) {
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);
ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.getName(), output);
ObjectNode state = JacksonUtil.newObjectNode();
state.set("entityOutput", output);
// The package's own entity stays the package's, whatever the request says, so later versions update it
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId());
String resolution = step.getResolution() == null || (owned && "use-existing".equals(step.getResolution())) ? "created" : step.getResolution();
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();
if (checksum != null) {
state.put("checksum", checksum);
}
if (step.isDefaultConverter()) {
state.put("defaultConverter", true);
}
installState.put(step.getId() != null ? step.getId() : step.getName(), state);
if (!"use-existing".equals(resolution)) {
stepEntityIds.add(result.entityId());
} else {
usedExistingIds.putIfAbsent(result.entityId().getId(), result.entityId());
}
if (result.entityId() instanceof DashboardId id) {
dashboardId = id;
}
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
attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes()));
}
} catch (StepFailure e) {
throw e;
} catch (Exception e) {
throw new StepFailure(step.getName(), e);
}
}
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
// The new version may not offer the method the package was installed with
descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod());
descriptor.setCreatedEntityIds(createdEntityIds(tenantId, previous, stepEntityIds));
// Carried over like createdEntityIds, so an entity the user chose to use stays theirs after a version drops its step
Set<UUID> tracked = createdIds(descriptor).keySet();
descriptor.setUsedExistingEntityIds(usedExistingIds.values().stream().filter(id -> tracked.contains(id.getId())).toList());
descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous));
Map<String, JsonNode> state = new LinkedHashMap<>(installState);
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<StepAttributes> 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);
}
/** The checksums the installed device packages recorded, by entity. */
private Map<UUID, Set<String>> recordedChecksums(TenantId tenantId) {
Map<UUID, Set<String>> checksums = new HashMap<>();
PageLink pageLink = new PageLink(100);
PageData<IotHubInstalledItem> page;
do {
page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink);
for (IotHubInstalledItem item : page.getData()) {
if (item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor && descriptor.getInstallState() != null) {
descriptor.getInstallState().values().forEach(state -> {
UUID id = toUuid(state.path("entityOutput").path("id").asText());
JsonNode checksum = state.get("checksum");
if (id != null && checksum != null && checksum.isTextual()) {
checksums.computeIfAbsent(id, k -> new HashSet<>()).add(checksum.asText());
}
});
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext());
return checksums;
}
private static UUID toUuid(String id) {
try {
return UUID.fromString(id);
} catch (IllegalArgumentException e) {
return null;
}
}
/**
* 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) {
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())
|| !Objects.equals(devicePackage.installedItem().getItemVersionId(), installedItem.getItemVersionId())) {
throw new IllegalArgumentException("The package was updated meanwhile. Check the update again.");
}
return installedItem;
}
private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) 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 "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity);
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity);
case "INTEGRATION" -> saveIntegration(tenantId, step, entity);
default -> throw new IllegalArgumentException("Unsupported step type: " + step.getType());
};
}
private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.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) {
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) {
existing(tenantId, current, step);
prepareOverwrite(profile, id, current, step);
// The tenant's default profile stays the default one
profile.setDefault(current.isDefault());
} else {
profile.setId(null);
profile.setVersion(null);
}
DeviceProfile result = deviceProfileService.saveDeviceProfile(profile);
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null;
Device device;
boolean created = false;
if (step.getAction() == DeviceUpdateRequest.Action.CREATE) {
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
template.setId(null);
template.setVersion(null);
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
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
prepareOverwrite(template, id, current, step);
device = deviceService.saveDevice(template);
created = true;
}
}
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId());
if (created && step.getCredentials() != null && step.getCredentials().isObject()) {
credentials = applyCredentials(tenantId, credentials, step.getCredentials());
}
ObjectNode output = output(device.getId(), device.getName());
if (credentials != null) {
output.put("token", credentials.getCredentialsId());
}
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;
return new StepResult(device.getId(), output, null, saved);
}
private DeviceCredentials applyCredentials(TenantId tenantId, DeviceCredentials credentials, JsonNode template) {
JsonNode type = template.get("credentialsType");
if (type != null && type.isTextual()) {
credentials.setCredentialsType(DeviceCredentialsType.valueOf(type.asText()));
}
JsonNode value = template.get("credentialsValue");
if (value != null && !value.isNull()) {
credentials.setCredentialsValue(value.isTextual() ? value.asText() : value.toString());
}
JsonNode credentialsId = template.get("credentialsId");
if (credentialsId != null && credentialsId.isTextual()) {
credentials.setCredentialsId(credentialsId.asText());
}
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials);
}
private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
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) {
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) {
existing(tenantId, current, step);
prepareOverwrite(dashboard, id, current, step);
// The dashboard keeps its owner and the customers it is assigned to
if (dashboard.getCustomerId() == null) {
dashboard.setCustomerId(current.getCustomerId());
}
dashboard.setAssignedCustomers(current.getAssignedCustomers());
} else {
dashboard.setId(null);
dashboard.setVersion(null);
}
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 {
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) {
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) {
existing(tenantId, current, step);
prepareOverwrite(ruleChain, id, current, step);
// A rule chain the tenant made its root one stays the root
ruleChain.setRoot(current.isRoot());
} else {
ruleChain.setId(null);
ruleChain.setVersion(null);
ruleChain.setRoot(false);
}
RuleChain result = ruleChainService.saveRuleChain(ruleChain);
if (entity.has("metadata") && entity.get("metadata").isObject()) {
RuleChainMetaData metadata = JacksonUtil.treeToValue(entity.get("metadata"), RuleChainMetaData.class);
metadata.setRuleChainId(result.getId());
metadata.setVersion(result.getVersion());
if (!ruleChainService.saveRuleChainMetaData(tenantId, metadata, tbRuleChainService::updateRuleNodeConfiguration).isSuccess()) {
throw new IllegalStateException("Failed to save the rule chain metadata");
}
result = ruleChainService.findRuleChainById(tenantId, result.getId());
}
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.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) {
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) {
existing(tenantId, current, step);
prepareOverwrite(converter, id, current, step);
} else {
converter.setId(null);
converter.setVersion(null);
}
Converter result = converterService.saveConverter(converter);
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.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) {
existing(tenantId, current, step);
Integration merged = withMergedMetadata(current, step.getMetadata());
if (merged != null) {
Integration result = integrationService.saveIntegration(merged);
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result));
}
return new StepResult(id, integrationOutput(current), null, null);
}
Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
integration.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(integration, id, current, step);
// The devices keep sending to the same endpoint
integration.setRoutingKey(current.getRoutingKey());
} else {
integration.setId(null);
integration.setVersion(null);
if (integration.getRoutingKey() == null) {
integration.setRoutingKey(UUID.randomUUID().toString());
}
}
Integration result = integrationService.saveIntegration(integration);
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result));
}
/**
* 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.
*/
private static Integration withMergedMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) {
return null;
}
Integration copy = new Integration(integration);
ObjectNode configuration = copy.getConfiguration() instanceof ObjectNode current ? current : JacksonUtil.newObjectNode();
JsonNode before = configuration.get("metadata");
ObjectNode metadata = before instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode();
entries.fields().forEachRemaining(entry -> {
if (entry.getValue() == null || entry.getValue().isNull()) {
metadata.remove(entry.getKey());
} else {
metadata.put(entry.getKey(), entry.getValue().asText());
}
});
if (metadata.equals(before) || (metadata.isEmpty() && before == null)) {
return null;
}
configuration.set("metadata", metadata);
copy.setConfiguration(configuration);
return copy;
}
/**
* 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) {
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()); }
case Dashboard d -> { d.setId((DashboardId) id); d.setTitle(((Dashboard) current).getTitle()); }
case RuleChain r -> { r.setId((RuleChainId) id); r.setName(((RuleChain) current).getName()); }
case Converter c -> { c.setId((ConverterId) id); c.setName(((Converter) current).getName()); }
case Integration i -> { i.setId((IntegrationId) id); i.setName(((Integration) current).getName()); }
default -> throw new IllegalArgumentException("Unsupported entity: " + entity.getClass().getSimpleName());
}
Long currentVersion = ((HasVersion) current).getVersion();
if (step.getExpectedVersion() != null && !step.getExpectedVersion().equals(currentVersion)) {
throw new EntityVersionMismatchException(id.getEntityType(), null);
}
((HasVersion) entity).setVersion(currentVersion);
}
private <T> T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) {
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) {
throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again.");
}
return current;
}
private StepResult kept(EntityId id, String name) {
return new StepResult(id, output(id, name), null, null);
}
/** The checksum the installed version recorded for the entity, under whichever step it was installed with. */
private static String previousChecksum(DeviceInstalledItemDescriptor previous, UUID entityId) {
if (previous.getInstallState() == null || entityId == null) {
return null;
}
for (JsonNode state : previous.getInstallState().values()) {
JsonNode checksum = state.get("checksum");
if (entityId.toString().equals(state.path("entityOutput").path("id").asText()) && checksum != null && checksum.isTextual()) {
return checksum.asText();
}
}
return null;
}
/**
* The checksum is of the entity the save returned: a profile or an integration read back by id inside the
* 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) {
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));
}
private static ObjectNode output(EntityId id, String name) {
ObjectNode output = JacksonUtil.newObjectNode();
output.put("id", id.getId().toString());
output.put("name", name);
return output;
}
/** With what the install instructions resolve: ${integration.routingKey}, ${integration.httpEndpoint}, ${integration.baseUrl}. */
private static ObjectNode integrationOutput(Integration integration) {
ObjectNode output = output(integration.getId(), integration.getName());
output.put("routingKey", integration.getRoutingKey());
JsonNode configuration = integration.getConfiguration() != null ? integration.getConfiguration() : JacksonUtil.newObjectNode();
JsonNode client = configuration.path("clientConfiguration");
putText(output, "httpEndpoint", client.path("httpEndpoint"), configuration.path("httpEndpoint"));
putText(output, "baseUrl", client.path("baseUrl"), configuration.path("baseUrl"));
return output;
}
private static void putText(ObjectNode output, String key, JsonNode first, JsonNode second) {
JsonNode value = first.isTextual() ? first : second;
if (value.isTextual()) {
output.put(key, value.asText());
}
}
/** Replaces ${<alias>.<property>} of entities this update has saved, e.g. the id of a converter it created. */
static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) {
if (node == null) {
return null;
}
if (node.isTextual()) {
String text = node.asText();
Matcher matcher = ENTITY_PLACEHOLDER.matcher(text);
StringBuilder resolved = new StringBuilder();
boolean changed = false;
while (matcher.find()) {
ObjectNode output = aliasOutputs.get(matcher.group(1));
JsonNode value = output != null ? output.get(matcher.group(2)) : null;
String replacement = value != null && !value.isNull() ? value.asText() : matcher.group();
changed |= value != null && !value.isNull();
matcher.appendReplacement(resolved, Matcher.quoteReplacement(replacement));
}
matcher.appendTail(resolved);
return changed ? TextNode.valueOf(resolved.toString()) : node;
}
if (node.isObject()) {
ObjectNode copy = JacksonUtil.newObjectNode();
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) {
Map.Entry<String, JsonNode> field = it.next();
copy.set(field.getKey(), resolvePlaceholders(field.getValue(), aliasOutputs));
}
return copy;
}
if (node.isArray()) {
ArrayNode copy = JacksonUtil.newArrayNode();
node.forEach(item -> copy.add(resolvePlaceholders(item, aliasOutputs)));
return copy;
}
return node;
}
/**
* The ids the package tracks: the entities of this version's steps, and those of the installed version this one
* no longer uses, so deleting the package still deletes them. Entities deleted since are dropped.
*/
private List<EntityId> createdEntityIds(TenantId tenantId, DeviceInstalledItemDescriptor previous, List<EntityId> stepEntityIds) {
List<EntityId> ids = new ArrayList<>(stepEntityIds);
Set<UUID> known = new HashSet<>();
ids.forEach(id -> known.add(id.getId()));
if (previous.getCreatedEntityIds() != null) {
for (EntityId id : previous.getCreatedEntityIds()) {
if (known.add(id.getId()) && entityService.fetchEntity(tenantId, id).isPresent()) {
ids.add(id);
}
}
}
return ids;
}
private DashboardId existingDashboard(TenantId tenantId, DeviceInstalledItemDescriptor previous) {
DashboardId id = previous.getDashboardId();
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. */
private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) {
for (SavedEntity saved : applied.saved()) {
try {
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(),
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);
}
}
for (StepAttributes step : applied.attributes()) {
try {
saveAttributes(tenantId, step.entityId(), AttributeScope.SERVER_SCOPE, step.server());
saveAttributes(tenantId, step.entityId(), AttributeScope.SHARED_SCOPE, step.shared());
} catch (Exception e) {
log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e);
}
}
for (DeviceUpdateRequest.Step step : applied.connectorSteps()) {
try {
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity());
} catch (Exception e) {
log.warn("[{}] Failed to save the gateway connector of device package step [{}]", tenantId, step.getName(), e);
}
}
}
private void saveConnector(TenantId tenantId, ObjectNode gateway, JsonNode connector) throws Exception {
if (gateway == null || connector == null || !connector.has("name")) {
return;
}
DeviceId gatewayId = new DeviceId(UUID.fromString(gateway.get("id").asText()));
String name = connector.get("name").asText();
List<String> active = new ArrayList<>();
for (AttributeKvEntry entry : attributesService.find(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, List.of("active_connectors")).get()) {
JsonNode value = JacksonUtil.toJsonNode(entry.getValueAsString());
if (value != null && value.isArray()) {
value.forEach(v -> active.add(v.asText()));
}
}
if (!active.contains(name)) {
active.add(name);
}
ObjectNode attributes = JacksonUtil.newObjectNode();
attributes.set("active_connectors", JacksonUtil.valueToTree(active));
attributes.set(name, connector);
saveAttributes(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, attributes);
}
private void saveAttributes(TenantId tenantId, EntityId entityId, AttributeScope scope, JsonNode attributes) {
if (attributes == null || !attributes.isObject() || attributes.isEmpty()) {
return;
}
List<AttributeKvEntry> entries = JsonConverter.convertToAttributes(JsonParser.parseString(attributes.toString()));
telemetryService.saveAttributes(AttributesSaveRequest.builder()
.tenantId(tenantId)
.entityId(entityId)
.scope(scope)
.entries(entries)
.build());
}
/**
* The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database
* error, as a common message, with the details in the log.
*/
static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) {
return "Someone changed it while you were reviewing the update. Check the update again.";
}
if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException
|| e instanceof SubscriptionException) {
return e.getMessage();
}
if (e instanceof ThingsboardException te && te.getErrorCode() != ThingsboardErrorCode.GENERAL) {
return te.getMessage();
}
return UNEXPECTED_ERROR;
}
private static boolean isKnownType(String type) {
return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type));
}
/**
* The entities the package owns: those it created, not the ones the user chose to use as they were. The install adds
* those to createdEntityIds too, so they are subtracted; an entity of a step a later version dropped stays owned.
*/
private static Set<UUID> ownedIds(DeviceInstalledItemDescriptor descriptor) {
Set<UUID> ids = new HashSet<>(createdIds(descriptor).keySet());
ids.removeAll(usedExistingIds(descriptor).keySet());
return ids;
}
/**
* The entities the user chose to use as they were. An install made before the descriptor kept them has them only in
* its install state, which the first update carries over into the descriptor.
*/
private static Map<UUID, EntityId> usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
Map<UUID, EntityId> ids = new LinkedHashMap<>();
if (descriptor.getUsedExistingEntityIds() != null) {
descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id));
return ids;
}
Map<UUID, EntityId> createdIds = createdIds(descriptor);
if (descriptor.getInstallState() != null) {
descriptor.getInstallState().values().forEach(state -> {
UUID id = toUuid(state.path("entityOutput").path("id").asText());
if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) {
ids.put(id, createdIds.get(id));
}
});
}
return ids;
}
private static Map<UUID, EntityId> createdIds(DeviceInstalledItemDescriptor descriptor) {
Map<UUID, EntityId> ids = new HashMap<>();
if (descriptor.getCreatedEntityIds() != null) {
descriptor.getCreatedEntityIds().forEach(id -> ids.put(id.getId(), id));
}
return ids;
}
private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) {
DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class);
if (entity != null) {
copy.setEntity(entity);
}
return copy;
}
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) {
}
private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) {
}
private record SavedEntity(EntityId id, Object entity, boolean created) {
}
private record StepAttributes(String stepName, EntityId entityId, JsonNode server, JsonNode shared) {
}
private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved,
List<DeviceUpdateRequest.Step> connectorSteps, List<StepAttributes> attributes,
Map<String, ObjectNode> aliasOutputs) {
}
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */
private static class StepFailure extends RuntimeException {
private final String stepName;
StepFailure(String stepName, Throwable cause) {
super(cause.getMessage(), cause);
this.stepName = stepName;
}
}
}

47
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -133,6 +133,7 @@ public class DefaultIotHubService implements IotHubService {
private final ConverterService converterService; private final ConverterService converterService;
private final TbConverterService tbConverterService; private final TbConverterService tbConverterService;
private final ProjectInfo projectInfo; private final ProjectInfo projectInfo;
private final DevicePackageEntities devicePackageEntities;
// Field names of the marketplace version JSON payload. Both the install path and the // Field names of the marketplace version JSON payload. Both the install path and the
// install-plan resolver parse the same shape, so the contract lives here in one place. // install-plan resolver parse the same shape, so the contract lives here in one place.
@ -416,6 +417,10 @@ public class DefaultIotHubService implements IotHubService {
} }
String itemType = installedItem.getItemType(); String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) {
// Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService
throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
}
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
// Skip checksum validation for solution templates // Skip checksum validation for solution templates
@ -460,12 +465,6 @@ public class DefaultIotHubService implements IotHubService {
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData); case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData); case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData); case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
case "DEVICE" -> {
DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor;
deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user);
dd.setCreatedEntityIds(null);
dd.setDashboardId(null);
}
case "SOLUTION_TEMPLATE" -> { case "SOLUTION_TEMPLATE" -> {
SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor; SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor;
solutionService.deleteSolution(tenantId, stDescriptor, user); solutionService.deleteSolution(tenantId, stDescriptor, user);
@ -679,6 +678,8 @@ public class DefaultIotHubService implements IotHubService {
installedItem.setItemName(itemName); installedItem.setItemName(itemName);
installedItem.setItemType("DEVICE"); installedItem.setItemType("DEVICE");
installedItem.setVersion(version); installedItem.setVersion(version);
// So that an update can tell whether someone changed an entity since
devicePackageEntities.addChecksums(tenantId, descriptor);
installedItem.setDescriptor(descriptor); installedItem.setDescriptor(descriptor);
try { try {
iotHubInstalledItemService.save(tenantId, installedItem); iotHubInstalledItemService.save(tenantId, installedItem);
@ -712,17 +713,24 @@ public class DefaultIotHubService implements IotHubService {
/** /**
* Deletes what a device package created, except the entities another installed device package * Deletes what a device package created, except the entities another installed device package
* also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package,
* and the ones the user had before and the package took as they were (use existing).
*/ */
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
List<EntityId> createdEntityIds, SecurityUser user) { DeviceInstalledItemDescriptor descriptor, SecurityUser user) {
List<EntityId> createdEntityIds = descriptor.getCreatedEntityIds();
if (createdEntityIds == null || createdEntityIds.isEmpty()) { if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return; return;
} }
Set<UUID> usedExisting = usedExistingIds(descriptor);
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId);
List<EntityId> reversed = new ArrayList<>(createdEntityIds); List<EntityId> reversed = new ArrayList<>(createdEntityIds);
Collections.reverse(reversed); Collections.reverse(reversed);
for (EntityId entityId : reversed) { for (EntityId entityId : reversed) {
if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
continue;
}
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) { if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
@ -745,17 +753,34 @@ public class DefaultIotHubService implements IotHubService {
} }
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>(); List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>(); Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Set<UUID> usedExisting = usedExistingIds(dd);
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId); Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId);
for (EntityId entityId : dd.getCreatedEntityIds()) { for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) { boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) {
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)));
}
if (usedBy != null) {
usedByItems.addAll(usedBy); usedByItems.addAll(usedBy);
} }
if (taken) {
usedExistingCount++;
}
} }
} }
return new InstalledItemKeptEntities(kept, usedByItems.size()); return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount);
}
/** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */
private static Set<UUID> usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
Set<UUID> ids = new HashSet<>();
if (descriptor.getUsedExistingEntityIds() != null) {
descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId()));
}
return ids;
} }
private Map<UUID, Set<IotHubInstalledItemId>> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) { private Map<UUID, Set<IotHubInstalledItemId>> findEntitiesOfOtherDevicePackages(TenantId tenantId, IotHubInstalledItemId installedItemId) {
@ -853,7 +878,7 @@ public class DefaultIotHubService implements IotHubService {
} }
} }
} else if (descriptor instanceof DeviceInstalledItemDescriptor dd) { } else if (descriptor instanceof DeviceInstalledItemDescriptor dd) {
deleteDevicePackageEntities(tenantId, installedItemId, dd.getCreatedEntityIds(), user); deleteDevicePackageEntities(tenantId, installedItemId, dd, user);
} else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) { } else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) {
try { try {
solutionService.deleteSolution(tenantId, st, user); solutionService.deleteSolution(tenantId, st, user);

119
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntities.java

@ -0,0 +1,119 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway
* and a gateway connector don't have one: an update never changes them.
*/
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class DevicePackageEntities {
static final Set<EntityType> CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD,
EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION);
private final DeviceProfileService deviceProfileService;
private final DashboardService dashboardService;
private final RuleChainService ruleChainService;
private final ConverterService converterService;
private final IntegrationService integrationService;
/** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */
public Snapshot load(TenantId tenantId, EntityId entityId) {
Object entity = switch (entityId.getEntityType()) {
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId);
case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId);
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId);
case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId);
case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId);
default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType());
};
if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) {
return null;
}
Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null;
return new Snapshot(entity, metadata);
}
public String checksum(TenantId tenantId, EntityId entityId) {
Snapshot snapshot = load(tenantId, entityId);
return snapshot != null ? snapshot.checksum() : null;
}
/**
* Adds the checksum of each entity the install state names, so that an update can tell whether someone changed
* it since. Entities the user kept at install are left out: an update never overwrites them.
*/
public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) {
if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) {
return;
}
Map<UUID, EntityId> createdIds = new HashMap<>();
descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id));
descriptor.getInstallState().forEach((stepName, state) -> {
EntityId entityId = entityIdOf(state, createdIds);
if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) {
String checksum = checksum(tenantId, entityId);
if (checksum != null) {
((ObjectNode) state).put("checksum", checksum);
}
}
});
}
/** The package entity an install-state step recorded, with its type from the ids the package created. */
static EntityId entityIdOf(JsonNode state, Map<UUID, EntityId> createdIds) {
JsonNode id = state != null ? state.path("entityOutput").path("id") : null;
if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) {
return null;
}
try {
return createdIds.get(UUID.fromString(id.asText()));
} catch (IllegalArgumentException e) {
return null;
}
}
public record Snapshot(Object entity, Object metadata) {
public Long version() {
return ((HasVersion) entity).getVersion();
}
public String checksum() {
return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity);
}
}
}

27
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageEntityState.java

@ -0,0 +1,27 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.id.EntityId;
/** An entity of an installed device package as an update finds it, before it changes anything. */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DevicePackageEntityState {
private String stepName;
private EntityId entityId;
private boolean exists;
// Sent back with the update, which fails if someone changed the entity in between
private Long version;
// Changed since the package installed or last updated it; null when the install state has no checksum of it
// (installed before checksums were kept)
private Boolean modified;
// Other installed device packages use it, so overwriting it affects them
private boolean shared;
}

19
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java

@ -0,0 +1,19 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
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 {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId);
/** 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);
}

71
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java

@ -0,0 +1,71 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import java.util.List;
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.
*/
@Data
public class DeviceUpdateRequest {
private String versionId;
// The version installed when the wizard planned the update; the update fails if the package changed since
private UUID fromVersionId;
// The install method of the new version's steps; the installed one when not set
private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it
private Map<String, JsonNode> installState;
private List<Step> steps;
public enum Action {
// Taken as it is: the 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
CREATE
}
@Data
public static class Step {
private String name;
// The package step's id, which keys its install state; the name when not set
private String id;
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
private String type;
private Action action;
// KEEP and OVERWRITE: the entity
private UUID entityId;
// OVERWRITE: the version the user reviewed; a different one means someone changed the entity since
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. ${<alias>.<property>} of an entity this
// update 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 ${<alias>.<property>} of an entity this update creates.
private JsonNode serverAttributes;
private JsonNode sharedAttributes;
// The resolution the install state records for it
private String resolution;
// 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
private boolean defaultConverter;
}
}

37
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java

@ -0,0 +1,37 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import java.util.Map;
/**
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep
* names the step that failed, if one did.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeviceUpdateResult {
private boolean success;
private String errorMessage;
private String failedStep;
private DeviceInstalledItemDescriptor descriptor;
// By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DeviceUpdateResult(true, null, null, descriptor, outputs);
}
public static DeviceUpdateResult error(String errorMessage, String failedStep) {
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null);
}
}

116
application/src/main/java/org/thingsboard/server/service/iot_hub/EntityChecksum.java

@ -0,0 +1,116 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.rule.RuleChainMetaData;
import org.thingsboard.server.common.data.rule.RuleNode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* The checksum of an entity as the server stores it, kept in the install state of a device package. A different
* checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name,
* which an update keeps, don't count, nor do the debug settings, which the user turns on without changing what the
* entity does, and whether a profile is the default one, which changes when another profile becomes the default.
*/
final class EntityChecksum {
private static final Set<String> SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId",
"customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources", "debugMode", "debugSettings", "default");
private EntityChecksum() {
}
/** A rule chain is checked with its metadata: pass both. */
static String of(Object... parts) {
StringBuilder canonical = new StringBuilder();
for (Object part : parts) {
JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part);
if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) {
// Device packages on one integration add their entries to its metadata: that is no change to the integration
configuration.remove("metadata");
}
appendCanonical(canonical, node, true);
canonical.append('|');
}
try {
byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(hash);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
/**
* What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and
* configuration, and the connections. Node ids, layout and debug settings change without the user changing
* what the rule chain does, e.g. when it is saved again.
*/
private static JsonNode ruleChainContent(RuleChainMetaData metadata) {
ObjectNode content = JacksonUtil.newObjectNode();
ArrayNode nodes = content.putArray("nodes");
if (metadata.getNodes() != null) {
for (RuleNode node : metadata.getNodes()) {
ObjectNode n = nodes.addObject();
n.put("type", node.getType());
n.put("name", node.getName());
n.set("configuration", node.getConfiguration());
n.put("singletonMode", node.isSingletonMode());
n.put("queueName", node.getQueueName());
}
}
content.set("connections", JacksonUtil.valueToTree(metadata.getConnections()));
content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections()));
content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex()));
return content;
}
/** JSON with the keys sorted, so the same entity always gives the same text. */
private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) {
if (node == null || node.isNull() || node.isMissingNode()) {
out.append("null");
} else if (node.isObject()) {
List<String> keys = new ArrayList<>();
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
String key = it.next();
if (!topLevel || !SKIPPED_KEYS.contains(key)) {
keys.add(key);
}
}
keys.sort(null);
out.append('{');
for (int i = 0; i < keys.size(); i++) {
if (i > 0) {
out.append(',');
}
out.append(JacksonUtil.toString(keys.get(i))).append(':');
appendCanonical(out, node.get(keys.get(i)), false);
}
out.append('}');
} else if (node.isArray()) {
out.append('[');
for (int i = 0; i < node.size(); i++) {
if (i > 0) {
out.append(',');
}
appendCanonical(out, node.get(i), false);
}
out.append(']');
} else {
out.append(node.toString());
}
}
}

4
application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java

@ -9,7 +9,7 @@ import org.thingsboard.server.common.data.id.EntityId;
import java.util.List; import java.util.List;
/** What deleting an installed item keeps, because other installed items use it too. */ /** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@ -18,6 +18,8 @@ public class InstalledItemKeptEntities {
private List<KeptEntity> entities; private List<KeptEntity> entities;
// How many other installed items use at least one of the kept entities // How many other installed items use at least one of the kept entities
private int usedByItemsCount; private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount;
@Data @Data
@NoArgsConstructor @NoArgsConstructor

29
application/src/test/java/org/thingsboard/server/controller/ConverterControllerTest.java

@ -686,9 +686,7 @@ public class ConverterControllerTest extends AbstractControllerTest {
testDecoder(TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter); testDecoder(TTI_UPLINK_DECODER, DEFAULT_TTI_UPLINK_CONVERTER_MESSAGE, expectedDecodedMessage, converter);
} }
@Test private static final String THINGS_STACK_REPOSITORY_DEVICE_RESULT = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," +
public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException {
String expectedDecodedMessage = "{\"entityType\":\"DEVICE\",\"name\":\"am308-office\",\"profile\":\"milesight-iot-am308\",\"label\":\"am308-office\",\"group\":\"my-app\"," +
"\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560," + "\"telemetry\":[{\"ts\":1793170000000,\"values\":{\"temperature\":24.1,\"co2\":550}},{\"ts\":1793181600100,\"values\":{\"battery\":95,\"temperature\":24.5,\"co2\":560," +
"\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," + "\"fCnt\":12,\"data\":\"AXVk\",\"rssi\":-60,\"snr\":9.5,\"channel\":2,\"consumedAirtime\":\"0.061696s\"}}]," +
"\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," + "\"attributes\":{\"eui\":\"24E124707C481005\",\"joinEui\":\"24E124C0002A0001\",\"devAddr\":\"260B1234\",\"deviceId\":\"am308-office\",\"applicationId\":\"my-app\"," +
@ -696,7 +694,17 @@ public class ConverterControllerTest extends AbstractControllerTest {
"\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," + "\"hardwareVersion\":\"1.0\",\"firmwareVersion\":\"1.0\",\"bandId\":\"EU_863_870\",\"netId\":\"000013\",\"tenantId\":\"ttn\",\"clusterId\":\"eu1\"," +
"\"clusterAddress\":\"eu1.cloud.thethings.network\"}}"; "\"clusterAddress\":\"eu1.cloud.thethings.network\"}}";
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, expectedDecodedMessage); @Test
public void testThingsStackDefaultConvertersGiveRepositoryDeviceItsModelProfile() throws IOException {
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, Map.of(), THINGS_STACK_REPOSITORY_DEVICE_RESULT);
}
@Test
public void testThingsStackDefaultConvertersTakeProfileNameFromIntegrationMetadata() throws IOException {
String expectedDecodedMessage = THINGS_STACK_REPOSITORY_DEVICE_RESULT.replace("\"profile\":\"milesight-iot-am308\"", "\"profile\":\"AM308\"");
Map<String, String> integrationMetadata = Map.of("profile.milesight-iot-am308", "AM308", "profile.milesight-iot-ws202", "WS202");
testThingsStackDefaultConverters(THINGS_STACK_REPOSITORY_DEVICE_PAYLOAD, integrationMetadata, expectedDecodedMessage);
} }
@Test @Test
@ -706,18 +714,18 @@ public class ConverterControllerTest extends AbstractControllerTest {
"\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," + "\"attributes\":{\"eui\":\"70B3D57ED006F370\",\"deviceId\":\"manual-node\",\"applicationId\":\"my-app\",\"fPort\":1,\"bandwidth\":125000," +
"\"spreadingFactor\":9,\"frequency\":\"868300000\"}}"; "\"spreadingFactor\":9,\"frequency\":\"868300000\"}}";
testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, expectedDecodedMessage); testThingsStackDefaultConverters(THINGS_STACK_MANUAL_DEVICE_PAYLOAD, Map.of("profile.milesight-iot-am308", "AM308"), expectedDecodedMessage);
} }
// The TBEL and JS defaults are two copies of one script, so each of them must give this result for TTN and TTI // The TBEL and JS defaults are two copies of one script, so each of them must give this result for TTN and TTI
private void testThingsStackDefaultConverters(String payloadFile, String expectedResult) throws IOException { private void testThingsStackDefaultConverters(String payloadFile, Map<String, String> integrationMetadata, String expectedResult) throws IOException {
JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION)); JsonNode defaultConfigurations = JacksonUtil.toJsonNode(readResource(DEFAULT_V2_CONFIGURATION));
String payload = readResource(payloadFile); String payload = readResource(payloadFile);
for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) { for (IntegrationType integrationType : List.of(IntegrationType.TTN, IntegrationType.TTI)) {
Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2); Converter converter = createConverter(defaultConfigurations.get(integrationType.name()), integrationType, 2);
for (ScriptLanguage scriptLang : ScriptLanguage.values()) { for (ScriptLanguage scriptLang : ScriptLanguage.values()) {
String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw"; String decoderFileName = "converters/" + scriptLang.name().toLowerCase() + "-" + integrationType.name().toLowerCase() + "-decoder.raw";
assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang))) assertThat(JacksonUtil.toJsonNode(decode(decoderFileName, payload, converter, scriptLang, integrationMetadata)))
.as("%s %s", integrationType, scriptLang) .as("%s %s", integrationType, scriptLang)
.isEqualTo(JacksonUtil.toJsonNode(expectedResult)); .isEqualTo(JacksonUtil.toJsonNode(expectedResult));
} }
@ -896,6 +904,12 @@ public class ConverterControllerTest extends AbstractControllerTest {
} }
private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException { private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang) throws IOException {
return decode(decoderFileName, payloadExample, converter, scriptLang, Map.of());
}
// integrationMetadata: what the integration adds to the metadata of every uplink, from its configuration
private String decode(String decoderFileName, String payloadExample, Converter converter, ScriptLanguage scriptLang,
Map<String, String> integrationMetadata) throws IOException {
byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName)); byte[] bytes = IOUtils.toByteArray(ConverterControllerTest.class.getClassLoader().getResourceAsStream(decoderFileName));
String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8)); String base64Payload = Base64.getEncoder().encodeToString(payloadExample.getBytes(StandardCharsets.UTF_8));
@ -917,6 +931,7 @@ public class ConverterControllerTest extends AbstractControllerTest {
inputParams.set("payload", unwrapped.get("payload")); inputParams.set("payload", unwrapped.get("payload"));
} }
inputParams.set("metadata",unwrapped.get("metadata")); inputParams.set("metadata",unwrapped.get("metadata"));
integrationMetadata.forEach(((ObjectNode) inputParams.get("metadata"))::put);
} else { } else {
inputParams.set("payload", new TextNode(base64Payload)); inputParams.set("payload", new TextNode(base64Payload));
} }

748
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -0,0 +1,748 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
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.thingsboard.common.util.JacksonUtil;
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.AttributeScope;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
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.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.integration.Integration;
import org.thingsboard.server.common.data.page.PageData;
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.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.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.subscription.PlatformFeature;
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.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
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.Mockito.doThrow;
import static org.mockito.Mockito.never;
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 {
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
private final SecurityUser user = mock(SecurityUser.class);
private final UUID itemId = UUID.randomUUID();
private final String versionId = UUID.randomUUID().toString();
private final UUID installedVersionId = UUID.randomUUID();
private final DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID());
private final DashboardId dashboardId = new DashboardId(UUID.randomUUID());
private final DeviceId deviceId = new DeviceId(UUID.randomUUID());
private final IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
@Mock
private IotHubInstalledItemService installedItemService;
@Mock
private IotHubRestClient iotHubRestClient;
@Mock
private DevicePackageEntities packageEntities;
@Mock
private DeviceProfileService deviceProfileService;
@Mock
private DashboardService dashboardService;
@Mock
private DeviceService deviceService;
@Mock
private DeviceCredentialsService deviceCredentialsService;
@Mock
private ConverterService converterService;
@Mock
private IntegrationService integrationService;
@Mock
private TransactionTemplate transactionTemplate;
@Mock
private EntityService entityService;
@Mock
private TbLogEntityActionService logEntityActionService;
@Mock
private TbIntegrationService tbIntegrationService;
@Mock
private SubscriptionService subscriptionService;
@Mock
private TelemetrySubscriptionService telemetryService;
@Mock
private IotHubService iotHubService;
@InjectMocks
private DefaultDevicePackageUpdateService service;
private IotHubInstalledItem installedItem;
// Set when the transaction callback threw, so the transaction would roll back
private final List<RuntimeException> rolledBack = new ArrayList<>();
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(service, "entityService", entityService);
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService);
when(user.getTenantId()).thenReturn(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setSelectedInstallMethod("INTEGRATION_TTN");
descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId));
descriptor.setDashboardId(dashboardId);
// The package created these entities
descriptor.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"),
"Dashboard", stateOf(dashboardId, "created"), "Integration", stateOf(integrationId, "created")));
installedItem = new IotHubInstalledItem();
installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID()));
installedItem.setTenantId(tenantId);
installedItem.setItemId(itemId);
installedItem.setItemType("DEVICE");
installedItem.setVersion("1.0.0");
installedItem.setItemVersionId(installedVersionId);
installedItem.setDescriptor(descriptor);
when(installedItemService.findById(tenantId, installedItem.getId())).thenReturn(installedItem);
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(installedItem);
ObjectNode versionInfo = JacksonUtil.newObjectNode();
versionInfo.put("itemId", itemId.toString());
versionInfo.put("name", "AM308");
versionInfo.put("version", "1.0.1");
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
try {
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null);
} catch (RuntimeException e) {
rolledBack.add(e);
throw e;
}
});
when(packageEntities.checksum(any(), any())).thenReturn("checksum");
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.empty());
Device device = new Device(deviceId);
device.setTenantId(tenantId);
device.setName("AM308");
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>());
}
@Test
void overwritesTheEntitiesAndRecordsTheNewVersionInOneTransaction() {
DeviceProfile profile = profile(3L, "AM308 renamed");
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile);
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0));
Dashboard dashboard = dashboard(7L);
dashboard.setCustomerId(new CustomerId(UUID.randomUUID()));
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(
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"))));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<DeviceProfile> savedProfile = ArgumentCaptor.forClass(DeviceProfile.class);
verify(deviceProfileService).saveDeviceProfile(savedProfile.capture());
// Same id, the name the user gave it, the version they reviewed
assertThat(savedProfile.getValue().getId()).isEqualTo(profileId);
assertThat(savedProfile.getValue().getName()).isEqualTo("AM308 renamed");
assertThat(savedProfile.getValue().getDescription()).isEqualTo("new");
assertThat(savedProfile.getValue().getVersion()).isEqualTo(3L);
ArgumentCaptor<Dashboard> savedDashboard = ArgumentCaptor.forClass(Dashboard.class);
verify(dashboardService).saveDashboard(savedDashboard.capture());
assertThat(savedDashboard.getValue().getCustomerId()).isEqualTo(dashboard.getCustomerId());
verify(installedItemService).save(tenantId, installedItem);
assertThat(installedItem.getVersion()).isEqualTo("1.0.1");
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText())
.isEqualTo(EntityChecksum.of(savedDashboard.getValue()));
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId);
}
@Test
void keptEntity_keepsTheChecksumThePackageLeft() {
// The user changed the dashboard since: its current checksum must not become the package's
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created");
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));
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@Test
void keptEntityOfAStepWithAnId_keepsItsChecksumUnderTheId() {
// Installed by a version whose step had no id: the entry is under the step's name
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created");
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);
overview.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed");
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview");
}
@Test
void keptEntity_doesNotTakeTheChecksumOfAnotherEntity() {
// The entry under the step's key was recorded for an entity deleted since
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "of-the-deleted-one").put("resolution", "created");
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", UUID.randomUUID().toString()));
((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)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse();
}
@Test
void useExistingOfAPackageEntity_staysThePackages() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created");
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId);
}
@Test
void useExistingAtInstall_staysUseExisting() {
// 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);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing");
}
@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"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void sharedEntityOverwrittenByAnotherPackage_isNotChangedBySomeoneElse() {
Dashboard shared = dashboard(9L);
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null);
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot);
when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0));
// This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one
ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it");
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own));
IotHubInstalledItem other = otherPackage(Map.of("Dashboard", stateOf(dashboardId, "created").put("checksum", snapshot.checksum())));
when(installedItemService.findByTenantId(any(), any(), any(), any()))
.thenReturn(new PageData<>(List.of(installedItem, other), 1, 2, false));
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isFalse();
shared.setConfiguration(JacksonUtil.newObjectNode().put("description", "Changed by hand"));
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isTrue();
}
@Test
void entityOfAStepAVersionDropped_staysThePackages() {
// 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);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created");
}
@Test
void entityUsedAtInstall_staysTheUsersAfterAVersionDropsItsStep() {
// Recorded at install; the step is gone from the install state since
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"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void entitiesUsedAtInstall_areCarriedIntoTheDescriptor() {
// Installed before the descriptor kept them: the install state has them
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing")));
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)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
}
@Test
void keptIntegration_getsTheStepsMetadataEntries() {
// Taken as it was at install: other packages' entries stay, the step's are merged, a null one is removed
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", stateOf(integrationId, "use-existing")));
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other").put("profile.milesight-iot-am308", "AM308"));
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);
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));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
JsonNode metadata = saved.getValue().getConfiguration().get("metadata");
assertThat(metadata.get("profile.other-model").asText()).isEqualTo("Other");
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge");
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse();
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
assertThat(saved.getValue()).isNotSameAs(current);
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText())
.isEqualTo("use-existing");
}
@Test
void keptIntegrationWithTheEntriesItHas_isNotSaved() {
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode();
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);
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any());
}
@Test
void twoStepsWithOneKey_areRejected() {
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
first.setId("main-dashboard");
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
second.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void failedStep_rollsBackAndReportsTheStep() {
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308"));
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0));
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(
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")),
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
assertThat(rolledBack).hasSize(1);
verify(installedItemService, never()).save(any(), any());
verifyNoInteractions(logEntityActionService);
assertThat(installedItem.getVersion()).isEqualTo("1.0.0");
}
@Test
void entityChangedSinceTheCheck_isAVersionConflict() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("Dashboard");
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@Test
void integrationGetsTheIdOfTheConverterCreatedInTheSameUpdate() throws Exception {
ConverterId converterId = new ConverterId(UUID.randomUUID());
when(converterService.saveConverter(any())).thenAnswer(i -> {
Converter converter = i.getArgument(0);
converter.setId(converterId);
return converter;
});
Integration current = new Integration();
current.setId(integrationId);
current.setTenantId(tenantId);
current.setName("TTN my-app");
current.setRoutingKey("routing-key");
current.setVersion(2L);
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
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(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")),
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration)));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
verify(integrationService).saveIntegration(saved.capture());
assertThat(saved.getValue().getDefaultConverterId()).isEqualTo(converterId);
// The devices keep sending to the same endpoint
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key");
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app");
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key");
}
@Test
void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() {
ConverterId converterId = new ConverterId(UUID.randomUUID());
Converter current = new Converter(converterId);
current.setTenantId(tenantId);
current.setName("Uplink data converter for TTN my-app");
current.setVersion(4L);
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current);
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0));
// The package that created the converter records its checksum; one that took it as it was records none
ObjectNode created = JacksonUtil.newObjectNode().put("checksum", "before").put("resolution", "created");
created.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString()));
ObjectNode usedExisting = JacksonUtil.newObjectNode().put("resolution", "use-existing");
usedExisting.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString()));
IotHubInstalledItem creator = otherPackage(Map.of("Uplink", created));
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,
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));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink");
assertThat(state.get("defaultConverter").asBoolean()).isTrue();
// The other packages keep what they recorded: check() takes the checksum of any installed package
assertThat(created.get("checksum").asText()).isEqualTo("before");
verify(installedItemService, never()).save(tenantId, creator);
verify(installedItemService, never()).save(tenantId, taker);
}
@Test
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
}
@Test
void theDeviceIsNeverOverwritten() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("The device and its credentials don't change on update");
verify(transactionTemplate, never()).execute(any());
}
@Test
void versionOfAnotherItem_isRejected() {
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)));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
}
@Test
void anotherUpdateCommittedMeanwhile_failsWithoutChanges() {
// E.g. a second click: it waits for the first one's lock and finds the package on another version
IotHubInstalledItem updated = new IotHubInstalledItem();
updated.setId(installedItem.getId());
updated.setItemVersionId(UUID.fromString(versionId));
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).contains("Check the update again");
verify(converterService, never()).saveConverter(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void planOfAnotherInstalledVersion_isRejected() {
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId));
request.setFromVersionId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
}
@Test
void integrationsNotInThePlan_areRefused() {
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED))
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Integrations feature is disabled!");
verify(transactionTemplate, never()).execute(any());
}
@Test
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"));
step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
verify(telemetryService).saveAttributes(saved.capture());
assertThat(saved.getValue().getEntityId()).isEqualTo(dashboardId);
assertThat(saved.getValue().getScope()).isEqualTo(AttributeScope.SERVER_SCOPE);
assertThat(saved.getValue().getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString());
}
@Test
void checksum_ignoresDebugSettingsAndTheDefaultProfile() {
Converter converter = new Converter();
converter.setName("Uplink");
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {};"));
String installed = EntityChecksum.of(converter);
converter.setDebugMode(true);
converter.setDebugSettings(DebugSettings.all());
assertThat(EntityChecksum.of(converter)).isEqualTo(installed);
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {a: 1};"));
assertThat(EntityChecksum.of(converter)).isNotEqualTo(installed);
DeviceProfile profile = profile(1L, "AM308");
String profileChecksum = EntityChecksum.of(profile);
profile.setDefault(true);
assertThat(EntityChecksum.of(profile)).isEqualTo(profileChecksum);
}
@Test
void checksum_ignoresTheMetadataOfAnIntegration() {
Integration integration = new Integration();
integration.setName("TTN my-app");
ObjectNode configuration = JacksonUtil.newObjectNode().put("host", "eu1.cloud.thethings.network");
configuration.set("metadata", JacksonUtil.newObjectNode());
integration.setConfiguration(configuration);
String installed = EntityChecksum.of(integration);
// Another package on the integration adds its profile name
((ObjectNode) configuration.get("metadata")).put("profile.milesight-iot-am308", "AM308");
assertThat(EntityChecksum.of(integration)).isEqualTo(installed);
assertThat(integration.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue();
configuration.put("host", "nam1.cloud.thethings.network");
assertThat(EntityChecksum.of(integration)).isNotEqualTo(installed);
}
@Test
void userMessage_showsValidationMessagesAndHidesInternalOnes() {
assertThat(DefaultDevicePackageUpdateService.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");
}
@Test
void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() {
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));
assertThat(resolved.get("a").asText()).isEqualTo("123");
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}");
}
private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState);
IotHubInstalledItem item = new IotHubInstalledItem();
item.setId(new IotHubInstalledItemId(UUID.randomUUID()));
item.setTenantId(tenantId);
item.setItemType("DEVICE");
item.setDescriptor(descriptor);
return item;
}
private DeviceProfile profile(Long version, String name) {
DeviceProfile profile = new DeviceProfile(profileId);
profile.setTenantId(tenantId);
profile.setName(name);
profile.setVersion(version);
return profile;
}
private Dashboard dashboard(Long version) {
Dashboard dashboard = new Dashboard(dashboardId);
dashboard.setTenantId(tenantId);
dashboard.setTitle("AM308 dashboard");
dashboard.setVersion(version);
return dashboard;
}
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) {
DeviceUpdateRequest request = new DeviceUpdateRequest();
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);
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);
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);
step.setEntity(entity);
return step;
}
private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) {
DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step();
step.setName(name);
step.setType(type);
step.setAction(action);
return step;
}
private static ObjectNode stateOf(EntityId id, String resolution) {
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", resolution);
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", id.getId().toString()));
return state;
}
}

52
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -481,6 +481,43 @@ class DefaultIotHubServiceTest {
assertThat(kept.getUsedByItemsCount()).isEqualTo(2); assertThat(kept.getUsedByItemsCount()).isEqualTo(2);
} }
@Test
void deleteInstalledItem_devicePackage_keepsEntitiesTheUserHadBefore() {
mockTenant();
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(deviceId, usersDashboardId);
((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
Device device = new Device(deviceId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceService).delete(device, user);
verify(tbDashboardService, never()).delete(any(), any());
}
@Test
void findKeptEntities_devicePackage_namesTheEntitiesTheUserHadBefore() {
DeviceId deviceId = new DeviceId(UUID.randomUUID());
DashboardId usersDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(deviceId, usersDashboardId);
((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(usersDashboardId));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(usersDashboardId, "My dashboard"));
assertThat(kept.getUsedByItemsCount()).isZero();
assertThat(kept.getUsedExistingCount()).isEqualTo(1);
}
@Test @Test
void findKeptEntities_devicePackageSharingNothing_keepsNothing() { void findKeptEntities_devicePackageSharingNothing_keepsNothing() {
IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID())); IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()));
@ -495,6 +532,21 @@ class DefaultIotHubServiceTest {
assertThat(kept.getUsedByItemsCount()).isZero(); assertThat(kept.getUsedByItemsCount()).isZero();
} }
@Test
void updateItemVersion_devicePackage_deletesNothing() {
mockTenant();
IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID()), new DashboardId(UUID.randomUUID()));
installed.setItemType("DEVICE");
when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed);
UpdateItemVersionResult result = service.updateItemVersion(user, installed.getId(), UUID.randomUUID().toString(), true, null);
assertThat(result.isSuccess()).isFalse();
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(tbDashboardService, never()).delete(any(), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds)); descriptor.setCreatedEntityIds(List.of(createdEntityIds));

2
common/data/src/main/java/org/thingsboard/server/common/data/iot_hub/DeviceInstalledItemDescriptor.java

@ -14,6 +14,8 @@ import java.util.Map;
public class DeviceInstalledItemDescriptor implements IotHubInstalledItemDescriptor { public class DeviceInstalledItemDescriptor implements IotHubInstalledItemDescriptor {
private List<EntityId> createdEntityIds; private List<EntityId> createdEntityIds;
// Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them
private List<EntityId> usedExistingEntityIds;
private DashboardId dashboardId; private DashboardId dashboardId;
private String selectedInstallMethod; private String selectedInstallMethod;
private Map<String, JsonNode> installState; private Map<String, JsonNode> installState;

3
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemDao.java

@ -19,6 +19,9 @@ public interface IotHubInstalledItemDao extends Dao<IotHubInstalledItem> {
Optional<IotHubInstalledItem> findByTenantIdAndId(TenantId tenantId, IotHubInstalledItemId installedItemId); Optional<IotHubInstalledItem> findByTenantIdAndId(TenantId tenantId, IotHubInstalledItemId installedItemId);
// Locks the row until the end of the current transaction
Optional<IotHubInstalledItem> findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId);
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink); PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId); List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

3
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemService.java

@ -19,6 +19,9 @@ public interface IotHubInstalledItemService {
IotHubInstalledItem findById(TenantId tenantId, IotHubInstalledItemId id); IotHubInstalledItem findById(TenantId tenantId, IotHubInstalledItemId id);
// Locks the item until the end of the current transaction, so concurrent updates of it run one after another
IotHubInstalledItem findByIdForUpdate(TenantId tenantId, IotHubInstalledItemId id);
PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink); PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink);
List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId); List<UUID> findInstalledItemIdsByTenantId(TenantId tenantId);

5
dao/src/main/java/org/thingsboard/server/dao/iot_hub/IotHubInstalledItemServiceImpl.java

@ -37,6 +37,11 @@ class IotHubInstalledItemServiceImpl implements IotHubInstalledItemService {
return iotHubInstalledItemDao.findByTenantIdAndId(tenantId, id).orElse(null); return iotHubInstalledItemDao.findByTenantIdAndId(tenantId, id).orElse(null);
} }
@Override
public IotHubInstalledItem findByIdForUpdate(TenantId tenantId, IotHubInstalledItemId id) {
return iotHubInstalledItemDao.findByTenantIdAndIdForUpdate(tenantId, id).orElse(null);
}
@Override @Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) { public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES); validatePageLink(pageLink, IotHubInstalledItemEntity.ALLOWED_SORT_PROPERTIES);

3
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/IotHubInstalledItemRepository.java

@ -21,6 +21,9 @@ interface IotHubInstalledItemRepository extends JpaRepository<IotHubInstalledIte
Optional<IotHubInstalledItemEntity> findByTenantIdAndId(UUID tenantId, UUID id); Optional<IotHubInstalledItemEntity> findByTenantIdAndId(UUID tenantId, UUID id);
@Query(value = "SELECT * FROM iot_hub_installed_item i WHERE i.tenant_id = :tenantId AND i.id = :id FOR UPDATE", nativeQuery = true)
Optional<IotHubInstalledItemEntity> findByTenantIdAndIdForUpdate(@Param("tenantId") UUID tenantId, @Param("id") UUID id);
@Query("SELECT DISTINCT item.itemId FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId") @Query("SELECT DISTINCT item.itemId FROM IotHubInstalledItemEntity item WHERE item.tenantId = :tenantId")
List<UUID> findInstalledItemIdsByTenantId(@Param("tenantId") UUID tenantId); List<UUID> findInstalledItemIdsByTenantId(@Param("tenantId") UUID tenantId);

5
dao/src/main/java/org/thingsboard/server/dao/sql/iot_hub/JpaIotHubInstalledItemDao.java

@ -40,6 +40,11 @@ class JpaIotHubInstalledItemDao extends JpaAbstractDao<IotHubInstalledItemEntity
return repository.findByTenantIdAndId(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData); return repository.findByTenantIdAndId(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData);
} }
@Override
public Optional<IotHubInstalledItem> findByTenantIdAndIdForUpdate(TenantId tenantId, IotHubInstalledItemId installedItemId) {
return repository.findByTenantIdAndIdForUpdate(tenantId.getId(), installedItemId.getId()).map(DaoUtil::getData);
}
@Override @Override
public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) { public PageData<IotHubInstalledItem> findByTenantId(TenantId tenantId, List<String> itemTypes, UUID itemId, PageLink pageLink) {
return DaoUtil.toPageData(repository.findByTenantId( return DaoUtil.toPageData(repository.findByTenantId(

21
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -13,7 +13,7 @@ import {
MpItemVersionView MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models'; } from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models'; import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models';
import { IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, 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 { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params'; import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params';
import { InterceptorConfig } from '@core/interceptors/interceptor-config'; import { InterceptorConfig } from '@core/interceptors/interceptor-config';
@ -179,7 +179,7 @@ export class IotHubApiService {
public registerDeviceInstall( public registerDeviceInstall(
versionId: string, versionId: string,
descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> }, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> },
config?: IotHubRequestConfig config?: IotHubRequestConfig
): Observable<InstallItemVersionResult> { ): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>( return this.http.post<InstallItemVersionResult>(
@ -269,6 +269,23 @@ export class IotHubApiService {
); );
} }
/** The entities of an installed device package as they are now: whether they exist, changed since, or are shared. */
public checkDeviceUpdate(installedItemId: string, config?: IotHubRequestConfig): Observable<DevicePackageEntityState[]> {
return this.http.get<DevicePackageEntityState[]>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate/check`,
{ params: this.buildParams(config) }
);
}
/** Applies a device package update in one transaction: all of it, or nothing. */
public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable<DeviceUpdateResult> {
return this.http.post<DeviceUpdateResult>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`,
request,
{ params: this.buildParams(config) }
);
}
public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> { public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> {
return this.http.get<IotHubInstalledItemKeptEntities>( return this.http.get<IotHubInstalledItemKeptEntities>(
`/api/iot-hub/installedItems/${installedItemId}/keptEntities`, `/api/iot-hub/installedItems/${installedItemId}/keptEntities`,

195
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -55,12 +55,16 @@
[fields]="ws.formFields" [fields]="ws.formFields"
[formGroup]="ws.formGroup" [formGroup]="ws.formGroup"
[resolveImagePath]="resolveImagePathFn" [resolveImagePath]="resolveImagePathFn"
[reviewMode]="reviewMode"> [reviewMode]="reviewMode"
[newFieldKeys]="ws.newFieldKeys">
</tb-install-form-renderer> </tb-install-form-renderer>
</div> </div>
} }
@case ('progress') { @case ('progress') {
@if (data.update) {
<ng-container *ngTemplateOutlet="updateRows; context: { $implicit: ws }"></ng-container>
} @else {
<div class="flex flex-col p-6"> <div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) { @for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) { @if (i > 0) {
@ -144,6 +148,148 @@
} }
} }
</div> </div>
}
}
}
</div>
</ng-template>
<!-- Update: an entity someone changed since install, which the user can save before the update overwrites it -->
<ng-template #modifiedHint let-ep>
@let hint = textWithLink('iot-hub.device-update-modified');
{{ hint.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ hint.link }}</a>{{ hint.after }}
</ng-template>
<!-- Update: the package's entities and what the update does with them -->
<ng-template #updateRows let-ws>
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) {
<div class="tb-progress-divider"></div>
}
@let plan = updatePlanOf(ep);
@let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name);
@if (ws.reviewing && plan && !plan.confirmed) {
<div class="tb-progress-row tb-progress-row-alert">
<div class="flex min-w-0 flex-1 items-start gap-4">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-warning">warning</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">{{ label }}</span>
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
</span>
}
@if (plan.shared) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@if (plan.modified) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
<ng-container *ngTemplateOutlet="modifiedHint; context: { $implicit: ep }"></ng-container>
</span>
}
</div>
</div>
<div class="flex shrink-0 gap-2">
@if (plan.existing) {
@if (ep.step.type === 'DASHBOARD') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }}
</button>
}
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep)">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
</div>
</div>
} @else if (ep.status === 'error') {
<div class="tb-progress-row tb-progress-row-error">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-error">error</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">{{ label }}</span>
@if (ep.errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ ep.errorMessage }}</span>
}
</div>
<span class="tb-progress-status tb-progress-status-failed">{{ 'iot-hub.device-install-step-error' | translate }}</span>
</div>
} @else {
<div class="tb-progress-row" [class.tb-progress-row-active]="ep.status === 'running'">
<div class="tb-progress-icon">
@switch (ep.status) {
@case ('running') {
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
}
@default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
}
}
</div>
<div class="flex min-w-0 flex-1 flex-col">
<div class="flex min-w-0 items-center gap-2">
<span class="tb-progress-label tb-progress-label-fit"
[class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="!ws.reviewing && (ep.status === 'pending' || ep.status === 'skipped')">{{ label }}</span>
@if (plan?.action === 'create' && plan.resolution !== 'use-existing') {
<span class="tb-progress-new">{{ 'iot-hub.device-update-new' | translate }}</span>
}
</div>
<!-- A confirmed warning stays visible: the status says the conflict is resolved, the hint what happens -->
@if (ws.reviewing && plan?.confirmed) {
@if (plan.newDefaultConverter) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-new-default-converter' | translate }}</span>
}
@if (plan.existing) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-existing-' + plan.resolution | translate }}</span>
}
@if (plan.shared) {
<span class="tb-progress-hint">{{ 'iot-hub.device-update-shared' | translate }}</span>
}
@if (plan.modified) {
<span class="tb-progress-hint">
<ng-container *ngTemplateOutlet="modifiedHint; context: { $implicit: ep }"></ng-container>
</span>
}
}
</div>
<span class="tb-progress-status">
@switch (ep.status) {
@case ('running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
@case ('success') {
<span class="tb-progress-status-done">{{ updateOutcomeOf(plan) | translate }}</span>
}
@case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span>
}
@default {
@if (ws.reviewing && plan) {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-no-conflicts' | translate }}</span>
}
}
}
</span>
</div>
} }
} }
</div> </div>
@ -171,7 +317,14 @@
</div> </div>
} @else { } @else {
<div class="tb-device-install-header flex items-center gap-3 py-2 pl-6 pr-2"> <div class="tb-device-install-header flex items-center gap-3 py-2 pl-6 pr-2">
<h2 class="tb-device-install-title">{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}</h2> <h2 class="tb-device-install-title">
@if (data.update) {
{{ 'iot-hub.device-update-title' | translate:{ name: packageInfo?.name || data.item.name } }}
<span class="tb-device-update-version">{{ data.update.fromVersion }} → {{ data.item.version }}</span>
} @else {
{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}
}
</h2>
<button mat-icon-button (click)="cancel()" tabindex="-1"> <button mat-icon-button (click)="cancel()" tabindex="-1">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
@ -225,9 +378,24 @@
} }
</ng-template> </ng-template>
@if (data.update && currentWizardStep?.type === 'progress') {
@let step = currentWizardStep;
@if (hasUpdateError(step)) {
<div class="tb-update-banner tb-update-banner-error">
<mat-icon>error</mat-icon>
<span>{{ step.progressError }}</span>
</div>
} @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) {
<div class="tb-update-banner tb-update-banner-warning">
<mat-icon>warning</mat-icon>
<span>{{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }}</span>
</div>
}
}
<mat-dialog-actions> <mat-dialog-actions>
@if (!isFirstWizardStep) { @if (!isFirstWizardStep) {
<button mat-stroked-button [disabled]="connectionChecking(currentWizardStep)" (click)="previousStep()">{{ 'action.back' | translate }}</button> <button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isUpdating || currentWizardStep?.checking" (click)="previousStep()">{{ 'action.back' | translate }}</button>
} }
<span class="flex-1"></span> <span class="flex-1"></span>
@if (currentWizardStep; as step) { @if (currentWizardStep; as step) {
@ -264,7 +432,26 @@
</button> </button>
} }
@case ('progress') { @case ('progress') {
@if (step.progressError) { @if (data.update && (step.reviewing || step.updating || step.progressError)) {
@if (step.progressError && !step.updating) {
<button mat-button (click)="done()">{{ 'action.close' | translate }}</button>
<button mat-flat-button color="primary" (click)="retryUpdate(step)">
{{ 'iot-hub.device-update-try-again' | translate }}
</button>
} @else if (step.updating) {
<button mat-button disabled>{{ 'action.cancel' | translate }}</button>
<button mat-stroked-button color="primary" disabled>
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
</button>
} @else {
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary"
[disabled]="step.checking || unconfirmedUpdateWarnings(step) > 0"
(click)="runUpdate(step)">
{{ 'action.update' | translate }}
</button>
}
} @else if (step.progressError) {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container> <ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-flat-button color="primary" (click)="retryEntitySteps(step)"> <button mat-flat-button color="primary" (click)="retryEntitySteps(step)">
{{ 'action.retry' | translate }} {{ 'action.retry' | translate }}

84
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss

@ -223,6 +223,11 @@
flex-wrap: wrap; flex-wrap: wrap;
gap: 12px; gap: 12px;
} }
&.tb-progress-row-error {
background: rgba(211, 47, 47, 0.06);
align-items: flex-start;
}
} }
.tb-progress-icon { .tb-progress-icon {
@ -246,6 +251,10 @@
.tb-progress-warning { .tb-progress-warning {
color: #f66716; color: #f66716;
} }
.tb-progress-error {
color: #c62828;
}
} }
.tb-progress-pending-circle { .tb-progress-pending-circle {
@ -294,6 +303,36 @@
&.tb-progress-label-pending { &.tb-progress-label-pending {
color: rgba(0, 0, 0, 0.54); color: rgba(0, 0, 0, 0.54);
} }
// Next to a badge instead of taking the whole row
&.tb-progress-label-fit {
flex: 0 1 auto;
}
}
.tb-progress-hint {
font-size: 12px;
line-height: 16px;
letter-spacing: 0.4px;
color: rgba(0, 0, 0, 0.54);
}
.tb-progress-link {
color: #305680;
text-decoration: underline;
cursor: pointer;
}
.tb-progress-new {
flex-shrink: 0;
font-size: 12px;
font-weight: 500;
line-height: 16px;
letter-spacing: 0.4px;
color: #305680;
background: rgba(48, 86, 128, 0.08);
border-radius: 4px;
padding: 2px 8px;
} }
.tb-progress-status { .tb-progress-status {
@ -313,6 +352,51 @@
color: rgba(0, 0, 0, 0.54); color: rgba(0, 0, 0, 0.54);
} }
.tb-progress-status-failed {
color: #c62828;
}
.tb-device-update-version {
margin-left: 8px;
font-size: 14px;
font-weight: 400;
color: rgba(0, 0, 0, 0.54);
}
// Update: above the actions, so the list doesn't move when it goes away
.tb-update-banner {
display: flex;
align-items: center;
gap: 12px;
margin: 0 24px 16px;
padding: 12px 16px;
border-radius: 4px;
font-size: 14px;
font-weight: 500;
line-height: 20px;
mat-icon {
flex-shrink: 0;
font-size: 20px;
width: 20px;
height: 20px;
}
&.tb-update-banner-warning {
background: rgba(246, 103, 22, 0.08);
color: #b5470b;
mat-icon {
color: #f66716;
}
}
&.tb-update-banner-error {
background: rgba(211, 47, 47, 0.06);
color: #c62828;
}
}
.tb-progress-alert-msg { .tb-progress-alert-msg {
font-size: 12px; font-size: 12px;

1246
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts

File diff suppressed because it is too large

28
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.html

@ -93,9 +93,9 @@
</div> </div>
} }
@case (FormFieldType.SELECT) { @case (FormFieldType.SELECT) {
<mat-form-field appearance="outline" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'" <mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'"> [floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<mat-select [formControlName]="field.key"> <mat-select [formControlName]="field.key">
@for (opt of field.options; track opt.value) { @for (opt of field.options; track opt.value) {
<mat-option [value]="opt.value">{{ opt.label }}</mat-option> <mat-option [value]="opt.value">{{ opt.label }}</mat-option>
@ -110,9 +110,9 @@
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.STRING_AUTOCOMPLETE) { @case (FormFieldType.STRING_AUTOCOMPLETE) {
<mat-form-field appearance="outline" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'" <mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'"> [floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" [matAutocomplete]="auto" <input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" [matAutocomplete]="auto"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
data-lpignore="true" data-1p-ignore data-bwignore> data-lpignore="true" data-1p-ignore data-bwignore>
@ -136,9 +136,9 @@
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.PASSWORD) { @case (FormFieldType.PASSWORD) {
<mat-form-field appearance="outline" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'" <mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'"> [floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [type]="passwordVisible[field.key] ? 'text' : 'password'" <input matInput [type]="passwordVisible[field.key] ? 'text' : 'password'"
[formControlName]="field.key" [placeholder]="field.placeholder ?? ''" [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
@ -170,9 +170,9 @@
</mat-form-field> </mat-form-field>
} }
@case (FormFieldType.INTEGER) { @case (FormFieldType.INTEGER) {
<mat-form-field appearance="outline" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'" <mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'"> [floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput type="number" [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" <input matInput type="number" [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
data-lpignore="true" data-1p-ignore data-bwignore> data-lpignore="true" data-1p-ignore data-bwignore>
@ -191,9 +191,9 @@
</mat-form-field> </mat-form-field>
} }
@default { @default {
<mat-form-field appearance="outline" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'" <mat-form-field appearance="outline" [class.tb-install-form-field-new]="isNewField(field)" [subscriptSizing]="row.hasHintBox ? 'dynamic' : 'fixed'"
[floatLabel]="field.placeholder ? 'always' : 'auto'"> [floatLabel]="field.placeholder ? 'always' : 'auto'">
<mat-label>{{ field.label }}</mat-label> <mat-label>{{ field.label }}@if (isNewField(field)) {<span> · {{ 'iot-hub.device-update-new' | translate }}</span>}</mat-label>
<input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''" <input matInput [formControlName]="field.key" [placeholder]="field.placeholder ?? ''"
[errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)" [errorStateMatcher]="errorStateMatcher" (focus)="onFocus(field)" (blur)="onBlur(field)"
autocomplete="new-username" data-lpignore="true" data-1p-ignore data-bwignore> autocomplete="new-username" data-lpignore="true" data-1p-ignore data-bwignore>
@ -205,6 +205,14 @@
<mat-icon>autorenew</mat-icon> <mat-icon>autorenew</mat-icon>
</button> </button>
} }
@if (canResetToDefault(field)) {
<button mat-icon-button matSuffix type="button"
[matTooltip]="'action.reset-default' | translate"
matTooltipPosition="above"
(click)="resetToDefault(field)">
<tb-icon>mdi:broom</tb-icon>
</button>
}
@if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) { @if (helpTextOf(field) && !(row.hasHintBox && field.helpPopupId)) {
<mat-hint>{{ helpTextOf(field) }}</mat-hint> <mat-hint>{{ helpTextOf(field) }}</mat-hint>
} }

19
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.scss

@ -14,3 +14,22 @@
max-width: 100%; max-width: 100%;
margin-top: 8px; margin-top: 8px;
} }
// Update: a field the installed version didn't have: a thicker outline, a tint and the label in the primary color
:host ::ng-deep .mat-mdc-form-field.tb-install-form-field-new {
.mdc-notched-outline__leading,
.mdc-notched-outline__notch,
.mdc-notched-outline__trailing {
border-color: var(--tb-primary-500);
border-width: 2px;
}
.mat-mdc-text-field-wrapper {
border-radius: 4px;
background: color-mix(in srgb, var(--tb-primary-500) 4%, transparent);
}
.mdc-floating-label,
.mat-mdc-floating-label {
color: var(--tb-primary-500);
font-weight: 500;
}
}

18
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/install-form-renderer/install-form-renderer.component.ts

@ -49,6 +49,8 @@ export class InstallFormRendererComponent implements OnChanges {
@Input() resolveImagePath?: (path: string) => string; @Input() resolveImagePath?: (path: string) => string;
/** When true, PASSWORD inputs render unmasked by default (used by review mode). */ /** When true, PASSWORD inputs render unmasked by default (used by review mode). */
@Input() reviewMode = false; @Input() reviewMode = false;
/** Update: the fields the installed version's form didn't have, highlighted as new. */
@Input() newFieldKeys?: Set<string>;
passwordVisible: Record<string, boolean> = {}; passwordVisible: Record<string, boolean> = {};
// Fields in render order: consecutive fields of a group form a section, and consecutive fields // Fields in render order: consecutive fields of a group form a section, and consecutive fields
@ -136,6 +138,18 @@ export class InstallFormRendererComponent implements OnChanges {
control.markAsDirty(); control.markAsDirty();
} }
/** A resettable field the user changed shows a button that puts its defaultValue back. */
canResetToDefault(field: FormFieldDefinition): boolean {
const control = this.formGroup.controls[field.key];
return !!field.resettable && !!control?.enabled && control.value !== (field.defaultValue ?? '');
}
resetToDefault(field: FormFieldDefinition): void {
const control = this.formGroup.controls[field.key];
control.setValue(field.defaultValue ?? '');
control.markAsDirty();
}
onFocus(field: FormFieldDefinition): void { onFocus(field: FormFieldDefinition): void {
const control = this.formGroup.controls[field.key]; const control = this.formGroup.controls[field.key];
this.focusedControl = control ?? null; this.focusedControl = control ?? null;
@ -170,4 +184,8 @@ export class InstallFormRendererComponent implements OnChanges {
imagePath(path: string): string { imagePath(path: string): string {
return this.resolveImagePath ? this.resolveImagePath(path) : path; return this.resolveImagePath ? this.resolveImagePath(path) : path;
} }
isNewField(field: FormFieldDefinition): boolean {
return !!this.newFieldKeys?.has(field.key);
}
} }

28
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -17,7 +17,7 @@ import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubIt
import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component'; import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component';
import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component'; import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component';
import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component'; import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component';
import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallUpdate } from './device-install-dialog/device-install-dialog.component';
import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component';
import { IotHubBuiltInService } from './iot-hub-built-in.service'; import { IotHubBuiltInService } from './iot-hub-built-in.service';
import { isBuiltInItem } from './iot-hub-utils'; import { isBuiltInItem } from './iot-hub-utils';
@ -150,6 +150,9 @@ export class IotHubActionsService {
if (!installedItem) { if (!installedItem) {
return of(false); return of(false);
} }
if (installedItem.itemType === ItemType.DEVICE) {
return this.updateDevice(installedItem, versionId);
}
return this.dialog.open<TbIotHubUpdateDialogComponent, IotHubUpdateDialogData, string | boolean>(TbIotHubUpdateDialogComponent, { return this.dialog.open<TbIotHubUpdateDialogComponent, IotHubUpdateDialogData, string | boolean>(TbIotHubUpdateDialogComponent, {
panelClass: ['tb-dialog'], panelClass: ['tb-dialog'],
disableClose: true, disableClose: true,
@ -199,9 +202,30 @@ export class IotHubActionsService {
}); });
} }
/**
* A device package is updated by the install wizard of the new version: its steps change what
* the package created in place, so the device and its history stay. When only texts changed,
* the wizard records the new version without opening.
*/
private updateDevice(installedItem: IotHubInstalledItem, versionId: string): Observable<string | boolean> {
return this.iotHubApiService.getVersionInfo(versionId).pipe(
switchMap(item => this.openDeviceInstallDialog(item, {
update: {
installedItemId: installedItem.id.id,
descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor,
fromVersionId: installedItem.itemVersionId,
fromVersion: installedItem.version
}
})),
map(result => result === 'installed' ? 'updated' : result),
// The request has already shown the error
catchError(() => of(false))
);
}
private openDeviceInstallDialog(item: MpItemVersionView, private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
entityGroupId?: string; customerId?: string}): Observable<any> { entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable<any> {
return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, { return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, {
panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'],
disableClose: true, disableClose: true,

84
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -0,0 +1,84 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0
import { firstValueFrom } from 'rxjs';
import { ResourcesService } from '@core/services/resources.service';
import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models';
import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { PageLink } from '@shared/models/page/page-link';
import { PageData } from '@shared/models/page/page-data';
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json';
// The settings of a default converter that decide what it does: the script is compared on its own
const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] =
['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys'];
/**
* The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with
* "default": true installs it. Null when ThingsBoard has no default converter settings for the type.
*/
export const loadDefaultUplinkConverter = async (resourcesService: ResourcesService, integrationType: IntegrationType,
scriptLang: ScriptLanguage, name: string): Promise<Partial<Converter> | null> => {
const configurations = await firstValueFrom(
resourcesService.loadJsonResource<Record<string, ConverterConfigV2>>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL));
const configuration = configurations?.[integrationType];
if (!configuration) {
return null;
}
const script = await firstValueFrom(resourcesService.loadJsonResource<string>(
getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2)));
return {
name,
type: ConverterType.UPLINK,
integrationType,
converterVersion: 2,
edgeTemplate: false,
// As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing
debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 },
configuration: {
...configuration,
scriptLang,
decoder: null,
tbelDecoder: null,
encoder: null,
tbelEncoder: null,
[getTargetField(ConverterType.UPLINK, scriptLang)]: script
},
additionalInfo: { description: '' }
};
};
/** True when the converter does something else than the default one: another script or other settings. */
export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial<Converter>): boolean => {
const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang);
const script = (value: string) => (value ?? '').trimEnd();
return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) ||
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null));
};
/**
* The converters device packages installed themselves as their default converter, not ones they took as they were, of
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version
* may change. The installed items table and the update dialog both decide by it.
*/
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => {
const ids = new Set<string>();
let pageLink = new PageLink(100);
let page: PageData<IotHubInstalledItem>;
do {
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true }));
for (const item of page.data) {
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) {
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') {
ids.add(state.entityOutput.id);
}
}
}
pageLink = pageLink.nextPageLink();
} while (page.hasNext);
return ids;
};

6
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -45,8 +45,10 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
const kept = data.keptEntities; const kept = data.keptEntities;
if (kept?.entities.length) { if (kept?.entities.length) {
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name })); this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
this.description = this.translate.instant('iot-hub.remove-desc-kept', // Kept because other packages use them, because the user had them before the package, or both
{ count: kept.usedByItemsCount, kept: kept.entities.length }); const key = !kept.usedExistingCount ? 'iot-hub.remove-desc-kept' :
!kept.usedByItemsCount ? 'iot-hub.remove-desc-kept-own' : 'iot-hub.remove-desc-kept-own-or-used';
this.description = this.translate.instant(key, { count: kept.usedByItemsCount, kept: kept.entities.length });
} else { } else {
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc'); this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
} }

39
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.html

@ -42,29 +42,26 @@
<th mat-header-cell *matHeaderCellDef>@if (updatesChecked) { {{ 'iot-hub.updates' | translate }} }</th> <th mat-header-cell *matHeaderCellDef>@if (updatesChecked) { {{ 'iot-hub.updates' | translate }} }</th>
<td mat-cell *matCellDef="let item"> <td mat-cell *matCellDef="let item">
@if (updatesChecked) { @if (updatesChecked) {
@if (getPublishedVersionInfo(item); as pubInfo) { @let pubInfo = getPublishedVersionInfo(item);
@if (pubInfo.publishedVersionId !== item.itemVersionId) { @if (pubInfo && pubInfo.publishedVersionId !== item.itemVersionId) {
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
@if (!itemVersion) { @if (!itemVersion) {
<button class="tb-installed-version-btn" (click)="viewUpdateDetails(pubInfo, item)">
<mat-icon>arrow_upward</mat-icon>
v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
</button>
}
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)"> <button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
@if (itemVersion) { <mat-icon>arrow_upward</mat-icon>
{{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }} v{{ pubInfo.publishedVersion }} {{ 'iot-hub.available' | translate }}
} @else {
{{ 'iot-hub.update' | translate }}
}
</button> </button>
</div> } @else {
} @else { <button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateItem(item, pubInfo)">
<span class="tb-installed-up-to-date"> {{ 'iot-hub.update-to-version' | translate:{ version: pubInfo.publishedVersion } }}
<mat-icon>check</mat-icon> </button>
{{ 'iot-hub.up-to-date' | translate }} }
</span> </div>
} } @else if (hasConverterUpdate(item)) {
<!-- The update of the same version: only ThingsBoard's default converter changed -->
<button mat-stroked-button color="warn" class="tb-installed-update-btn" (click)="updateConverter(item)">
<mat-icon>arrow_upward</mat-icon>
{{ 'iot-hub.new-converter-available' | translate }}
</button>
} @else { } @else {
<span class="tb-installed-up-to-date"> <span class="tb-installed-up-to-date">
<mat-icon>check</mat-icon> <mat-icon>check</mat-icon>

33
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.scss

@ -117,45 +117,20 @@
.tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); } .tb-type-alarm-rule { color: #d7702f; background: rgba(215, 112, 47, 0.06); }
.tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); } .tb-type-rule-chain { color: #aa5be3; background: rgba(170, 91, 227, 0.06); }
// "vX.X.X Available" button — Design: border rgba(0,0,0,0.12), rounded-4, px-12 py-6, gap-8 // "vX.X.X available" and "Update to" buttons: border matches the text color
.tb-installed-version-btn { .tb-installed-update-btn.mat-mdc-outlined-button {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 14px; font-size: 14px;
font-weight: 500; font-weight: 500;
line-height: 20px; line-height: 20px;
letter-spacing: 0.25px; letter-spacing: 0.25px;
color: rgba(0, 0, 0, 0.76);
background: none;
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 4px;
padding: 6px 12px; padding: 6px 12px;
cursor: pointer; height: auto;
font-family: inherit; --mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color);
mat-icon { mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
color: inherit !important; color: inherit !important;
--mat-icon-color: currentColor; --mat-icon-color: currentColor;
} }
&:hover {
background: rgba(0, 0, 0, 0.04);
}
}
// "Update" button — Design: same height as available btn, border matches text color
.tb-installed-update-btn.mat-mdc-outlined-button {
font-size: 14px;
font-weight: 500;
line-height: 20px;
letter-spacing: 0.25px;
padding: 6px 12px;
height: auto;
--mat-button-outlined-outline-color: var(--mat-button-outlined-label-text-color);
} }
// "Up to date" — Design: 14px Medium, #198038, gap-8, py-6 // "Up to date" — Design: 14px Medium, #198038, gap-8, py-6

82
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts

@ -36,6 +36,10 @@ import { entityTypeTranslations } from '@shared/models/entity-type.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; import { getItemTypeIcon, ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models';
import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service';
import { ConverterService } from '@core/http/converter.service';
import { ResourcesService } from '@core/services/resources.service';
import { differsFromDefaultConverter, loadDefaultUplinkConverter, loadOwnDefaultConverterIds } from '@home/components/iot-hub/iot-hub-default-converter';
import { firstValueFrom } from 'rxjs';
@Component({ @Component({
selector: 'tb-iot-hub-installed-items-table', selector: 'tb-iot-hub-installed-items-table',
@ -68,6 +72,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
isLoading = false; isLoading = false;
publishedVersionMap = new Map<string, ItemPublishedVersionInfo>(); publishedVersionMap = new Map<string, ItemPublishedVersionInfo>();
// Installed device packages whose default converter differs from ThingsBoard's default converter now
converterUpdates = new Set<string>();
private converterCheckRun = 0;
updatesChecked = false; updatesChecked = false;
isCheckingUpdates = false; isCheckingUpdates = false;
@ -83,7 +90,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
private iotHubActions: IotHubActionsService, private iotHubActions: IotHubActionsService,
private elementRef: ElementRef, private elementRef: ElementRef,
private zone: NgZone, private zone: NgZone,
private cd: ChangeDetectorRef private cd: ChangeDetectorRef,
private converterService: ConverterService,
private resourcesService: ResourcesService
) { ) {
this.widgetResize$ = new ResizeObserver(() => { this.widgetResize$ = new ResizeObserver(() => {
this.zone.run(() => { this.zone.run(() => {
@ -235,6 +244,7 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
infos.forEach(info => this.publishedVersionMap.set(info.itemId, info)); infos.forEach(info => this.publishedVersionMap.set(info.itemId, info));
this.updatesChecked = true; this.updatesChecked = true;
this.isCheckingUpdates = false; this.isCheckingUpdates = false;
void this.checkConverterUpdates();
}, },
error: () => { error: () => {
this.isCheckingUpdates = false; this.isCheckingUpdates = false;
@ -242,24 +252,73 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
}); });
} }
viewUpdateDetails(publishedInfo: ItemPublishedVersionInfo, installedItem: IotHubInstalledItem): void { updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void {
this.iotHubApiService.getVersionInfo(publishedInfo.publishedVersionId, {ignoreLoading: true}).subscribe(versionView => { this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => {
this.iotHubActions.openItemDetail(versionView, installedItem).subscribe(result => { if (result === 'updated') {
if (result === 'updated' || result === 'deleted') { this.loadData();
this.loadData(); }
}
});
}); });
} }
updateItem(item: IotHubInstalledItem, publishedInfo: ItemPublishedVersionInfo): void { hasConverterUpdate(item: IotHubInstalledItem): boolean {
this.iotHubActions.updateItem(item, publishedInfo.publishedVersion, publishedInfo.publishedVersionId).subscribe(result => { return this.converterUpdates.has(item.id.id);
}
/** The update to the installed version itself brings the converter to ThingsBoard's default one. */
updateConverter(item: IotHubInstalledItem): void {
this.iotHubActions.updateItem(item, item.version, item.itemVersionId).subscribe(result => {
if (result === 'updated') { if (result === 'updated') {
this.loadData(); this.loadData();
} }
}); });
} }
/**
* The device packages on this page whose step with "default": true installed a converter that differs from
* ThingsBoard's default converter now. ThingsBoard's default changes with ThingsBoard, so the package has no new version for it.
*/
private async checkConverterUpdates(): Promise<void> {
// A later load (another page, sort or search) starts another run: an earlier one finishing last mustn't win
const run = ++this.converterCheckRun;
// The package's default converter of each DEVICE package on the page
const checks: { itemId: string; converterId: string }[] = [];
// Over all installed packages, not only this page's, as the update dialog decides
let ownDefaultConverterIds: Set<string> | undefined;
for (const item of this.dataSource) {
const states = item.itemType === 'DEVICE' ? Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {}) : [];
for (const state of states) {
const id: string = state?.defaultConverter ? state.entityOutput?.id : undefined;
if (!id) {
continue;
}
// A converter taken as it was counts only when a package installed it as its default converter
if (state.resolution === 'use-existing') {
ownDefaultConverterIds ??= await loadOwnDefaultConverterIds(this.iotHubApiService);
if (!ownDefaultConverterIds.has(id)) {
continue;
}
}
checks.push({ itemId: item.id.id, converterId: id });
}
}
const changed = await Promise.all(checks.map(async ({ itemId, converterId }) => {
const converter = await firstValueFrom(this.converterService.getConverter(converterId, {ignoreErrors: true, ignoreLoading: true}))
.catch(() => null);
if (!converter) {
return null;
}
const defaultConverter = await loadDefaultUplinkConverter(this.resourcesService, converter.integrationType,
converter.configuration.scriptLang, converter.name);
return defaultConverter && differsFromDefaultConverter(converter, defaultConverter) ? itemId : null;
}));
if (run !== this.converterCheckRun) {
return;
}
this.converterUpdates = new Set(changed.filter(itemId => !!itemId));
this.cd.markForCheck();
}
getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined { getPublishedVersionInfo(item: IotHubInstalledItem): ItemPublishedVersionInfo | undefined {
return this.publishedVersionMap.get(item.itemId); return this.publishedVersionMap.get(item.itemId);
} }
@ -277,6 +336,9 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
this.dataSource = data.data; this.dataSource = data.data;
this.totalElements = data.totalElements; this.totalElements = data.totalElements;
this.isLoading = false; this.isLoading = false;
if (this.updatesChecked && !this.itemVersion) {
void this.checkConverterUpdates();
}
}, },
error: () => { error: () => {
this.dataSource = []; this.dataSource = [];

12
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -215,6 +215,9 @@ export const stepTypeAliasMap: Record<string, string> = {
export interface DeviceInstallStep { export interface DeviceInstallStep {
type: InstallStepType; type: InstallStepType;
name: string; name: string;
// Optional stable id of the step, unique within the install method: the key of the step's install state,
// so the next version can rename the step. Without it, the name is the key.
id?: string;
file?: string; file?: string;
template?: string; template?: string;
serverAttributes?: string; serverAttributes?: string;
@ -223,6 +226,10 @@ export interface DeviceInstallStep {
dockerCompose?: string; dockerCompose?: string;
// INTEGRATION step references the integration-form.json artifact alongside the template. // INTEGRATION step references the integration-form.json artifact alongside the template.
form?: string; form?: string;
// UPLINK_CONVERTER: ThingsBoard's default converter for the method's integration instead of a template
default?: boolean;
// INTEGRATION: entries added to the integration's metadata, which keeps the entries it has
metadata?: Record<string, string>;
} }
export interface DevicePackageInfo { export interface DevicePackageInfo {
@ -282,6 +289,8 @@ export interface FormFieldDefinition {
// Consecutive fields with the same group are shown in one panel titled with the group // Consecutive fields with the same group are shown in one panel titled with the group
group?: string; group?: string;
readOnly?: boolean; readOnly?: boolean;
// A STRING field the user changed shows a button that puts defaultValue back
resettable?: boolean;
// Shown inside the empty field; the label then always stays above it // Shown inside the empty field; the label then always stays above it
placeholder?: string; placeholder?: string;
// Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it. // Fills the field from other fields of the form, e.g. "TTN – ${appId}", until the user edits it.
@ -346,7 +355,8 @@ export interface EntityStepOutput {
baseUrl?: string; baseUrl?: string;
} }
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict'; // skipped: a step of an update that failed, so nothing was changed
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict' | 'skipped';
export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy'; export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy';

56
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -30,11 +30,65 @@ export interface RuleChainInstalledItemDescriptor {
export interface DeviceInstalledItemDescriptor { export interface DeviceInstalledItemDescriptor {
type: 'DEVICE'; type: 'DEVICE';
createdEntityIds?: { entityType: string; id: string }[]; createdEntityIds?: { entityType: string; id: string }[];
// Of createdEntityIds, the entities the user chose to use as they were: the package doesn't own them
usedExistingEntityIds?: { entityType: string; id: string }[];
dashboardId?: { id: string }; dashboardId?: { id: string };
selectedInstallMethod?: string; selectedInstallMethod?: string;
installState?: Record<string, any>; installState?: Record<string, any>;
} }
/** An entity of an installed device package as the server finds it before an update. */
export interface DevicePackageEntityState {
stepName: string;
entityId: { entityType: string; id: string };
exists: boolean;
version?: number;
// Changed since the package installed or last updated it; null when the server has no checksum of it
modified?: boolean | null;
shared: boolean;
}
/** A step of a device package update, with its entity resolved from the template of the new version. */
export interface DeviceUpdateStep {
name: string;
type: string;
action: 'KEEP' | 'OVERWRITE' | 'CREATE';
entityId?: string;
expectedVersion?: number;
confirmed?: boolean;
entity?: any;
credentials?: any;
// OVERWRITE and CREATE: the attributes the saved entity gets, as at install
serverAttributes?: any;
sharedAttributes?: any;
resolution?: string;
// The package step's id, which keys its install state; the name when not set
id?: string;
// INTEGRATION: the step's metadata entries, which a KEEP merges into the integration; null removes an entry
metadata?: Record<string, string | null>;
// The step takes ThingsBoard's default converter: its install state says so, for the update check
defaultConverter?: boolean;
}
export interface DeviceUpdateRequest {
versionId: string;
// The version installed when the update was planned: the server refuses the update if the package changed since
fromVersionId?: string;
// The install method of the new version's steps
selectedInstallMethod?: string;
installState: Record<string, any>;
steps: DeviceUpdateStep[];
}
/** All of the update was applied, or none of it: failedStep names the step that failed, if one did. */
export interface DeviceUpdateResult {
success: boolean;
errorMessage?: string;
failedStep?: string;
descriptor?: DeviceInstalledItemDescriptor;
outputs?: Record<string, any>;
}
export interface SolutionTemplateInstalledItemDescriptor { export interface SolutionTemplateInstalledItemDescriptor {
type: 'SOLUTION_TEMPLATE'; type: 'SOLUTION_TEMPLATE';
createdEntityIds: { entityType: string; id: string }[]; createdEntityIds: { entityType: string; id: string }[];
@ -112,6 +166,8 @@ export interface IotHubKeptEntity {
export interface IotHubInstalledItemKeptEntities { export interface IotHubInstalledItemKeptEntities {
entities: IotHubKeptEntity[]; entities: IotHubKeptEntity[];
usedByItemsCount: number; usedByItemsCount: number;
// Of the kept entities, the ones the user had before and the package took as they were
usedExistingCount: number;
} }
export interface IotHubInstalledItem extends BaseData<{id: string}> { export interface IotHubInstalledItem extends BaseData<{id: string}> {

12
ui-ngx/src/assets/converters/js-tti-decoder.raw

@ -1,6 +1,7 @@
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device. // Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
var values = {}; var values = {};
var history = []; var history = [];
if (metadata.payloadFormat == 'JSON') { if (metadata.payloadFormat == 'JSON') {
@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') {
var profile = 'LoRaWAN Device'; var profile = 'LoRaWAN Device';
if (metadata.brandId != null && metadata.modelId != null) { if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + '-' + metadata.modelId; profile = metadata.brandId + '-' + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
} }
// To give a model its own profile name, map it here, for example:
// if (profile == 'milesight-iot-am308') {
// profile = 'AM308';
// }
if (history.length == 0) { if (history.length == 0) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
} }

12
ui-ngx/src/assets/converters/js-ttn-decoder.raw

@ -1,6 +1,7 @@
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device. // Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
var values = {}; var values = {};
var history = []; var history = [];
if (metadata.payloadFormat == 'JSON') { if (metadata.payloadFormat == 'JSON') {
@ -19,11 +20,12 @@ if (metadata.payloadFormat == 'JSON') {
var profile = 'LoRaWAN Device'; var profile = 'LoRaWAN Device';
if (metadata.brandId != null && metadata.modelId != null) { if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + '-' + metadata.modelId; profile = metadata.brandId + '-' + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata['profile.' + profile];
if (customProfile != null && customProfile != '') {
profile = customProfile;
}
} }
// To give a model its own profile name, map it here, for example:
// if (profile == 'milesight-iot-am308') {
// profile = 'AM308';
// }
if (history.length == 0) { if (history.length == 0) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
} }

12
ui-ngx/src/assets/converters/tbel-tti-decoder.raw

@ -1,6 +1,7 @@
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device. // Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
var values = {}; var values = {};
var history = []; var history = [];
if (metadata.payloadFormat == "JSON") { if (metadata.payloadFormat == "JSON") {
@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") {
var profile = "LoRaWAN Device"; var profile = "LoRaWAN Device";
if (metadata.brandId != null && metadata.modelId != null) { if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + "-" + metadata.modelId; profile = metadata.brandId + "-" + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
} }
// To give a model its own profile name, map it here, for example:
// if (profile == "milesight-iot-am308") {
// profile = "AM308";
// }
if (history.isEmpty()) { if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
} }

12
ui-ngx/src/assets/converters/tbel-ttn-decoder.raw

@ -1,6 +1,7 @@
// The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload // The Things Stack adds decoded_payload for a device registered from the LoRaWAN Device Repository, and the payload
// is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time. // is then that JSON: its keys become telemetry. A Milesight-style history list keeps each record's time.
// Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it. Any other device gets LoRaWAN Device. // Such a device gets the profile <brand_id>-<model_id>, so all devices of one model share it,
// or the name the integration metadata gives it under profile.<brand_id>-<model_id>. Any other device gets LoRaWAN Device.
var values = {}; var values = {};
var history = []; var history = [];
if (metadata.payloadFormat == "JSON") { if (metadata.payloadFormat == "JSON") {
@ -19,11 +20,12 @@ if (metadata.payloadFormat == "JSON") {
var profile = "LoRaWAN Device"; var profile = "LoRaWAN Device";
if (metadata.brandId != null && metadata.modelId != null) { if (metadata.brandId != null && metadata.modelId != null) {
profile = metadata.brandId + "-" + metadata.modelId; profile = metadata.brandId + "-" + metadata.modelId;
// The profile name chosen at install, kept in the integration metadata
var customProfile = metadata["profile." + profile];
if (customProfile != null && customProfile != "") {
profile = customProfile;
}
} }
// To give a model its own profile name, map it here, for example:
// if (profile == "milesight-iot-am308") {
// profile = "AM308";
// }
if (history.isEmpty()) { if (history.isEmpty()) {
return { profile: profile, telemetry: { ts: metadata.ts, values: values } }; return { profile: profile, telemetry: { ts: metadata.ts, values: values } };
} }

21
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -6325,7 +6325,7 @@
"items-per-page": "Items per page", "items-per-page": "Items per page",
"filter": "Filter", "filter": "Filter",
"clear-filters": "Clear filters", "clear-filters": "Clear filters",
"available": "Available", "available": "available",
"items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.", "items-page-desc-widgets": "Jumpstart your IoT journey with pre-configured widgets designed for your industry. Deploy proven architectures instantly and focus your energy on what matters: your unique business logic.",
"items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.", "items-page-desc-solution-templates": "Complete IoT solution packages with dashboards, rule chains, and device configurations. Get started with proven architectures.",
"items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.", "items-page-desc-calculated-fields": "Use pre-configured Calculated Fields to automate complex metrics like fuel efficiency or power factor. Skip the manual logic and keep your dashboards clean and actionable.",
@ -6405,6 +6405,8 @@
"remove": "Remove", "remove": "Remove",
"remove-confirm-title": "Remove '{{name}}'?", "remove-confirm-title": "Remove '{{name}}'?",
"remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant", "remove-desc": "Removing this will also remove the installed entity and its associated resources within your tenant",
"remove-desc-kept-own": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it} other {entities will not be removed, because you had them} } before the package was installed:",
"remove-desc-kept-own-or-used": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because you had it before the package was installed or it is used by} other {entities will not be removed, because you had them before the package was installed or they are used by} } { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:", "remove-desc-kept": "Removing this will also remove the installed entity and its associated resources within your tenant. The following { kept, plural, =1 {entity will not be removed, because it is} other {entities will not be removed, because they are} } used by { count, plural, =1 {1 other installed package} other {# other installed packages} }:",
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant", "remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway", "remove-anyway": "Remove anyway",
@ -6452,6 +6454,7 @@
"check-for-updates": "Check for updates", "check-for-updates": "Check for updates",
"updates": "Updates", "updates": "Updates",
"up-to-date": "Up to date", "up-to-date": "Up to date",
"new-converter-available": "New converter available",
"update": "Update", "update": "Update",
"update-to-version": "Update to v {{ version }}", "update-to-version": "Update to v {{ version }}",
"update-item-title": "Update Item", "update-item-title": "Update Item",
@ -6533,6 +6536,22 @@
"device-install-resolution-create-copy": "Created copy", "device-install-resolution-create-copy": "Created copy",
"device-install-title": "Connect \"{{name}}\"", "device-install-title": "Connect \"{{name}}\"",
"device-installing-title": "Installing \"{{name}}\"", "device-installing-title": "Installing \"{{name}}\"",
"device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update",
"device-update-no-conflicts": "No conflicts",
"device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.",
"device-update-new-default-converter": "ThingsBoard has a new version of the default converter used by this package.",
"device-update-modified": "Has local changes. You can download the current version <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.",
"device-update-existing-use-existing": "Already exists. The existing one will be used.",
"device-update-existing-overwrite": "Already exists. It will be overwritten.",
"device-update-existing-create-copy": "Already exists. A copy will be created.",
"device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update",
"device-update-skipped": "Not changed",
"device-update-updated": "Updated",
"device-update-created": "Created",
"device-update-try-again": "Try again",
"done": "Done", "done": "Done",
"in-progress": "In progress", "in-progress": "In progress",
"item-detail": "IoT Hub item", "item-detail": "IoT Hub item",

Loading…
Cancel
Save