Browse Source

IoT Hub device package delete: a device profile devices use stays, with what it refers to, and the dialog says so (PROD-9340)

pull/16694/head
dpinkevych 3 weeks ago
parent
commit
c1d8d73f2a
  1. 85
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  2. 10
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  3. 2
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java
  4. 83
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  5. 24
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  6. 7
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  7. 1
      ui-ngx/src/assets/locale/locale.constant-en_US.json

85
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -12,6 +12,7 @@ import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile;
@ -91,8 +92,10 @@ import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
@Service
@TbCoreComponent
@ -720,7 +723,9 @@ public class DefaultIotHubService implements IotHubService {
/**
* 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,
* and the ones the user had before and the package took as they were (use existing).
* and the ones the user had before and the package took as they were (use existing). A device profile that devices
* still use stays too, e.g. with the devices a LoRaWAN integration created, and so does what it refers to that the
* package created: TB deletes neither.
* A kept integration loses the metadata entries the package added.
*/
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
@ -737,6 +742,8 @@ public class DefaultIotHubService implements IotHubService {
List<EntityId> ordered = new ArrayList<>(createdEntityIds);
Collections.reverse(ordered);
ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size())));
// What a kept profile refers to: its default rule chain and dashboard, which come after it in the order
Set<UUID> referencedByKeptProfiles = new HashSet<>();
for (EntityId entityId : ordered) {
if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
@ -749,6 +756,17 @@ public class DefaultIotHubService implements IotHubService {
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
continue;
}
if (referencedByKeptProfiles.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId());
continue;
}
// The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration
long devices = countProfileDevices(tenantId, entityId, Set.of());
if (devices > 0) {
log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue;
}
try {
deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) {
@ -811,16 +829,27 @@ public class DefaultIotHubService implements IotHubService {
throw new IllegalArgumentException("Installed item not found");
}
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
List<InstalledItemKeptEntities.KeptEntity> keptForDevices = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 0;
long devicesCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Set<UUID> usedExisting = usedExistingIds(dd);
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>());
// The delete removes these before the profiles, so they don't keep a profile; a kept device does
Set<UUID> deletedDevices = new HashSet<>();
dd.getCreatedEntityIds().stream()
.filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId()))
.forEach(id -> deletedDevices.add(id.getId()));
Set<UUID> created = new HashSet<>();
dd.getCreatedEntityIds().forEach(id -> created.add(id.getId()));
Set<UUID> keptIds = new HashSet<>();
for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) {
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null)));
kept.add(keptEntity(tenantId, entityId));
keptIds.add(entityId.getId());
}
if (usedBy != null) {
usedByItems.addAll(usedBy);
@ -829,8 +858,58 @@ public class DefaultIotHubService implements IotHubService {
usedExistingCount++;
}
}
for (EntityId entityId : dd.getCreatedEntityIds()) {
long devices = keptIds.contains(entityId.getId()) ? 0 : countProfileDevices(tenantId, entityId, deletedDevices);
if (devices == 0) {
continue;
}
keptForDevices.add(keptEntity(tenantId, entityId));
keptIds.add(entityId.getId());
devicesCount += devices;
// What the profile refers to stays with it
for (EntityId reference : profileReferences(tenantId, entityId)) {
if (created.contains(reference.getId()) && keptIds.add(reference.getId())) {
keptForDevices.add(keptEntity(tenantId, reference));
}
}
}
}
return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, keptForDevices, devicesCount);
}
private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) {
return new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null));
}
/** The default rule chains and dashboard of the device profile {@code profileId}: TB doesn't delete them while it refers to them. */
private List<EntityId> profileReferences(TenantId tenantId, EntityId profileId) {
DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId()));
List<EntityId> references = new ArrayList<>();
if (profile != null) {
Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId())
.filter(Objects::nonNull)
.forEach(references::add);
}
return references;
}
/**
* How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity.
* TB doesn't delete a profile that devices use.
*/
private long countProfileDevices(TenantId tenantId, EntityId entityId, Set<UUID> excludedDevices) {
if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) {
return 0;
}
DeviceProfileId profileId = new DeviceProfileId(entityId.getId());
long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements();
for (UUID deviceId : excludedDevices) {
Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId));
if (device != null && profileId.equals(device.getDeviceProfileId())) {
count--;
}
}
return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount);
return Math.max(count, 0);
}
/** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */

10
application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java

@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId;
import java.util.List;
/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */
/**
* What deleting an installed item keeps: what other installed items use too, what the user had before it, and the device
* profiles devices still use (a LoRaWAN integration creates its devices on the first uplink, not the package).
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ -20,6 +23,11 @@ public class InstalledItemKeptEntities {
private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount;
// The package's device profiles that devices use and what they refer to (default rule chain, dashboard): TB deletes
// neither. Apart from entities, which an update reads as shared with other packages
private List<KeptEntity> keptForDevices;
// How many devices use those profiles
private long devicesCount;
@Data
@NoArgsConstructor

2
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java

@ -308,7 +308,7 @@ class DefaultDevicePackageUpdateServiceTest {
Dashboard shared = dashboard(9L);
DevicePackageEntities.Snapshot snapshot = new DevicePackageEntities.Snapshot(shared, null);
when(packageEntities.load(tenantId, dashboardId)).thenReturn(snapshot);
when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0));
when(iotHubService.findKeptEntities(tenantId, installedItem.getId())).thenReturn(new InstalledItemKeptEntities(List.of(), 0, 0, List.of(), 0));
// This package recorded the dashboard as it left it; the other one overwrote it since and recorded the new one
ObjectNode own = stateOf(dashboardId, "created").put("checksum", "as-this-package-left-it");
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", own));

83
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
@ -39,10 +40,12 @@ import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService;
import org.thingsboard.server.service.entitiy.device.TbDeviceService;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService;
import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
@ -95,6 +98,10 @@ class DefaultIotHubServiceTest {
private ConverterService converterService;
@Mock
private TbConverterService tbConverterService;
@Mock
private RuleChainService ruleChainService;
@Mock
private TbRuleChainService tbRuleChainService;
@Spy
@InjectMocks
@ -474,6 +481,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
noDevices(profile.getId());
when(dashboardService.findDashboardById(tenantId, dashboard.getId())).thenReturn(dashboard);
when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
@ -736,6 +744,81 @@ class DefaultIotHubServiceTest {
return integration;
}
@Test
void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndItsRuleChain_apartFromTheShared() {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
profile.setDefaultRuleChainId(ruleChainId);
Device packageDevice = new Device(new DeviceId(UUID.randomUUID()));
packageDevice.setDeviceProfileId(profile.getId());
IotHubInstalledItem checked = devicePackage(ruleChainId, profile.getId(), packageDevice.getId());
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
// 3 devices on the profile: the package's own, which the delete removes first, and 2 the integration created
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(), 3, 3, true));
when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice);
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr"));
when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
// An update reads entities as shared with other packages: the profile is not among them
assertThat(kept.getEntities()).isEmpty();
assertThat(kept.getKeptForDevices()).containsExactly(
new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"),
new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"));
assertThat(kept.getDevicesCount()).isEqualTo(2);
}
@Test
void findKeptEntities_devicePackage_aKeptDeviceKeepsItsProfile() {
DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID());
DeviceId sharedDeviceId = new DeviceId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(profileId, sharedDeviceId);
IotHubInstalledItem other = devicePackage(sharedDeviceId);
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, other), 1, 2, false));
// The only device on the profile is the one another package uses: the delete keeps it, so it keeps the profile
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any()))
.thenReturn(new PageData<>(List.of(sharedDeviceId), 1, 1, false));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getKeptForDevices()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId);
assertThat(kept.getDevicesCount()).isEqualTo(1);
}
@Test
void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndItsRuleChain() throws Exception {
mockTenant();
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
profile.setDefaultRuleChainId(ruleChainId);
IotHubInstalledItem deleted = devicePackage(ruleChainId, profile.getId());
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(new DeviceId(UUID.randomUUID())), 1, 1, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceProfileService, never()).delete(any(), any());
verify(ruleChainService, never()).findRuleChainById(any(), any());
verify(tbRuleChainService, never()).delete(any(), any());
verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
}
private void noDevices(DeviceProfileId profileId) {
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profileId), any()))
.thenReturn(new PageData<>(List.of(), 0, 0, false));
}
private IotHubInstalledItem devicePackage(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds));

24
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts

@ -46,13 +46,23 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
super(store, router, dialogRef);
this.description = this.translate.instant(data.itemType === 'SOLUTION_TEMPLATE' ? 'iot-hub.remove-desc-solution-template' : 'iot-hub.remove-desc');
const kept = data.keptEntities;
if (kept?.entities.length) {
this.keptReferences = kept.entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
// Kept because other packages use them, because the user had them before the package, or both
const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' :
!kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used';
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length });
this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length });
const shared = kept?.entities ?? [];
const withDevices = kept?.keptForDevices ?? [];
if (shared.length || withDevices.length) {
this.keptReferences = [...shared, ...withDevices].map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
const reasons: string[] = [];
if (shared.length) {
// Kept because other packages use them, because the user had them before the package, or both
const reasonKey = !kept.usedExistingCount ? 'iot-hub.remove-kept-used' :
!kept.usedByItemsCount ? 'iot-hub.remove-kept-own' : 'iot-hub.remove-kept-own-or-used';
reasons.push(this.translate.instant(reasonKey, { kept: shared.length }));
}
if (withDevices.length) {
const profiles = withDevices.filter(entity => entity.entityId.entityType === 'DEVICE_PROFILE').length;
reasons.push(this.translate.instant('iot-hub.remove-kept-devices', { profiles, devices: kept.devicesCount ?? 0 }));
}
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + withDevices.length });
this.keptReason = reasons.join(' ');
}
}

7
ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts

@ -159,7 +159,7 @@ export interface ItemPublishedVersionInfo {
publishedVersion: string;
}
/** An entity that deleting an installed item keeps, because other installed items use it too. */
/** An entity that deleting an installed item keeps. */
export interface IotHubKeptEntity {
entityId: { id: string; entityType: string };
name: string;
@ -170,6 +170,11 @@ export interface IotHubInstalledItemKeptEntities {
usedByItemsCount: number;
// Of the kept entities, the ones the user had before and the package took as they were
usedExistingCount: number;
// The package's device profiles that devices use (e.g. the ones a LoRaWAN integration created) and what they refer to:
// TB deletes neither. Absent from an older backend
keptForDevices?: IotHubKeptEntity[];
// How many devices use those profiles
devicesCount?: number;
}
export interface IotHubInstalledItem extends BaseData<{id: string}> {

1
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -6449,6 +6449,7 @@
"remove-kept-title": "{ kept, plural, =1 {This entity will not be removed} other {These entities will not be removed} }",
"remove-kept-used": "Other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-kept-own": "You had { kept, plural, =1 {it} other {them} } before the package was installed.",
"remove-kept-devices": "{ devices, plural, =1 {1 device still uses} other {# devices still use} } { profiles, plural, =1 {the device profile} other {the device profiles} }, and ThingsBoard doesn't remove a profile in use. Delete the devices first to remove it.",
"remove-kept-own-or-used": "You had { kept, plural, =1 {it} other {them} } before the package was installed, or other installed packages use { kept, plural, =1 {it} other {them} }.",
"remove-desc-solution-template": "Removing this solution template will also remove all created entities including dashboards, rule chains, devices, and other associated resources within your tenant",
"remove-anyway": "Remove anyway",

Loading…
Cancel
Save