From 7e2802d24dd31b8ac8964db3a7da06ca60741f3c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 11:45:27 +0200 Subject: [PATCH] fix(iot-hub): keep tracking the entities a device package update could not remove An entity that is not removed stays in the installed item and the removal fails, so the wizard shows the error and Retry removes the rest. Closing the wizard after the removal asks first, and the update warning says that the new devices get new access tokens. --- .../service/iot_hub/DefaultIotHubService.java | 23 ++++++++++--- .../server/service/iot_hub/IotHubService.java | 6 ++-- .../iot_hub/DefaultIotHubServiceTest.java | 34 +++++++++++++++++++ .../device-install-dialog.component.ts | 17 ++++++++-- .../assets/locale/locale.constant-en_US.json | 6 ++-- 5 files changed, 75 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 8b3678bbbc..ab9c00fbc1 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 @@ -691,15 +691,22 @@ public class DefaultIotHubService implements IotHubService { } checkSameItem(installedItem, UUID.fromString(itemId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); - descriptor.setCreatedEntityIds(null); - descriptor.setDashboardId(null); + Map failed = deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); + // An entity that could not be removed stays tracked, so that Retry, a later update or Delete removes it. + 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); + 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()); } @@ -751,9 +758,11 @@ public class DefaultIotHubService implements IotHubService { } } - private void deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { + /** 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); @@ -762,8 +771,12 @@ 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. */ 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 24d88ac4da..42854e48c1 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 @@ -23,8 +23,10 @@ public interface IotHubService { /** * 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. Repeating it is safe. Refused, - * before anything is removed, when {@code versionId} (the version to install) is not a version of that item. + * 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, before anything is removed, when {@code versionId} (the version to install) is not a version of that item. */ void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId); 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 0d6a8d49b8..e367794b94 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 @@ -655,6 +655,40 @@ class DefaultIotHubServiceTest { 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_versionOfAnotherItem_refusedBeforeRemoving() { mockTenant(); 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 d9ad8974d5..92c76d3cfa 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 @@ -18,6 +18,7 @@ import { TranslateService } from '@ngx-translate/core'; import { PageLink } from '@shared/models/page/page-link'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { DialogService } from '@core/services/dialog.service'; import { DeviceProfileService } from '@core/http/device-profile.service'; import { DeviceService } from '@core/http/device.service'; import { DashboardService } from '@core/http/dashboard.service'; @@ -154,7 +155,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent ws.removingReplaced); } - cancel(): void { + async cancel(): Promise { if (this.removingReplaced) { // The removal is irreversible and already running: closing now would leave the outcome unknown. return; } + if (this.replaceStarted && !this.installRegistered) { + // The installed version may already be gone while the new one is not installed: the user has to know before leaving. + const close = await firstValueFrom(this.dialogService.confirm( + this.translate.instant('iot-hub.device-update-close-title'), + this.translate.instant('iot-hub.device-update-close-text'), + this.translate.instant('action.cancel'), + this.translate.instant('action.close'))); + if (!close) { + return; + } + } this.closed = true; // Once the replaced version's entities may be gone, the caller has to reload its installed items as well. this.dialogRef.close(this.installRegistered || this.replaceStarted ? 'installed' : false); 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 d4d249f2b7..8f5882c3e3 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4481,9 +4481,11 @@ "update-confirm-title": "Update '{{name}}'?", "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-remove-error": "The entities of the installed version were not removed: {{error}}. Retry removes them again", + "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": "Updating re-installs the package through the installation wizard of the new version. When the wizard starts the installation, the entities the current version created (devices, gateways, profiles, rule chains, dashboard) are removed together with their data, including device telemetry", + "update-desc-device": "Updating re-installs the package through the installation wizard of the new version. When the wizard starts the installation, the entities the current version created (devices, gateways, profiles, rule chains, dashboard) are removed together with their data, including device telemetry. The new devices get new access tokens: set up your physical devices and gateways again with the new credentials, and update anything outside the package that refers to the old devices", "update-desc-solution-template": "Updating this solution template will delete and recreate all entities it created, including dashboards, rule chains, devices, and other associated resources within your tenant. Any changes you made to them will be lost", "update-success-desc": "'{{name}}' has been updated successfully", "updating": "Updating...",