Browse Source

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.
pull/16554/head
dpinkevych 4 weeks ago
parent
commit
7e2802d24d
Failed to extract signature
  1. 23
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  2. 6
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  3. 34
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  4. 17
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  5. 6
      ui-ngx/src/assets/locale/locale.constant-en_US.json

23
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<EntityId, String> 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<EntityId> 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<EntityId, String> deleteDevicePackageEntities(TenantId tenantId, List<EntityId> createdEntityIds, SecurityUser user) {
Map<EntityId, String> failed = new LinkedHashMap<>();
if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return;
return failed;
}
List<EntityId> 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<EntityId, String> 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. */

6
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);

34
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.<EntityId>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();

17
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<TbDeviceInst
private attributeService: AttributeService,
private iotHubApiService: IotHubApiService,
private translate: TranslateService,
private dialog: MatDialog
private dialog: MatDialog,
private dialogService: DialogService
) {
super(store, router, dialogRef);
}
@ -418,11 +420,22 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
return this.wizardSteps.some(ws => ws.removingReplaced);
}
cancel(): void {
async cancel(): Promise<void> {
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);

6
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...",

Loading…
Cancel
Save