From cd704379fc19c8570ed96b42dce0973a13e73d65 Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 11 Nov 2026 15:57:41 +0200 Subject: [PATCH] IoT Hub: a device package update keeps the device's entity group and customer (PROD-9245) The PE part of thingsboard-pe#5291 for 4.4.0.x, by hand: the update opens the wizard of the new version with the entity group (the first one other than All) and the customer of the installed version's device, and the server keeps them in the install state ($placement) when it removes the entities, so a retry after the device is gone still creates the new one there. 4.4.1 does not need it: its update keeps the same device. --- .../server/controller/IotHubController.java | 7 ++- .../service/iot_hub/DefaultIotHubService.java | 28 +++++++++-- .../server/service/iot_hub/IotHubService.java | 11 ++++- .../iot_hub/DefaultIotHubServiceTest.java | 34 ++++++++++++++ .../src/app/core/http/iot-hub-api.service.ts | 5 +- .../device-install-dialog.component.ts | 4 +- .../iot-hub/iot-hub-actions.service.ts | 46 +++++++++++++++++-- 7 files changed, 120 insertions(+), 15 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 95cbc7c1aa..5890480c68 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -101,9 +101,12 @@ public class IotHubController extends BaseController { @PostMapping("/installedItems/{installedItemId}/device/removeEntities") @ResponseBody public void removeDevicePackageEntities(@PathVariable UUID installedItemId, - @RequestParam String versionId) throws ThingsboardException { + @RequestParam String versionId, + @RequestParam(required = false) UUID entityGroupId, + @RequestParam(required = false) UUID customerId) throws ThingsboardException { checkAllPermissions(); - iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId); + iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, + entityGroupId, customerId); } @PreAuthorize("hasAuthority('TENANT_ADMIN')") diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java index 0f39f4581e..66bc9e1313 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.iot_hub; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -800,7 +801,8 @@ public class DefaultIotHubService implements IotHubService { } @Override - public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) { + public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, + UUID entityGroupId, UUID customerId) { TenantId tenantId = user.getTenantId(); IotHubInstalledItem installedItem = findDevicePackage(tenantId, installedItemId); // Checked before anything is removed: the registration of the new version checks the same and would fail. @@ -832,9 +834,23 @@ public class DefaultIotHubService implements IotHubService { } // Keep what the user entered in the forms (the wizard of the new version starts from it), drop the outputs of // the removed entities: their ids, links and tokens no longer exist. - if (descriptor.getInstallState() != null) { - descriptor.setInstallState(stripEntityOutputs(descriptor.getInstallState())); + Map installState = descriptor.getInstallState() != null + ? stripEntityOutputs(descriptor.getInstallState()) : null; + // PE: where the removed device was, so that a retry still creates the new one there. + if (entityGroupId != null || customerId != null) { + if (installState == null) { + installState = new LinkedHashMap<>(); + } + ObjectNode placement = JacksonUtil.newObjectNode(); + if (entityGroupId != null) { + placement.put("entityGroupId", entityGroupId.toString()); + } + if (customerId != null) { + placement.put("customerId", customerId.toString()); + } + installState.put(PLACEMENT_STATE, placement); } + descriptor.setInstallState(installState); iotHubInstalledItemService.save(tenantId, installedItem); } catch (RuntimeException e) { // Without the cause: BaseController answers 400 for an IncorrectParameterException cause, and a 400 tells the @@ -849,11 +865,15 @@ public class DefaultIotHubService implements IotHubService { log.info("[{}] Removed the entities of device package {} for its update", tenantId, installedItem.getItemName()); } + private static final String PLACEMENT_STATE = "$placement"; + private static Map stripEntityOutputs(Map installState) { Map stripped = new LinkedHashMap<>(); installState.forEach((step, state) -> { JsonNode formValues = state != null ? state.get("formValues") : null; - if (formValues != null) { + if (PLACEMENT_STATE.equals(step) && state != null) { + stripped.put(step, state); + } else if (formValues != null) { stripped.put(step, JacksonUtil.newObjectNode().set("formValues", formValues)); } }); diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java index 39f7f1df70..055811d35b 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java @@ -10,6 +10,8 @@ import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.service.security.model.SecurityUser; +import java.util.UUID; + public interface IotHubService { InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request); @@ -31,8 +33,15 @@ public interface IotHubService { * Refused with an {@link IllegalArgumentException} (a 400), before anything is removed, when the item is not a device * package, {@code versionId} (the version to install) is not a version of that item, or IoT Hub does not answer. A failure once removing started is an * {@link IllegalStateException}: entities may already be removed. + * PE: the entity group and the customer of the removed device are kept in the install state ({@code $placement}), + * so the new version's device is created there even when the update is retried after the device is gone. */ - void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId); + void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, + UUID entityGroupId, UUID customerId); + + default void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) { + removeDevicePackageEntities(user, installedItemId, versionId, null, null); + } void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index a8672bf668..2c770f2fa2 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java @@ -504,6 +504,40 @@ class DefaultIotHubServiceTest { verify(iotHubInstalledItemService, never()).deleteById(any(), any()); } + @Test + void removeDevicePackageEntities_keepsThePlacementOfTheRemovedDeviceForARetry() throws Exception { + mockTenant(); + Device device = new Device(new DeviceId(UUID.randomUUID())); + device.setTenantId(tenantId); + DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); + descriptor.setCreatedEntityIds(List.of(device.getId())); + descriptor.setInstallState(new LinkedHashMap<>(Map.of( + "Configuration", JacksonUtil.toJsonNode("{\"formValues\":{\"gatewayName\":\"GW\"}}")))); + IotHubInstalledItem item = installedItem(UUID.randomUUID()); + item.setItemType("DEVICE"); + item.setItemId(UUID.randomUUID()); + item.setDescriptor(descriptor); + when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item); + String newVersionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(newVersionId)) + .thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2")); + when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device); + UUID entityGroupId = UUID.randomUUID(); + UUID customerId = UUID.randomUUID(); + + service.removeDevicePackageEntities(user, item.getId(), newVersionId, entityGroupId, customerId); + + verify(tbDeviceService).delete(device, user); + assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement"); + assertThat(descriptor.getInstallState().get("$placement").get("entityGroupId").asText()).isEqualTo(entityGroupId.toString()); + assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString()); + + // A retry after the device is gone: the wizard sends the kept placement again, and it stays. + service.removeDevicePackageEntities(user, item.getId(), newVersionId); + assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement"); + assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString()); + } + @Test void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() { mockTenant(); diff --git a/ui-ngx/src/app/core/http/iot-hub-api.service.ts b/ui-ngx/src/app/core/http/iot-hub-api.service.ts index b83635c774..b443daafe9 100644 --- a/ui-ngx/src/app/core/http/iot-hub-api.service.ts +++ b/ui-ngx/src/app/core/http/iot-hub-api.service.ts @@ -175,11 +175,12 @@ export class IotHubApiService { ); } - public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig): Observable { + public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig, + placement?: { entityGroupId?: string; customerId?: string }): Observable { return this.http.post( `/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`, null, - { params: this.buildParams(config, { versionId }) } + { params: this.buildParams(config, { versionId, entityGroupId: placement?.entityGroupId, customerId: placement?.customerId }) } ); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 355f7753a3..8ad5fc9c76 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -937,8 +937,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor; - return this.iotHubApiService.getVersionInfo(versionId).pipe( - switchMap(item => this.openDeviceInstallDialog(item, { + return forkJoin({ + item: this.iotHubApiService.getVersionInfo(versionId), + placement: this.findDevicePlacement(descriptor) + }).pipe( + switchMap(({ item, placement }) => this.openDeviceInstallDialog(item, { replaceInstalledItemId: installedItem.id.id, selectedInstallMethod: descriptor?.selectedInstallMethod, - installState: descriptor?.installState + installState: descriptor?.installState, + ...placement })), map(result => result === 'installed' ? 'updated' : false), // The error itself is shown by the HTTP interceptor; nothing is changed yet. @@ -224,6 +234,32 @@ export class IotHubActionsService { }); } + /** + * The customer and the entity group of the installed version's device: the new version's device is created there + * too, as the wizard creates it in the group and for the customer it was installed from. With several groups the + * first one other than "All" is taken; nothing when the device cannot be read. When an earlier update already removed + * the device, the placement the server kept for it ($placement in the install state). + */ + private findDevicePlacement(descriptor: DeviceInstalledItemDescriptor): Observable<{ entityGroupId?: string; customerId?: string }> { + const deviceId = descriptor?.createdEntityIds?.find(id => id.entityType === EntityType.DEVICE)?.id; + if (!deviceId) { + const kept = descriptor?.installState?.['$placement']; + return of({ entityGroupId: kept?.entityGroupId, customerId: kept?.customerId }); + } + const config = { ignoreLoading: true, ignoreErrors: true }; + // Each lookup failing on its own (a deleted device, no access to its groups) only leaves its part out. + return forkJoin({ + customerId: this.deviceService.getDevice(deviceId, config).pipe( + map(device => device.customerId && device.customerId.id !== NULL_UUID ? device.customerId.id : undefined), + catchError(() => of(undefined))), + entityGroupId: this.entityGroupService.getEntityGroupIdsForEntityId(EntityType.DEVICE, deviceId, config).pipe( + switchMap(groupIds => groupIds.length + ? this.entityGroupService.getEntityGroupsByIds(groupIds.map(groupId => groupId.id), config) : of([])), + map(groups => groups.find(group => !group.groupAll)?.id.id), + catchError(() => of(undefined))) + }); + } + private openDeviceInstallDialog(item: MpItemVersionView, options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; entityGroupId?: string; customerId?: string; replaceInstalledItemId?: string}): Observable {