Browse Source

IoT Hub: an update that can't remove the package's profile, rule chain or converter is refused before removing (PROD-9245)

By hand from the 4.2 and PE lines: ThingsBoard refuses to delete a device profile that is the default one or that
devices outside the package use, a converter that an integration outside the package uses, and a rule chain that is
the root one or the default rule chain of a profile outside the package. Found after the dashboard and the device were
gone, such a refusal left the package half removed and failed every Retry. Now it is checked before anything is
removed, and the update is refused with a 400 that names what blocks it.
pull/16625/head
dpinkevych 3 weeks ago
parent
commit
6b8e62cebc
  1. 74
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  2. 117
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

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

@ -3,6 +3,9 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.common.data.page.PageDataIterable;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.integration.Integration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
@ -820,9 +823,10 @@ public class DefaultIotHubService implements IotHubService {
throw new IllegalArgumentException("IoT Hub returned the version without its item");
}
checkSameItem(installedItem, UUID.fromString(itemId));
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
checkPackageEntitiesCanBeRemoved(tenantId, packageOwnedEntityIds(descriptor));
// Refusals above are a 400 and remove nothing. Any failure from here on is not a 400, so the wizard knows that
// entities may already be gone (each delete is committed on its own).
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
Map<EntityId, String> failed;
try {
failed = deleteDevicePackageEntities(tenantId, packageOwnedEntityIds(descriptor), user);
@ -921,6 +925,74 @@ public class DefaultIotHubService implements IotHubService {
* The entities the package created: the tracked ones without those the user chose, on a name conflict, to use as they
* were (the install state keeps that choice). The default device profile, for example, is never the package's.
*/
/**
* The update removes the package's entities one by one. ThingsBoard refuses to delete a device profile that is the
* default one or that devices outside the package use, a converter that an integration outside the package uses,
* and a rule chain that is the root one or the default rule chain of a profile outside the package. Found after the first deletes, such a refusal would leave the package half
* removed and fail every Retry the same way, so it is checked before anything is removed: a 400 removes nothing.
*/
private void checkPackageEntitiesCanBeRemoved(TenantId tenantId, List<EntityId> packageEntityIds) {
if (packageEntityIds == null || packageEntityIds.isEmpty()) {
return;
}
Set<UUID> owned = new HashSet<>();
packageEntityIds.forEach(id -> owned.add(id.getId()));
List<String> blockers = new ArrayList<>();
for (EntityId entityId : packageEntityIds) {
if (entityId.getEntityType() == EntityType.DEVICE_PROFILE) {
DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
if (!isOwnedBy(profile, tenantId)) {
continue;
}
if (profile.isDefault()) {
blockers.add("the device profile '" + profile.getName() + "' is the default device profile");
}
long otherDevices = 0;
for (DeviceId deviceId : new PageDataIterable<>(link -> deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(
tenantId, profile.getId(), link), 1000)) {
if (!owned.contains(deviceId.getId())) {
otherDevices++;
}
}
if (otherDevices > 0) {
blockers.add("the device profile '" + profile.getName() + "' is used by " + otherDevices + " other device(s)");
}
} else if (entityId.getEntityType() == EntityType.CONVERTER) {
Converter converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
if (!isOwnedBy(converter, tenantId)) {
continue;
}
for (Integration integration : integrationService.findIntegrationsByConverterId(tenantId, converter.getId())) {
if (!owned.contains(integration.getId().getId())) {
blockers.add("the converter '" + converter.getName() + "' is used by the integration '" + integration.getName() + "'");
}
}
} else if (entityId.getEntityType() == EntityType.RULE_CHAIN) {
RuleChain ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
if (!isOwnedBy(ruleChain, tenantId)) {
continue;
}
if (ruleChain.isRoot()) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the root rule chain");
}
for (DeviceProfile profile : new PageDataIterable<>(link -> deviceProfileService.findDeviceProfiles(tenantId, link), 1000)) {
if (ruleChain.getId().equals(profile.getDefaultRuleChainId()) && !owned.contains(profile.getId().getId())) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the rule chain of the device profile '" + profile.getName() + "'");
}
}
for (AssetProfile profile : new PageDataIterable<>(link -> assetProfileService.findAssetProfiles(tenantId, link), 1000)) {
if (ruleChain.getId().equals(profile.getDefaultRuleChainId())) {
blockers.add("the rule chain '" + ruleChain.getName() + "' is the rule chain of the asset profile '" + profile.getName() + "'");
}
}
}
}
if (!blockers.isEmpty()) {
throw new IllegalArgumentException("The package can't be updated: " + String.join("; ", blockers)
+ ". Move them to other profiles or rule chains first, or delete them. Nothing was removed.");
}
}
private static List<EntityId> packageOwnedEntityIds(DeviceInstalledItemDescriptor descriptor) {
List<EntityId> tracked = descriptor.getCreatedEntityIds();
if (tracked == null || descriptor.getInstallState() == null) {

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

@ -2,6 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.service.iot_hub;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileService;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.DeviceProfile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
@ -71,6 +80,12 @@ class DefaultIotHubServiceTest {
@Mock
private TbDeviceService tbDeviceService;
@Mock
private IntegrationService integrationService;
@Mock
private ConverterService converterService;
@Mock
private TbDeviceProfileService tbDeviceProfileService;
@Mock
private DashboardService dashboardService;
@Mock
private TbDashboardService tbDashboardService;
@ -755,6 +770,108 @@ class DefaultIotHubServiceTest {
verify(tbDeviceService).delete(device, user);
}
@Test
void removeDevicePackageEntities_profileUsedByAnotherDevice_refusedBeforeRemoving() {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceProfile profile = packageProfile(false);
IotHubInstalledItem item = devicePackage(profile.getId(), device.getId());
DeviceId otherDevice = new DeviceId(UUID.randomUUID());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(device.getId(), otherDevice), 1, 2, false));
String newVersionId = mockNewVersion(item);
// Deleting the profile would fail after the device is gone, and every Retry the same way: nothing is touched.
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package profile' is used by 1 other device(s)")
.hasMessageContaining("Nothing was removed");
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_defaultProfile_refusedBeforeRemoving() {
mockTenant();
DeviceProfile profile = packageProfile(true);
IotHubInstalledItem item = devicePackage(profile.getId());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(), 0, 0, false));
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package profile' is the default device profile");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void removeDevicePackageEntities_profileUsedOnlyByThePackageDevice_removed() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceProfile profile = packageProfile(false);
IotHubInstalledItem item = devicePackage(profile.getId(), device.getId());
when(deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(eq(tenantId), eq(profile.getId()), any()))
.thenReturn(new PageData<>(List.of(device.getId()), 1, 1, false));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
String newVersionId = mockNewVersion(item);
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
verify(tbDeviceService).delete(device, user);
verify(tbDeviceProfileService).delete(profile, user);
}
private DeviceProfile packageProfile(boolean isDefault) {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
profile.setTenantId(tenantId);
profile.setName("Package profile");
profile.setDefault(isDefault);
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
return profile;
}
@Test
void removeDevicePackageEntities_converterUsedByAnotherIntegration_refusedBeforeRemoving() {
mockTenant();
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
converter.setTenantId(tenantId);
converter.setName("Package converter");
Integration own = new Integration(new IntegrationId(UUID.randomUUID()));
Integration other = new Integration(new IntegrationId(UUID.randomUUID()));
other.setName("Another integration");
IotHubInstalledItem item = devicePackage(converter.getId(), own.getId());
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
when(integrationService.findIntegrationsByConverterId(tenantId, converter.getId())).thenReturn(List.of(own, other));
String newVersionId = mockNewVersion(item);
assertThatThrownBy(() -> service.removeDevicePackageEntities(user, item.getId(), newVersionId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("'Package converter' is used by the integration 'Another integration'");
verify(iotHubInstalledItemService, never()).save(any(), any());
}
private IotHubInstalledItem devicePackage(EntityId... created) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(created));
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);
return item;
}
private String mockNewVersion(IotHubInstalledItem item) {
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
return newVersionId;
}
@Test
void removeDevicePackageEntities_entityUsedAsItWas_neitherRemovedNorTracked() throws Exception {
mockTenant();

Loading…
Cancel
Save