Browse Source

Merge pull request #16694 from pinkevmladchy/fix/iot-hub-delete-dialog-profile-with-devices

IoT Hub: fixed removing a device package silently leaving a device profile that devices use
pull/16704/head
Viacheslav Klimov 2 weeks ago
committed by GitHub
parent
commit
ee6727d3ba
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 100
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  2. 8
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  3. 2
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
  4. 186
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  5. 2
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts
  6. 39
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html
  7. 33
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss
  8. 22
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.ts
  9. 4
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  10. 1
      ui-ngx/src/assets/locale/locale.constant-en_US.json

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

@ -8,10 +8,12 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
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;
@ -43,6 +45,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript
import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
@ -91,8 +94,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 +725,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 any kept profile keeps what it refers
* to: TB deletes neither.
* A kept integration loses the metadata entries the package added.
*/
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
@ -737,22 +744,42 @@ 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());
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue;
}
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
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) {
log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
// A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain
if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) {
log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e));
} else {
log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
}
}
}
}
@ -811,16 +838,26 @@ public class DefaultIotHubService implements IotHubService {
throw new IllegalArgumentException("Installed item not found");
}
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
List<InstalledItemKeptEntities.KeptEntity> referenced = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 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 +866,63 @@ public class DefaultIotHubService implements IotHubService {
usedExistingCount++;
}
}
for (EntityId entityId : dd.getCreatedEntityIds()) {
if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) {
referenced.add(keptEntity(tenantId, entityId));
keptIds.add(entityId.getId());
}
}
// A kept profile, for whatever reason, keeps what it refers to
for (EntityId entityId : dd.getCreatedEntityIds()) {
if (!keptIds.contains(entityId.getId())) {
continue;
}
for (EntityId reference : profileReferences(tenantId, entityId)) {
if (created.contains(reference.getId()) && keptIds.add(reference.getId())) {
referenced.add(keptEntity(tenantId, reference));
}
}
}
}
return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced);
}
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 a device profile, which TB doesn't delete while it refers to them; none for another entity. */
private List<EntityId> profileReferences(TenantId tenantId, EntityId profileId) {
List<EntityId> references = new ArrayList<>();
if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) {
return references;
}
DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId()));
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. */

8
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 what other
* tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package).
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ -20,6 +23,9 @@ 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;
// What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and
// dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages
private List<KeptEntity> referencedEntities;
@Data
@NoArgsConstructor

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

@ -341,7 +341,7 @@ class DefaultDevicePackageServiceTest {
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()));
// 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));

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

@ -3,6 +3,10 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
@ -14,6 +18,7 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.id.DashboardId;
@ -22,6 +27,9 @@ 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.rule.RuleChain;
import org.thingsboard.server.exception.DataValidationException;
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 +47,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 +105,10 @@ class DefaultIotHubServiceTest {
private ConverterService converterService;
@Mock
private TbConverterService tbConverterService;
@Mock
private RuleChainService ruleChainService;
@Mock
private TbRuleChainService tbRuleChainService;
@Spy
@InjectMocks
@ -475,6 +489,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);
@ -738,6 +753,177 @@ class DefaultIotHubServiceTest {
return integration;
}
@Test
void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
DashboardId dashboardId = new DashboardId(UUID.randomUUID());
profile.setDefaultRuleChainId(ruleChainId);
profile.setDefaultDashboardId(dashboardId);
// The user's, not the package's: not listed
profile.setDefaultEdgeRuleChainId(new RuleChainId(UUID.randomUUID()));
Device packageDevice = new Device(new DeviceId(UUID.randomUUID()));
packageDevice.setDeviceProfileId(profile.getId());
IotHubInstalledItem checked = devicePackage(ruleChainId, dashboardId, 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"));
when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet"));
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.getReferencedEntities()).containsExactly(
new InstalledItemKeptEntities.KeptEntity(profile.getId(), "smartico-l2-lr"),
new InstalledItemKeptEntities.KeptEntity(ruleChainId, "Smartico L2-LR"),
new InstalledItemKeptEntities.KeptEntity(dashboardId, "Smartico L2-LR Fleet"));
}
@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.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profileId);
}
@Test
void findKeptEntities_devicePackage_aSharedProfileKeepsWhatItRefersTo() {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
RuleChainId edgeRuleChainId = new RuleChainId(UUID.randomUUID());
profile.setDefaultRuleChainId(ruleChainId);
profile.setDefaultEdgeRuleChainId(edgeRuleChainId);
IotHubInstalledItem checked = devicePackage(ruleChainId, edgeRuleChainId, profile.getId());
IotHubInstalledItem other = devicePackage(profile.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, other), 1, 2, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId).containsExactly(profile.getId());
assertThat(kept.getReferencedEntities()).extracting(InstalledItemKeptEntities.KeptEntity::getEntityId)
.containsExactly(ruleChainId, edgeRuleChainId);
}
@Test
void deleteInstalledItem_devicePackage_keepsTheProfileDevicesUseAndWhatItRefersTo() throws Exception {
mockTenant();
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
DashboardId dashboardId = new DashboardId(UUID.randomUUID());
profile.setDefaultRuleChainId(ruleChainId);
profile.setDefaultDashboardId(dashboardId);
IotHubInstalledItem deleted = devicePackage(ruleChainId, dashboardId, 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(tbRuleChainService, never()).delete(any(), any());
verify(tbDashboardService, never()).delete(any(), any());
verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
}
@Test
void deleteInstalledItem_devicePackage_aSharedProfileKeepsItsRuleChain() 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());
IotHubInstalledItem other = devicePackage(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, other), 1, 2, false));
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
service.deleteInstalledItem(user, deleted.getId());
verify(tbDeviceProfileService, never()).delete(any(), any());
verify(tbRuleChainService, never()).delete(any(), any());
}
@Test
void deleteInstalledItem_devicePackage_anEntitySomethingElseRefersToStays_loggedAsKept() throws Exception {
// A profile the user made after the install uses the package's rule chain
List<ILoggingEvent> logs = deleteRuleChainFailingWith(
new DataValidationException("The rule chain referenced by the device profiles cannot be deleted!"));
assertThat(logs).anySatisfy(event -> {
assertThat(event.getLevel()).isEqualTo(Level.INFO);
assertThat(event.getFormattedMessage()).contains("Kept RULE_CHAIN").contains("referenced by the device profiles");
});
assertThat(logs).noneMatch(event -> event.getLevel() == Level.ERROR);
}
@Test
void deleteInstalledItem_devicePackage_aFailedDelete_staysAnError() throws Exception {
List<ILoggingEvent> logs = deleteRuleChainFailingWith(new RuntimeException("Database is down"));
assertThat(logs).anySatisfy(event -> {
assertThat(event.getLevel()).isEqualTo(Level.ERROR);
assertThat(event.getFormattedMessage()).contains("Failed to delete device package entity");
});
}
/** Deletes a package whose only entity is a rule chain that fails to delete with {@code failure}; the service's logs. */
private List<ILoggingEvent> deleteRuleChainFailingWith(Exception failure) throws Exception {
mockTenant();
RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
IotHubInstalledItem deleted = devicePackage(ruleChain.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(ruleChainService.findRuleChainById(tenantId, ruleChain.getId())).thenReturn(ruleChain);
doThrow(failure).when(tbRuleChainService).delete(ruleChain, user);
Logger logger = (Logger) LoggerFactory.getLogger(DefaultIotHubService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
Level level = logger.getLevel();
logger.setLevel(Level.INFO);
try {
service.deleteInstalledItem(user, deleted.getId());
} finally {
logger.setLevel(level);
logger.detachAppender(appender);
}
// The delete goes on either way
verify(iotHubInstalledItemService).deleteById(tenantId, deleted.getId());
return appender.list;
}
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));

2
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -212,7 +212,7 @@ export class IotHubActionsService {
if (!installedItem) {
return of(false);
}
// A device package keeps what other installed packages use: the dialog opens with that already known
// A device package keeps some entities: the dialog opens with them already known
const keptEntities$: Observable<IotHubInstalledItemKeptEntities | null> = installedItem.itemType === 'DEVICE' ?
this.iotHubApiService.getInstalledItemKeptEntities(installedItem.id.id, {ignoreErrors: true}).pipe(catchError(() => of(null))) :
of(null);

39
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.html

@ -5,21 +5,30 @@
SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
-->
<div class="flex flex-col gap-5 p-6">
<h2 class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<p class="tb-iot-hub-delete-desc">{{ description }}</p>
@if (keptReferences) {
<div class="tb-form-hint tb-primary-fill">
<mat-icon>info_outline</mat-icon>
<div class="flex flex-col">
<div class="font-medium">{{ keptTitle }}</div>
<div>{{ keptReason }}</div>
<tb-image-references class="mt-3" [references]="keptReferences"></tb-image-references>
<h2 mat-dialog-title class="tb-iot-hub-delete-title">{{ 'iot-hub.remove-confirm-title' | translate:{ name: data.itemName } }}</h2>
<mat-dialog-content class="!pt-0">
<div class="flex flex-col gap-5">
<p class="tb-iot-hub-delete-desc">{{ description }}</p>
@if (keptGroups.length) {
<div class="tb-form-hint tb-primary-fill">
<mat-icon>info_outline</mat-icon>
<div class="flex min-w-0 flex-col">
<div class="font-medium">{{ keptTitle }}</div>
<div class="tb-iot-hub-kept-groups mt-2 divide-y divide-solid divide-black/[.08] rounded bg-white">
@for (group of keptGroups; track group.reason) {
<div role="group" class="flex flex-col gap-1 border-0 py-2"
[attr.aria-labelledby]="'tb-iot-hub-kept-reason-' + $index">
<div class="px-3 pt-1 font-medium leading-4" [id]="'tb-iot-hub-kept-reason-' + $index">{{ group.reason }}</div>
<tb-image-references [references]="group.references"></tb-image-references>
</div>
}
</div>
</div>
</div>
</div>
}
</div>
<div class="flex items-center justify-end gap-2 p-2">
}
</div>
</mat-dialog-content>
<mat-dialog-actions align="end">
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="warn" (click)="confirm()">{{ 'iot-hub.remove-anyway' | translate }}</button>
</div>
</mat-dialog-actions>

33
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-delete-dialog.component.scss

@ -1,6 +1,8 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
@import "../../../../../scss/constants";
:host {
display: block;
max-width: 600px;
@ -13,6 +15,12 @@
letter-spacing: 0.1px;
color: rgba(0, 0, 0, 0.87);
margin: 0;
padding: 24px 24px 20px;
// No baseline strut: the title keeps its own line height
&::before {
display: none;
}
}
.tb-iot-hub-delete-desc {
@ -23,3 +31,28 @@
color: rgba(0, 0, 0, 0.54);
margin: 0;
}
.tb-iot-hub-kept-groups {
border: 1px solid color-mix(in srgb, var(--tb-primary-500) 40%, transparent);
// Groups share the outer border; hide tb-image-references' own
::ng-deep tb-image-references table.tb-entities-list-table {
padding: 0 10px 0 4px;
background: transparent;
&:before {
display: none;
}
// Narrow dialog: let type and name wrap
td.tb-entity-type {
@media #{$mat-xs} {
white-space: normal !important;
}
}
td.tb-entity-name {
overflow-wrap: anywhere;
}
}
}

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

@ -7,7 +7,7 @@ import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { AppState } from '@core/core.state';
import { DialogComponent } from '@shared/components/dialog.component';
import { IotHubInstalledItemKeptEntities } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubInstalledItemKeptEntities, IotHubKeptEntity } from 'src/app/shared/models/iot-hub/iot-hub-installed-item.models';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { TranslateService } from '@ngx-translate/core';
import { ResourceReferences } from '@shared/models/resource.models';
@ -30,10 +30,8 @@ export class TbIotHubDeleteDialogComponent extends DialogComponent<TbIotHubDelet
description: string;
// A device package keeps the entities other installed packages use, and the dialog lists them before the user confirms
keptReferences: ResourceReferences | null = null;
keptGroups: { reason: string; references: ResourceReferences }[] = [];
keptTitle: string;
keptReason: string;
constructor(
protected store: Store<AppState>,
@ -46,13 +44,21 @@ 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 }));
const shared = kept?.entities ?? [];
const referenced = kept?.referencedEntities ?? [];
const references = (entities: IotHubKeptEntity[]): ResourceReferences =>
entities.map(entity => ({ id: entity.entityId as EntityId, name: entity.name }));
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';
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: kept.entities.length });
this.keptReason = this.translate.instant(reasonKey, { kept: kept.entities.length });
this.keptGroups.push({ reason: this.translate.instant(reasonKey, { kept: shared.length }), references: references(shared) });
}
if (referenced.length) {
this.keptGroups.push({ reason: this.translate.instant('iot-hub.remove-kept-referenced'), references: references(referenced) });
}
if (this.keptGroups.length) {
this.keptTitle = this.translate.instant('iot-hub.remove-kept-title', { kept: shared.length + referenced.length });
}
}

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

@ -162,7 +162,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;
@ -173,6 +173,8 @@ export interface IotHubInstalledItemKeptEntities {
usedByItemsCount: number;
// Of the kept entities, the ones the user had before and the package took as they were
usedExistingCount: number;
// Absent from older backends
referencedEntities?: IotHubKeptEntity[];
}
export interface IotHubInstalledItem extends BaseData<{id: string}> {

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

@ -6452,6 +6452,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-referenced": "Referenced by other tenant entities.",
"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