From d53982905a1f2e2a4c76274e3e9af2bb5543092b Mon Sep 17 00:00:00 2001 From: dpinkevych Date: Wed, 28 Oct 2026 12:58:29 +0200 Subject: [PATCH] fix(iot-hub): update a device package in place instead of deleting its entities Updating an installed device package deleted everything the package created, the device included, so its telemetry and attributes were lost, and nothing was installed again. Now the update opens the install wizard of the new version over the installed package. It keeps the install method and the form values, finds the entities by the ids in the install state (so a renamed profile is still found), keeps the device and gateway as they are (id, credentials, history) and overwrites the device profile, converters, integration, dashboard and rule chain with the new templates under their current names. The installed item then takes the new version through registerDeviceUpdate. The server no longer updates a device package by itself. PROD-9096 --- .../server/controller/IotHubController.java | 4 + .../service/iot_hub/DefaultIotHubService.java | 45 ++++- .../server/service/iot_hub/IotHubService.java | 2 + .../iot_hub/DefaultIotHubServiceTest.java | 55 ++++++ .../src/app/core/http/iot-hub-api.service.ts | 7 +- .../device-install-dialog.component.ts | 166 +++++++++++++++--- .../iot-hub/iot-hub-actions.service.ts | 20 ++- 7 files changed, 265 insertions(+), 34 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 1645505c00..e5388bd28b 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -92,9 +92,13 @@ public class IotHubController extends BaseController { @ResponseBody public InstallItemVersionResult registerDeviceInstall( @RequestParam String versionId, + @RequestParam(required = false) UUID installedItemId, @RequestBody JsonNode body) throws ThingsboardException { checkAllPermissions(); DeviceInstalledItemDescriptor descriptor = JacksonUtil.treeToValue(body, DeviceInstalledItemDescriptor.class); + if (installedItemId != null) { + return iotHubService.registerDeviceUpdate(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId, descriptor); + } return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); } 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 a3cf0599fa..6f0f9db86f 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 @@ -416,6 +416,10 @@ public class DefaultIotHubService implements IotHubService { } String itemType = installedItem.getItemType(); + if ("DEVICE".equals(itemType)) { + // The install wizard of the new version changes the package's entities in place, see registerDeviceUpdate + throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); + } IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); // Skip checksum validation for solution templates @@ -460,12 +464,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, installedItemId, dd.getCreatedEntityIds(), user); - dd.setCreatedEntityIds(null); - dd.setDashboardId(null); - } case "SOLUTION_TEMPLATE" -> { SolutionTemplateInstalledItemDescriptor stDescriptor = (SolutionTemplateInstalledItemDescriptor) descriptor; solutionService.deleteSolution(tenantId, stDescriptor, user); @@ -710,6 +708,41 @@ public class DefaultIotHubService implements IotHubService { } } + @Override + public InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, + DeviceInstalledItemDescriptor descriptor) { + TenantId tenantId = user.getTenantId(); + log.info("[{}] Registering device package update of {} to version: {}", tenantId, installedItemId, versionId); + + try { + IotHubInstalledItem installedItem = iotHubInstalledItemService.findById(tenantId, installedItemId); + if (installedItem == null || !"DEVICE".equals(installedItem.getItemType())) { + throw new IllegalArgumentException("Installed device package not found"); + } + + JsonNode versionInfo = iotHubRestClient.getVersionInfo(versionId); + if (versionInfo == null) { + throw new IllegalArgumentException("Failed to get version info from IoT Hub"); + } + if (!installedItem.getItemId().toString().equals(versionInfo.get("itemId").asText())) { + throw new IllegalArgumentException("The version belongs to another item"); + } + + // The wizard has already changed the entities in place: a failure here must not delete them + installedItem.setItemVersionId(UUID.fromString(versionId)); + installedItem.setItemName(versionInfo.get("name").asText()); + installedItem.setVersion(versionInfo.get("version").asText()); + installedItem.setDescriptor(descriptor); + iotHubInstalledItemService.save(tenantId, installedItem); + log.info("[{}] Registered device package update: {} (version {})", tenantId, installedItem.getItemName(), installedItem.getVersion()); + + return InstallItemVersionResult.success(descriptor); + } catch (Exception e) { + log.error("[{}] Failed to register device package update of {} to version: {}", tenantId, installedItemId, versionId, e); + return InstallItemVersionResult.error(e.getMessage()); + } + } + /** * Deletes what a device package created, except the entities another installed device package * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package. 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 e1d0cd666b..3a3fd372b0 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 @@ -19,6 +19,8 @@ public interface IotHubService { InstallItemVersionResult registerDeviceInstall(SecurityUser user, String versionId, DeviceInstalledItemDescriptor descriptor); + InstallItemVersionResult registerDeviceUpdate(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId, DeviceInstalledItemDescriptor descriptor); + void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId); InstalledItemKeptEntities findKeptEntities(TenantId tenantId, IotHubInstalledItemId installedItemId); diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java index 0f0068872c..cf4f25bfd7 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 @@ -495,6 +495,61 @@ class DefaultIotHubServiceTest { assertThat(kept.getUsedByItemsCount()).isZero(); } + @Test + void updateItemVersion_devicePackage_deletesNothing() { + mockTenant(); + IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID()), new DashboardId(UUID.randomUUID())); + installed.setItemType("DEVICE"); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + + UpdateItemVersionResult result = service.updateItemVersion(user, installed.getId(), UUID.randomUUID().toString(), true, null); + + assertThat(result.isSuccess()).isFalse(); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + verify(tbDashboardService, never()).delete(any(), any()); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + + @Test + void registerDeviceUpdate_keepsTheInstalledItemAndRecordsTheNewVersion() { + mockTenant(); + DeviceId deviceId = new DeviceId(UUID.randomUUID()); + IotHubInstalledItem installed = devicePackage(deviceId); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + installed.setVersion("1.0"); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, installed.getItemId().toString(), "DEVICE", "AM308", "1.1")); + DeviceInstalledItemDescriptor updated = new DeviceInstalledItemDescriptor(); + updated.setCreatedEntityIds(List.of(deviceId)); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, updated); + + assertThat(result.isSuccess()).isTrue(); + verify(iotHubInstalledItemService).save(tenantId, installed); + assertThat(installed.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); + assertThat(installed.getVersion()).isEqualTo("1.1"); + assertThat(installed.getDescriptor()).isSameAs(updated); + verify(tbDeviceService, never()).delete(any(Device.class), any()); + } + + @Test + void registerDeviceUpdate_versionOfAnotherItem_isRejected() { + mockTenant(); + IotHubInstalledItem installed = devicePackage(new DeviceId(UUID.randomUUID())); + installed.setItemType("DEVICE"); + installed.setItemId(UUID.randomUUID()); + when(iotHubInstalledItemService.findById(tenantId, installed.getId())).thenReturn(installed); + String versionId = UUID.randomUUID().toString(); + when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Other", "1.0")); + + InstallItemVersionResult result = service.registerDeviceUpdate(user, installed.getId(), versionId, new DeviceInstalledItemDescriptor()); + + assertThat(result.isSuccess()).isFalse(); + verify(iotHubInstalledItemService, never()).save(any(), any()); + } + private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) { DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); descriptor.setCreatedEntityIds(List.of(createdEntityIds)); 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 49da0f4e6a..639127e075 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 @@ -180,10 +180,13 @@ export class IotHubApiService { public registerDeviceInstall( versionId: string, descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record }, - config?: IotHubRequestConfig + config?: IotHubRequestConfig, + // Set for an update: the installed item takes the version and the descriptor + installedItemId?: string ): Observable { + const installedItemParam = installedItemId ? `&installedItemId=${installedItemId}` : ''; return this.http.post( - `/api/iot-hub/device/register?versionId=${versionId}`, + `/api/iot-hub/device/register?versionId=${versionId}${installedItemParam}`, { type: 'DEVICE', ...descriptor }, { params: this.buildParams(config) } ); 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 0f2a99df36..ea37b3bbe5 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 @@ -14,6 +14,7 @@ import { firstValueFrom, Subscription } from 'rxjs'; 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 { DeviceInstalledItemDescriptor } from '@shared/models/iot-hub/iot-hub-installed-item.models'; import { IotHubApiService } from '@core/http/iot-hub-api.service'; import { DeviceProfileService } from '@core/http/device-profile.service'; import { DeviceService } from '@core/http/device.service'; @@ -57,6 +58,17 @@ export interface DeviceInstallDialogData { installState?: Record; entityGroupId?: string; customerId?: string; + // Set when the wizard updates an installed package to the item version + update?: DeviceInstallUpdate; +} + +/** + * The installed package an update changes. The steps of the new version change the entities + * the package created in place, so the device keeps its id, credentials and history. + */ +export interface DeviceInstallUpdate { + installedItemId: string; + descriptor: DeviceInstalledItemDescriptor; } export type WizardStepType = 'connectivity' | 'placeholder' | 'instruction' | 'form' | 'progress'; @@ -318,6 +330,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent field); ws.formFields = [...packageFields, ...(ws.extraFormFields ?? [])]; const controls: Record = {}; - // In review mode, use stored values; otherwise use defaults - const storedValues = this.reviewMode && this.data.installState?.[ws.stateKey ?? ws.label]?.formValues; + // In review mode, use stored values; an update starts from the values of the installed version; otherwise use defaults + const storedState = this.reviewMode ? this.data.installState : this.data.update?.descriptor.installState; + const storedValues = storedState?.[ws.stateKey ?? ws.label]?.formValues; for (const field of ws.formFields) { this.fieldTypes.set(field.key, field.type); const validators = []; @@ -1250,17 +1259,26 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + /** keepName: the entity keeps its current name instead of the template's, e.g. a device profile the user renamed. */ + private async overwriteEntity(step: DeviceInstallStep, existing: EntityStepOutput, keepName = false): Promise { const raw = this.zipFiles.get(step.template); if (!raw) throw new Error(`Template file not found: ${step.template}`); // Overwriting an existing integration reuses its routingKey, so resolve @@ -1563,6 +1583,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent { + if (step.type !== InstallStepType.DEVICE && step.type !== InstallStepType.GATEWAY) { + return existing; + } + const creds = await firstValueFrom(this.deviceService.getDeviceCredentials(existing.id, false, {ignoreErrors: true})); + const output: EntityStepOutput = { ...existing, token: creds.credentialsId }; + if (step.type === InstallStepType.GATEWAY) { + output.dockerComposeUrl = `/api/device-connectivity/gateway-launch/${output.id}/docker-compose/download`; + // As createEntity does: the docker-compose template resolves ${gateway.token} + this.entityOutputs.set('gateway', output); + if (step.dockerCompose) { + const dcRaw = this.zipFiles.get(step.dockerCompose); + if (dcRaw) this.gatewayDockerComposeContent = this.resolveVariables(dcRaw); + } + } + return output; + } + + /** + * Update: the entity the installed version created for this step. It is found by the id kept in + * the install state, not by name, so an entity the user renamed is still found. Null when this + * is not an update, when the installed version had no such step, or when the entity was deleted since. + */ + private async findPreviousEntity(step: DeviceInstallStep): Promise { + const installState = this.data.update?.descriptor.installState; + // A connector lives in the gateway's attributes: its step runs again over the same gateway + if (!installState || step.type === InstallStepType.GATEWAY_CONNECTOR) { + return null; + } + const id: string = (installState[step.name] || installState[this.resolveVariables(step.name)])?.entityOutput?.id; + if (!id) { + return null; + } + const config = {ignoreErrors: true}; + try { + switch (step.type) { + case InstallStepType.DEVICE_PROFILE: { + const profile = await firstValueFrom(this.deviceProfileService.getDeviceProfileInfo(id, config)); + return { id, name: profile.name, url: `/profiles/deviceProfiles/${id}` }; + } + case InstallStepType.DEVICE: { + const device = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: device.name, url: `/entities/devices/all/${id}` }; + } + case InstallStepType.GATEWAY: { + const gateway = await firstValueFrom(this.deviceService.getDevice(id, config)); + return { id, name: gateway.name, url: '/entities/gateways' }; + } + case InstallStepType.DASHBOARD: { + const dashboard = await firstValueFrom(this.dashboardService.getDashboardInfo(id, config)); + return { id, name: dashboard.title, url: `/dashboards/all/${id}` }; + } + case InstallStepType.RULE_CHAIN: { + const ruleChain = await firstValueFrom(this.ruleChainService.getRuleChain(id, config)); + return { id, name: ruleChain.name, url: `/ruleChains/${id}` }; + } + case InstallStepType.UPLINK_CONVERTER: + case InstallStepType.DOWNLINK_CONVERTER: { + const converter = await firstValueFrom(this.converterService.getConverter(id, config)); + const type = step.type === InstallStepType.UPLINK_CONVERTER ? ConverterType.UPLINK : ConverterType.DOWNLINK; + return converter.type === type ? { id, name: converter.name, url: `/converters/${id}` } : null; + } + case InstallStepType.INTEGRATION: { + const integration = await firstValueFrom(this.integrationService.getIntegration(id, config)); + return { id, name: integration.name, url: `/integrations/${id}`, routingKey: integration.routingKey }; + } + default: + return null; + } + } catch (_e) { + // Deleted since: the step creates it again + return null; + } + } + + /** + * Update: a device or gateway is kept as it is, so its credentials, which the firmware uses, don't change. + * Other entities take the new version's template and keep their id and current name. + */ + private updatePreviousEntity(step: DeviceInstallStep, previous: EntityStepOutput): Promise { + if (step.type === InstallStepType.DEVICE || step.type === InstallStepType.GATEWAY) { + return this.useExistingEntity(step, previous); + } + return this.overwriteEntity(step, previous, true); + } + private async preCheckEntity(step: DeviceInstallStep): Promise { const raw = this.zipFiles.get(step.template); if (!raw) return null; @@ -1711,6 +1822,13 @@ export class TbDeviceInstallDialogComponent extends DialogComponent id.id === previousId.id)) { + ids.push(previousId); + } + } return ids; } 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 b04932040d..fb5c9125d0 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 @@ -17,7 +17,7 @@ import { TbIotHubItemDetailDialogComponent, IotHubItemDetailDialogData, IotHubIt import { TbIotHubInstallDialogComponent, IotHubInstallDialogData } from './iot-hub-install-dialog.component'; import { TbIotHubUpdateDialogComponent, IotHubUpdateDialogData } from './iot-hub-update-dialog.component'; import { TbIotHubDeleteDialogComponent, IotHubDeleteDialogData } from './iot-hub-delete-dialog.component'; -import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './device-install-dialog/device-install-dialog.component'; +import { TbDeviceInstallDialogComponent, DeviceInstallDialogData, DeviceInstallUpdate } 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 { isBuiltInItem } from './iot-hub-utils'; @@ -150,6 +150,9 @@ export class IotHubActionsService { if (!installedItem) { return of(false); } + if (installedItem.itemType === ItemType.DEVICE) { + return this.updateDevice(installedItem, versionId); + } return this.dialog.open(TbIotHubUpdateDialogComponent, { panelClass: ['tb-dialog'], disableClose: true, @@ -199,9 +202,22 @@ export class IotHubActionsService { }); } + /** + * A device package is updated by the install wizard of the new version: its steps change what + * the package created in place, so the device and its history stay. + */ + private updateDevice(installedItem: IotHubInstalledItem, versionId: string): Observable { + return this.iotHubApiService.getVersionInfo(versionId).pipe( + switchMap(item => this.openDeviceInstallDialog(item, { + update: { installedItemId: installedItem.id.id, descriptor: installedItem.descriptor as DeviceInstalledItemDescriptor } + })), + map(result => result === 'installed' ? 'updated' : result) + ); + } + private openDeviceInstallDialog(item: MpItemVersionView, options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any; - entityGroupId?: string; customerId?: string}): Observable { + entityGroupId?: string; customerId?: string; update?: DeviceInstallUpdate}): Observable { return this.dialog.open(TbDeviceInstallDialogComponent, { panelClass: ['tb-dialog', 'tb-fullscreen-dialog-lt-md'], disableClose: true,