From 3a7b192d6a96b3825787cc39a8356fea76e17ded Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 4 Nov 2026 15:00:12 +0200 Subject: [PATCH 01/33] fix(iot-hub): update a device package through the install wizard of the new version Updating an installed device package removed every entity it created and installed nothing again, while the installed item showed the new version. The update dialog now warns that the package is installed again and opens the install wizard of the new version. The wizard removes the installed version with its entities only when it starts creating the new entities, so closing it earlier keeps the package as it was. The server removes the installed item together with its entities, and the wizard registers the new version when it is done. The entity-modified check is skipped for device packages: their checksum was never computed, so it asked on every update. --- .../service/iot_hub/DefaultIotHubService.java | 23 ++++-- .../iot_hub/DefaultIotHubServiceTest.java | 74 +++++++++++++++++++ .../device-install-dialog.component.ts | 49 +++++++++++- .../iot-hub/iot-hub-actions.service.ts | 23 +++++- .../iot-hub-update-dialog.component.ts | 16 +++- .../assets/locale/locale.constant-en_US.json | 1 + 6 files changed, 171 insertions(+), 15 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 7e6a2d88ad..e727e28f30 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 @@ -346,8 +346,9 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); - // Skip checksum validation for solution templates - if (!"SOLUTION_TEMPLATE".equals(itemType)) { + // Skip checksum validation for solution templates and device packages: both are removed and installed again, + // and the update dialog warns about that before the user confirms. + if (!"SOLUTION_TEMPLATE".equals(itemType) && !"DEVICE".equals(itemType)) { JsonNode installedVersionInfo = iotHubRestClient.getVersionInfo(installedItem.getItemVersionId().toString()); if (installedVersionInfo == null) { throw new IllegalArgumentException("Failed to get installed version info from IoT Hub"); @@ -377,6 +378,18 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item type does not match the new version's item type."); } + if ("DEVICE".equals(itemType)) { + // A device package is installed by the wizard in the UI: it needs the user's input (gateway name, + // credentials and so on), so the server cannot install the new version itself. The wizard calls this + // right before it creates the new version's entities, and registers the new version when it is done. + // Remove the installed item together with its entities, so it never shows the new version with + // nothing installed. + deleteDevicePackageEntities(tenantId, ((DeviceInstalledItemDescriptor) descriptor).getCreatedEntityIds(), user); + iotHubInstalledItemService.deleteById(tenantId, installedItemId); + log.info("[{}] Removed device package {} for the install of version {}", tenantId, installedItem.getItemName(), versionId); + return UpdateItemVersionResult.success(descriptor); + } + String itemName = versionInfo.get("name").asText(); String version = versionInfo.get("version").asText(); @@ -387,12 +400,6 @@ public class DefaultIotHubService implements IotHubService { case "WIDGET" -> updateWidget(user, tenantId, (WidgetInstalledItemDescriptor) descriptor, fileData); case "CALCULATED_FIELD" -> updateCalculatedField(user, tenantId, (CalculatedFieldInstalledItemDescriptor) 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); 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 559215e526..856629ddfb 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 @@ -13,11 +13,21 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; 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.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.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.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.List; @@ -48,6 +58,14 @@ class DefaultIotHubServiceTest { private IotHubRestClient iotHubRestClient; @Mock private IotHubInstalledItemService iotHubInstalledItemService; + @Mock + private DeviceService deviceService; + @Mock + private TbDeviceService tbDeviceService; + @Mock + private DashboardService dashboardService; + @Mock + private TbDashboardService tbDashboardService; @Spy @InjectMocks @@ -411,4 +429,60 @@ class DefaultIotHubServiceTest { assertThat(result.isRolledBack()).isFalse(); assertThat(result.getErrorMessage()).contains("install failed"); } + + @Test + void updateItemVersion_device_removesInstalledItemWithItsEntities() throws Exception { + mockTenant(); + String newVersionId = UUID.randomUUID().toString(); + 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"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(newVersionId)) + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "DEVICE", "Gateway", "1.0.2")); + when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device); + when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + + // No "entity modified" question: the update dialog warns that the package is installed again. + assertThat(result.isSuccess()).isTrue(); + assertThat(result.isEntityModified()).isFalse(); + // The entities are removed in reverse order of creation, then the installed item itself: the install + // wizard registers the new version, and until then the package is not shown as installed. + InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService); + order.verify(tbDashboardService).delete(dashboard, user); + order.verify(tbDeviceService).delete(device, user); + order.verify(iotHubInstalledItemService).deleteById(tenantId, item.getId()); + // Nothing is installed or saved on the server: the new version is never recorded with no entities. + verify(iotHubRestClient, never()).getVersionInfo(item.getItemVersionId().toString()); + verify(iotHubRestClient, never()).getVersionFileData(anyString()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void updateItemVersion_device_versionOfAnotherType_keepsEverything() { + mockTenant(); + String newVersionId = UUID.randomUUID().toString(); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("DEVICE"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(new DeviceInstalledItemDescriptor()); + + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(newVersionId)) + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "WIDGET", "Widget", "1.0.0")); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + } } 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 33f2a6d08a..bd8accdb79 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 @@ -47,6 +47,12 @@ export interface DeviceInstallDialogData { reviewMode?: boolean; selectedInstallMethod?: string; installState?: Record; + /** + * Update of an installed device package: the installed item of the current version. It is removed together + * with its entities right before the wizard creates the new version's entities, not earlier, so closing the + * wizard before that leaves the package as it was. + */ + replaceInstalledItemId?: string; } export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress'; @@ -102,6 +108,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -373,7 +381,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (!await this.removeReplacedItem(ws)) { + return; + } for (const ep of ws.entitySteps) { if (ep.status === 'success') { continue; @@ -840,6 +852,41 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (!this.data.replaceInstalledItemId || this.replacedItemRemoved) { + return true; + } + // Nothing is created yet: the first step shows the removal running and, if it fails, why. + const ep = ws.entitySteps.find(s => s.status !== 'success'); + if (ep) { + ep.status = 'running'; + ep.errorMessage = null; + this.cdr.detectChanges(); + } + try { + const result = await firstValueFrom(this.iotHubApiService.updateItemVersion( + this.data.replaceInstalledItemId, this.data.item.id as string, { ignoreLoading: true }, true)); + if (!result.success) { + throw new Error(result.errorMessage || this.translate.instant('iot-hub.update-error', { name: this.data.item.name })); + } + this.replacedItemRemoved = true; + return true; + } catch (err: any) { + // Retry runs the removal again. + ws.progressError = err?.error?.message || err?.message || 'Unknown error'; + if (ep) { + ep.status = 'error'; + ep.errorMessage = ws.progressError; + } + this.cdr.detectChanges(); + return false; + } + } + private async createEntity(step: DeviceInstallStep): Promise { const raw = this.zipFiles.get(step.template); if (!raw) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index dc06f0b5d2..36b4c83bcb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -18,6 +18,7 @@ import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; import { IotHubBuiltInService } from './iot-hub-built-in.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { isBuiltInItem } from './iot-hub-utils'; /** @@ -34,7 +35,8 @@ export class IotHubActionsService { private dialog: MatDialog, private dialogService: DialogService, private translate: TranslateService, - private builtInService: IotHubBuiltInService + private builtInService: IotHubBuiltInService, + private iotHubApiService: IotHubApiService ) {} openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, @@ -163,7 +165,21 @@ export class IotHubActionsService { version, versionId } - }).afterClosed(); + }).afterClosed().pipe( + switchMap(result => result === 'reinstall' ? this.reinstallDevice(installedItem, versionId) : of(result)) + ); + } + + /** + * A device package is updated by installing the new version through the install wizard: it needs the user's + * input, so the server cannot install it alone. The wizard removes the installed version only when it starts + * creating the entities, so closing it before that leaves the package as it was. + */ + private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + return this.iotHubApiService.getVersionInfo(versionId).pipe( + switchMap(item => this.openDeviceInstallDialog(item, { replaceInstalledItemId: installedItem.id.id })), + map(result => result === 'installed' ? 'updated' : false) + ); } deleteItem(installedItem: IotHubInstalledItem): Observable { @@ -193,7 +209,8 @@ export class IotHubActionsService { } private openDeviceInstallDialog(item: MpItemVersionView, - options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any }): Observable { + options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; + replaceInstalledItemId?: string }): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], disableClose: true, 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 e5472c45a1..d5d0398f00 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 @@ -65,12 +65,22 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent { 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 7974f825fc..ad313ecc0c 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3870,6 +3870,7 @@ "update-confirm": "Update '{{name}}' to version {{version}}?", "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", + "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-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...", From cc175fa641b95c305445d6106046fd64b854f605 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 4 Nov 2026 15:00:12 +0200 Subject: [PATCH 02/33] fix(iot-hub): update a device package through the install wizard of the new version Updating an installed device package removed every entity it created and installed nothing again, while the installed item showed the new version. The update dialog now warns that the package is installed again and opens the install wizard of the new version. The wizard removes the installed version with its entities only when it starts creating the new entities, so closing it earlier keeps the package as it was. The server removes the installed item together with its entities, and the wizard registers the new version when it is done. The entity-modified check is skipped for device packages: their checksum was never computed, so it asked on every update. --- .../service/iot_hub/DefaultIotHubService.java | 23 ++++-- .../iot_hub/DefaultIotHubServiceTest.java | 74 +++++++++++++++++++ .../device-install-dialog.component.ts | 49 +++++++++++- .../iot-hub/iot-hub-actions.service.ts | 23 +++++- .../iot-hub-update-dialog.component.ts | 16 +++- .../assets/locale/locale.constant-en_US.json | 1 + 6 files changed, 171 insertions(+), 15 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 2fd3425ed0..83a0038268 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 @@ -377,8 +377,9 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); - // Skip checksum validation for solution templates - if (!"SOLUTION_TEMPLATE".equals(itemType)) { + // Skip checksum validation for solution templates and device packages: both are removed and installed again, + // and the update dialog warns about that before the user confirms. + if (!"SOLUTION_TEMPLATE".equals(itemType) && !"DEVICE".equals(itemType)) { JsonNode installedVersionInfo = iotHubRestClient.getVersionInfo(installedItem.getItemVersionId().toString()); if (installedVersionInfo == null) { throw new IllegalArgumentException("Failed to get installed version info from IoT Hub"); @@ -408,6 +409,18 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item type does not match the new version's item type."); } + if ("DEVICE".equals(itemType)) { + // A device package is installed by the wizard in the UI: it needs the user's input (gateway name, + // credentials and so on), so the server cannot install the new version itself. The wizard calls this + // right before it creates the new version's entities, and registers the new version when it is done. + // Remove the installed item together with its entities, so it never shows the new version with + // nothing installed. + deleteDevicePackageEntities(tenantId, ((DeviceInstalledItemDescriptor) descriptor).getCreatedEntityIds(), user); + iotHubInstalledItemService.deleteById(tenantId, installedItemId); + log.info("[{}] Removed device package {} for the install of version {}", tenantId, installedItem.getItemName(), versionId); + return UpdateItemVersionResult.success(descriptor); + } + String itemName = versionInfo.get("name").asText(); String version = versionInfo.get("version").asText(); @@ -419,12 +432,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); 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 559215e526..856629ddfb 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 @@ -13,11 +13,21 @@ import org.mockito.Mock; import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; 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.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.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.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.List; @@ -48,6 +58,14 @@ class DefaultIotHubServiceTest { private IotHubRestClient iotHubRestClient; @Mock private IotHubInstalledItemService iotHubInstalledItemService; + @Mock + private DeviceService deviceService; + @Mock + private TbDeviceService tbDeviceService; + @Mock + private DashboardService dashboardService; + @Mock + private TbDashboardService tbDashboardService; @Spy @InjectMocks @@ -411,4 +429,60 @@ class DefaultIotHubServiceTest { assertThat(result.isRolledBack()).isFalse(); assertThat(result.getErrorMessage()).contains("install failed"); } + + @Test + void updateItemVersion_device_removesInstalledItemWithItsEntities() throws Exception { + mockTenant(); + String newVersionId = UUID.randomUUID().toString(); + 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"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(descriptor); + + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(newVersionId)) + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "DEVICE", "Gateway", "1.0.2")); + when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device); + when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + + // No "entity modified" question: the update dialog warns that the package is installed again. + assertThat(result.isSuccess()).isTrue(); + assertThat(result.isEntityModified()).isFalse(); + // The entities are removed in reverse order of creation, then the installed item itself: the install + // wizard registers the new version, and until then the package is not shown as installed. + InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService); + order.verify(tbDashboardService).delete(dashboard, user); + order.verify(tbDeviceService).delete(device, user); + order.verify(iotHubInstalledItemService).deleteById(tenantId, item.getId()); + // Nothing is installed or saved on the server: the new version is never recorded with no entities. + verify(iotHubRestClient, never()).getVersionInfo(item.getItemVersionId().toString()); + verify(iotHubRestClient, never()).getVersionFileData(anyString()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void updateItemVersion_device_versionOfAnotherType_keepsEverything() { + mockTenant(); + String newVersionId = UUID.randomUUID().toString(); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("DEVICE"); + item.setItemVersionId(UUID.randomUUID()); + item.setDescriptor(new DeviceInstalledItemDescriptor()); + + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + when(iotHubRestClient.getVersionInfo(newVersionId)) + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "WIDGET", "Widget", "1.0.0")); + + UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + } } 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 a55d5ce2a3..5fe32d30a1 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 @@ -47,6 +47,12 @@ export interface DeviceInstallDialogData { reviewMode?: boolean; selectedInstallMethod?: string; installState?: Record; + /** + * Update of an installed device package: the installed item of the current version. It is removed together + * with its entities right before the wizard creates the new version's entities, not earlier, so closing the + * wizard before that leaves the package as it was. + */ + replaceInstalledItemId?: string; } export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress'; @@ -102,6 +108,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -373,7 +381,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (!await this.removeReplacedItem(ws)) { + return; + } for (const ep of ws.entitySteps) { if (ep.status === 'success') { continue; @@ -840,6 +852,41 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (!this.data.replaceInstalledItemId || this.replacedItemRemoved) { + return true; + } + // Nothing is created yet: the first step shows the removal running and, if it fails, why. + const ep = ws.entitySteps.find(s => s.status !== 'success'); + if (ep) { + ep.status = 'running'; + ep.errorMessage = null; + this.cdr.detectChanges(); + } + try { + const result = await firstValueFrom(this.iotHubApiService.updateItemVersion( + this.data.replaceInstalledItemId, this.data.item.id as string, { ignoreLoading: true }, true)); + if (!result.success) { + throw new Error(result.errorMessage || this.translate.instant('iot-hub.update-error', { name: this.data.item.name })); + } + this.replacedItemRemoved = true; + return true; + } catch (err: any) { + // Retry runs the removal again. + ws.progressError = err?.error?.message || err?.message || 'Unknown error'; + if (ep) { + ep.status = 'error'; + ep.errorMessage = ws.progressError; + } + this.cdr.detectChanges(); + return false; + } + } + private async createEntity(step: DeviceInstallStep): Promise { const raw = this.zipFiles.get(step.template); if (!raw) { diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index dc06f0b5d2..36b4c83bcb 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -18,6 +18,7 @@ import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; import { IotHubBuiltInService } from './iot-hub-built-in.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { isBuiltInItem } from './iot-hub-utils'; /** @@ -34,7 +35,8 @@ export class IotHubActionsService { private dialog: MatDialog, private dialogService: DialogService, private translate: TranslateService, - private builtInService: IotHubBuiltInService + private builtInService: IotHubBuiltInService, + private iotHubApiService: IotHubApiService ) {} openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number, @@ -163,7 +165,21 @@ export class IotHubActionsService { version, versionId } - }).afterClosed(); + }).afterClosed().pipe( + switchMap(result => result === 'reinstall' ? this.reinstallDevice(installedItem, versionId) : of(result)) + ); + } + + /** + * A device package is updated by installing the new version through the install wizard: it needs the user's + * input, so the server cannot install it alone. The wizard removes the installed version only when it starts + * creating the entities, so closing it before that leaves the package as it was. + */ + private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + return this.iotHubApiService.getVersionInfo(versionId).pipe( + switchMap(item => this.openDeviceInstallDialog(item, { replaceInstalledItemId: installedItem.id.id })), + map(result => result === 'installed' ? 'updated' : false) + ); } deleteItem(installedItem: IotHubInstalledItem): Observable { @@ -193,7 +209,8 @@ export class IotHubActionsService { } private openDeviceInstallDialog(item: MpItemVersionView, - options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any }): Observable { + options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; + replaceInstalledItemId?: string }): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], disableClose: true, 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 e5472c45a1..d5d0398f00 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 @@ -65,12 +65,22 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent { 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 cb00b81daf..ba48007bab 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4480,6 +4480,7 @@ "update-confirm": "Update '{{name}}' to version {{version}}?", "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", + "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-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...", From f5194808425752bb019370d399f8939eca07c470 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 4 Nov 2026 16:15:57 +0200 Subject: [PATCH 03/33] fix(iot-hub): keep the installed version until the wizard registers the new one Review of the device package update: - The update endpoint refuses device packages instead of removing them, so a client that reads it as an update no longer reports success with nothing installed. - The wizard removes only the entities of the installed version (installedItems/{id}/device/removeEntities, checked against the new version first), right before it creates the new ones. The installed item keeps its version until the wizard registers the new one on the same item (device/register?replaceInstalledItemId), so closing the wizard never leaves an item that claims a version that is not installed. - Every registration (one per group of entity steps, and each Retry) updates that one item and keeps tracking the entities it already tracks. A package with several groups no longer gets an installed item per group. - A failed registration is shown with Retry instead of being swallowed, and no longer rolls the entities back; the step is done only once registered. - The forms and the connection method start from what the user entered for the installed version, when the value fits the new field. - An entity of another tenant is never deleted for a package. --- .../server/controller/IotHubController.java | 12 +- .../service/iot_hub/DefaultIotHubService.java | 159 ++++++++---- .../iot_hub/InstallItemVersionResult.java | 12 +- .../server/service/iot_hub/IotHubService.java | 14 +- .../iot_hub/DefaultIotHubServiceTest.java | 232 ++++++++++++++++-- .../src/app/core/http/iot-hub-api.service.ts | 13 + .../device-install-dialog.component.html | 15 +- .../device-install-dialog.component.ts | 168 +++++++++---- .../iot-hub/iot-hub-actions.service.ts | 17 +- ...iot-hub-installed-items-table.component.ts | 9 +- .../iot-hub/iot-hub-installed-item.models.ts | 8 + .../assets/locale/locale.constant-en_US.json | 3 + 12 files changed, 540 insertions(+), 122 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 13bd02c5da..2376c67b77 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -82,9 +82,19 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, + @RequestParam(required = false) UUID replaceInstalledItemId, @RequestBody JsonNode body) throws ThingsboardException { 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 { + 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 e727e28f30..c4389517d0 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 @@ -11,6 +11,7 @@ import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.AssetProfileId; @@ -62,6 +63,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; @@ -346,9 +348,16 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); - // Skip checksum validation for solution templates and device packages: both are removed and installed again, - // and the update dialog warns about that before the user confirms. - if (!"SOLUTION_TEMPLATE".equals(itemType) && !"DEVICE".equals(itemType)) { + 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()); if (installedVersionInfo == null) { throw new IllegalArgumentException("Failed to get installed version info from IoT Hub"); @@ -378,18 +387,6 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item type does not match the new version's item type."); } - if ("DEVICE".equals(itemType)) { - // A device package is installed by the wizard in the UI: it needs the user's input (gateway name, - // credentials and so on), so the server cannot install the new version itself. The wizard calls this - // right before it creates the new version's entities, and registers the new version when it is done. - // Remove the installed item together with its entities, so it never shows the new version with - // nothing installed. - deleteDevicePackageEntities(tenantId, ((DeviceInstalledItemDescriptor) descriptor).getCreatedEntityIds(), user); - iotHubInstalledItemService.deleteById(tenantId, installedItemId); - log.info("[{}] Removed device package {} for the install of version {}", tenantId, installedItem.getItemName(), versionId); - return UpdateItemVersionResult.success(descriptor); - } - String itemName = versionInfo.get("name").asText(); String version = versionInfo.get("version").asText(); @@ -568,7 +565,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); @@ -583,44 +581,118 @@ 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()); } } + @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 = iotHubRestClient.getVersionInfo(versionId); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + checkSameItem(installedItem, UUID.fromString(versionInfo.get(FIELD_ITEM_ID).asText())); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); + descriptor.setCreatedEntityIds(null); + 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); + 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"); + } + } + private void deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; @@ -636,23 +708,28 @@ public class DefaultIotHubService implements IotHubService { } } + /** 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) { 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); } default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType()); } 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 04c9e6a80d..22aa2d5671 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 2e8d0c453f..24d88ac4da 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 @@ -14,7 +14,19 @@ 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. Repeating it is safe. 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); 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 856629ddfb..b07b3c8195 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 @@ -30,7 +30,9 @@ 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; @@ -431,9 +433,30 @@ class DefaultIotHubServiceTest { } @Test - void updateItemVersion_device_removesInstalledItemWithItsEntities() throws Exception { + 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(), any()); + verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void removeDevicePackageEntities_removesEntitiesInReverseOrderAndKeepsTheItemVersion() throws Exception { mockTenant(); - String newVersionId = UUID.randomUUID().toString(); Device device = new Device(new DeviceId(UUID.randomUUID())); Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -441,48 +464,215 @@ class DefaultIotHubServiceTest { descriptor.setDashboardId(dashboard.getId()); IotHubInstalledItem item = installedItem(UUID.randomUUID()); item.setItemType("DEVICE"); - item.setItemVersionId(UUID.randomUUID()); + 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, UUID.randomUUID().toString(), "DEVICE", "Gateway", "1.0.2")); + .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); - UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + service.removeDevicePackageEntities(user, item.getId(), newVersionId); - // No "entity modified" question: the update dialog warns that the package is installed again. - assertThat(result.isSuccess()).isTrue(); - assertThat(result.isEntityModified()).isFalse(); - // The entities are removed in reverse order of creation, then the installed item itself: the install - // wizard registers the new version, and until then the package is not shown as installed. InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService); order.verify(tbDashboardService).delete(dashboard, user); order.verify(tbDeviceService).delete(device, user); - order.verify(iotHubInstalledItemService).deleteById(tenantId, item.getId()); - // Nothing is installed or saved on the server: the new version is never recorded with no entities. - verify(iotHubRestClient, never()).getVersionInfo(item.getItemVersionId().toString()); - verify(iotHubRestClient, never()).getVersionFileData(anyString()); - verify(iotHubInstalledItemService, never()).save(any(), any()); + 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 updateItemVersion_device_versionOfAnotherType_keepsEverything() { + void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() { mockTenant(); - String newVersionId = UUID.randomUUID().toString(); 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(), "WIDGET", "Widget", "1.0.0")); + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "DEVICE", "Other", "2.0.0")); - UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + InstallItemVersionResult result = service.registerDeviceInstall(user, newVersionId, new DeviceInstalledItemDescriptor(), item.getId()); assertThat(result.isSuccess()).isFalse(); - verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + 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(), any()); + } + + @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(), 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 70f97ed061..ba19c0f6e6 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 @@ -179,11 +179,24 @@ 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 { + let params = this.buildParams(config); + if (replaceInstalledItemId) { + params = params.set('replaceInstalledItemId', replaceInstalledItemId); + } return this.http.post( `/api/iot-hub/device/register?versionId=${versionId}`, { type: 'DEVICE', ...descriptor }, + { params } + ); + } + + public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities?versionId=${versionId}`, + null, { params: this.buildParams(config) } ); } 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 28e7f61ceb..6db53d1cfb 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 @@ -143,6 +143,15 @@ } } + @if (ws.removingReplaced) { +
+ + {{ 'iot-hub.device-update-removing' | translate }} +
+ } + @if (stepLevelError(ws); as error) { + {{ error }} + } } } @@ -157,7 +166,7 @@ } @else {

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

-
@@ -211,13 +220,13 @@ @if (allProgressDone) { } @else { - + } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { 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 bd8accdb79..c9aa546f23 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 @@ -48,9 +48,10 @@ export interface DeviceInstallDialogData { selectedInstallMethod?: string; installState?: Record; /** - * Update of an installed device package: the installed item of the current version. It is removed together - * with its entities right before the wizard creates the new version's entities, not earlier, so closing the - * wizard before that leaves the package as it was. + * Update of an installed device package: the installed item of the current version. Its entities are removed + * right before the wizard creates the new version's entities, not earlier, so closing the wizard before that + * leaves the package as it was; the item takes the new version when the wizard registers it. The forms start + * from installState and the connection method from selectedInstallMethod, as the user filled them before. */ replaceInstalledItemId?: string; } @@ -71,6 +72,8 @@ export interface WizardStep { entitySteps?: EntityStepProgress[]; progressError?: string; progressDone?: boolean; + /** Update only: the entities of the replaced version are being removed. */ + removingReplaced?: boolean; } const ENTITY_STEP_MIN_DELAY = 2000; @@ -108,8 +111,24 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -141,6 +160,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + this.registeredItemId = this.data.replaceInstalledItemId; try { const zipData = await firstValueFrom(this.iotHubApiService.getVersionFileData(this.data.item.id, { ignoreLoading: true }).pipe( mergeMap((blob: Blob) => blob.arrayBuffer()) @@ -199,12 +219,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent ws.removingReplaced); + } + cancel(): void { - // Once the replaced version is removed, the caller has to reload its installed items as well. - this.dialogRef.close(this.installRegistered || this.replacedItemRemoved ? 'installed' : false); + if (this.removingReplaced) { + // The removal is irreversible and already running: closing now would leave the outcome unknown. + 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); } retryEntitySteps(step: WizardStep): void { @@ -420,7 +463,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; - // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; + // In review mode and on an update, use stored values; otherwise use defaults + const storedValues = (this.reviewMode || this.data.replaceInstalledItemId) && this.data.installState?.[ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -713,7 +756,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === output.id)) { + this.packageEntityIds.push({ entityType, id: output.id }); + } const alias = stepTypeAliasMap[ep.step.type]; if (alias) { this.entityOutputs.set(alias, output); @@ -786,7 +835,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (!await this.removeReplacedItem(ws)) { + if (!await this.removeReplacedEntities(ws) || this.closed) { + // The dialog was closed meanwhile (navigating away): create nothing. return; } for (const ep of ws.entitySteps) { @@ -818,31 +868,44 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === id.id)) { + this.packageEntityIds.push(id); + } + } + const createdEntityIds = [...this.packageEntityIds]; const dashboardId = this.findCreatedDashboardId(); - await firstValueFrom( + const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, { createdEntityIds, dashboardId, selectedInstallMethod: this.selectedInstallMethod, installState: this.buildInstallState() }, - { ignoreLoading: true } + this.registeredItemId, + { ignoreLoading: true, ignoreErrors: true } ) ); + if (!result?.success) { + throw new Error(result?.errorMessage); + } this.installRegistered = true; - } catch (_e) { - // Non-critical — entities are created, tracking registration failed - console.error('Failed to register device install', _e); + this.registeredItemId = result.installedItemId ?? this.registeredItemId; + } catch (err: any) { + // The entities stay as they are: Retry registers them again. + ws.progressError = this.translate.instant('iot-hub.device-install-register-error', { error: this.errorText(err) }); + this.cdr.detectChanges(); + return; } + ws.progressDone = true; + ws.completed = true; // Auto-advance to next step after a short pause if (!this.isLastWizardStep) { @@ -853,37 +916,50 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (!this.data.replaceInstalledItemId || this.replacedItemRemoved) { + private async removeReplacedEntities(ws: WizardStep): Promise { + if (!this.data.replaceInstalledItemId || this.replacedEntitiesRemoved) { return true; } - // Nothing is created yet: the first step shows the removal running and, if it fails, why. - const ep = ws.entitySteps.find(s => s.status !== 'success'); - if (ep) { - ep.status = 'running'; - ep.errorMessage = null; - this.cdr.detectChanges(); - } + this.replaceStarted = true; + ws.removingReplaced = true; + this.cdr.detectChanges(); try { - const result = await firstValueFrom(this.iotHubApiService.updateItemVersion( - this.data.replaceInstalledItemId, this.data.item.id as string, { ignoreLoading: true }, true)); - if (!result.success) { - throw new Error(result.errorMessage || this.translate.instant('iot-hub.update-error', { name: this.data.item.name })); - } - this.replacedItemRemoved = true; + await firstValueFrom(this.iotHubApiService.removeDevicePackageEntities(this.data.replaceInstalledItemId, + this.data.item.id as string, { ignoreLoading: true, ignoreErrors: true })); + this.replacedEntitiesRemoved = true; return true; } catch (err: any) { - // Retry runs the removal again. - ws.progressError = err?.error?.message || err?.message || 'Unknown error'; - if (ep) { - ep.status = 'error'; - ep.errorMessage = ws.progressError; - } - this.cdr.detectChanges(); + ws.progressError = this.translate.instant('iot-hub.device-update-remove-error', { error: this.errorText(err) }); return false; + } finally { + ws.removingReplaced = false; + this.cdr.detectChanges(); + } + } + + /** An error of the step that is not one entity's (removing the replaced entities, registering), shown below them. */ + stepLevelError(ws: WizardStep): string | null { + return ws.progressError && !ws.entitySteps?.some(ep => ep.status === 'error') ? ws.progressError : null; + } + + private errorText(err: any): string { + return err?.error?.message || err?.message || 'Unknown error'; + } + + private fitsField(field: FormFieldDefinition, value: any): boolean { + switch (field.type) { + case FormFieldType.BOOLEAN: + return typeof value === 'boolean'; + case FormFieldType.INTEGER: + return Number.isInteger(value) || (typeof value === 'string' && /^-?\d*$/.test(value)); + case FormFieldType.SELECT: + return typeof value === 'string' && (!field.options?.length || field.options.some(option => option.value === value)); + default: + return typeof value === 'string'; } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 36b4c83bcb..5ec83949bd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -3,7 +3,7 @@ import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of, EMPTY } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; import { DialogService } from '@core/services/dialog.service'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -172,13 +172,20 @@ export class IotHubActionsService { /** * A device package is updated by installing the new version through the install wizard: it needs the user's - * input, so the server cannot install it alone. The wizard removes the installed version only when it starts - * creating the entities, so closing it before that leaves the package as it was. + * input, so the server cannot install it alone. The wizard removes the installed version's entities only when it starts + * creating the new ones, so closing it before that leaves the package as it was. */ private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor; return this.iotHubApiService.getVersionInfo(versionId).pipe( - switchMap(item => this.openDeviceInstallDialog(item, { replaceInstalledItemId: installedItem.id.id })), - map(result => result === 'installed' ? 'updated' : false) + switchMap(item => this.openDeviceInstallDialog(item, { + replaceInstalledItemId: installedItem.id.id, + selectedInstallMethod: descriptor?.selectedInstallMethod, + installState: descriptor?.installState + })), + map(result => result === 'installed' ? 'updated' : false), + // The error itself is shown by the HTTP interceptor; nothing is changed yet. + catchError(() => of(false)) ); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 63c88b4cce..2c715bec1c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -25,6 +25,7 @@ import { switchMap } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { + canReviewDeviceInstall, DeviceInstalledItemDescriptor, getInstalledItemUrl, IotHubInstalledItem, @@ -182,9 +183,13 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private openDeviceReviewDialog(item: IotHubInstalledItem): void { const descriptor = item.descriptor as DeviceInstalledItemDescriptor; - if (!descriptor.installState || !descriptor.selectedInstallMethod) { + if (!canReviewDeviceInstall(descriptor)) { this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { - this.iotHubActions.openItemDetail(versionView, item).subscribe(); + this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { + if (result === 'updated' || result === 'deleted') { + this.loadData(); + } + }); }); return; } 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 106f6fa13a..96815a0854 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 @@ -34,6 +34,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 }[]; @@ -55,6 +62,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 ad313ecc0c..7a926cc39a 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3870,6 +3870,9 @@ "update-confirm": "Update '{{name}}' to version {{version}}?", "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-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-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", From 9803832a400e3ddf06897ed0e306a9d6dfd8d044 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 4 Nov 2026 16:15:57 +0200 Subject: [PATCH 04/33] fix(iot-hub): keep the installed version until the wizard registers the new one Review of the device package update: - The update endpoint refuses device packages instead of removing them, so a client that reads it as an update no longer reports success with nothing installed. - The wizard removes only the entities of the installed version (installedItems/{id}/device/removeEntities, checked against the new version first), right before it creates the new ones. The installed item keeps its version until the wizard registers the new one on the same item (device/register?replaceInstalledItemId), so closing the wizard never leaves an item that claims a version that is not installed. - Every registration (one per group of entity steps, and each Retry) updates that one item and keeps tracking the entities it already tracks. A package with several groups no longer gets an installed item per group. - A failed registration is shown with Retry instead of being swallowed, and no longer rolls the entities back; the step is done only once registered. - The forms and the connection method start from what the user entered for the installed version, when the value fits the new field. - An entity of another tenant is never deleted for a package. --- .../server/controller/IotHubController.java | 12 +- .../service/iot_hub/DefaultIotHubService.java | 159 ++++++++---- .../iot_hub/InstallItemVersionResult.java | 12 +- .../server/service/iot_hub/IotHubService.java | 14 +- .../iot_hub/DefaultIotHubServiceTest.java | 232 ++++++++++++++++-- .../src/app/core/http/iot-hub-api.service.ts | 13 + .../device-install-dialog.component.html | 15 +- .../device-install-dialog.component.ts | 168 +++++++++---- .../iot-hub/iot-hub-actions.service.ts | 17 +- ...iot-hub-installed-items-table.component.ts | 9 +- .../iot-hub/iot-hub-installed-item.models.ts | 8 + .../assets/locale/locale.constant-en_US.json | 3 + 12 files changed, 540 insertions(+), 122 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 13bd02c5da..2376c67b77 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -82,9 +82,19 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, + @RequestParam(required = false) UUID replaceInstalledItemId, @RequestBody JsonNode body) throws ThingsboardException { 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 { + 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 83a0038268..5a091db85a 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 @@ -11,6 +11,7 @@ import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedFieldType; import org.thingsboard.server.common.data.id.CalculatedFieldId; @@ -66,6 +67,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; @@ -377,9 +379,16 @@ public class DefaultIotHubService implements IotHubService { String itemType = installedItem.getItemType(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); - // Skip checksum validation for solution templates and device packages: both are removed and installed again, - // and the update dialog warns about that before the user confirms. - if (!"SOLUTION_TEMPLATE".equals(itemType) && !"DEVICE".equals(itemType)) { + 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()); if (installedVersionInfo == null) { throw new IllegalArgumentException("Failed to get installed version info from IoT Hub"); @@ -409,18 +418,6 @@ public class DefaultIotHubService implements IotHubService { throw new IllegalArgumentException("Installed item type does not match the new version's item type."); } - if ("DEVICE".equals(itemType)) { - // A device package is installed by the wizard in the UI: it needs the user's input (gateway name, - // credentials and so on), so the server cannot install the new version itself. The wizard calls this - // right before it creates the new version's entities, and registers the new version when it is done. - // Remove the installed item together with its entities, so it never shows the new version with - // nothing installed. - deleteDevicePackageEntities(tenantId, ((DeviceInstalledItemDescriptor) descriptor).getCreatedEntityIds(), user); - iotHubInstalledItemService.deleteById(tenantId, installedItemId); - log.info("[{}] Removed device package {} for the install of version {}", tenantId, installedItem.getItemName(), versionId); - return UpdateItemVersionResult.success(descriptor); - } - String itemName = versionInfo.get("name").asText(); String version = versionInfo.get("version").asText(); @@ -622,7 +619,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); @@ -637,44 +635,118 @@ 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()); } } + @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 = iotHubRestClient.getVersionInfo(versionId); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + checkSameItem(installedItem, UUID.fromString(versionInfo.get(FIELD_ITEM_ID).asText())); + DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); + deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); + descriptor.setCreatedEntityIds(null); + 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); + 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"); + } + } + private void deleteDevicePackageEntities(TenantId tenantId, List createdEntityIds, SecurityUser user) { if (createdEntityIds == null || createdEntityIds.isEmpty()) { return; @@ -690,23 +762,28 @@ public class DefaultIotHubService implements IotHubService { } } + /** 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) { 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); } default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType()); } 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 04c9e6a80d..22aa2d5671 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 2e8d0c453f..24d88ac4da 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 @@ -14,7 +14,19 @@ 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. Repeating it is safe. 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); 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 856629ddfb..b07b3c8195 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 @@ -30,7 +30,9 @@ 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; @@ -431,9 +433,30 @@ class DefaultIotHubServiceTest { } @Test - void updateItemVersion_device_removesInstalledItemWithItsEntities() throws Exception { + 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(), any()); + verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void removeDevicePackageEntities_removesEntitiesInReverseOrderAndKeepsTheItemVersion() throws Exception { mockTenant(); - String newVersionId = UUID.randomUUID().toString(); Device device = new Device(new DeviceId(UUID.randomUUID())); Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID())); DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); @@ -441,48 +464,215 @@ class DefaultIotHubServiceTest { descriptor.setDashboardId(dashboard.getId()); IotHubInstalledItem item = installedItem(UUID.randomUUID()); item.setItemType("DEVICE"); - item.setItemVersionId(UUID.randomUUID()); + 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, UUID.randomUUID().toString(), "DEVICE", "Gateway", "1.0.2")); + .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); - UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + service.removeDevicePackageEntities(user, item.getId(), newVersionId); - // No "entity modified" question: the update dialog warns that the package is installed again. - assertThat(result.isSuccess()).isTrue(); - assertThat(result.isEntityModified()).isFalse(); - // The entities are removed in reverse order of creation, then the installed item itself: the install - // wizard registers the new version, and until then the package is not shown as installed. InOrder order = inOrder(tbDashboardService, tbDeviceService, iotHubInstalledItemService); order.verify(tbDashboardService).delete(dashboard, user); order.verify(tbDeviceService).delete(device, user); - order.verify(iotHubInstalledItemService).deleteById(tenantId, item.getId()); - // Nothing is installed or saved on the server: the new version is never recorded with no entities. - verify(iotHubRestClient, never()).getVersionInfo(item.getItemVersionId().toString()); - verify(iotHubRestClient, never()).getVersionFileData(anyString()); - verify(iotHubInstalledItemService, never()).save(any(), any()); + 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 updateItemVersion_device_versionOfAnotherType_keepsEverything() { + void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() { mockTenant(); - String newVersionId = UUID.randomUUID().toString(); 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(), "WIDGET", "Widget", "1.0.0")); + .thenReturn(version(newVersionId, UUID.randomUUID().toString(), "DEVICE", "Other", "2.0.0")); - UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), newVersionId, false, null); + InstallItemVersionResult result = service.registerDeviceInstall(user, newVersionId, new DeviceInstalledItemDescriptor(), item.getId()); assertThat(result.isSuccess()).isFalse(); - verify(iotHubInstalledItemService, never()).deleteById(any(), any()); + 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(), any()); + } + + @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(), 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 70f97ed061..ba19c0f6e6 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 @@ -179,11 +179,24 @@ 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 { + let params = this.buildParams(config); + if (replaceInstalledItemId) { + params = params.set('replaceInstalledItemId', replaceInstalledItemId); + } return this.http.post( `/api/iot-hub/device/register?versionId=${versionId}`, { type: 'DEVICE', ...descriptor }, + { params } + ); + } + + public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig): Observable { + return this.http.post( + `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities?versionId=${versionId}`, + null, { params: this.buildParams(config) } ); } 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 28e7f61ceb..6db53d1cfb 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 @@ -143,6 +143,15 @@ } } + @if (ws.removingReplaced) { +
+ + {{ 'iot-hub.device-update-removing' | translate }} +
+ } + @if (stepLevelError(ws); as error) { + {{ error }} + } } } @@ -157,7 +166,7 @@ } @else {

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

-
@@ -211,13 +220,13 @@ @if (allProgressDone) { } @else { - + } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { 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 5fe32d30a1..0b46df81bb 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 @@ -48,9 +48,10 @@ export interface DeviceInstallDialogData { selectedInstallMethod?: string; installState?: Record; /** - * Update of an installed device package: the installed item of the current version. It is removed together - * with its entities right before the wizard creates the new version's entities, not earlier, so closing the - * wizard before that leaves the package as it was. + * Update of an installed device package: the installed item of the current version. Its entities are removed + * right before the wizard creates the new version's entities, not earlier, so closing the wizard before that + * leaves the package as it was; the item takes the new version when the wizard registers it. The forms start + * from installState and the connection method from selectedInstallMethod, as the user filled them before. */ replaceInstalledItemId?: string; } @@ -71,6 +72,8 @@ export interface WizardStep { entitySteps?: EntityStepProgress[]; progressError?: string; progressDone?: boolean; + /** Update only: the entities of the replaced version are being removed. */ + removingReplaced?: boolean; } const ENTITY_STEP_MIN_DELAY = 2000; @@ -108,8 +111,24 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; @@ -141,6 +160,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + this.registeredItemId = this.data.replaceInstalledItemId; try { const zipData = await firstValueFrom(this.iotHubApiService.getVersionFileData(this.data.item.id, { ignoreLoading: true }).pipe( mergeMap((blob: Blob) => blob.arrayBuffer()) @@ -199,12 +219,19 @@ export class TbDeviceInstallDialogComponent extends DialogComponent ws.removingReplaced); + } + cancel(): void { - // Once the replaced version is removed, the caller has to reload its installed items as well. - this.dialogRef.close(this.installRegistered || this.replacedItemRemoved ? 'installed' : false); + if (this.removingReplaced) { + // The removal is irreversible and already running: closing now would leave the outcome unknown. + 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); } retryEntitySteps(step: WizardStep): void { @@ -420,7 +463,7 @@ export class TbDeviceInstallDialogComponent extends DialogComponent = {}; - // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.label]?.formValues; + // In review mode and on an update, use stored values; otherwise use defaults + const storedValues = (this.reviewMode || this.data.replaceInstalledItemId) && this.data.installState?.[ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -713,7 +756,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === output.id)) { + this.packageEntityIds.push({ entityType, id: output.id }); + } const alias = stepTypeAliasMap[ep.step.type]; if (alias) { this.entityOutputs.set(alias, output); @@ -786,7 +835,8 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (!await this.removeReplacedItem(ws)) { + if (!await this.removeReplacedEntities(ws) || this.closed) { + // The dialog was closed meanwhile (navigating away): create nothing. return; } for (const ep of ws.entitySteps) { @@ -818,31 +868,44 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === id.id)) { + this.packageEntityIds.push(id); + } + } + const createdEntityIds = [...this.packageEntityIds]; const dashboardId = this.findCreatedDashboardId(); - await firstValueFrom( + const result = await firstValueFrom( this.iotHubApiService.registerDeviceInstall( this.data.item.id as string, { createdEntityIds, dashboardId, selectedInstallMethod: this.selectedInstallMethod, installState: this.buildInstallState() }, - { ignoreLoading: true } + this.registeredItemId, + { ignoreLoading: true, ignoreErrors: true } ) ); + if (!result?.success) { + throw new Error(result?.errorMessage); + } this.installRegistered = true; - } catch (_e) { - // Non-critical — entities are created, tracking registration failed - console.error('Failed to register device install', _e); + this.registeredItemId = result.installedItemId ?? this.registeredItemId; + } catch (err: any) { + // The entities stay as they are: Retry registers them again. + ws.progressError = this.translate.instant('iot-hub.device-install-register-error', { error: this.errorText(err) }); + this.cdr.detectChanges(); + return; } + ws.progressDone = true; + ws.completed = true; // Auto-advance to next step after a short pause if (!this.isLastWizardStep) { @@ -853,37 +916,50 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { - if (!this.data.replaceInstalledItemId || this.replacedItemRemoved) { + private async removeReplacedEntities(ws: WizardStep): Promise { + if (!this.data.replaceInstalledItemId || this.replacedEntitiesRemoved) { return true; } - // Nothing is created yet: the first step shows the removal running and, if it fails, why. - const ep = ws.entitySteps.find(s => s.status !== 'success'); - if (ep) { - ep.status = 'running'; - ep.errorMessage = null; - this.cdr.detectChanges(); - } + this.replaceStarted = true; + ws.removingReplaced = true; + this.cdr.detectChanges(); try { - const result = await firstValueFrom(this.iotHubApiService.updateItemVersion( - this.data.replaceInstalledItemId, this.data.item.id as string, { ignoreLoading: true }, true)); - if (!result.success) { - throw new Error(result.errorMessage || this.translate.instant('iot-hub.update-error', { name: this.data.item.name })); - } - this.replacedItemRemoved = true; + await firstValueFrom(this.iotHubApiService.removeDevicePackageEntities(this.data.replaceInstalledItemId, + this.data.item.id as string, { ignoreLoading: true, ignoreErrors: true })); + this.replacedEntitiesRemoved = true; return true; } catch (err: any) { - // Retry runs the removal again. - ws.progressError = err?.error?.message || err?.message || 'Unknown error'; - if (ep) { - ep.status = 'error'; - ep.errorMessage = ws.progressError; - } - this.cdr.detectChanges(); + ws.progressError = this.translate.instant('iot-hub.device-update-remove-error', { error: this.errorText(err) }); return false; + } finally { + ws.removingReplaced = false; + this.cdr.detectChanges(); + } + } + + /** An error of the step that is not one entity's (removing the replaced entities, registering), shown below them. */ + stepLevelError(ws: WizardStep): string | null { + return ws.progressError && !ws.entitySteps?.some(ep => ep.status === 'error') ? ws.progressError : null; + } + + private errorText(err: any): string { + return err?.error?.message || err?.message || 'Unknown error'; + } + + private fitsField(field: FormFieldDefinition, value: any): boolean { + switch (field.type) { + case FormFieldType.BOOLEAN: + return typeof value === 'boolean'; + case FormFieldType.INTEGER: + return Number.isInteger(value) || (typeof value === 'string' && /^-?\d*$/.test(value)); + case FormFieldType.SELECT: + return typeof value === 'string' && (!field.options?.length || field.options.some(option => option.value === value)); + default: + return typeof value === 'string'; } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 36b4c83bcb..5ec83949bd 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -3,7 +3,7 @@ import { Injectable } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable, of, EMPTY } from 'rxjs'; -import { map, switchMap } from 'rxjs/operators'; +import { catchError, map, switchMap } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; import { DialogService } from '@core/services/dialog.service'; import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; @@ -172,13 +172,20 @@ export class IotHubActionsService { /** * A device package is updated by installing the new version through the install wizard: it needs the user's - * input, so the server cannot install it alone. The wizard removes the installed version only when it starts - * creating the entities, so closing it before that leaves the package as it was. + * input, so the server cannot install it alone. The wizard removes the installed version's entities only when it starts + * creating the new ones, so closing it before that leaves the package as it was. */ private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor; return this.iotHubApiService.getVersionInfo(versionId).pipe( - switchMap(item => this.openDeviceInstallDialog(item, { replaceInstalledItemId: installedItem.id.id })), - map(result => result === 'installed' ? 'updated' : false) + switchMap(item => this.openDeviceInstallDialog(item, { + replaceInstalledItemId: installedItem.id.id, + selectedInstallMethod: descriptor?.selectedInstallMethod, + installState: descriptor?.installState + })), + map(result => result === 'installed' ? 'updated' : false), + // The error itself is shown by the HTTP interceptor; nothing is changed yet. + catchError(() => of(false)) ); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts index 63c88b4cce..2c715bec1c 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-installed-items-table.component.ts @@ -25,6 +25,7 @@ import { switchMap } from 'rxjs/operators'; import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { + canReviewDeviceInstall, DeviceInstalledItemDescriptor, getInstalledItemUrl, IotHubInstalledItem, @@ -182,9 +183,13 @@ export class TbIotHubInstalledItemsTableComponent implements OnInit, OnChanges, private openDeviceReviewDialog(item: IotHubInstalledItem): void { const descriptor = item.descriptor as DeviceInstalledItemDescriptor; - if (!descriptor.installState || !descriptor.selectedInstallMethod) { + if (!canReviewDeviceInstall(descriptor)) { this.iotHubApiService.getVersionInfo(item.itemVersionId, {ignoreLoading: true}).subscribe(versionView => { - this.iotHubActions.openItemDetail(versionView, item).subscribe(); + this.iotHubActions.openItemDetail(versionView, item).subscribe(result => { + if (result === 'updated' || result === 'deleted') { + this.loadData(); + } + }); }); return; } 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 c836687a45..5a18c4a6a4 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 @@ -34,6 +34,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 }[]; @@ -55,6 +62,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 ba48007bab..d4d249f2b7 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4480,6 +4480,9 @@ "update-confirm": "Update '{{name}}' to version {{version}}?", "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-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-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", From 358ca210f971cdd397b1fa05fbc2578ff11cd162 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 08:56:46 +0200 Subject: [PATCH 05/33] fix(iot-hub): keep the request config on a device package registration - The registration sends replaceInstalledItemId in the URL: HttpParams.set() returned a plain HttpParams, which dropped ignoreLoading/ignoreErrors, so a failed registration showed a toast next to the wizard's own error. - The stepper header cannot go back while the installed version's entities are being removed, like the Back button. - A version from the Hub without its item is reported as such instead of a NullPointerException. - The wizard registers the entities it keeps from the moment they exist; the second collection of the same ids before each registration is gone. - The tests verify TbDeviceService.delete through the Device overload, as 4.4 and PE also have one for a DeviceId, so the test is the same file everywhere. --- .../service/iot_hub/DefaultIotHubService.java | 6 ++++- .../iot_hub/DefaultIotHubServiceTest.java | 6 ++--- .../src/app/core/http/iot-hub-api.service.ts | 10 ++++----- .../device-install-dialog.component.html | 2 +- .../device-install-dialog.component.ts | 22 ------------------- 5 files changed, 13 insertions(+), 33 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 c4389517d0..ece9c0cad9 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 @@ -631,7 +631,11 @@ public class DefaultIotHubService implements IotHubService { if (versionInfo == null) { throw new IllegalArgumentException("Failed to get version info from IoT Hub"); } - checkSameItem(installedItem, UUID.fromString(versionInfo.get(FIELD_ITEM_ID).asText())); + String itemId = optText(versionInfo, FIELD_ITEM_ID); + if (itemId == null) { + throw new IllegalArgumentException("IoT Hub returned the version without its item"); + } + checkSameItem(installedItem, UUID.fromString(itemId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); descriptor.setCreatedEntityIds(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 b07b3c8195..0d6a8d49b8 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 @@ -449,7 +449,7 @@ class DefaultIotHubServiceTest { assertThat(result.isSuccess()).isFalse(); assertThat(result.getErrorMessage()).contains("install wizard"); - verify(tbDeviceService, never()).delete(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); verify(iotHubInstalledItemService, never()).deleteById(any(), any()); verify(iotHubInstalledItemService, never()).save(any(), any()); } @@ -652,7 +652,7 @@ class DefaultIotHubServiceTest { service.removeDevicePackageEntities(user, item.getId(), newVersionId); - verify(tbDeviceService, never()).delete(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); } @Test @@ -672,7 +672,7 @@ class DefaultIotHubServiceTest { // 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(), any()); + 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 ba19c0f6e6..07c1c9a64d 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 @@ -182,14 +182,12 @@ export class IotHubApiService { replaceInstalledItemId?: string, config?: IotHubRequestConfig ): Observable { - let params = this.buildParams(config); - if (replaceInstalledItemId) { - params = params.set('replaceInstalledItemId', replaceInstalledItemId); - } + // In the URL: HttpParams.set() would drop the interceptor config (ignoreLoading, ignoreErrors) of buildParams. + const replace = replaceInstalledItemId ? `&replaceInstalledItemId=${replaceInstalledItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, + `/api/iot-hub/device/register?versionId=${versionId}${replace}`, { type: 'DEVICE', ...descriptor }, - { params } + { params: this.buildParams(config) } ); } 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 6db53d1cfb..45060d91bc 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 @@ -206,7 +206,7 @@ @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} 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 c9aa546f23..51903723b1 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 @@ -878,11 +878,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === id.id)) { - this.packageEntityIds.push(id); - } - } const createdEntityIds = [...this.packageEntityIds]; const dashboardId = this.findCreatedDashboardId(); const result = await firstValueFrom( @@ -1215,23 +1210,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 08:56:46 +0200 Subject: [PATCH 06/33] fix(iot-hub): keep the request config on a device package registration - The registration sends replaceInstalledItemId in the URL: HttpParams.set() returned a plain HttpParams, which dropped ignoreLoading/ignoreErrors, so a failed registration showed a toast next to the wizard's own error. - The stepper header cannot go back while the installed version's entities are being removed, like the Back button. - A version from the Hub without its item is reported as such instead of a NullPointerException. - The wizard registers the entities it keeps from the moment they exist; the second collection of the same ids before each registration is gone. - The tests verify TbDeviceService.delete through the Device overload, as 4.4 and PE also have one for a DeviceId, so the test is the same file everywhere. --- .../service/iot_hub/DefaultIotHubService.java | 6 ++++- .../iot_hub/DefaultIotHubServiceTest.java | 6 ++--- .../src/app/core/http/iot-hub-api.service.ts | 10 ++++----- .../device-install-dialog.component.html | 2 +- .../device-install-dialog.component.ts | 22 ------------------- 5 files changed, 13 insertions(+), 33 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 5a091db85a..8b3678bbbc 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 @@ -685,7 +685,11 @@ public class DefaultIotHubService implements IotHubService { if (versionInfo == null) { throw new IllegalArgumentException("Failed to get version info from IoT Hub"); } - checkSameItem(installedItem, UUID.fromString(versionInfo.get(FIELD_ITEM_ID).asText())); + String itemId = optText(versionInfo, FIELD_ITEM_ID); + if (itemId == null) { + throw new IllegalArgumentException("IoT Hub returned the version without its item"); + } + checkSameItem(installedItem, UUID.fromString(itemId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); deleteDevicePackageEntities(tenantId, descriptor.getCreatedEntityIds(), user); descriptor.setCreatedEntityIds(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 b07b3c8195..0d6a8d49b8 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 @@ -449,7 +449,7 @@ class DefaultIotHubServiceTest { assertThat(result.isSuccess()).isFalse(); assertThat(result.getErrorMessage()).contains("install wizard"); - verify(tbDeviceService, never()).delete(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); verify(iotHubInstalledItemService, never()).deleteById(any(), any()); verify(iotHubInstalledItemService, never()).save(any(), any()); } @@ -652,7 +652,7 @@ class DefaultIotHubServiceTest { service.removeDevicePackageEntities(user, item.getId(), newVersionId); - verify(tbDeviceService, never()).delete(any(), any()); + verify(tbDeviceService, never()).delete(any(Device.class), any()); } @Test @@ -672,7 +672,7 @@ class DefaultIotHubServiceTest { // 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(), any()); + 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 ba19c0f6e6..07c1c9a64d 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 @@ -182,14 +182,12 @@ export class IotHubApiService { replaceInstalledItemId?: string, config?: IotHubRequestConfig ): Observable { - let params = this.buildParams(config); - if (replaceInstalledItemId) { - params = params.set('replaceInstalledItemId', replaceInstalledItemId); - } + // In the URL: HttpParams.set() would drop the interceptor config (ignoreLoading, ignoreErrors) of buildParams. + const replace = replaceInstalledItemId ? `&replaceInstalledItemId=${replaceInstalledItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, + `/api/iot-hub/device/register?versionId=${versionId}${replace}`, { type: 'DEVICE', ...descriptor }, - { params } + { params: this.buildParams(config) } ); } 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 6db53d1cfb..45060d91bc 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 @@ -206,7 +206,7 @@ @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} 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 0b46df81bb..d9ad8974d5 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 @@ -878,11 +878,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent known.id === id.id)) { - this.packageEntityIds.push(id); - } - } const createdEntityIds = [...this.packageEntityIds]; const dashboardId = this.findCreatedDashboardId(); const result = await firstValueFrom( @@ -1215,23 +1210,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 11:45:27 +0200 Subject: [PATCH 07/33] 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 ece9c0cad9..004c822dc5 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 @@ -637,15 +637,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()); } @@ -697,9 +704,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); @@ -708,8 +717,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 51903723b1..d1d7680470 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 7a926cc39a..9306351638 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3871,9 +3871,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...", From 7e2802d24dd31b8ac8964db3a7da06ca60741f3c Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 11:45:27 +0200 Subject: [PATCH 08/33] 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...", From 5cd1d98f9acc326c1ea0440253531f56762a7c31 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 12:33:54 +0200 Subject: [PATCH 09/33] fix(iot-hub): keep the entities a device package used as they were An entity the user chose to use as it was, on a name conflict, is not the package's: updating or deleting the package neither removes nor tracks it. The default device profile is one, and it cannot be removed, so it blocked the update. The update warning also says plainly that this version reinstalls a device package. --- .../service/iot_hub/DefaultIotHubService.java | 29 +++++++++-- .../iot_hub/DefaultIotHubServiceTest.java | 52 +++++++++++++++++++ .../assets/locale/locale.constant-en_US.json | 2 +- 3 files changed, 79 insertions(+), 4 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 004c822dc5..d343e20c24 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 @@ -637,8 +637,9 @@ public class DefaultIotHubService implements IotHubService { } checkSameItem(installedItem, UUID.fromString(itemId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - 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. + Map 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); @@ -704,6 +705,28 @@ 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. + */ + 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<>(); @@ -792,7 +815,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/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index e367794b94..7199fe7fcc 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 @@ -17,6 +17,7 @@ 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; @@ -24,6 +25,7 @@ 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; @@ -63,6 +65,8 @@ class DefaultIotHubServiceTest { @Mock private DeviceService deviceService; @Mock + private DeviceProfileService deviceProfileService; + @Mock private TbDeviceService tbDeviceService; @Mock private DashboardService dashboardService; @@ -689,6 +693,54 @@ class DefaultIotHubServiceTest { assertThat(item.getVersion()).isEqualTo("1.0.1"); } + @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(); 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 9306351638..994e0be3af 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -3875,7 +3875,7 @@ "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. 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-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", "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...", From 07b72d10b252d94a722e53af092695a5b0cbc03f Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 12:33:54 +0200 Subject: [PATCH 10/33] fix(iot-hub): keep the entities a device package used as they were An entity the user chose to use as it was, on a name conflict, is not the package's: updating or deleting the package neither removes nor tracks it. The default device profile is one, and it cannot be removed, so it blocked the update. The update warning also says plainly that this version reinstalls a device package. --- .../service/iot_hub/DefaultIotHubService.java | 29 +++++++++-- .../iot_hub/DefaultIotHubServiceTest.java | 52 +++++++++++++++++++ .../assets/locale/locale.constant-en_US.json | 2 +- 3 files changed, 79 insertions(+), 4 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 ab9c00fbc1..6ae127d68d 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,8 +691,9 @@ public class DefaultIotHubService implements IotHubService { } checkSameItem(installedItem, UUID.fromString(itemId)); DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); - 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. + Map 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); @@ -758,6 +759,28 @@ 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. + */ + 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<>(); @@ -851,7 +874,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/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index e367794b94..7199fe7fcc 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 @@ -17,6 +17,7 @@ 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; @@ -24,6 +25,7 @@ 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; @@ -63,6 +65,8 @@ class DefaultIotHubServiceTest { @Mock private DeviceService deviceService; @Mock + private DeviceProfileService deviceProfileService; + @Mock private TbDeviceService tbDeviceService; @Mock private DashboardService dashboardService; @@ -689,6 +693,54 @@ class DefaultIotHubServiceTest { assertThat(item.getVersion()).isEqualTo("1.0.1"); } + @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(); 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 8f5882c3e3..36d93a9938 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4485,7 +4485,7 @@ "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. 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-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", "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...", From ff661a5e7437f22cd94a99ba044a306d0619bc35 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 12:34:20 +0200 Subject: [PATCH 11/33] fix(iot-hub): point a device package update to ThingsBoard 4.4.1 on lts-4.3 ThingsBoard 4.4.1 updates device packages without reinstalling them; the update warning says so and links the Community Grant Program, as the dialog of an item that needs 4.4 does. --- .../components/iot-hub/iot-hub-update-dialog.component.html | 4 ++-- ui-ngx/src/assets/locale/locale.constant-en_US.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html index a1fffb0a9d..8f65bba065 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html @@ -8,11 +8,11 @@ @switch (state) { @case ('confirm') {

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

-

{{ updateDescKey | translate }}

+

} @case ('updating') {

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

-

{{ updateDescKey | translate }}

+

} @case ('success') {

{{ 'iot-hub.update-success-title' | translate }}

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 36d93a9938..cbde03a653 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4485,7 +4485,7 @@ "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", + "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.

ThingsBoard 4.4.1 and newer update device packages without reinstalling. If your instance was running before September 29, 2026, the Community Grant Program lets you upgrade for free.", "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...", From 89627b7242bd2f779900f195987c45c780e70f9e Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Thu, 5 Nov 2026 12:41:23 +0200 Subject: [PATCH 12/33] fix(iot-hub): ask to update a device package anyway, as on Remove Updating a device package removes its entities and their data, like Remove, so the button is the same warning "Update anyway". --- .../components/iot-hub/iot-hub-update-dialog.component.html | 4 +++- .../components/iot-hub/iot-hub-update-dialog.component.ts | 5 +++++ ui-ngx/src/assets/locale/locale.constant-en_US.json | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html index 8f65bba065..f6fd5b7a04 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html @@ -35,7 +35,9 @@ @switch (state) { @case ('confirm') { - + } @case ('updating') { 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 d5d0398f00..fbcd148b6e 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 @@ -64,6 +64,11 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 12:41:23 +0200 Subject: [PATCH 13/33] fix(iot-hub): ask to update a device package anyway, as on Remove Updating a device package removes its entities and their data, like Remove, so the button is the same warning "Update anyway". --- .../components/iot-hub/iot-hub-update-dialog.component.html | 4 +++- .../components/iot-hub/iot-hub-update-dialog.component.ts | 5 +++++ ui-ngx/src/assets/locale/locale.constant-en_US.json | 1 + 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html index a1fffb0a9d..ab583ca072 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html @@ -35,7 +35,9 @@ @switch (state) { @case ('confirm') { - + } @case ('updating') { 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 d5d0398f00..fbcd148b6e 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 @@ -64,6 +64,11 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 12:54:10 +0200 Subject: [PATCH 14/33] refactor(iot-hub): keep the update description's javadoc on its getter --- .../iot-hub/iot-hub-update-dialog.component.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 fbcd148b6e..d2b1132938 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 @@ -59,16 +59,16 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 12:54:10 +0200 Subject: [PATCH 15/33] refactor(iot-hub): keep the update description's javadoc on its getter --- .../iot-hub/iot-hub-update-dialog.component.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 fbcd148b6e..d2b1132938 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 @@ -59,16 +59,16 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent Date: Thu, 5 Nov 2026 12:56:29 +0200 Subject: [PATCH 16/33] fix(iot-hub): lead the update of a device package to the upgrade on lts-4.3 This version can only reinstall a device package. Update opens the same kind of window as an item that needs ThingsBoard 4.4 (#16231): it says so, leads to the Community Grant Program, and keeps "Update anyway" to reinstall through the install wizard. --- .../iot-hub/iot-hub-actions.service.ts | 20 ++++++-- .../iot-hub/iot-hub-components.module.ts | 3 ++ ...ot-hub-device-update-dialog.component.html | 29 ++++++++++++ .../iot-hub-device-update-dialog.component.ts | 47 +++++++++++++++++++ .../iot-hub-update-dialog.component.html | 8 ++-- .../iot-hub-update-dialog.component.ts | 21 ++------- 6 files changed, 102 insertions(+), 26 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/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 5ec83949bd..9027e71323 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -14,6 +14,10 @@ import { TbIotHubAddItemDialogComponent, IotHubAddItemDialogData, IotHubAddItemD import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubItemDetailDialogMode } from './iot-hub-item-detail-dialog.component'; import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component'; import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component'; +import { + IotHubDeviceUpdateDialogData, + TbIotHubDeviceUpdateDialogComponent +} from './iot-hub-device-update-dialog.component'; import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component'; import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component'; @@ -154,6 +158,18 @@ export class IotHubActionsService { if (!installedItem) { return of(false); } + if (installedItem.itemType === ItemType.DEVICE) { + // This version can only reinstall a device package: the dialog leads to the upgrade first. + return this.dialog.open( + TbIotHubDeviceUpdateDialogComponent, { + panelClass: ['tb-dialog'], + disableClose: true, + autoFocus: false, + data: { itemName: installedItem.itemName } + }).afterClosed().pipe( + switchMap(result => result === 'reinstall' ? this.reinstallDevice(installedItem, versionId) : of(result)) + ); + } return this.dialog.open(TbIotHubUpdateDialogComponent, { panelClass: ['tb-dialog'], disableClose: true, @@ -165,9 +181,7 @@ export class IotHubActionsService { version, versionId } - }).afterClosed().pipe( - switchMap(result => result === 'reinstall' ? this.reinstallDevice(installedItem, versionId) : of(result)) - ); + }).afterClosed(); } /** diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index f6591ac8f8..d81a34e407 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -20,6 +20,7 @@ import { TbIotHubInstalledItemsDialogComponent } from './iot-hub-installed-items import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entity-dialog.component'; import { TbPeConnectivityMethodPromptComponent } from './pe-connectivity-method-prompt.component'; import { TbIotHubPeRequiredDialogComponent } from './iot-hub-pe-required-dialog.component'; +import { TbIotHubDeviceUpdateDialogComponent } from './iot-hub-device-update-dialog.component'; import { TbIotHubUpgradeRequiredDialogComponent } from './iot-hub-upgrade-required-dialog.component'; import { TbIotHubMarkdownComponent } from './iot-hub-markdown.component'; import { SolutionInstallDialogComponent } from './solution-install-dialog.component'; @@ -47,6 +48,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link SolutionInstallDialogComponent, InstallFormRendererComponent, TbIotHubPeRequiredDialogComponent, + TbIotHubDeviceUpdateDialogComponent, TbIotHubUpgradeRequiredDialogComponent ], imports: [ @@ -76,6 +78,7 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link TbIotHubMarkdownComponent, SolutionInstallDialogComponent, TbIotHubPeRequiredDialogComponent, + TbIotHubDeviceUpdateDialogComponent, TbIotHubUpgradeRequiredDialogComponent ] }) diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.html new file mode 100644 index 0000000000..4f7ca41696 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.html @@ -0,0 +1,29 @@ + +
+ + + + +

+ {{ '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..fb0cc99f03 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-device-update-dialog.component.ts @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +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-pe-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'); + } + + viewUpgradeOptions(): void { + window.open('https://thingsboard.io/community-grant-program/', '_blank'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html index f6fd5b7a04..a1fffb0a9d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-update-dialog.component.html @@ -8,11 +8,11 @@ @switch (state) { @case ('confirm') {

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

-

+

{{ updateDescKey | translate }}

} @case ('updating') {

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

-

+

{{ updateDescKey | translate }}

} @case ('success') {

{{ 'iot-hub.update-success-title' | translate }}

@@ -35,9 +35,7 @@ @switch (state) { @case ('confirm') { - + } @case ('updating') { 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 d2b1132938..e5472c45a1 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 @@ -59,33 +59,18 @@ export class TbIotHubUpdateDialogComponent extends DialogComponent { From e8683bd85a21af516e89c746033dbd1e57d43684 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Fri, 6 Nov 2026 10:12:36 +0200 Subject: [PATCH 17/33] fix(iot-hub): review of the device package update: new access tokens in the warning, a package's own entity stays its own, the close prompt only once entities may be gone - update-desc-device says again that the new devices get new access tokens - an existing entity the wizard created a moment ago is recorded as created, not use-existing - the close prompt shows only after the removal, a partial removal or a lost answer - query params go through InterceptorHttpParams (also fixes force losing the interceptor config) - one iotHubErrorMessage helper on parseHttpErrorMessage for the iot-hub dialogs - removingReplaced is one signal, stepError a field, no template method calls or extra detectChanges - fewer comments, readonly fields in the update dialog, cdr renamed to cd --- .../src/app/core/http/iot-hub-api.service.ts | 21 ++- .../device-install-dialog.component.html | 31 ++--- .../device-install-dialog.component.ts | 122 +++++++----------- .../iot-hub/iot-hub-actions.service.ts | 6 +- .../iot-hub-add-item-dialog.component.ts | 4 +- .../iot-hub-install-dialog.component.ts | 3 +- .../iot-hub-update-dialog.component.ts | 37 ++---- .../home/components/iot-hub/iot-hub-utils.ts | 8 ++ .../assets/locale/locale.constant-en_US.json | 2 +- 9 files changed, 100 insertions(+), 134 deletions(-) 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 07c1c9a64d..89df8e9d3b 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 @@ -182,20 +182,18 @@ export class IotHubApiService { replaceInstalledItemId?: string, config?: IotHubRequestConfig ): Observable { - // In the URL: HttpParams.set() would drop the interceptor config (ignoreLoading, ignoreErrors) of buildParams. - const replace = replaceInstalledItemId ? `&replaceInstalledItemId=${replaceInstalledItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}${replace}`, + `/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?versionId=${versionId}`, + `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`, null, - { params: this.buildParams(config) } + { params: this.buildParams(config, { versionId }) } ); } @@ -223,10 +221,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, @@ -294,9 +289,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 45060d91bc..93902b5338 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 @@ -133,24 +133,25 @@ {{ ('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 (ws.removingReplaced) { + @if (removingReplaced()) {
{{ 'iot-hub.device-update-removing' | translate }}
- } - @if (stepLevelError(ws); as error) { - {{ error }} + } @else if (ws.stepError) { + {{ ws.stepError }} } } @@ -166,7 +167,7 @@ } @else {

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

-
@@ -206,7 +207,7 @@ @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -220,13 +221,13 @@ @if (allProgressDone) { } @else { - + } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -261,7 +262,7 @@ } @case ('progress') { - @if (step.progressError) { + @if (step.progressError || step.stepError) { } - } @else if (!step.progressError) { + } @else { @@ -206,7 +207,7 @@ @for (ws of wizardSteps; track ws.label) { - {{ ws.label }} @@ -220,13 +221,13 @@ @if (allProgressDone) { } @else { - + } @if (!isFirstWizardStep) { - + } @if (currentWizardStep; as step) { @@ -261,7 +262,7 @@ } @case ('progress') { - @if (step.progressError) { + @if (step.progressError || step.stepError) { } - } @else if (!step.progressError) { + } @else {