Browse Source

Merge pull request #16625 from pinkevmladchy/fix/iot-hub-device-update-reinstall-4.4.0.3

IoT Hub: device package Update reinstalls the package on 4.4.0.x
pull/16633/head
Viacheslav Klimov 3 weeks ago
committed by GitHub
parent
commit
8b382f9eec
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 16
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 349
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  3. 12
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstallItemVersionResult.java
  4. 27
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  5. 759
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  6. 25
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  7. 32
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  8. 187
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  9. 77
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  10. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts
  11. 3
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts
  12. 30
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.html
  13. 48
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.ts
  14. 3
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts
  15. 9
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts
  16. 3
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts
  17. 8
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts
  18. 8
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  19. 7
      ui-ngx/src/assets/locale/locale.constant-en_US.json

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

@ -89,10 +89,24 @@ public class IotHubController extends BaseController {
@ResponseBody
public InstallItemVersionResult registerDeviceInstall(
@RequestParam String versionId,
@RequestParam(required = false) UUID replaceInstalledItemId,
@RequestBody JsonNode body) throws ThingsboardException {
checkAllPermissions();
DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class);
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor,
replaceInstalledItemId != null ? new IotHubInstalledItemId(replaceInstalledItemId) : null);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/device/removeEntities")
@ResponseBody
public void removeDevicePackageEntities(@PathVariable UUID installedItemId,
@RequestParam String versionId,
@RequestParam(required = false) UUID entityGroupId,
@RequestParam(required = false) UUID customerId) throws ThingsboardException {
checkAllPermissions();
iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId,
entityGroupId, customerId);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")

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

@ -3,17 +3,23 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.common.data.page.PageDataIterable;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.integration.Integration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
@ -81,10 +87,12 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
@ -469,6 +477,14 @@ public class DefaultIotHubService implements IotHubService {
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
if ("DEVICE".equals(itemType)) {
// A device package needs the user's input to install (gateway name, credentials and so on), so the
// server cannot install the new version alone: the install wizard of the new version does the update
// (removeDevicePackageEntities, then registerDeviceInstall with this item). Refuse instead of removing
// the package here: a client that reads this as an update would report success with nothing installed.
throw new IllegalArgumentException("A device package is updated through the install wizard of its new version.");
}
// Skip checksum validation for solution templates
if (!"SOLUTION_TEMPLATE".equals(itemType)) {
JsonNode installedVersionInfo = iotHubRestClient.getVersionInfo(installedItem.getItemVersionId().toString());
@ -512,12 +528,6 @@ public class DefaultIotHubService implements IotHubService {
case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) descriptor, fileData);
case "ALARM_RULE" -> updateAlarmRule(user, tenantId, (AlarmRuleInstalledItemDescriptor) descriptor, fileData);
case "RULE_CHAIN" -> updateRuleChain(tenantId, (RuleChainInstalledItemDescriptor) descriptor, fileData);
case "DEVICE" -> {
DeviceInstalledItemDescriptor dd = (DeviceInstalledItemDescriptor) descriptor;
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user);
dd.setCreatedEntityIds(null);
dd.setDashboardId(null);
}
case "SOLUTION_TEMPLATE" -> {
SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor;
solutionService.deleteSolution(tenantId, stDescriptor, user);
@ -737,7 +747,8 @@ public class DefaultIotHubService implements IotHubService {
}
@Override
public InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor) {
public InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor,
IotHubInstalledItemId replaceInstalledItemId) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Registering device package install for version: {}", tenantId, versionId);
@ -752,87 +763,345 @@ public class DefaultIotHubService implements IotHubService {
UUID itemId = UUID.fromString(versionInfo.get("itemId").asText());
String version = versionInfo.get("version").asText();
IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
// An item replaced in the meantime (deleted from another tab) leaves a new one: the entities stay tracked.
IotHubInstalledItem installedItem = replaceInstalledItemId != null
? iotHubInstalledItemService.findById(tenantId, replaceInstalledItemId) : null;
boolean newItem = installedItem == null;
if (newItem) {
installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
} else {
checkDevicePackage(installedItem);
checkSameItem(installedItem, itemId);
keepTracking((DeviceInstalledItemDescriptor) installedItem.getDescriptor(), descriptor);
}
installedItem.setItemId(itemId);
installedItem.setItemVersionId(UUID.fromString(versionId));
installedItem.setItemName(itemName);
installedItem.setItemType("DEVICE");
installedItem.setVersion(version);
installedItem.setDescriptor(descriptor);
try {
iotHubInstalledItemService.save(tenantId, installedItem);
} catch (Exception e) {
log.error("[{}] Failed to save IoT Hub installed-item tracking row for device package {} (version {}); rolling back created entities",
tenantId, itemName, version, e);
// Not rolled back when the save fails: the wizard shows the error, and Retry registers the same entities again.
installedItem = iotHubInstalledItemService.save(tenantId, installedItem);
// Reported once per install, as before: the wizard registers again after each group of entities, on Retry
// and on an update.
if (newItem) {
try {
deleteEntityForDescriptor(user, tenantId, descriptor, null);
} catch (Exception rb) {
log.error("[{}] Compensating delete after failed tracking save threw — device package entities may remain orphaned",
tenantId, rb);
InstallReport report = buildInstallReport(tenantId.getId(), user.getId().getId(),
projectInfo.getProjectVersion(), projectInfo.getProductType());
iotHubRestClient.reportVersionInstalled(versionId, report);
} catch (Exception e) {
log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage());
}
throw e;
}
try {
InstallReport report = buildInstallReport(tenantId.getId(), user.getId().getId(),
projectInfo.getProjectVersion(), projectInfo.getProductType());
iotHubRestClient.reportVersionInstalled(versionId, report);
} catch (Exception e) {
log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage());
}
log.info("[{}] Registered device package install: {} (version {})", tenantId, itemName, version);
return InstallItemVersionResult.success(descriptor);
return InstallItemVersionResult.success(descriptor, installedItem.getId().getId());
} catch (Exception e) {
log.error("[{}] Failed to register device package install: {}", tenantId, versionId, e);
return InstallItemVersionResult.error(e.getMessage());
}
}
private void deleteDevicePackageEntities(TenantId tenantId, List<EntityId> createdEntityIds, SecurityUser user) {
if (createdEntityIds == null || createdEntityIds.isEmpty()) {
@Override
public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId,
UUID entityGroupId, UUID customerId) {
TenantId tenantId = user.getTenantId();
IotHubInstalledItem installedItem = findDevicePackage(tenantId, installedItemId);
// Checked before anything is removed: the registration of the new version checks the same and would fail.
JsonNode versionInfo;
try {
versionInfo = iotHubRestClient.getVersionInfo(versionId);
} catch (RestClientException e) {
throw new IllegalArgumentException("Failed to get version info from IoT Hub: " + e.getMessage(), e);
}
if (versionInfo == null) {
throw new IllegalArgumentException("Failed to get version info from IoT Hub");
}
String itemId = optText(versionInfo, FIELD_ITEM_ID);
if (itemId == null) {
throw new IllegalArgumentException("IoT Hub returned the version without its item");
}
checkSameItem(installedItem, UUID.fromString(itemId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
checkPackageEntitiesCanBeRemoved(tenantId, packageOwnedEntityIds(descriptor));
// Refusals above are a 400 and remove nothing. Any failure from here on is not a 400, so the wizard knows that
// entities may already be gone (each delete is committed on its own).
Map<EntityId, String> failed;
try {
failed = deleteDevicePackageEntities(tenantId, packageOwnedEntityIds(descriptor), user);
// An entity that could not be removed stays tracked, so that Retry, a later update or Delete removes it. The ones
// the user chose to use as they were are neither removed nor tracked any more.
descriptor.setCreatedEntityIds(failed.isEmpty() ? null : new ArrayList<>(failed.keySet()));
if (descriptor.getDashboardId() != null && !failed.containsKey(descriptor.getDashboardId())) {
descriptor.setDashboardId(null);
}
// Keep what the user entered in the forms (the wizard of the new version starts from it), drop the outputs of
// the removed entities: their ids, links and tokens no longer exist.
Map<String, JsonNode> installState = descriptor.getInstallState() != null
? stripEntityOutputs(descriptor.getInstallState()) : null;
// PE: where the removed device was, so that a retry still creates the new one there.
if (entityGroupId != null || customerId != null) {
if (installState == null) {
installState = new LinkedHashMap<>();
}
ObjectNode placement = JacksonUtil.newObjectNode();
if (entityGroupId != null) {
placement.put("entityGroupId", entityGroupId.toString());
}
if (customerId != null) {
placement.put("customerId", customerId.toString());
}
installState.put(PLACEMENT_STATE, placement);
}
descriptor.setInstallState(installState);
iotHubInstalledItemService.save(tenantId, installedItem);
} catch (RuntimeException e) {
// Without the cause: BaseController answers 400 for an IncorrectParameterException cause, and a 400 tells the
// wizard that nothing was removed.
log.warn("[{}] Removing the entities of device package {} failed", tenantId, installedItem.getItemName(), e);
throw new IllegalStateException("Removing the entities failed: " + e.getMessage());
}
if (!failed.isEmpty()) {
// The wizard must not create the new version's entities next to the ones left: it shows this and Retry.
throw new IllegalStateException("not removed: " + String.join(", ", failed.values()));
}
log.info("[{}] Removed the entities of device package {} for its update", tenantId, installedItem.getItemName());
}
private static final String PLACEMENT_STATE = "$placement";
private static Map<String, JsonNode> stripEntityOutputs(Map<String, JsonNode> installState) {
Map<String, JsonNode> stripped = new LinkedHashMap<>();
installState.forEach((step, state) -> {
JsonNode formValues = state != null ? state.get("formValues") : null;
if (PLACEMENT_STATE.equals(step) && state != null) {
stripped.put(step, state);
} else if (formValues != null) {
stripped.put(step, JacksonUtil.newObjectNode().set("formValues", formValues));
}
});
return stripped;
}
private static void checkSameItem(IotHubInstalledItem installedItem, UUID itemId) {
if (!itemId.equals(installedItem.getItemId())) {
throw new IllegalArgumentException("The new version belongs to another IoT Hub item.");
}
}
/**
* The new descriptor keeps tracking every entity the item tracks: the wizard registers again after each group of
* entities, and an entity left out would stay in the tenant with nothing to remove it. An update registers only
* after removing the entities of the installed version, so it tracks none of them any more.
*/
private static void keepTracking(DeviceInstalledItemDescriptor tracked, DeviceInstalledItemDescriptor descriptor) {
if (tracked.getCreatedEntityIds() != null) {
List<EntityId> ids = descriptor.getCreatedEntityIds() != null ? new ArrayList<>(descriptor.getCreatedEntityIds()) : new ArrayList<>();
tracked.getCreatedEntityIds().stream().filter(id -> !ids.contains(id)).forEach(ids::add);
descriptor.setCreatedEntityIds(ids);
}
if (descriptor.getDashboardId() == null) {
descriptor.setDashboardId(tracked.getDashboardId());
}
// PE: the wizard registers its own install state after each group of entities. The placement of the removed
// device stays until the new version tracks a device again, so that an update after a failure still creates it
// in the same group and for the same customer.
JsonNode placement = tracked.getInstallState() != null ? tracked.getInstallState().get(PLACEMENT_STATE) : null;
boolean tracksDevice = descriptor.getCreatedEntityIds() != null
&& descriptor.getCreatedEntityIds().stream().anyMatch(id -> id.getEntityType() == EntityType.DEVICE);
if (placement != null && !tracksDevice) {
Map<String, JsonNode> installState = descriptor.getInstallState() != null
? new LinkedHashMap<>(descriptor.getInstallState()) : new LinkedHashMap<>();
installState.putIfAbsent(PLACEMENT_STATE, placement);
descriptor.setInstallState(installState);
}
}
private IotHubInstalledItem findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) {
IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId);
if (installedItem == null) {
throw new IllegalArgumentException("Installed item not found");
}
checkDevicePackage(installedItem);
return installedItem;
}
private static void checkDevicePackage(IotHubInstalledItem installedItem) {
if (!"DEVICE".equals(installedItem.getItemType()) || !(installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor)) {
throw new IllegalArgumentException("Installed item is not a device package");
}
}
/**
* The update removes the package's entities one by one. ThingsBoard refuses to delete a device profile that is the
* default one or that devices outside the package use; a converter that an integration outside the package uses; a
* dashboard that a profile outside the package uses as its default dashboard; and a rule chain that is the root one
* or the default rule chain of a profile outside the package. (The firmware and software of a profile are deleted
* with it.) Found after the first deletes, such a refusal would leave the package half removed and fail every Retry
* the same way, so it is checked before anything is removed.
*/
private void checkPackageEntitiesCanBeRemoved(TenantId tenantId, List<EntityId> packageEntityIds) {
if (packageEntityIds == null || packageEntityIds.isEmpty()) {
return;
}
List<EntityId> reversed = new ArrayList<>(createdEntityIds);
Collections.reverse(reversed);
for (EntityId entityId : reversed) {
Set<UUID> owned = new HashSet<>();
packageEntityIds.forEach(id -> owned.add(id.getId()));
List<String> blockers = new ArrayList<>();
for (EntityId entityId : packageEntityIds) {
if (entityId.getEntityType() == EntityType.DEVICE_PROFILE) {
DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
if (!isOwnedBy(profile, tenantId)) {
continue;
}
if (profile.isDefault()) {
blockers.add("the device profile '" + profile.getName() + "' is the default device profile");
}
long otherDevices = 0;
for (DeviceId deviceId : new PageDataIterable<>(link -> deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(
tenantId, profile.getId(), link), 1000)) {
if (!owned.contains(deviceId.getId())) {
otherDevices++;
}
}
if (otherDevices > 0) {
blockers.add("the device profile '" + profile.getName() + "' is used by " + otherDevices + " other device(s)");
}
} else if (entityId.getEntityType() == EntityType.DASHBOARD) {
Dashboard dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
if (!isOwnedBy(dashboard, tenantId)) {
continue;
}
for (DeviceProfile profile : new PageDataIterable<>(link -> deviceProfileService.findDeviceProfiles(tenantId, link), 1000)) {
if (dashboard.getId().equals(profile.getDefaultDashboardId()) && !owned.contains(profile.getId().getId())) {
blockers.add("the dashboard '" + dashboard.getTitle() + "' is the default dashboard of the device profile '" + profile.getName() + "'");
}
}
for (AssetProfile profile : new PageDataIterable<>(link -> assetProfileService.findAssetProfiles(tenantId, link), 1000)) {
if (dashboard.getId().equals(profile.getDefaultDashboardId())) {
blockers.add("the dashboard '" + dashboard.getTitle() + "' is the default dashboard of the asset profile '" + profile.getName() + "'");
}
}
} else if (entityId.getEntityType() == EntityType.CONVERTER) {
Converter converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
if (!isOwnedBy(converter, tenantId)) {
continue;
}
for (Integration integration : integrationService.findIntegrationsByConverterId(tenantId, converter.getId())) {
if (!owned.contains(integration.getId().getId())) {
blockers.add("the converter '" + converter.getName() + "' is used by the integration '" + integration.getName() + "'");
}
}
} else if (entityId.getEntityType() == EntityType.RULE_CHAIN) {
RuleChain ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
if (!isOwnedBy(ruleChain, tenantId)) {
continue;
}
if (ruleChain.isRoot()) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the root rule chain");
}
for (DeviceProfile profile : new PageDataIterable<>(link -> deviceProfileService.findDeviceProfiles(tenantId, link), 1000)) {
if (ruleChain.getId().equals(profile.getDefaultRuleChainId()) && !owned.contains(profile.getId().getId())) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the rule chain of the device profile '" + profile.getName() + "'");
}
}
for (AssetProfile profile : new PageDataIterable<>(link -> assetProfileService.findAssetProfiles(tenantId, link), 1000)) {
if (ruleChain.getId().equals(profile.getDefaultRuleChainId())) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the rule chain of the asset profile '" + profile.getName() + "'");
}
}
}
}
if (!blockers.isEmpty()) {
// Not "nothing was removed": an earlier attempt may have removed part of the package already.
throw new IllegalArgumentException("The package can't be updated: " + String.join("; ", blockers)
+ ". Change or delete them first.");
}
}
/**
* The entities the package created: the tracked ones without those the user chose, on a name conflict, to use as they
* were (the install state keeps that choice). The default device profile, for example, is never the package's.
*/
private static List<EntityId> packageOwnedEntityIds(DeviceInstalledItemDescriptor descriptor) {
List<EntityId> tracked = descriptor.getCreatedEntityIds();
if (tracked == null || descriptor.getInstallState() == null) {
return tracked;
}
Set<String> usedExisting = new HashSet<>();
descriptor.getInstallState().values().forEach(state -> {
if (state != null && "use-existing".equals(optText(state, "resolution"))) {
JsonNode output = state.get("entityOutput");
String id = output != null ? optText(output, "id") : null;
if (id != null) {
usedExisting.add(id);
}
}
});
return tracked.stream().filter(id -> !usedExisting.contains(id.getId().toString())).toList();
}
private static final Map<EntityType, Integer> DELETE_ORDER = Map.of(EntityType.DEVICE, 0, EntityType.DEVICE_PROFILE, 1,
EntityType.DASHBOARD, 2, EntityType.RULE_CHAIN, 3, EntityType.INTEGRATION, 4, EntityType.CONVERTER, 5);
/** Removes the entities, each before what it refers to. Returns the ones that failed, in order of creation, with the reason. */
private Map<EntityId, String> deleteDevicePackageEntities(TenantId tenantId, List<EntityId> createdEntityIds, SecurityUser user) {
Map<EntityId, String> failed = new LinkedHashMap<>();
if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return failed;
}
// An entity goes before what it refers to: a device before its profile, a profile before its default dashboard
// and rule chain, an integration before its converters. Within a type, the reverse of the creation order.
List<EntityId> ordered = new ArrayList<>(createdEntityIds);
Collections.reverse(ordered);
ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size())));
for (EntityId entityId : ordered) {
try {
deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) {
log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
failed.put(entityId, entityId.getEntityType() + " (" + e.getMessage() + ")");
}
}
Map<EntityId, String> inCreationOrder = new LinkedHashMap<>();
createdEntityIds.stream().filter(failed::containsKey).forEach(id -> inCreationOrder.put(id, failed.get(id)));
return inCreationOrder;
}
/** The ids come from what the client registered: never delete an entity of another tenant. */
private static boolean isOwnedBy(HasTenantId entity, TenantId tenantId) {
return entity != null && tenantId.equals(entity.getTenantId());
}
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
switch (entityId.getEntityType()) {
case DEVICE -> {
var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
if (device != null) tbDeviceService.delete(device, user);
if (isOwnedBy(device, tenantId)) tbDeviceService.delete(device, user);
}
case DEVICE_PROFILE -> {
var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
if (profile != null) tbDeviceProfileService.delete(profile, user);
if (isOwnedBy(profile, tenantId)) tbDeviceProfileService.delete(profile, user);
}
case DASHBOARD -> {
var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
if (dashboard != null) tbDashboardService.delete(dashboard, user);
if (isOwnedBy(dashboard, tenantId)) tbDashboardService.delete(dashboard, user);
}
case RULE_CHAIN -> {
var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
if (ruleChain != null) tbRuleChainService.delete(ruleChain, user);
if (isOwnedBy(ruleChain, tenantId)) tbRuleChainService.delete(ruleChain, user);
}
case INTEGRATION -> {
IntegrationId integrationId = new IntegrationId(entityId.getId());
var integration = integrationService.findIntegrationById(tenantId, integrationId);
if (integration != null) {
if (isOwnedBy(integration, tenantId)) {
integrationService.deleteIntegration(tenantId, integrationId);
}
}
case CONVERTER -> {
var converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
if (converter != null) tbConverterService.delete(converter, user);
if (isOwnedBy(converter, tenantId)) tbConverterService.delete(converter, user);
}
default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType());
}
@ -888,7 +1157,7 @@ public class DefaultIotHubService implements IotHubService {
}
}
} else if (descriptor instanceof DeviceInstalledItemDescriptor dd) {
deleteDevicePackageEntities(tenantId, dd.getCreatedEntityIds(), user);
deleteDevicePackageEntities(tenantId, packageOwnedEntityIds(dd), user);
} else if (descriptor instanceof SolutionTemplateInstalledItemDescriptor st) {
try {
solutionService.deleteSolution(tenantId, st, user);

12
application/src/main/java/org/thingsboard/server/service/iot_hub/InstallItemVersionResult.java

@ -7,6 +7,8 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItemDescriptor;
import java.util.UUID;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ -15,13 +17,19 @@ public class InstallItemVersionResult {
private boolean success;
private String errorMessage;
private IotHubInstalledItemDescriptor descriptor;
/** The installed item that was saved; null when unknown. */
private UUID installedItemId;
public static InstallItemVersionResult success(IotHubInstalledItemDescriptor descriptor) {
return new InstallItemVersionResult(true, null, descriptor);
return new InstallItemVersionResult(true, null, descriptor, null);
}
public static InstallItemVersionResult success(IotHubInstalledItemDescriptor descriptor, UUID installedItemId) {
return new InstallItemVersionResult(true, null, descriptor, installedItemId);
}
public static InstallItemVersionResult error(String errorMessage) {
return new InstallItemVersionResult(false, errorMessage, null);
return new InstallItemVersionResult(false, errorMessage, null, null);
}
}

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

@ -10,13 +10,38 @@ import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
public interface IotHubService {
InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request);
UpdateItemVersionResult updateItemVersion(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, boolean force, HttpServletRequest request);
InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor);
/**
* Records a device package installed by the install wizard. With {@code replaceInstalledItemId} (an update), that
* installed item takes the new version instead of a new installed item being created.
*/
InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor,
IotHubInstalledItemId replaceInstalledItemId);
/**
* First step of a device package update: removes the entities the package created and keeps the installed item at
* its current version, so it is never shown with a version that is not installed. The item keeps that version even
* when its entities are gone and the new version is never registered (the wizard was closed): Update installs it
* again. An entity that could not be removed stays tracked and the call fails, so repeating it removes the rest.
* Refused with an {@link IllegalArgumentException} (a 400), before anything is removed, when the item is not a device
* package, {@code versionId} (the version to install) is not a version of that item, or IoT Hub does not answer. A failure once removing started is an
* {@link IllegalStateException}: entities may already be removed.
* PE: the entity group and the customer of the removed device are kept in the install state ({@code $placement}),
* so the new version's device is created there even when the update is retried after the device is gone.
*/
void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId,
UUID entityGroupId, UUID customerId);
default void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) {
removeDevicePackageEntities(user, installedItemId, versionId, null, null);
}
void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId);

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

@ -2,6 +2,24 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.dao.asset.AssetProfileService;
import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.id.AssetProfileId;
import static org.mockito.Mockito.lenient;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.DeviceProfile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
@ -12,15 +30,31 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.web.client.ResourceAccessException;
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.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.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.iot_hub.DashboardInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescriptor;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.device.DeviceProfileService;
import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@ -48,6 +82,30 @@ class DefaultIotHubServiceTest {
private IotHubRestClient iotHubRestClient;
@Mock
private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
private DeviceService deviceService;
@Mock
private DeviceProfileService deviceProfileService;
@Mock
private TbDeviceService tbDeviceService;
@Mock
private AssetProfileService assetProfileService;
@Mock
private TbRuleChainService tbRuleChainService;
@Mock
private RuleChainService ruleChainService;
@Mock
private IntegrationService integrationService;
@Mock
private ConverterService converterService;
@Mock
private TbConverterService tbConverterService;
@Mock
private TbDeviceProfileService tbDeviceProfileService;
@Mock
private DashboardService dashboardService;
@Mock
private TbDashboardService tbDashboardService;
@Spy
@InjectMocks
@ -411,4 +469,705 @@ class DefaultIotHubServiceTest {
assertThat(result.isRolledBack()).isFalse();
assertThat(result.getErrorMessage()).contains("install failed");
}
@Test
void updateItemVersion_device_refusedAndRemovesNothing() {
mockTenant();
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(new DeviceId(UUID.randomUUID())));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemVersionId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
// The install wizard of the new version does the update. A client that called this as an update before
// got success while the package was removed and nothing was installed again.
UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), UUID.randomUUID().toString(), true, null);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).contains("install wizard");
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(iotHubInstalledItemService, never()).deleteById(any(), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_removesTheDeviceBeforeTheDashboardAndKeepsTheItemVersion() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(device.getId(), dashboard.getId()));
descriptor.setDashboardId(dashboard.getId());
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
UUID versionId = UUID.randomUUID();
item.setItemVersionId(versionId);
item.setVersion("1.0.1");
item.setDescriptor(descriptor);
descriptor.setInstallState(new LinkedHashMap<>(Map.of(
"Configuration", JacksonUtil.toJsonNode("{\"formValues\":{\"gatewayName\":\"GW\"}}"),
"Gateway", JacksonUtil.toJsonNode("{\"entityOutput\":{\"id\":\"x\"},\"resolution\":\"created\"}"))));
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
item.setItemId(UUID.randomUUID());
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
device.setTenantId(tenantId);
dashboard.setTenantId(tenantId);
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService);
order.verify(tbDeviceService).delete(device, user);
order.verify(tbDashboardService).delete(dashboard, user);
order.verify(iotHubInstalledItemService).save(tenantId, item);
// The item keeps its version until the wizard registers the new one, and lists nothing to remove again.
assertThat(item.getItemVersionId()).isEqualTo(versionId);
assertThat(item.getVersion()).isEqualTo("1.0.1");
assertThat(descriptor.getCreatedEntityIds()).isNull();
assertThat(descriptor.getDashboardId()).isNull();
// The form values stay for the wizard of the new version; the removed entities' outputs go.
assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration");
assertThat(descriptor.getInstallState().get("Configuration").get("formValues").get("gatewayName").asText()).isEqualTo("GW");
verify(iotHubInstalledItemService, never()).deleteById(any(), any());
}
@Test
void removeDevicePackageEntities_keepsThePlacementOfTheRemovedDeviceForARetry() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(device.getId()));
descriptor.setInstallState(new LinkedHashMap<>(Map.of(
"Configuration", JacksonUtil.toJsonNode("{\"formValues\":{\"gatewayName\":\"GW\"}}"))));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
UUID entityGroupId = UUID.randomUUID();
UUID customerId = UUID.randomUUID();
service.removeDevicePackageEntities(user, item.getId(), newVersionId, entityGroupId, customerId);
verify(tbDeviceService).delete(device, user);
assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement");
assertThat(descriptor.getInstallState().get("$placement").get("entityGroupId").asText()).isEqualTo(entityGroupId.toString());
assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString());
// A retry after the device is gone: the wizard sends the same placement again, and it stays.
service.removeDevicePackageEntities(user, item.getId(), newVersionId, entityGroupId, customerId);
assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement");
assertThat(descriptor.getInstallState().get("$placement").get("entityGroupId").asText()).isEqualTo(entityGroupId.toString());
assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString());
}
@Test
void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() {
mockTenant();
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemVersionId(UUID.randomUUID());
item.setVersion("1.0.1");
item.setDescriptor(new DeviceInstalledItemDescriptor());
String newVersionId = UUID.randomUUID().toString();
String itemId = UUID.randomUUID().toString();
item.setItemId(UUID.fromString(itemId));
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(newVersionId)).thenReturn(version(newVersionId, itemId, "DEVICE", "Gateway", "1.0.2"));
DeviceInstalledItemDescriptor newDescriptor = new DeviceInstalledItemDescriptor();
newDescriptor.setCreatedEntityIds(List.<EntityId>of(new DeviceId(UUID.randomUUID())));
when(iotHubInstalledItemService.save(tenantId, item)).thenReturn(item);
InstallItemVersionResult result = service.registerDeviceInstall(user, newVersionId, newDescriptor, item.getId());
assertThat(result.isSuccess()).isTrue();
assertThat(result.getInstalledItemId()).isEqualTo(item.getId().getId());
verify(iotHubInstalledItemService).save(tenantId, item);
assertThat(item.getId()).isNotNull();
assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(newVersionId));
assertThat(item.getVersion()).isEqualTo("1.0.2");
assertThat(item.getDescriptor()).isSameAs(newDescriptor);
}
@Test
void removeDevicePackageEntities_notADevicePackage_refused() {
mockTenant();
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("RULE_CHAIN");
item.setDescriptor(new RuleChainInstalledItemDescriptor());
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), UUID.randomUUID().toString()))
.isInstanceOf(IllegalArgumentException.class);
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void registerDeviceInstall_replace_keepsTrackingTheEntitiesTheItemTracks() {
mockTenant();
String itemId = UUID.randomUUID().toString();
EntityId gateway = new DeviceId(UUID.randomUUID());
DashboardId dashboard = new DashboardId(UUID.randomUUID());
DeviceInstalledItemDescriptor tracked = new DeviceInstalledItemDescriptor();
tracked.setCreatedEntityIds(List.of(gateway, dashboard));
tracked.setDashboardId(dashboard);
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.fromString(itemId));
item.setDescriptor(tracked);
String newVersionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(newVersionId)).thenReturn(version(newVersionId, itemId, "DEVICE", "Gateway", "1.0.2"));
when(iotHubInstalledItemService.save(tenantId, item)).thenReturn(item);
EntityId device = new DeviceId(UUID.randomUUID());
DeviceInstalledItemDescriptor next = new DeviceInstalledItemDescriptor();
next.setCreatedEntityIds(List.of(device));
InstallItemVersionResult result = service.registerDeviceInstall(user, newVersionId, next, item.getId());
// A registration that leaves tracked entities out (another group, another connection method) still tracks them.
assertThat(result.isSuccess()).isTrue();
assertThat(next.getCreatedEntityIds()).containsExactlyInAnyOrder(device, gateway, dashboard);
assertThat(next.getDashboardId()).isEqualTo(dashboard);
}
@Test
void registerDeviceInstall_replace_keepsThePlacementUntilADeviceIsTracked() {
mockTenant();
String itemId = UUID.randomUUID().toString();
// After the update removed the entities: nothing tracked, the placement of the removed device kept.
ObjectNode placement = JacksonUtil.newObjectNode().put("entityGroupId", UUID.randomUUID().toString())
.put("customerId", UUID.randomUUID().toString());
DeviceInstalledItemDescriptor tracked = new DeviceInstalledItemDescriptor();
tracked.setInstallState(new LinkedHashMap<>(Map.of("Configuration", JacksonUtil.newObjectNode(), "$placement", placement)));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.fromString(itemId));
item.setDescriptor(tracked);
String newVersionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(newVersionId)).thenReturn(version(newVersionId, itemId, "DEVICE", "Sensor", "1.0.2"));
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
EntityId profile = new DeviceProfileId(UUID.randomUUID());
DeviceInstalledItemDescriptor afterProfile = new DeviceInstalledItemDescriptor();
afterProfile.setCreatedEntityIds(List.of(profile));
afterProfile.setInstallState(Map.of("Configuration", JacksonUtil.newObjectNode()));
service.registerDeviceInstall(user, newVersionId, afterProfile, item.getId());
// The wizard registered the profile only, with its own install state, and may fail before the device: the
// placement stays for the next update.
assertThat(afterProfile.getInstallState().get("$placement")).isEqualTo(placement);
EntityId device = new DeviceId(UUID.randomUUID());
DeviceInstalledItemDescriptor afterDevice = new DeviceInstalledItemDescriptor();
afterDevice.setCreatedEntityIds(List.of(profile, device));
afterDevice.setInstallState(Map.of("Configuration", JacksonUtil.newObjectNode()));
service.registerDeviceInstall(user, newVersionId, afterDevice, item.getId());
// The new device is tracked: the next update reads its group and customer from it.
assertThat(afterDevice.getInstallState()).doesNotContainKey("$placement");
}
@Test
void registerDeviceInstall_replacedItemGone_savesANewItem() {
mockTenant();
IotHubInstalledItemId goneId = new IotHubInstalledItemId(UUID.randomUUID());
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Gateway", "1.0.2"));
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(inv -> {
IotHubInstalledItem saved = inv.getArgument(1);
saved.setId(new IotHubInstalledItemId(UUID.randomUUID()));
return saved;
});
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, new DeviceInstalledItemDescriptor(), goneId);
// Deleted from another tab during the update: the new entities are tracked by a new item, Retry is not stuck.
assertThat(result.isSuccess()).isTrue();
assertThat(result.getInstalledItemId()).isNotEqualTo(goneId.getId());
}
@Test
void registerDeviceInstall_replace_versionOfAnotherItem_refused() {
mockTenant();
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(new DeviceInstalledItemDescriptor());
String newVersionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, UUID.randomUUID().toString(), "DEVICE", "Other", "2.0.0"));
InstallItemVersionResult result = service.registerDeviceInstall(user, newVersionId, new DeviceInstalledItemDescriptor(), item.getId());
assertThat(result.isSuccess()).isFalse();
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void registerDeviceInstall_replace_nextGroupWithAllTrackedEntities_updatesTheItem() {
mockTenant();
String itemId = UUID.randomUUID().toString();
EntityId gateway = new DeviceId(UUID.randomUUID());
EntityId dashboard = new DashboardId(UUID.randomUUID());
DeviceInstalledItemDescriptor firstGroup = new DeviceInstalledItemDescriptor();
firstGroup.setCreatedEntityIds(List.of(gateway));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.fromString(itemId));
item.setDescriptor(firstGroup);
String versionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, itemId, "DEVICE", "Gateway", "1.0.2"));
when(iotHubInstalledItemService.save(tenantId, item)).thenReturn(item);
// The wizard registers after each group of entities with everything it created so far.
DeviceInstalledItemDescriptor bothGroups = new DeviceInstalledItemDescriptor();
bothGroups.setCreatedEntityIds(List.of(gateway, dashboard));
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, bothGroups, item.getId());
assertThat(result.isSuccess()).isTrue();
assertThat(item.getDescriptor()).isSameAs(bothGroups);
}
@Test
void removeDevicePackageEntities_entityOfAnotherTenant_notDeleted() {
mockTenant();
Device foreignDevice = new Device(new DeviceId(UUID.randomUUID()));
foreignDevice.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(foreignDevice.getId()));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
item.setItemId(UUID.randomUUID());
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, foreignDevice.getId())).thenReturn(foreignDevice);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
verify(tbDeviceService, never()).delete(any(Device.class), any());
}
@Test
void removeDevicePackageEntities_entityNotRemoved_staysTrackedAndFails() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
dashboard.setTenantId(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(device.getId(), dashboard.getId()));
descriptor.setDashboardId(dashboard.getId());
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setVersion("1.0.1");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
doThrow(new RuntimeException("dashboard is in use")).when(tbDashboardService).delete(dashboard, user);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.hasMessage("not removed: DASHBOARD (dashboard is in use)");
// The rest is removed; the one left stays tracked, so Retry, a later update or Delete removes it.
verify(tbDeviceService).delete(device, user);
verify(iotHubInstalledItemService).save(tenantId, item);
assertThat(descriptor.getCreatedEntityIds()).containsExactly(dashboard.getId());
assertThat(descriptor.getDashboardId()).isEqualTo(dashboard.getId());
assertThat(item.getVersion()).isEqualTo("1.0.1");
}
@Test
void removeDevicePackageEntities_saveFailsAfterRemoving_notARefusal() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(device.getId()));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setVersion("1.0.1");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
doThrow(new IllegalArgumentException("invalid item")).when(iotHubInstalledItemService).save(tenantId, item);
// The device is already removed: the failure must not look like a refusal (a 400) to the wizard.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("invalid item");
verify(tbDeviceService).delete(device, user);
}
@Test
void removeDevicePackageEntities_profileUsedByAnotherDevice_refusedBeforeRemoving() {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceProfile profile = packageProfile(false);
IotHubInstalledItem item = devicePackage(profile.getId(), device.getId());
DeviceId otherDevice = new DeviceId(UUID.randomUUID());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(device.getId(), otherDevice), 1, 2, false));
String newVersionId = mockNewVersion(item);
// Deleting the profile would fail after the device is gone, and every Retry the same way: nothing is touched.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package profile' is used by 1 other device(s)")
.hasMessageContaining("Change or delete them first");
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_defaultProfile_refusedBeforeRemoving() {
mockTenant();
DeviceProfile profile = packageProfile(true);
IotHubInstalledItem item = devicePackage(profile.getId());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(), 0, 0, false));
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package profile' is the default device profile");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_profileUsedOnlyByThePackageDevice_removed() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceProfile profile = packageProfile(false);
IotHubInstalledItem item = devicePackage(profile.getId(), device.getId());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(device.getId()), 1, 1, false));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
String newVersionId = mockNewVersion(item);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
verify(tbDeviceService).delete(device, user);
verify(tbDeviceProfileService).delete(profile, user);
}
@Test
void removeDevicePackageEntities_rootRuleChain_refusedBeforeRemoving() {
mockTenant();
RuleChain ruleChain = packageRuleChain(true);
IotHubInstalledItem item = devicePackage(ruleChain.getId());
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package rule chain' is the root rule chain");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_ruleChainOfAnotherProfile_refusedBeforeRemoving() {
mockTenant();
RuleChain ruleChain = packageRuleChain(false);
DeviceProfile other = otherProfile("User profile");
other.setDefaultRuleChainId(ruleChain.getId());
when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page(other));
IotHubInstalledItem item = devicePackage(ruleChain.getId());
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package rule chain' is the rule chain of the device profile 'User profile'");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_ruleChainOfThePackageProfile_removed() throws Exception {
mockTenant();
RuleChain ruleChain = packageRuleChain(false);
DeviceProfile profile = packageProfile(false);
profile.setDefaultRuleChainId(ruleChain.getId());
when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page(profile));
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())).thenReturn(page());
// The rule chain listed last: in reverse order of creation it would go before the profile that refers to it
IotHubInstalledItem item = devicePackage(profile.getId(), ruleChain.getId());
String newVersionId = mockNewVersion(item);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
InOrder order = inOrder(tbDeviceProfileService, tbRuleChainService);
order.verify(tbDeviceProfileService).delete(profile, user);
order.verify(tbRuleChainService).delete(ruleChain, user);
}
@Test
void removeDevicePackageEntities_ruleChainOfAnAssetProfile_refusedBeforeRemoving() {
mockTenant();
RuleChain ruleChain = packageRuleChain(false);
AssetProfile assetProfile = new AssetProfile(new AssetProfileId(UUID.randomUUID()));
assetProfile.setName("Building");
assetProfile.setDefaultRuleChainId(ruleChain.getId());
when(assetProfileService.findAssetProfiles(eq(tenantId), any())).thenReturn(page(assetProfile));
IotHubInstalledItem item = devicePackage(ruleChain.getId());
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package rule chain' is the rule chain of the asset profile 'Building'");
}
@Test
void removeDevicePackageEntities_dashboardOfAnotherProfile_refusedBeforeRemoving() {
mockTenant();
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
dashboard.setTenantId(tenantId);
dashboard.setTitle("Package dashboard");
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
DeviceProfile other = otherProfile("User profile");
other.setDefaultDashboardId(dashboard.getId());
when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page(other));
lenient().when(assetProfileService.findAssetProfiles(eq(tenantId), any())).thenReturn(page());
IotHubInstalledItem item = devicePackage(dashboard.getId());
String newVersionId = mockNewVersion(item);
// Deleted first (reverse order), the dashboard would fail after nothing else, and the rest after it: refused now.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package dashboard' is the default dashboard of the device profile 'User profile'");
verify(tbDashboardService, never()).delete(any(), any());
}
@Test
void removeDevicePackageEntities_dashboardOfThePackageProfile_profileDeletedFirst() throws Exception {
mockTenant();
DeviceProfile profile = packageProfile(false);
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
dashboard.setTenantId(tenantId);
dashboard.setTitle("Package dashboard");
profile.setDefaultDashboardId(dashboard.getId());
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page(profile));
lenient().when(assetProfileService.findAssetProfiles(eq(tenantId), any())).thenReturn(page());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())).thenReturn(page());
// Created in this order by the wizard: the profile, then the dashboard
IotHubInstalledItem item = devicePackage(profile.getId(), dashboard.getId());
String newVersionId = mockNewVersion(item);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
// The profile refers to the dashboard: deleting the dashboard first would fail on fk_default_dashboard_device_profile
InOrder order = inOrder(tbDeviceProfileService, tbDashboardService);
order.verify(tbDeviceProfileService).delete(profile, user);
order.verify(tbDashboardService).delete(dashboard, user);
}
private DeviceProfile packageProfile(boolean isDefault) {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
profile.setTenantId(tenantId);
profile.setName("Package profile");
profile.setDefault(isDefault);
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
return profile;
}
private static <T> PageData<T> page(T... items) {
return new PageData<>(List.of(items), 1, items.length, false);
}
private RuleChain packageRuleChain(boolean root) {
RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
ruleChain.setTenantId(tenantId);
ruleChain.setName("Package rule chain");
ruleChain.setRoot(root);
when(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain);
lenient().when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page());
lenient().when(assetProfileService.findAssetProfiles(eq(tenantId), any())).thenReturn(page());
return ruleChain;
}
private DeviceProfile otherProfile(String name) {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
profile.setTenantId(tenantId);
profile.setName(name);
return profile;
}
@Test
void removeDevicePackageEntities_converterUsedByAnotherIntegration_refusedBeforeRemoving() {
mockTenant();
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
converter.setTenantId(tenantId);
converter.setName("Package converter");
Integration own = new Integration(new IntegrationId(UUID.randomUUID()));
Integration other = new Integration(new IntegrationId(UUID.randomUUID()));
other.setName("Another integration");
IotHubInstalledItem item = devicePackage(converter.getId(), own.getId());
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
when(integrationService.findIntegrationsByConverterId(tenantId, converter.getId())).thenReturn(List.of(own, other));
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package converter' is used by the integration 'Another integration'");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_integrationRemovedBeforeItsConverter() throws Exception {
mockTenant();
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
converter.setTenantId(tenantId);
converter.setName("Package converter");
Integration integration = new Integration(new IntegrationId(UUID.randomUUID()));
integration.setTenantId(tenantId);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
when(integrationService.findIntegrationsByConverterId(tenantId, converter.getId())).thenReturn(List.of(integration));
when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
// The converter listed last: in reverse order of creation it would go before the integration that uses it
IotHubInstalledItem item = devicePackage(integration.getId(), converter.getId());
String newVersionId = mockNewVersion(item);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
InOrder order = inOrder(integrationService, tbConverterService);
order.verify(integrationService).deleteIntegration(tenantId, integration.getId());
order.verify(tbConverterService).delete(converter, user);
}
private IotHubInstalledItem devicePackage(EntityId... created) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(created));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setVersion("1.0.1");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
return item;
}
private String mockNewVersion(IotHubInstalledItem item) {
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
return newVersionId;
}
@Test
void removeDevicePackageEntities_entityUsedAsItWas_neitherRemovedNorTracked() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceProfileId defaultProfileId = new DeviceProfileId(UUID.randomUUID());
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(defaultProfileId, device.getId()));
descriptor.setInstallState(new LinkedHashMap<>(Map.of(
"default", JacksonUtil.toJsonNode("{\"entityOutput\":{\"id\":\"" + defaultProfileId.getId() + "\"},\"resolution\":\"use-existing\"}"),
"Gateway", JacksonUtil.toJsonNode("{\"entityOutput\":{\"id\":\"" + device.getId().getId() + "\"},\"resolution\":\"created\"}"))));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
// The profile the user chose to use as it was (here the default one, which cannot be removed) is the user's.
verify(tbDeviceService).delete(device, user);
verify(deviceProfileService, never()).findDeviceProfileById(any(), any());
assertThat(descriptor.getCreatedEntityIds()).isNull();
}
@Test
void deleteInstalledItem_devicePackage_keepsEntityUsedAsItWas() {
mockTenant();
DeviceProfileId usersProfileId = new DeviceProfileId(UUID.randomUUID());
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(usersProfileId));
descriptor.setInstallState(new LinkedHashMap<>(Map.of(
"Profile", JacksonUtil.toJsonNode("{\"entityOutput\":{\"id\":\"" + usersProfileId.getId() + "\"},\"resolution\":\"use-existing\"}"))));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
service.deleteInstalledItem(user, item.getId());
verify(deviceProfileService, never()).findDeviceProfileById(any(), any());
verify(iotHubInstalledItemService).deleteById(tenantId, item.getId());
}
@Test
void removeDevicePackageEntities_versionOfAnotherItem_refusedBeforeRemoving() {
mockTenant();
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(new DeviceId(UUID.randomUUID())));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
String otherVersionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(otherVersionId))
.thenReturn(version(otherVersionId, UUID.randomUUID().toString(), "DEVICE", "Other", "2.0.0"));
// The registration of that version would be refused: nothing may be removed for it.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), otherVersionId))
.isInstanceOf(IllegalArgumentException.class);
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_iotHubUnavailable_refusedBeforeRemoving() {
mockTenant();
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(new DeviceId(UUID.randomUUID())));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
String newVersionId = UUID.randomUUID().toString();
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(newVersionId)).thenThrow(new ResourceAccessException("Connection refused"));
// A 400: nothing was removed, so the wizard does not warn that entities are gone.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class);
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
}

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

@ -165,12 +165,22 @@ export class IotHubApiService {
public registerDeviceInstall(
versionId: string,
descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> },
replaceInstalledItemId?: string,
config?: IotHubRequestConfig
): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>(
`/api/iot-hub/device/register?versionId=${versionId}`,
`/api/iot-hub/device/register`,
{ type: 'DEVICE', ...descriptor },
{ params: this.buildParams(config) }
{ params: this.buildParams(config, { versionId, replaceInstalledItemId }) }
);
}
public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig,
placement?: { entityGroupId?: string; customerId?: string }): Observable<void> {
return this.http.post<void>(
`/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`,
null,
{ params: this.buildParams(config, { versionId, entityGroupId: placement?.entityGroupId, customerId: placement?.customerId }) }
);
}
@ -198,10 +208,7 @@ export class IotHubApiService {
}
public updateItemVersion(installedItemId: string, versionId: string, config?: IotHubRequestConfig, force?: boolean): Observable<UpdateItemVersionResult> {
let params = this.buildParams(config);
if (force) {
params = params.set('force', 'true');
}
const params = this.buildParams(config, { force: force ? 'true' : undefined });
return this.http.post<UpdateItemVersionResult>(
`/api/iot-hub/installedItems/${installedItemId}/update/${versionId}`,
null,
@ -269,9 +276,11 @@ export class IotHubApiService {
);
}
private buildParams(config?: IotHubRequestConfig): HttpParams {
private buildParams(config?: IotHubRequestConfig, params?: Record<string, string | undefined>): HttpParams {
const defined = Object.fromEntries(Object.entries(params ?? {}).filter(([, value]) => value != null));
return new InterceptorHttpParams(
new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false)
new InterceptorConfig(config?.ignoreLoading ?? false, config?.ignoreErrors ?? false),
defined
);
}
}

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

@ -132,16 +132,26 @@
{{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }}
</span>
<span class="tb-progress-status">
@if (ep.status === 'success') {
<span class="tb-progress-status-done">{{ 'iot-hub.done' | translate }}</span>
}
@if (ep.status === 'running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
@switch (ep.status) {
@case ('success') {
<span class="tb-progress-status-done">{{ 'iot-hub.done' | translate }}</span>
}
@case ('running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
}
</span>
</div>
}
}
@if (removingReplaced()) {
<div class="mt-4 flex items-center gap-2">
<mat-spinner diameter="18"></mat-spinner>
<span class="tb-progress-status">{{ 'iot-hub.device-update-removing' | translate }}</span>
</div>
} @else if (ws.stepError) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error mt-4">{{ ws.stepError }}</span>
}
</div>
}
}
@ -171,7 +181,7 @@
} @else {
<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>
<button mat-icon-button (click)="cancel()" tabindex="-1">
<button mat-icon-button [disabled]="removingReplaced()" (click)="cancel()" tabindex="-1">
<mat-icon>close</mat-icon>
</button>
</div>
@ -205,7 +215,7 @@
</ng-template>
@for (ws of wizardSteps; track ws.label) {
<mat-step [editable]="true"
<mat-step [editable]="!removingReplaced()"
[completed]="ws.completed"
[stepControl]="ws.type === 'form' ? ws.formGroup : null">
<ng-template matStepLabel>{{ ws.label }}</ng-template>
@ -219,13 +229,13 @@
@if (allProgressDone) {
<button mat-button (click)="done()">{{ 'action.close' | translate }}</button>
} @else {
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-button [disabled]="removingReplaced()" (click)="cancel()">{{ 'action.cancel' | translate }}</button>
}
</ng-template>
<mat-dialog-actions>
@if (!isFirstWizardStep) {
<button mat-stroked-button (click)="previousStep()">{{ 'action.back' | translate }}</button>
<button mat-stroked-button [disabled]="removingReplaced()" (click)="previousStep()">{{ 'action.back' | translate }}</button>
}
<span class="flex-1"></span>
@if (currentWizardStep; as step) {
@ -255,14 +265,14 @@
</button>
}
@case ('progress') {
@if (step.progressError) {
@if (step.progressError || step.stepError) {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-flat-button color="primary" (click)="retryEntitySteps(step)">
{{ 'action.retry' | translate }}
</button>
} @else if (step.progressDone && isLastWizardStep) {
<ng-container *ngTemplateOutlet="finishActions"></ng-container>
} @else if (!step.progressError) {
} @else {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-stroked-button color="primary" [disabled]="!step.progressDone" (click)="nextStep()">
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}

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

@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { ChangeDetectorRef, Component, DestroyRef, Inject, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ChangeDetectorRef, Component, DestroyRef, Inject, OnDestroy, OnInit, signal, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Store } from '@ngrx/store';
@ -14,6 +14,7 @@ import { TranslateService } from '@ngx-translate/core';
import { PageLink } from '@shared/models/page/page-link';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DialogService } from '@core/services/dialog.service';
import { DeviceProfileService } from '@core/http/device-profile.service';
import { DeviceService } from '@core/http/device.service';
import { DashboardService } from '@core/http/dashboard.service';
@ -41,6 +42,8 @@ import {
stepTypeAliasMap
} from '@shared/models/iot-hub/device-package.models';
import { mergeMap } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';
import { iotHubErrorMessage } from '../iot-hub-utils';
export interface DeviceInstallDialogData {
item: MpItemVersionView;
@ -49,6 +52,8 @@ export interface DeviceInstallDialogData {
installState?: Record<string, any>;
entityGroupId?: string;
customerId?: string;
/** Update: the installed item whose entities are replaced by this version's. */
replaceInstalledItemId?: string;
}
export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress';
@ -67,6 +72,8 @@ export interface WizardStep {
entitySteps?: EntityStepProgress[];
progressError?: string;
progressDone?: boolean;
/** An error of the whole step (removal of the replaced entities, registration), not of one entity. */
stepError?: string;
}
const ENTITY_STEP_MIN_DELAY = 2000;
@ -104,6 +111,15 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
* has to report 'installed', or the caller keeps showing pre-install counts and badges.
*/
private installRegistered = false;
readonly removingReplaced = signal(false);
private replacedEntitiesRemoved = false;
private replacedEntitiesMayBeGone = false;
private registeredItemId: string | undefined;
// Kept as soon as an entity exists: going back resets a progress step, but every registration must still track it.
private packageEntityIds: { entityType: string; id: string }[] = [];
private createdInThisWizard = new Set<string>();
private methodPreselected = false;
private closed = false;
// Variable resolution state
formValues: Record<string, any> = {};
@ -126,7 +142,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
protected dialogRef: MatDialogRef<TbDeviceInstallDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: DeviceInstallDialogData,
private destroyRef: DestroyRef,
private cdr: ChangeDetectorRef,
private cd: ChangeDetectorRef,
private deviceProfileService: DeviceProfileService,
private deviceService: DeviceService,
private dashboardService: DashboardService,
@ -136,12 +152,14 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
private converterService: ConverterService,
private integrationService: IntegrationService,
private aiDashboardGenerationService: AiDashboardGenerationService,
private translate: TranslateService
private translate: TranslateService,
private dialogService: DialogService
) {
super(store, router, dialogRef);
}
async ngOnInit(): Promise<void> {
this.registeredItemId = this.data.replaceInstalledItemId;
this.allowAiDashboardGenerate = this.aiDashboardGenerationService.isAllowedDashboardGenerate({ requireTelemetry: true });
try {
const zipData = await firstValueFrom(this.iotHubApiService.getVersionFileData(this.data.item.id, { ignoreLoading: true }).pipe(
@ -198,12 +216,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// Multiple methods: render the connection method step as the
// wizard's first step.
this.startWizard();
// Update: preselect the method the installed version uses; the user can still pick another one.
const installedMethod = this.data.replaceInstalledItemId && this.data.selectedInstallMethod;
if (installedMethod && this.availableInstallMethods.includes(installedMethod)) {
this.selectedInstallMethod = installedMethod;
this.methodPreselected = true;
}
}
this.loading = false;
this.cdr.detectChanges();
this.cd.detectChanges();
}
ngOnDestroy() {
this.closed = true;
for (const url of this.zipImages.values()) {
URL.revokeObjectURL(url);
}
@ -213,6 +238,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
// --- Connectivity ---
selectConnectivity(ct: string): void {
if (this.selectedInstallMethod === ct && this.methodPreselected) {
this.confirmConnectivity();
return;
}
if (this.selectedInstallMethod === ct) {
// Re-clicking the already-selected card is a no-op; users who
// want to proceed without changing selection use the Next button.
@ -240,6 +269,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
if (!this.selectedInstallMethod) {
return;
}
this.methodPreselected = false;
// If we are already inside the wizard (connectivity step is the
// first one), append the remaining steps and advance the stepper.
const onConnectivityStep = this.currentWizardStep?.type === 'connectivity';
@ -250,7 +280,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.wizardSteps.length = 1;
this.appendInstallSteps();
connectivityStep.completed = true;
this.cdr.detectChanges();
this.cd.detectChanges();
// Wait for new mat-step children to register before advancing.
setTimeout(() => {
this.stepper?.next();
@ -318,7 +348,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return;
}
step.completed = true;
this.cdr.detectChanges();
this.cd.detectChanges();
this.stepper.next();
this.onStepActivated();
}
@ -371,19 +401,34 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.dialogRef.close('installed');
}
cancel(): void {
this.dialogRef.close(this.installRegistered ? 'installed' : false);
async cancel(): Promise<void> {
if (this.removingReplaced()) {
return;
}
if (this.replacedEntitiesMayBeGone && !this.installRegistered) {
const close = await firstValueFrom(this.dialogService.confirm(
this.translate.instant('iot-hub.device-update-close-title'),
this.translate.instant('iot-hub.device-update-close-text'),
this.translate.instant('action.cancel'),
this.translate.instant('action.close')));
if (!close) {
return;
}
}
this.closed = true;
this.dialogRef.close(this.installRegistered || this.replacedEntitiesMayBeGone ? 'installed' : false);
}
retryEntitySteps(step: WizardStep): void {
step.progressError = null;
step.stepError = null;
void this.runEntitySteps(step);
}
async resolveConflict(ws: WizardStep, ep: EntityStepProgress, resolution: string): Promise<void> {
ep.status = 'running';
ep.errorMessage = null;
this.cdr.detectChanges();
this.cd.detectChanges();
try {
let output: EntityStepOutput;
if (resolution === 'use-existing') {
@ -405,14 +450,16 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
await this.saveStepAttributes(ep.step, output);
ep.existingEntity = null;
ep.conflictType = null;
this.markEntityStepSuccess(ws, ep, output, resolution);
// An entity this wizard created a moment ago (the user went back and ran the step again) stays the package's own.
const recorded = resolution === 'use-existing' && this.createdInThisWizard.has(output.id) ? 'created' : resolution;
this.markEntityStepSuccess(ws, ep, output, recorded);
// Resume running remaining steps
await this.runEntitySteps(ws);
} catch (err: any) {
ep.status = 'error';
ep.errorMessage = err?.error?.message || err?.message || 'Unknown error';
ep.errorMessage = iotHubErrorMessage(err, this.translate);
ws.progressError = ep.errorMessage;
this.cdr.detectChanges();
this.cd.detectChanges();
}
}
@ -425,6 +472,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const progressStep = this.wizardSteps[currentIdx];
progressStep.entitySteps = null;
progressStep.progressError = null;
progressStep.stepError = null;
progressStep.progressDone = false;
progressStep.completed = false;
// Allow navigation back by making intermediate steps editable
@ -704,8 +752,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
const formJson = this.zipFiles.get(ws.rawSteps[0].file) || '[]';
ws.formFields = JSON.parse(formJson) as FormFieldDefinition[];
const controls: Record<string, UntypedFormControl> = {};
// In review mode, use stored values; otherwise use defaults
const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues;
// In review mode and on an update, use stored values; otherwise use defaults
const storedValues = (this.reviewMode || this.data.replaceInstalledItemId) && this.data.installState?.[ws.label]?.formValues;
for (const field of ws.formFields) {
this.fieldTypes.set(field.key, field.type);
const validators = [];
@ -726,7 +774,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
private resolveInitialFieldValue(field: FormFieldDefinition, storedValue: any): any {
if (storedValue !== undefined) {
// On an update the stored value comes from the previous version, whose field may have changed since.
if (storedValue !== undefined && (this.reviewMode || this.fitsField(field, storedValue))) {
return storedValue;
}
const isStringLike = field.type === FormFieldType.STRING || field.type === FormFieldType.PASSWORD;
@ -776,6 +825,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
resolvedName: this.resolveVariables(s.name)
}));
ws.progressError = null;
ws.stepError = null;
ws.progressDone = false;
void this.runEntitySteps(ws);
}
@ -785,6 +835,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
ep.entityOutput = output;
ep.resolution = resolution;
ep.status = 'success';
// The connector is attributes on the gateway, not an entity of its own: its output is the gateway, which the gateway
// step already accounted for (created, or used as it was).
const connector = ep.step.type === InstallStepType.GATEWAY_CONNECTOR;
if (resolution !== 'use-existing' && !connector) {
this.createdInThisWizard.add(output.id);
}
const entityType = connector ? null : this.stepTypeToEntityType(ep.step.type);
// An entity the user had before the install and chose to use is not the package's: a later update or Delete must
// not remove it, even after Back reruns the steps and its "use existing" mark is gone from the install state.
const packageOwned = resolution !== 'use-existing' || this.createdInThisWizard.has(output.id);
if (entityType && packageOwned && !this.packageEntityIds.some(known => known.id === output.id)) {
this.packageEntityIds.push({ entityType, id: output.id });
}
const alias = stepTypeAliasMap[ep.step.type];
if (alias) {
this.entityOutputs.set(alias, output);
@ -794,17 +857,20 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
remaining.resolvedName = this.resolveVariables(remaining.step.name);
}
}
this.cdr.detectChanges();
this.cd.detectChanges();
}
private async runEntitySteps(ws: WizardStep): Promise<void> {
if (!await this.removeReplacedEntities(ws) || this.closed) {
return;
}
for (const ep of ws.entitySteps) {
if (ep.status === 'success') {
continue;
}
ep.status = 'running';
ep.errorMessage = null;
this.cdr.detectChanges();
this.cd.detectChanges();
try {
// Pre-check for existing entity
const existing = await this.preCheckEntity(ep.step);
@ -812,7 +878,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
ep.status = 'conflict';
ep.existingEntity = existing;
ep.conflictType = this.getConflictType(ep.step.type);
this.cdr.detectChanges();
this.cd.detectChanges();
return; // Pause — user must choose a resolution
}
const startTime = Date.now();
@ -827,41 +893,85 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
this.markEntityStepSuccess(ws, ep, output, 'created');
} catch (err: any) {
ep.status = 'error';
ep.errorMessage = err?.error?.message || err?.message || 'Unknown error';
ep.errorMessage = iotHubErrorMessage(err, this.translate);
ws.progressError = ep.errorMessage;
this.cdr.detectChanges();
this.cd.detectChanges();
return;
}
}
// All done — register install with created entity IDs
ws.progressDone = true;
ws.completed = true;
// All done — register install with created entity IDs. Until then nothing tracks them, so the step is not done.
try {
const createdEntityIds = this.collectCreatedEntityIds();
const createdEntityIds = [...this.packageEntityIds];
const dashboardId = this.findCreatedDashboardId();
await firstValueFrom(
const result = await firstValueFrom(
this.iotHubApiService.registerDeviceInstall(
this.data.item.id as string,
{ createdEntityIds, dashboardId, selectedInstallMethod: this.selectedInstallMethod, installState: this.buildInstallState() },
{ ignoreLoading: true }
this.registeredItemId,
{ ignoreLoading: true, ignoreErrors: true }
)
);
if (!result?.success) {
throw new Error(result?.errorMessage);
}
this.installRegistered = true;
} catch (_e) {
// Non-critical — entities are created, tracking registration failed
console.error('Failed to register device install', _e);
this.registeredItemId = result.installedItemId ?? this.registeredItemId;
} catch (err: any) {
ws.stepError = this.translate.instant('iot-hub.device-install-register-error', { error: iotHubErrorMessage(err, this.translate) });
return;
}
ws.progressDone = true;
ws.completed = true;
// Auto-advance to next step after a short pause
if (!this.isLastWizardStep) {
await this.delay(500);
this.stepper.next();
this.cdr.detectChanges();
this.cd.detectChanges();
this.onStepActivated();
}
}
/** Update: the replaced version's entities are removed right before the new ones are created, or their names conflict. */
private async removeReplacedEntities(ws: WizardStep): Promise<boolean> {
if (!this.data.replaceInstalledItemId || this.replacedEntitiesRemoved) {
return true;
}
this.removingReplaced.set(true);
try {
// The server keeps the placement, so that a retry after the device is gone still creates the new one there.
await firstValueFrom(this.iotHubApiService.removeDevicePackageEntities(this.data.replaceInstalledItemId,
this.data.item.id as string, { ignoreLoading: true, ignoreErrors: true },
{ entityGroupId: this.data.entityGroupId, customerId: this.data.customerId }));
this.replacedEntitiesRemoved = true;
this.replacedEntitiesMayBeGone = true;
return true;
} catch (err: any) {
// Only a 400 is a refusal before anything was removed; any other failure (a proxy timeout too) may follow removals.
if (!(err instanceof HttpErrorResponse && err.status === 400)) {
this.replacedEntitiesMayBeGone = true;
}
ws.stepError = this.translate.instant('iot-hub.device-update-remove-error', { error: iotHubErrorMessage(err, this.translate) });
return false;
} finally {
this.removingReplaced.set(false);
}
}
private fitsField(field: FormFieldDefinition, value: any): boolean {
switch (field.type) {
case FormFieldType.BOOLEAN:
return typeof value === 'boolean';
case FormFieldType.INTEGER:
return Number.isInteger(value) || (typeof value === 'string' && /^-?\d*$/.test(value));
case FormFieldType.SELECT:
return typeof value === 'string' && (!field.options?.length || field.options.some(option => option.value === value));
default:
return typeof value === 'string';
}
}
private async createEntity(step: DeviceInstallStep): Promise<EntityStepOutput> {
const raw = this.zipFiles.get(step.template);
if (!raw) {
@ -1254,23 +1364,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return state;
}
private collectCreatedEntityIds(): { entityType: string; id: string }[] {
const ids: { entityType: string; id: string }[] = [];
for (const ws of this.wizardSteps) {
if (ws.type === 'progress' && ws.entitySteps) {
for (const ep of ws.entitySteps) {
if (ep.status === 'success' && ep.entityOutput) {
const entityType = this.stepTypeToEntityType(ep.step.type);
if (entityType) {
ids.push({ entityType, id: ep.entityOutput.id });
}
}
}
}
}
return ids;
}
private findCreatedDashboardId(): { entityType: string; id: string } | undefined {
for (const ws of this.wizardSteps) {
if (ws.type === 'progress' && ws.entitySteps) {

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

@ -3,8 +3,8 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable, of, EMPTY } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';
import { Observable, of, EMPTY, forkJoin } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { DialogService } from '@core/services/dialog.service';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
@ -15,10 +15,19 @@ import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemD
import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component';
import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component';
import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component';
import {
IotHubDeviceUpdateDialogData,
TbIotHubDeviceUpdateDialogComponent
} from './iot-hub-device-update-dialog.component';
import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component';
import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component';
import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component';
import { IotHubBuiltInService } from './iot-hub-built-in.service';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DeviceService } from '@core/http/device.service';
import { EntityGroupService } from '@core/http/entity-group.service';
import { EntityType } from '@shared/models/entity-type.models';
import { NULL_UUID } from '@shared/models/id/has-uuid';
import { isBuiltInItem } from './iot-hub-utils';
/**
@ -35,7 +44,10 @@ export class IotHubActionsService {
private dialog: MatDialog,
private dialogService: DialogService,
private translate: TranslateService,
private builtInService: IotHubBuiltInService
private builtInService: IotHubBuiltInService,
private iotHubApiService: IotHubApiService,
private deviceService: DeviceService,
private entityGroupService: EntityGroupService
) {}
openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number,
@ -148,6 +160,18 @@ export class IotHubActionsService {
if (!installedItem) {
return of(false);
}
if (installedItem.itemType === ItemType.DEVICE) {
// This version can only reinstall a device package: the dialog leads to the upgrade first.
return this.dialog.open<TbIotHubDeviceUpdateDialogComponent, IotHubDeviceUpdateDialogData, string | boolean>(
TbIotHubDeviceUpdateDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
autoFocus: false,
data: { itemName: installedItem.itemName }
}).afterClosed().pipe(
switchMap(result => result === 'reinstall' ? this.reinstallDevice(installedItem, versionId) : of(result))
);
}
return this.dialog.open<TbIotHubUpdateDialogComponent, IotHubUpdateDialogData, string | boolean>(TbIotHubUpdateDialogComponent, {
panelClass: ['tb-dialog'],
disableClose: true,
@ -162,6 +186,25 @@ export class IotHubActionsService {
}).afterClosed();
}
/** The install wizard of the new version updates a device package: it needs the user's input. */
private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable<string | boolean> {
const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor;
return forkJoin({
item: this.iotHubApiService.getVersionInfo(versionId),
placement: this.findDevicePlacement(descriptor)
}).pipe(
switchMap(({ item, placement }) => this.openDeviceInstallDialog(item, {
replaceInstalledItemId: installedItem.id.id,
selectedInstallMethod: descriptor?.selectedInstallMethod,
installState: descriptor?.installState,
...placement
})),
map(result => result === 'installed' ? 'updated' : false),
// The error itself is shown by the HTTP interceptor; nothing is changed yet.
catchError(() => of(false))
);
}
deleteItem(installedItem: IotHubInstalledItem): Observable<boolean> {
if (!installedItem) {
return of(false);
@ -191,9 +234,35 @@ export class IotHubActionsService {
});
}
/**
* The customer and the entity group of the installed version's device: the new version's device is created there
* too, as the wizard creates it in the group and for the customer it was installed from. With several groups the
* first one other than "All" is taken; nothing when the device cannot be read. When an earlier update already removed
* the device, the placement the server kept for it ($placement in the install state).
*/
private findDevicePlacement(descriptor: DeviceInstalledItemDescriptor): Observable<{ entityGroupId?: string; customerId?: string }> {
const deviceId = descriptor?.createdEntityIds?.find(id => id.entityType === EntityType.DEVICE)?.id;
if (!deviceId) {
const kept = descriptor?.installState?.['$placement'];
return of({ entityGroupId: kept?.entityGroupId, customerId: kept?.customerId });
}
const config = { ignoreLoading: true, ignoreErrors: true };
// Each lookup failing on its own (a deleted device, no access to its groups) only leaves its part out.
return forkJoin({
customerId: this.deviceService.getDevice(deviceId, config).pipe(
map(device => device.customerId && device.customerId.id !== NULL_UUID ? device.customerId.id : undefined),
catchError(() => of(undefined))),
entityGroupId: this.entityGroupService.getEntityGroupIdsForEntityId(EntityType.DEVICE, deviceId, config).pipe(
switchMap(groupIds => groupIds.length
? this.entityGroupService.getEntityGroupsByIds(groupIds.map(groupId => groupId.id), config) : of([])),
map(groups => groups.find(group => !group.groupAll)?.id.id),
catchError(() => of(undefined)))
});
}
private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
entityGroupId?: string; customerId?: string}): Observable<any> {
entityGroupId?: string; customerId?: string; replaceInstalledItemId?: string}): Observable<any> {
return this.dialog.open<TbDeviceInstallDialogComponent, DeviceInstallDialogData>(TbDeviceInstallDialogComponent, {
panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'],
disableClose: true,

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-add-item-dialog.component.ts

@ -14,7 +14,7 @@ import { DialogService } from '@core/services/dialog.service';
import { TranslateService } from '@ngx-translate/core';
import { EntityId } from '@shared/models/id/entity-id';
import { IotHubActionsService } from './iot-hub-actions.service';
import { isBuiltInItem } from './iot-hub-utils';
import { iotHubErrorMessage, isBuiltInItem } from './iot-hub-utils';
import {
IotHubSelectCfEntityDialogData,
TbIotHubSelectCfEntityDialogComponent
@ -132,7 +132,7 @@ export class TbIotHubAddItemDialogComponent extends DialogComponent<TbIotHubAddI
},
error: (err) => {
this.isInstalling = false;
const message = err?.error?.message || err?.message || this.translate.instant('iot-hub.install-error', { name: item.name });
const message = iotHubErrorMessage(err, this.translate, this.translate.instant('iot-hub.install-error', { name: item.name }));
this.dialogService.alert(
this.translate.instant('iot-hub.install-error-title'),
message

3
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts

@ -18,6 +18,7 @@ import { TbIotHubSearchComponent } from './iot-hub-search.component';
import { TbIotHubInstalledItemsTableComponent } from './iot-hub-installed-items-table.component';
import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items-dialog.component';
import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entity-dialog.component';
import { TbIotHubDeviceUpdateDialogComponent } from './iot-hub-device-update-dialog.component';
import { TbIotHubUpgradeRequiredDialogComponent } from './iot-hub-upgrade-required-dialog.component';
import { TbIotHubMarkdownComponent } from './iot-hub-markdown.component';
import { SolutionInstallDialogComponent } from './solution-install-dialog.component';
@ -42,6 +43,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
TbIotHubMarkdownComponent,
SolutionInstallDialogComponent,
InstallFormRendererComponent,
TbIotHubDeviceUpdateDialogComponent,
TbIotHubUpgradeRequiredDialogComponent
],
imports: [
@ -68,6 +70,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link
TbIotHubSelectCfEntityDialogComponent,
TbIotHubMarkdownComponent,
SolutionInstallDialogComponent,
TbIotHubDeviceUpdateDialogComponent,
TbIotHubUpgradeRequiredDialogComponent
]
})

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

@ -0,0 +1,30 @@
<!--
SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<div class="tb-iot-hub-upgrade-required">
<button mat-icon-button class="tb-iot-hub-upgrade-required-close" (click)="close()" tabindex="-1">
<mat-icon>close</mat-icon>
</button>
<span class="tb-iot-hub-upgrade-required-icon" aria-hidden="true"></span>
<h2 class="tb-iot-hub-upgrade-required-title">
{{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }}
</h2>
<p class="tb-iot-hub-upgrade-required-message"
[innerHTML]="'iot-hub.update-desc-device' | translate"></p>
<div class="tb-iot-hub-upgrade-required-actions">
<button mat-stroked-button color="warn" (click)="reinstall()">
{{ 'iot-hub.update-anyway' | translate }}
</button>
<button mat-flat-button color="primary" (click)="upgradeInstance()">
{{ 'iot-hub.upgrade-instance' | translate }}
</button>
</div>
</div>

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

@ -0,0 +1,48 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
export interface IotHubDeviceUpdateDialogData {
itemName: string;
}
/**
* Update of a device package. This version can only reinstall it, so the dialog leads to the upgrade that updates device
* packages without reinstalling, as the dialog of an item that needs a newer version does, and keeps the reinstall as
* the other way. Closes with 'reinstall' when the user chooses it.
*/
@Component({
selector: 'tb-iot-hub-device-update-dialog',
standalone: false,
templateUrl: './iot-hub-device-update-dialog.component.html',
styleUrls: ['./iot-hub-upgrade-required-dialog.component.scss']
})
export class TbIotHubDeviceUpdateDialogComponent extends DialogComponent<TbIotHubDeviceUpdateDialogComponent, string | boolean> {
constructor(
protected store: Store<AppState>,
protected router: Router,
protected dialogRef: MatDialogRef<TbIotHubDeviceUpdateDialogComponent, string | boolean>,
@Inject(MAT_DIALOG_DATA) public data: IotHubDeviceUpdateDialogData
) {
super(store, router, dialogRef);
}
close(): void {
this.dialogRef.close(false);
}
reinstall(): void {
this.dialogRef.close('reinstall');
}
upgradeInstance(): void {
window.open('https://thingsboard.io/docs/pe/installation/upgrade-instructions/', '_blank');
}
}

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

@ -30,6 +30,7 @@ import { DeviceProfileService } from '@core/http/device-profile.service';
import { AssetProfileService } from '@core/http/asset-profile.service';
import { RuleChainService } from '@core/http/rule-chain.service';
import { RuleChainId } from '@shared/models/id/rule-chain-id';
import { iotHubErrorMessage } from './iot-hub-utils';
interface SelectEntityConfig {
allowed: EntityType[];
@ -323,7 +324,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent<TbIotHubInst
private handleApiError(err: any): void {
this.state = 'error';
this.errorMessage = err?.error?.message || err?.message || '';
this.errorMessage = iotHubErrorMessage(err, this.translate);
}
private handlePlanResult(result: InstallPlanResult): void {

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

@ -26,6 +26,7 @@ import { switchMap } from 'rxjs/operators';
import { PageLink } from '@shared/models/page/page-link';
import { Direction, SortOrder } from '@shared/models/page/sort-order';
import {
canReviewDeviceInstall,
DeviceInstalledItemDescriptor,
getInstalledItemUrl,
IotHubInstalledItem,
@ -184,9 +185,13 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges,
private openDeviceReviewDialog(item: IotHubInstalledItem): void {
const descriptor = item.descriptor as DeviceInstalledItemDescriptor;
if (!descriptor.installState || !descriptor.selectedInstallMethod) {
if (!canReviewDeviceInstall(descriptor)) {
this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => {
this.iotHubActions.openItemDetail(versionView, item).subscribe();
this.iotHubActions.openItemDetail(versionView, item).subscribe(result => {
if (result === 'updated' || result === 'deleted') {
this.loadData();
}
});
});
return;
}

3
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts

@ -15,6 +15,7 @@ import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DialogService } from '@core/services/dialog.service';
import { TranslateService } from '@ngx-translate/core';
import { SolutionInstallDialogComponent } from '@home/components/iot-hub/solution-install-dialog.component';
import { iotHubErrorMessage } from './iot-hub-utils';
export interface IotHubUpdateDialogData {
installedItemId: string;
@ -95,7 +96,7 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent<TbIotHubUpdat
},
error: (err) => {
this.state = 'error';
this.errorMessage = err?.error?.message || err?.message || this.translate.instant('iot-hub.update-error', { name: this.data.itemName });
this.errorMessage = iotHubErrorMessage(err, this.translate, this.translate.instant('iot-hub.update-error', { name: this.data.itemName }));
}
});
}

8
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts

@ -3,6 +3,9 @@
import { FilterParamInfo, ItemType } from '@shared/models/iot-hub/iot-hub-item.models';
import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { HttpErrorResponse } from '@angular/common/http';
import { TranslateService } from '@ngx-translate/core';
import { parseHttpErrorMessage } from '@core/utils';
export const IOT_HUB_FILTER_GROUPING_THRESHOLD = 11;
export const IOT_HUB_FILTER_POPULAR_LIMIT = 10;
@ -103,3 +106,8 @@ export function resolveIotHubItemImageUrl(item: MpItemVersionView, api: IotHubAp
}
return null;
}
export function iotHubErrorMessage(err: any, translate: TranslateService, fallback?: string): string {
const message = err instanceof HttpErrorResponse ? parseHttpErrorMessage(err, translate).message : err?.message;
return message || fallback || translate.instant('error.unknown-error');
}

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

@ -40,6 +40,13 @@ export interface DeviceInstalledItemDescriptor {
installState?: Record<string, any>;
}
/**
* Whether the install of a device package can be reviewed: an update that removed the entities of the installed
* version but did not install the new one leaves the item with nothing to show.
*/
export const canReviewDeviceInstall = (descriptor: DeviceInstalledItemDescriptor): boolean =>
!!descriptor?.installState && !!descriptor.selectedInstallMethod && !!descriptor.createdEntityIds?.length;
export interface SolutionTemplateInstalledItemDescriptor {
type: 'SOLUTION_TEMPLATE';
createdEntityIds: { entityType: string; id: string }[];
@ -63,6 +70,7 @@ export interface InstallItemVersionResult {
success: boolean;
errorMessage: string;
descriptor: IotHubInstalledItemDescriptor;
installedItemId?: string;
}
export enum InstallPlanEntryStatus {

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

@ -6446,7 +6446,14 @@
"update-item-title": "Update Item",
"update-confirm": "Update '{{name}}' to version {{version}}?",
"update-confirm-title": "Update '{{name}}'?",
"update-anyway": "Update anyway",
"update-desc": "Updating this will replace the current version with the latest and reconfigure the associated resources within your tenant",
"device-update-removing": "Removing the entities of the installed version…",
"device-update-close-text": "The update has already removed entities of the installed version, and the new version is not installed yet. If you close the wizard now, the package stays at its installed version without them; Update installs it again.",
"device-update-close-title": "Close the installation wizard?",
"device-update-remove-error": "Removing the entities of the installed version failed: {{error}}. Retry removes them again",
"device-install-register-error": "The package is not recorded as installed: {{error}}. Retry records it again",
"update-desc-device": "Device packages can't be updated without reinstalling on this ThingsBoard version. Updating removes the installed entities and their data and installs the new version from scratch.<br><br>Upgrade to ThingsBoard 4.4.1 or newer to update device packages without reinstalling.",
"update-success-desc": "'{{name}}' has been updated successfully",
"updating": "Updating...",
"update-success-title": "Update Successful",

Loading…
Cancel
Save