From 29878c88fbfcd0cf17ba147779d840ad03096b43 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 14:46:16 +0200 Subject: [PATCH 1/8] IoT Hub: device package Update reinstalls the package on 4.4.0.x (PROD-9245) On 4.4.0.x the Update of a device package removed every entity the package created and installed nothing again. Now the Update opens the install wizard of the new version, with the forms filled from the installed version. Nothing is removed while the user goes through the forms; the entities of the installed version are removed right before the wizard creates the new ones, and the installed item keeps the old version until the wizard registers the new one on the same item. The update dialog warns that the package is reinstalled and its data removed. The diff of thingsboard#16558 (lts-4.4) applied onto hotfix-4.4, plus three fixes from its review: the removeEntities endpoint checks the permissions as the other IoT Hub endpoints do; an entity the user had before the install and chose to use is not tracked as the package's, so a later update or Delete never removes it; a failure after the removal has started is never answered with a 400, which tells the wizard that nothing was removed. --- .../server/controller/IotHubController.java | 13 +- .../service/iot_hub/DefaultIotHubService.java | 214 ++++++++-- .../iot_hub/InstallItemVersionResult.java | 12 +- .../server/service/iot_hub/IotHubService.java | 18 +- .../iot_hub/DefaultIotHubServiceTest.java | 398 ++++++++++++++++++ .../src/app/core/http/iot-hub-api.service.ts | 24 +- .../device-install-dialog.component.html | 32 +- .../device-install-dialog.component.ts | 182 +++++--- .../iot-hub/iot-hub-actions.service.ts | 39 +- .../iot-hub-add-item-dialog.component.ts | 4 +- .../iot-hub/iot-hub-components.module.ts | 3 + ...ot-hub-device-update-dialog.component.html | 30 ++ .../iot-hub-device-update-dialog.component.ts | 48 +++ .../iot-hub-install-dialog.component.ts | 3 +- ...iot-hub-installed-items-table.component.ts | 9 +- .../iot-hub-update-dialog.component.ts | 3 +- .../home/components/iot-hub/iot-hub-utils.ts | 8 + .../iot-hub/iot-hub-installed-item.models.ts | 8 + .../assets/locale/locale.constant-en_US.json | 7 + 19 files changed, 939 insertions(+), 116 deletions(-) create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.html create mode 100644 ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.ts diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index f3d32fedc8..95cbc7c1aa 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -89,10 +89,21 @@ 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) throws ThingsboardException { + checkAllPermissions(); + iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index c74c8be477..0f39f4581e 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -8,12 +8,14 @@ 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; @@ -85,6 +87,7 @@ 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 +472,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 +523,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 +742,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,47 +758,172 @@ 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 createdEntityIds, SecurityUser user) { + @Override + public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) { + 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)); + // 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). + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + Map 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. + if (descriptor.getInstallState() != null) { + descriptor.setInstallState(stripEntityOutputs(descriptor.getInstallState())); + } + 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 Map stripEntityOutputs(Map installState) { + Map stripped = new LinkedHashMap<>(); + installState.forEach((step, state) -> { + JsonNode formValues = state != null ? state.get("formValues") : null; + 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 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()); + } + } + + 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 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 packageOwnedEntityIds(DeviceInstalledItemDescriptor descriptor) { + List tracked = descriptor.getCreatedEntityIds(); + if (tracked == null || descriptor.getInstallState() == null) { + return tracked; + } + Set 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(); + } + + /** Removes the entities in reverse order of creation. Returns the ones that failed, in order of creation, with the reason. */ + private Map deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { + Map failed = new LinkedHashMap<>(); if (createdEntityIds == null || createdEntityIds.isEmpty()) { - return; + return failed; } List reversed = new ArrayList<>(createdEntityIds); Collections.reverse(reversed); @@ -801,38 +932,47 @@ public class DefaultIotHubService implements IotHubService { 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 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 +1028,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); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstallItemVersionResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/InstallItemVersionResult.java index b2fdb40c30..5c32afa7df 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/InstallItemVersionResult.java +++ b/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); } } diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index b934344e91..39f7f1df70 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -16,7 +16,23 @@ public interface IotHubService { 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. + */ + void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId); void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index cb9221db18..a8672bf668 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -12,15 +12,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 +64,16 @@ class DefaultIotHubServiceTest { private IotHubRestClient iotHubRestClient; @Mock private IotHubInstalledItemService iotHubInstalledItemService; + @Mock + private DeviceService deviceService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private TbDeviceService tbDeviceService; + @Mock + private DashboardService dashboardService; + @Mock + private TbDashboardService tbDashboardService; @Spy @InjectMocks @@ -411,4 +437,376 @@ 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.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_removesEntitiesInReverseOrderAndKeepsTheItemVersion() 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.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(tbDashboardService).delete(dashboard, user); + order.verify(tbDeviceService).delete(device, 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 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.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_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.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.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.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_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.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.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.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.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()); + } } diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index 99f5d5b716..b83635c774 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -165,12 +165,21 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, + replaceInstalledItemId?: string, config?: IotHubRequestConfig ): Observable { return this.http.post( - `/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): Observable { + return this.http.post( + `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`, + null, + { params: this.buildParams(config, { versionId }) } ); } @@ -198,10 +207,7 @@ export class IotHubApiService { } public updateItemVersion(installedItemId: string, versionId: string, config?: IotHubRequestConfig, force?: boolean): Observable { - 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( `/api/iot-hub/installedItems/${installedItemId}/update/${versionId}`, null, @@ -269,9 +275,11 @@ export class IotHubApiService { ); } - private buildParams(config?: IotHubRequestConfig): HttpParams { + private buildParams(config?: IotHubRequestConfig, params?: Record): 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 ); } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html index bea4732b05..819d43164c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html @@ -132,16 +132,26 @@ {{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }} - @if (ep.status === 'success') { - {{ 'iot-hub.done' | translate }} - } - @if (ep.status === 'running') { - {{ 'iot-hub.in-progress' | translate }} + @switch (ep.status) { + @case ('success') { + {{ 'iot-hub.done' | translate }} + } + @case ('running') { + {{ 'iot-hub.in-progress' | translate }} + } } } } + @if (removingReplaced()) { +
+ + {{ 'iot-hub.device-update-removing' | translate }} +
+ } @else if (ws.stepError) { + {{ ws.stepError }} + } } } @@ -171,7 +181,7 @@ } @else {

{{ 'iot-hub.device-install-title' | translate:{ name: packageInfo?.name || data.item.name } }}

-
@@ -205,7 +215,7 @@ @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -219,13 +229,13 @@ @if (allProgressDone) { } @else { - + } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -255,14 +265,14 @@ } @case ('progress') { - @if (step.progressError) { + @if (step.progressError || step.stepError) { } @else if (step.progressDone && isLastWizardStep) { - } @else if (!step.progressError) { + } @else { + + + +

+ {{ 'iot-hub.update-confirm-title' | translate:{ name: data.itemName } }} +

+ +

+ +
+ + +
+ diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.ts new file mode 100644 index 0000000000..29d104bb6d --- /dev/null +++ b/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 { + + constructor( + protected store: Store, + protected router: Router, + protected dialogRef: MatDialogRef, + @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'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 803fe17c3c..55ddf606e1 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/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 { - this.iotHubActions.openItemDetail(versionView, item).subscribe(); + this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { + if (result === 'updated' || result === 'deleted') { + this.loadData(); + } + }); }); return; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts index d47c2f8ada..2d5e821184 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.ts +++ b/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 { 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 })); } }); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts index 411ca58878..ce2422aaed 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-utils.ts +++ b/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'); +} diff --git a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts index a4bec2b193..5772e3c29a 100644 --- a/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts +++ b/ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts @@ -40,6 +40,13 @@ export interface DeviceInstalledItemDescriptor { installState?: Record; } +/** + * 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 { diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index fda314e14d..8e19062cca 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/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.

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", From cd704379fc19c8570ed96b42dce0973a13e73d65 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 15:57:41 +0200 Subject: [PATCH 2/8] IoT Hub: a device package update keeps the device's entity group and customer (PROD-9245) The PE part of thingsboard-pe#5291 for 4.4.0.x, by hand: the update opens the wizard of the new version with the entity group (the first one other than All) and the customer of the installed version's device, and the server keeps them in the install state ($placement) when it removes the entities, so a retry after the device is gone still creates the new one there. 4.4.1 does not need it: its update keeps the same device. --- .../server/controller/IotHubController.java | 7 ++- .../service/iot_hub/DefaultIotHubService.java | 28 +++++++++-- .../server/service/iot_hub/IotHubService.java | 11 ++++- .../iot_hub/DefaultIotHubServiceTest.java | 34 ++++++++++++++ .../src/app/core/http/iot-hub-api.service.ts | 5 +- .../device-install-dialog.component.ts | 4 +- .../iot-hub/iot-hub-actions.service.ts | 46 +++++++++++++++++-- 7 files changed, 120 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 95cbc7c1aa..5890480c68 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -101,9 +101,12 @@ public class IotHubController extends BaseController { @PostMapping("/installedItems/{installedItemId}/device/removeEntities") @ResponseBody public void removeDevicePackageEntities(@PathVariable UUID installedItemId, - @RequestParam String versionId) throws ThingsboardException { + @RequestParam String versionId, + @RequestParam(required = false) UUID entityGroupId, + @RequestParam(required = false) UUID customerId) throws ThingsboardException { checkAllPermissions(); - iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId); + iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, + entityGroupId, customerId); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 0f39f4581e..66bc9e1313 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.iot_hub; 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; @@ -800,7 +801,8 @@ public class DefaultIotHubService implements IotHubService { } @Override - public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) { + 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. @@ -832,9 +834,23 @@ public class DefaultIotHubService implements IotHubService { } // 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. - if (descriptor.getInstallState() != null) { - descriptor.setInstallState(stripEntityOutputs(descriptor.getInstallState())); + Map 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 @@ -849,11 +865,15 @@ public class DefaultIotHubService implements IotHubService { log.info("[{}] Removed the entities of device package {} for its update", tenantId, installedItem.getItemName()); } + private static final String PLACEMENT_STATE = "$placement"; + private static Map stripEntityOutputs(Map installState) { Map stripped = new LinkedHashMap<>(); installState.forEach((step, state) -> { JsonNode formValues = state != null ? state.get("formValues") : null; - if (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)); } }); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index 39f7f1df70..055811d35b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -10,6 +10,8 @@ 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); @@ -31,8 +33,15 @@ public interface IotHubService { * 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); + 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); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index a8672bf668..2c770f2fa2 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -504,6 +504,40 @@ class DefaultIotHubServiceTest { 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.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 kept placement again, and it stays. + service.removeDevicePackageEntities(user, item.getId(), newVersionId); + assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement"); + assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString()); + } + @Test void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() { mockTenant(); diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index b83635c774..b443daafe9 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -175,11 +175,12 @@ export class IotHubApiService { ); } - public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig): Observable { + public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig, + placement?: { entityGroupId?: string; customerId?: string }): Observable { return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`, null, - { params: this.buildParams(config, { versionId }) } + { params: this.buildParams(config, { versionId, entityGroupId: placement?.entityGroupId, customerId: placement?.customerId }) } ); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 355f7753a3..8ad5fc9c76 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -937,8 +937,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor; - return this.iotHubApiService.getVersionInfo(versionId).pipe( - switchMap(item => this.openDeviceInstallDialog(item, { + 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 + installState: descriptor?.installState, + ...placement })), map(result => result === 'installed' ? 'updated' : false), // The error itself is shown by the HTTP interceptor; nothing is changed yet. @@ -224,6 +234,32 @@ 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; replaceInstalledItemId?: string}): Observable { From 6b8e62cebc9443a49a847e2b0f6bb5db037cbbe4 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 15:59:44 +0200 Subject: [PATCH 3/8] IoT Hub: an update that can't remove the package's profile, rule chain or converter is refused before removing (PROD-9245) By hand from the 4.2 and PE lines: 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, and a rule chain that is the root one or the default rule chain of a profile outside the package. Found after the dashboard and the device were gone, such a refusal left the package half removed and failed every Retry. Now it is checked before anything is removed, and the update is refused with a 400 that names what blocks it. --- .../service/iot_hub/DefaultIotHubService.java | 74 ++++++++++- .../iot_hub/DefaultIotHubServiceTest.java | 117 ++++++++++++++++++ 2 files changed, 190 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 66bc9e1313..b8b6320ed9 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -3,6 +3,9 @@ // 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; @@ -820,9 +823,10 @@ public class DefaultIotHubService implements IotHubService { 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). - DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); Map failed; try { failed = deleteDevicePackageEntities(tenantId, packageOwnedEntityIds(descriptor), user); @@ -921,6 +925,74 @@ public class DefaultIotHubService implements IotHubService { * 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. */ + /** + * 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, + * and a rule chain that is the root one or the default rule chain of a profile outside the package. 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: a 400 removes nothing. + */ + private void checkPackageEntitiesCanBeRemoved(TenantId tenantId, List packageEntityIds) { + if (packageEntityIds == null || packageEntityIds.isEmpty()) { + return; + } + Set owned = new HashSet<>(); + packageEntityIds.forEach(id -> owned.add(id.getId())); + List 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.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()) { + throw new IllegalArgumentException("The package can't be updated: " + String.join("; ", blockers) + + ". Move them to other profiles or rule chains first, or delete them. Nothing was removed."); + } + } + private static List packageOwnedEntityIds(DeviceInstalledItemDescriptor descriptor) { List tracked = descriptor.getCreatedEntityIds(); if (tracked == null || descriptor.getInstallState() == null) { diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 2c770f2fa2..bfbf16794e 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -2,6 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 package org.thingsboard.server.service.iot_hub; +import org.thingsboard.server.dao.converter.ConverterService; +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; @@ -71,6 +80,12 @@ class DefaultIotHubServiceTest { @Mock private TbDeviceService tbDeviceService; @Mock + private IntegrationService integrationService; + @Mock + private ConverterService converterService; + @Mock + private TbDeviceProfileService tbDeviceProfileService; + @Mock private DashboardService dashboardService; @Mock private TbDashboardService tbDashboardService; @@ -755,6 +770,108 @@ class DefaultIotHubServiceTest { 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("Nothing was removed"); + 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); + } + + 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; + } + + @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()); + } + + 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(); From 4df83aba1bf47bc45a96fe67fa7077fce4313e27 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 17:08:32 +0200 Subject: [PATCH 4/8] IoT Hub: review of #16553 by hand: the removal check covers dashboards and firmware, the connector step owns no entity (PROD-9245) - A dashboard of the package that a profile outside the package uses as its default dashboard, and a device profile of the package that a firmware or software package refers to, refuse the update before anything is removed. - The refusal no longer says that nothing was removed: an earlier attempt may have removed part of the package. - The GATEWAY_CONNECTOR step neither marks the gateway as created in this wizard nor tracks it, so a gateway the user had and chose to use stays theirs after Back reruns the steps. - The doc of packageOwnedEntityIds is back above it; tests for the rule chain, the dashboard and the firmware. --- .../service/iot_hub/DefaultIotHubService.java | 43 ++++- .../iot_hub/DefaultIotHubServiceTest.java | 147 +++++++++++++++++- .../device-install-dialog.component.ts | 7 +- 3 files changed, 186 insertions(+), 11 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index b8b6320ed9..78d7b6b80c 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -3,6 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import org.thingsboard.server.dao.ota.OtaPackageService; +import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.page.PageDataIterable; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.integration.Integration; @@ -125,6 +127,7 @@ public class DefaultIotHubService implements IotHubService { private final IotHubInstalledItemService iotHubInstalledItemService; private final WidgetTypeService widgetTypeService; private final DashboardService dashboardService; + private final OtaPackageService otaPackageService; private final CalculatedFieldService calculatedFieldService; private final DeviceProfileService deviceProfileService; private final DeviceService deviceService; @@ -921,15 +924,13 @@ public class DefaultIotHubService implements IotHubService { } } - /** - * 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. - */ /** * 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, - * and a rule chain that is the root one or the default rule chain of a profile outside the package. 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: a 400 removes nothing. + * default one, that devices outside the package use or that a firmware or software package refers to; 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. 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 packageEntityIds) { if (packageEntityIds == null || packageEntityIds.isEmpty()) { @@ -957,6 +958,27 @@ public class DefaultIotHubService implements IotHubService { if (otherDevices > 0) { blockers.add("the device profile '" + profile.getName() + "' is used by " + otherDevices + " other device(s)"); } + for (OtaPackageInfo ota : new PageDataIterable<>(link -> otaPackageService.findTenantOtaPackagesByTenantId(tenantId, link), 1000)) { + if (profile.getId().equals(ota.getDeviceProfileId())) { + blockers.add("the device profile '" + profile.getName() + "' is used by the " + ota.getType().name().toLowerCase() + + " '" + ota.getTitle() + " " + ota.getVersion() + "'"); + } + } + } 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)) { @@ -988,11 +1010,16 @@ public class DefaultIotHubService implements IotHubService { } } 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) - + ". Move them to other profiles or rule chains first, or delete them. Nothing was removed."); + + ". 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 packageOwnedEntityIds(DeviceInstalledItemDescriptor descriptor) { List tracked = descriptor.getCreatedEntityIds(); if (tracked == null || descriptor.getInstallState() == null) { diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index bfbf16794e..6b87889815 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -2,6 +2,18 @@ // 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.dao.ota.OtaPackageService; +import org.thingsboard.server.common.data.OtaPackageInfo; +import org.thingsboard.server.common.data.ota.OtaPackageType; +import org.thingsboard.server.common.data.id.OtaPackageId; +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.dao.integration.IntegrationService; import org.thingsboard.server.common.data.id.IntegrationId; @@ -80,6 +92,14 @@ class DefaultIotHubServiceTest { @Mock private TbDeviceService tbDeviceService; @Mock + private OtaPackageService otaPackageService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private TbRuleChainService tbRuleChainService; + @Mock + private RuleChainService ruleChainService; + @Mock private IntegrationService integrationService; @Mock private ConverterService converterService; @@ -786,7 +806,7 @@ class DefaultIotHubServiceTest { assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("'Package profile' is used by 1 other device(s)") - .hasMessageContaining("Nothing was removed"); + .hasMessageContaining("Change or delete them first"); verify(tbDeviceService, never()).delete(any(Device.class), any()); verify(iotHubInstalledItemService, never()).save(any(), any()); } @@ -824,12 +844,137 @@ class DefaultIotHubServiceTest { 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()); + IotHubInstalledItem item = devicePackage(ruleChain.getId(), profile.getId()); + String newVersionId = mockNewVersion(item); + + service.removeDevicePackageEntities(user, item.getId(), newVersionId); + + verify(tbDeviceProfileService).delete(profile, user); + 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_profileOfAFirmware_refusedBeforeRemoving() { + mockTenant(); + DeviceProfile profile = packageProfile(false); + when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())).thenReturn(page()); + OtaPackageInfo firmware = new OtaPackageInfo(new OtaPackageId(UUID.randomUUID())); + firmware.setDeviceProfileId(profile.getId()); + firmware.setType(OtaPackageType.FIRMWARE); + firmware.setTitle("fw"); + firmware.setVersion("1.2"); + when(otaPackageService.findTenantOtaPackagesByTenantId(eq(tenantId), any())).thenReturn(page(firmware)); + IotHubInstalledItem item = devicePackage(profile.getId()); + String newVersionId = mockNewVersion(item); + + assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("'Package profile' is used by the firmware 'fw 1.2'"); + } + 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); + lenient().when(otaPackageService.findTenantOtaPackagesByTenantId(eq(tenantId), any())).thenReturn(page()); + return profile; + } + + private static PageData 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; } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 8ad5fc9c76..7e2c0c5843 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -835,10 +835,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent Date: Wed, 11 Nov 2026 17:46:51 +0200 Subject: [PATCH 5/8] IoT Hub device package update: no OTA check (the firmware goes with its profile), delete each entity before what it refers to (PROD-9245, by hand from #16553) --- .../service/iot_hub/DefaultIotHubService.java | 34 ++++++++--------- .../iot_hub/DefaultIotHubServiceTest.java | 38 +++++++++---------- 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 78d7b6b80c..dfe46e0aa6 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -3,8 +3,6 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.iot_hub; -import org.thingsboard.server.dao.ota.OtaPackageService; -import org.thingsboard.server.common.data.OtaPackageInfo; import org.thingsboard.server.common.data.page.PageDataIterable; import org.thingsboard.server.common.data.converter.Converter; import org.thingsboard.server.common.data.integration.Integration; @@ -89,6 +87,7 @@ 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; @@ -127,7 +126,6 @@ public class DefaultIotHubService implements IotHubService { private final IotHubInstalledItemService iotHubInstalledItemService; private final WidgetTypeService widgetTypeService; private final DashboardService dashboardService; - private final OtaPackageService otaPackageService; private final CalculatedFieldService calculatedFieldService; private final DeviceProfileService deviceProfileService; private final DeviceService deviceService; @@ -926,11 +924,11 @@ public class DefaultIotHubService implements IotHubService { /** * The update removes the package's entities one by one. ThingsBoard refuses to delete a device profile that is the - * default one, that devices outside the package use or that a firmware or software package refers to; 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. 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. + * 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 packageEntityIds) { if (packageEntityIds == null || packageEntityIds.isEmpty()) { @@ -958,12 +956,6 @@ public class DefaultIotHubService implements IotHubService { if (otherDevices > 0) { blockers.add("the device profile '" + profile.getName() + "' is used by " + otherDevices + " other device(s)"); } - for (OtaPackageInfo ota : new PageDataIterable<>(link -> otaPackageService.findTenantOtaPackagesByTenantId(tenantId, link), 1000)) { - if (profile.getId().equals(ota.getDeviceProfileId())) { - blockers.add("the device profile '" + profile.getName() + "' is used by the " + ota.getType().name().toLowerCase() - + " '" + ota.getTitle() + " " + ota.getVersion() + "'"); - } - } } else if (entityId.getEntityType() == EntityType.DASHBOARD) { Dashboard dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); if (!isOwnedBy(dashboard, tenantId)) { @@ -1038,15 +1030,21 @@ public class DefaultIotHubService implements IotHubService { return tracked.stream().filter(id -> !usedExisting.contains(id.getId().toString())).toList(); } - /** Removes the entities in reverse order of creation. Returns the ones that failed, in order of creation, with the reason. */ + private static final Map 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 deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { Map failed = new LinkedHashMap<>(); if (createdEntityIds == null || createdEntityIds.isEmpty()) { return failed; } - List reversed = new ArrayList<>(createdEntityIds); - Collections.reverse(reversed); - for (EntityId entityId : reversed) { + // 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 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) { diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 6b87889815..63d4621adf 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -5,10 +5,6 @@ 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.dao.ota.OtaPackageService; -import org.thingsboard.server.common.data.OtaPackageInfo; -import org.thingsboard.server.common.data.ota.OtaPackageType; -import org.thingsboard.server.common.data.id.OtaPackageId; import org.thingsboard.server.common.data.rule.RuleChain; import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.asset.AssetProfile; @@ -92,8 +88,6 @@ class DefaultIotHubServiceTest { @Mock private TbDeviceService tbDeviceService; @Mock - private OtaPackageService otaPackageService; - @Mock private AssetProfileService assetProfileService; @Mock private TbRuleChainService tbRuleChainService; @@ -496,7 +490,7 @@ class DefaultIotHubServiceTest { } @Test - void removeDevicePackageEntities_removesEntitiesInReverseOrderAndKeepsTheItemVersion() throws Exception { + void removeDevicePackageEntities_removesTheDeviceBeforeTheDashboardAndKeepsTheItemVersion() throws Exception { mockTenant(); Device device = new Device(new DeviceId(UUID.randomUUID())); Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); @@ -525,8 +519,8 @@ class DefaultIotHubServiceTest { service.removeDevicePackageEntities(user, item.getId(), newVersionId); InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService); - order.verify(tbDashboardService).delete(dashboard, user); 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); @@ -928,22 +922,27 @@ class DefaultIotHubServiceTest { } @Test - void removeDevicePackageEntities_profileOfAFirmware_refusedBeforeRemoving() { + 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()); - OtaPackageInfo firmware = new OtaPackageInfo(new OtaPackageId(UUID.randomUUID())); - firmware.setDeviceProfileId(profile.getId()); - firmware.setType(OtaPackageType.FIRMWARE); - firmware.setTitle("fw"); - firmware.setVersion("1.2"); - when(otaPackageService.findTenantOtaPackagesByTenantId(eq(tenantId), any())).thenReturn(page(firmware)); - IotHubInstalledItem item = devicePackage(profile.getId()); + // Created in this order by the wizard: the profile, then the dashboard + IotHubInstalledItem item = devicePackage(profile.getId(), dashboard.getId()); String newVersionId = mockNewVersion(item); - assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("'Package profile' is used by the firmware 'fw 1.2'"); + 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) { @@ -952,7 +951,6 @@ class DefaultIotHubServiceTest { profile.setName("Package profile"); profile.setDefault(isDefault); when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile); - lenient().when(otaPackageService.findTenantOtaPackagesByTenantId(eq(tenantId), any())).thenReturn(page()); return profile; } From 5537dc4e623e3ad7cc8a16d4b07af1cedb25fe5e Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 17:58:23 +0200 Subject: [PATCH 6/8] IoT Hub device package update: tests check that the profile goes before its rule chain and the integration before its converter (PROD-9245, review of #16553) --- .../iot_hub/DefaultIotHubServiceTest.java | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 63d4621adf..3387f2747a 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -11,6 +11,7 @@ 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; @@ -98,6 +99,8 @@ class DefaultIotHubServiceTest { @Mock private ConverterService converterService; @Mock + private TbConverterService tbConverterService; + @Mock private TbDeviceProfileService tbDeviceProfileService; @Mock private DashboardService dashboardService; @@ -875,13 +878,15 @@ class DefaultIotHubServiceTest { profile.setDefaultRuleChainId(ruleChain.getId()); when(deviceProfileService.findDeviceProfiles(eq(tenantId), any())).thenReturn(page(profile)); when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any())).thenReturn(page()); - IotHubInstalledItem item = devicePackage(ruleChain.getId(), profile.getId()); + // 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); - verify(tbDeviceProfileService).delete(profile, user); - verify(tbRuleChainService).delete(ruleChain, user); + InOrder order = inOrder(tbDeviceProfileService, tbRuleChainService); + order.verify(tbDeviceProfileService).delete(profile, user); + order.verify(tbRuleChainService).delete(ruleChain, user); } @Test @@ -996,6 +1001,28 @@ class DefaultIotHubServiceTest { 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)); From 4ee5497ac561fb3a77edbb2aa76745179bacce09 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 18:17:25 +0200 Subject: [PATCH 7/8] IoT Hub device package update: the placement of the removed device stays until the new version tracks a device (PROD-9245, review of #16625) --- .../service/iot_hub/DefaultIotHubService.java | 12 ++++++ .../iot_hub/DefaultIotHubServiceTest.java | 39 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index dfe46e0aa6..f427262afd 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -905,6 +905,18 @@ public class DefaultIotHubService implements IotHubService { 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 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) { diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 3387f2747a..b40773644b 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -641,6 +641,45 @@ class DefaultIotHubServiceTest { 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(); From 9926d4da53a726c2bad92dacf8cbf1e1016d6a39 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 12 Nov 2026 09:59:02 +0200 Subject: [PATCH 8/8] IoT Hub device package update: the retry in the placement test sends the same group and customer, as the wizard does --- .../server/service/iot_hub/DefaultIotHubServiceTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index b40773644b..a0cde96379 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -564,9 +564,10 @@ class DefaultIotHubServiceTest { 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 kept placement again, and it stays. - service.removeDevicePackageEntities(user, item.getId(), newVersionId); + // 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()); }