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 bb57ceab5d..2a245832da 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 @@ -7,6 +7,7 @@ import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.Dashboard; @@ -993,12 +994,13 @@ public class DefaultIotHubService implements IotHubService { } catch (Exception e) { log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId, entry.getName(), entry.getVersionId(), e.getMessage(), e); - resultEntry.setErrorMessage(e.getMessage()); + String failureMessage = ExceptionUtil.getMessage(e); + resultEntry.setErrorMessage(failureMessage); resultEntries.add(resultEntry); boolean rolledBack = rollbackInstalledItems(user, rollbackIds); result.setSuccess(false); result.setRolledBack(rolledBack); - result.setErrorMessage("Failed to install '" + entry.getName() + "': " + e.getMessage()); + result.setErrorMessage(failureMessage); result.setEntries(resultEntries); result.setMissingItemIds(missingItemIds); return result; diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java index 1a279b109c..e587661fc8 100644 --- a/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java @@ -19,7 +19,6 @@ import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Customer; -import org.thingsboard.server.common.data.DashboardInfo; import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.alarm.AlarmInfo; @@ -30,7 +29,6 @@ import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.kv.BaseDeleteTsKvQuery; import org.thingsboard.server.common.data.kv.DeleteTsKvQuery; -import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.TimePageLink; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.StringUtils; @@ -102,6 +100,7 @@ import org.thingsboard.server.service.solutions.data.DashboardLinkInfo; import org.thingsboard.server.service.solutions.data.DeviceCredentialsInfo; import org.thingsboard.server.service.solutions.data.EdgeLinkInfo; import org.thingsboard.server.service.solutions.data.SolutionInstallContext; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; import org.thingsboard.server.service.solutions.data.UserCredentialsInfo; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.thingsboard.server.service.solutions.data.definition.AssetDefinition; @@ -115,6 +114,7 @@ import org.thingsboard.server.service.solutions.data.definition.UserDefinition; import org.thingsboard.server.service.solutions.data.definition.DashboardDefinition; import org.thingsboard.server.service.solutions.data.definition.DeviceProfileDefinition; import org.thingsboard.server.service.solutions.data.definition.EdgeDefinition; +import org.thingsboard.server.service.solutions.data.definition.EntityDefinition; import org.thingsboard.server.service.solutions.data.definition.RelationDefinition; import org.thingsboard.server.service.solutions.data.definition.ReferenceableEntityDefinition; import org.thingsboard.server.service.solutions.data.definition.TenantDefinition; @@ -144,8 +144,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ExecutorService; @@ -166,6 +168,14 @@ import java.util.zip.ZipInputStream; @Slf4j public class DefaultSolutionService implements SolutionService { + private static final String BLANK_LINE = System.lineSeparator() + System.lineSeparator(); + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + private static final String RANDOM_PLACEHOLDER = "$random"; + private static final int MAX_LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + MAX_LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; + @Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}") private String docsBaseUrl; @@ -237,9 +247,9 @@ public class DefaultSolutionService implements SolutionService { throw new IllegalArgumentException("Solution template is missing solution.json or its 'title' field"); } - SolutionInstallResponse validateResult = validateSolution(tenantId, tempDir); - if (validateResult != null && !validateResult.isSuccess()) { - return validateResult; + SolutionValidationResult validation = validateSolution(tenantId, tempDir); + if (!validation.isPassed()) { + return conflictResponse(validation.getConflictReport()); } return doInstallSolution(user, tenantId, solutionId, tempDir, request); } finally { @@ -280,73 +290,159 @@ public class DefaultSolutionService implements SolutionService { } } - private SolutionInstallResponse validateSolution(TenantId tenantId, Path tempDir) { - Map> alreadyExistingEntities = new HashMap<>(); - - //TODO: check other entities. + SolutionValidationResult validateSolution(TenantId tenantId, Path tempDir) { + //TODO: pre-validate what still only fails at provision time: customer users (unique by email), + // alarm rules and calculated fields. List ruleChains = loadListOfEntitiesIfFileExists(tempDir, "rule_chains.json", new TypeReference<>() { }); - if (!ruleChains.isEmpty()) { - for (ReferenceableEntityDefinition ruleChain : ruleChains) { - List savedRuleChains = ruleChainService.findTenantRuleChainsByType(tenantId, RuleChainType.CORE, new PageLink(1, 0, ruleChain.getName())).getData(); - if (savedRuleChains != null && !savedRuleChains.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.RULE_CHAIN, key -> new ArrayList<>()).add(savedRuleChains.get(0)); - } - } - } - List deviceProfiles = loadListOfEntitiesIfFileExists(tempDir, "device_profiles.json", new TypeReference<>() { }); deviceProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "device_profiles", DeviceProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!deviceProfiles.isEmpty()) { - for (DeviceProfile deviceProfile : deviceProfiles) { - DeviceProfile savedProfile = deviceProfileService.findDeviceProfileByName(tenantId, deviceProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.DEVICE_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } - } - } - List assetProfiles = loadListOfEntitiesIfFileExists(tempDir, "asset_profiles.json", new TypeReference<>() { }); assetProfiles.addAll(loadListOfEntitiesFromDirectory(tempDir, "asset_profiles", AssetProfileDefinition.class)); - // Validate that entities with such name does not exist entities - if (!assetProfiles.isEmpty()) { - for (AssetProfile assetProfile : assetProfiles) { - AssetProfile savedProfile = assetProfileService.findAssetProfileByName(tenantId, assetProfile.getName()); - if (savedProfile != null) { - alreadyExistingEntities.computeIfAbsent(EntityType.ASSET_PROFILE, key -> new ArrayList<>()).add(savedProfile); - } + List customers = loadListOfEntitiesIfFileExists(tempDir, "customers.json", new TypeReference<>() { + }); + List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { + }); + List assets = loadListOfEntitiesIfFileExists(tempDir, "assets.json", new TypeReference<>() { + }); + List devices = loadListOfEntitiesIfFileExists(tempDir, "devices.json", new TypeReference<>() { + }); + List edges = loadListOfEntitiesIfFileExists(tempDir, "edges.json", new TypeReference<>() { + }); + + // Insertion ordered, so that the reported sections keep the order the entities are provisioned in. + Map> conflicts = new LinkedHashMap<>(); + collectRuleChainConflicts(conflicts, tenantId, tempDir, ruleChains); + collectConflicts(conflicts, EntityType.DEVICE_PROFILE, deviceProfiles, DeviceProfile::getName, + name -> deviceProfileService.findDeviceProfileByName(tenantId, name)); + collectConflicts(conflicts, EntityType.ASSET_PROFILE, assetProfiles, AssetProfile::getName, + name -> assetProfileService.findAssetProfileByName(tenantId, name)); + collectConflicts(conflicts, customers, + title -> isRandomizedCustomerTitle(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null)); + collectConflicts(conflicts, assets, name -> assetService.findAssetByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, devices, name -> deviceService.findDeviceByTenantIdAndName(tenantId, name)); + collectConflicts(conflicts, dashboards, title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title)); + collectConflicts(conflicts, edges, name -> edgeService.findEdgeByTenantIdAndName(tenantId, name)); + + if (conflicts.isEmpty()) { + return SolutionValidationResult.passed(); + } + StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE); + conflicts.forEach((entityType, conflictDescriptions) -> appendConflicts(details, entityType, conflictDescriptions)); + if (conflicts.values().stream().anyMatch(descriptions -> descriptions.size() > MAX_LISTED_NAMES_PER_TYPE)) { + details.append(System.lineSeparator()).append(TRUNCATION_NOTE); + } + + return SolutionValidationResult.conflictsFound(details.toString()); + } + + private static SolutionInstallResponse conflictResponse(String conflictReport) { + SolutionInstallResponse response = new SolutionInstallResponse(); + response.setSuccess(false); + response.setDetails(conflictReport); + return response; + } + + /** + * The entity type and the name both come from the definition, so a list can not end up checked against the + * wrong type by mistake. + */ + private void collectConflicts(Map> conflicts, List definitions, + Function lookup) { + Set checked = new HashSet<>(); + for (EntityDefinition definition : definitions) { + if (checked.add(definition.getName())) { + collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup); } } + } - List dashboards = loadListOfEntitiesIfFileExists(tempDir, "dashboards.json", new TypeReference<>() { - }); - if (!dashboards.isEmpty()) { - for (DashboardDefinition dashboard : dashboards) { - List savedDashboards = dashboardService.findDashboardsByTenantId(tenantId, new PageLink(1, 0, dashboard.getName())).getData(); - if (savedDashboards != null && !savedDashboards.isEmpty()) { - alreadyExistingEntities.computeIfAbsent(EntityType.DASHBOARD, key -> new ArrayList<>()).add(savedDashboards.get(0)); - } + private void collectConflicts(Map> conflicts, EntityType entityType, List definitions, + Function nameExtractor, Function lookup) { + Set checked = new HashSet<>(); + for (T definition : definitions) { + String name = nameExtractor.apply(definition); + if (checked.add(name)) { + collectConflict(conflicts, entityType, name, lookup); } } - if (!alreadyExistingEntities.isEmpty()) { - SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse(); - StringBuilder detailsBuilder = new StringBuilder(); - detailsBuilder.append("## Validation failed").append(System.lineSeparator()).append(System.lineSeparator()); - alreadyExistingEntities.forEach((type, list) -> detailsBuilder.append("The following **").append(getTypeLabel(type)).append("** entities already exist: ") - .append(list.stream().map(HasName::getName).map(name -> "'" + name + "'").collect(Collectors.joining(","))).append(";") - .append(System.lineSeparator()).append(System.lineSeparator())); - solutionInstallResponse.setSuccess(false); - solutionInstallResponse.setDetails(detailsBuilder.toString()); - return solutionInstallResponse; - } else { - return null; + } + + private void collectConflict(Map> conflicts, EntityType entityType, String name, + Function lookup) { + if (StringUtils.isEmpty(name)) { + return; + } + HasName existing = lookup.apply(name); + if (existing != null) { + conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(quoted(existing.getName())); + } + } + + /** + * A rule chain is created from the rule chain file, so both the name and the type of the chain the install will + * produce live there - the name in rule_chains.json is only a reference and the type defaults to CORE. + */ + private void collectRuleChainConflicts(Map> conflicts, TenantId tenantId, Path tempDir, + List definitions) { + Set checked = new HashSet<>(); + for (ReferenceableEntityDefinition definition : definitions) { + if (StringUtils.isEmpty(definition.getFile())) { + continue; + } + Path ruleChainPath = tempDir.resolve("rule_chains").resolve(definition.getFile()); + if (!Files.exists(ruleChainPath)) { + // provisionRuleChains logs and skips such a definition, so there is nothing to validate + continue; + } + JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain"); + if (ruleChain == null || !ruleChain.hasNonNull("name")) { + continue; + } + RuleChainType type = ruleChain.hasNonNull("type") + ? RuleChainType.valueOf(ruleChain.get("type").asText()) : RuleChainType.CORE; + String name = ruleChain.get("name").asText(); + if (!checked.add(type + name)) { + continue; + } + collectConflict(conflicts, EntityType.RULE_CHAIN, name, + ignored -> ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, type, name) + .stream().findFirst().orElse(null)); } } + /** + * Only customer titles, user names and attribute values go through {@link #randomize}, so a {@code $random} + * placeholder in a customer title is replaced at install time and there is nothing to check upfront. Names of + * every other entity are used as written, placeholder included, and must be looked up as is. + */ + private static boolean isRandomizedCustomerTitle(String title) { + return title.contains(RANDOM_PLACEHOLDER); + } + + private static String quoted(String value) { + return "'" + value + "'"; + } + + /** + * One markdown list item per entity type, so that the names of the conflicting entities are what the user reads, + * instead of the same sentence repeated for every type. Only the first {@value #MAX_LISTED_NAMES_PER_TYPE} + * names of a type are listed, the rest are counted - {@link #TRUNCATION_NOTE} tells the user that the list of + * that type is not complete. + */ + private static void appendConflicts(StringBuilder details, EntityType entityType, List conflictDescriptions) { + details.append("- **").append(entityType.getNormalName()).append("**: ") + .append(conflictDescriptions.stream().limit(MAX_LISTED_NAMES_PER_TYPE).collect(Collectors.joining(", "))); + if (conflictDescriptions.size() > MAX_LISTED_NAMES_PER_TYPE) { + details.append(" and ").append(conflictDescriptions.size() - MAX_LISTED_NAMES_PER_TYPE) + .append(" more (").append(conflictDescriptions.size()).append(" in total)"); + } + details.append(System.lineSeparator()); + } + private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) { SolutionInstallContext ctx = new SolutionInstallContext(tenantId, solutionId, tempDir, user, new TenantSolutionTemplateInstructions()); @@ -1442,10 +1538,6 @@ public class DefaultSolutionService implements SolutionService { return String.valueOf(now.toInstant().toEpochMilli()); } - private String getTypeLabel(EntityType type) { - return type.name().toLowerCase().replace('_', ' '); - } - private T loadEntityIfFileExists(Path tempDir, String fileName, Class clazz) { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { @@ -1459,7 +1551,7 @@ public class DefaultSolutionService implements SolutionService { Path filePath = tempDir.resolve("entities").resolve(fileName); if (Files.exists(filePath)) { try { - return JacksonUtil.readValue(filePath.toFile(), typeReference); + return Objects.requireNonNullElseGet(JacksonUtil.readValue(filePath.toFile(), typeReference), ArrayList::new); } catch (Exception e) { throw new IllegalArgumentException("Invalid json file " + fileName + " data structure", e); } diff --git a/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java new file mode 100644 index 0000000000..4b6b07c54b --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/solutions/data/SolutionValidationResult.java @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.solutions.data; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +/** + * The outcome of validating a solution template before anything is created: either the install can go ahead, or the + * entities of the tenant the template clashes with, reported as the markdown the install dialog renders. + */ +@Getter +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +public class SolutionValidationResult { + + private static final SolutionValidationResult PASSED = new SolutionValidationResult(true, ""); + + private final boolean passed; + private final String conflictReport; + + public static SolutionValidationResult passed() { + return PASSED; + } + + public static SolutionValidationResult conflictsFound(String conflictReport) { + return new SolutionValidationResult(false, conflictReport); + } + +} 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 e0efa4575b..7ac28ffdb5 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 @@ -331,6 +331,64 @@ class DefaultIotHubServiceTest { inOrder.verify(service).deleteInstalledItem(user, dep1Item.getId()); } + @Test + void installPlan_errorMessageIsTheFailureItselfWithoutAnyPrefix() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the sentence around the failure belongs to the dialog, which localizes it + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + } + + @Test + void installPlan_dependencyFails_failureIsReportedOnTheEntryAndAsTheResultMessage() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String depVersionId = UUID.randomUUID().toString(); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry dep = willInstall(depVersionId, false); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new IllegalStateException("install failed")).when(service).doInstallVersion(eq(user), eq(depVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(dep, root)), null, request); + + // the dialog names the failing dependency itself, from the entry it finds in the result + assertThat(result.getErrorMessage()).isEqualTo("install failed"); + assertThat(result.getEntries()).anySatisfy(entry -> { + assertThat(entry.getName()).isEqualTo("Dep"); + assertThat(entry.isRoot()).isFalse(); + assertThat(entry.getErrorMessage()).isEqualTo("install failed"); + }); + verify(service, never()).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + } + + @Test + void installPlan_failureWithoutMessage_reportsTheExceptionType() throws Exception { + mockTenant(); + HttpServletRequest request = mock(HttpServletRequest.class); + String rootVersionId = UUID.randomUUID().toString(); + InstallPlanEntry root = willInstall(rootVersionId, true); + + when(iotHubInstalledItemService.findInstalledItemIdsByTenantIdAndItemIdIn(eq(tenantId), any())).thenReturn(List.of()); + doThrow(new NullPointerException()).when(service).doInstallVersion(eq(user), eq(rootVersionId), any(), any()); + + InstallPlanResult result = service.installPlan(user, new InstallPlan(rootVersionId, List.of(root)), null, request); + + // the dialog looks the failing entry up by its error message, so it must never be blank + assertThat(result.getErrorMessage()).isEqualTo("NullPointerException"); + assertThat(result.getEntries()).allSatisfy(entry -> + assertThat(entry.getErrorMessage()).isEqualTo("NullPointerException")); + } + @Test void installPlan_rollbackFailure_reportsNotFullyRolledBack() throws Exception { mockTenant(); diff --git a/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java new file mode 100644 index 0000000000..d65868a7fb --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java @@ -0,0 +1,294 @@ +// SPDX-FileCopyrightText: Copyright The Thingsboard Authors +// SPDX-License-Identifier: Apache-2.0 +package org.thingsboard.server.service.solutions; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.Customer; +import org.thingsboard.server.common.data.DashboardInfo; +import org.thingsboard.server.common.data.Device; +import org.thingsboard.server.common.data.DeviceProfile; +import org.thingsboard.server.common.data.asset.Asset; +import org.thingsboard.server.common.data.asset.AssetProfile; +import org.thingsboard.server.common.data.edge.Edge; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.rule.RuleChain; +import org.thingsboard.server.common.data.rule.RuleChainType; +import org.thingsboard.server.dao.asset.AssetProfileService; +import org.thingsboard.server.dao.asset.AssetService; +import org.thingsboard.server.dao.customer.CustomerService; +import org.thingsboard.server.dao.dashboard.DashboardService; +import org.thingsboard.server.dao.device.DeviceProfileService; +import org.thingsboard.server.dao.device.DeviceService; +import org.thingsboard.server.dao.edge.EdgeService; +import org.thingsboard.server.dao.rule.RuleChainService; +import org.thingsboard.server.service.solutions.data.SolutionValidationResult; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DefaultSolutionServiceTest { + + private static final String CONFLICTS_INTRO = + "Some entities of the solution template already exist. Rename or delete them and install the template again:"; + // mirrors DefaultSolutionService.MAX_LISTED_NAMES_PER_TYPE and the note that goes with it + private static final int LISTED_NAMES_PER_TYPE = 10; + private static final String TRUNCATION_NOTE = "Only the first " + LISTED_NAMES_PER_TYPE + + " names of each type are listed. The rest are reported the next time the template is installed."; + + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + + @Mock + private CustomerService customerService; + @Mock + private DeviceService deviceService; + @Mock + private AssetService assetService; + @Mock + private DashboardService dashboardService; + @Mock + private RuleChainService ruleChainService; + @Mock + private DeviceProfileService deviceProfileService; + @Mock + private AssetProfileService assetProfileService; + @Mock + private EdgeService edgeService; + + @InjectMocks + private DefaultSolutionService service; + + @TempDir + private Path tempDir; + + @Test + void testValidateSolutionNamesEveryConflictingEntity() throws IOException { + writeEntitiesFile("customers.json", "[{\"name\": \"Existing customer\"}, {\"name\": \"Customer $random\"}]"); + writeEntitiesFile("devices.json", "[{\"name\": \"Existing device\"}, {\"name\": \"New device\"}]"); + writeEntitiesFile("assets.json", "[{\"name\": \"Existing asset\"}, {\"name\": \"New asset\"}]"); + + Customer customer = new Customer(); + customer.setTitle("Existing customer"); + + when(customerService.findCustomerByTenantIdAndTitle(tenantId, "Existing customer")).thenReturn(Optional.of(customer)); + Asset asset = new Asset(); + asset.setName("Existing asset"); + when(assetService.findAssetByTenantIdAndName(tenantId, "Existing asset")).thenReturn(asset); + when(assetService.findAssetByTenantIdAndName(tenantId, "New asset")).thenReturn(null); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Existing device")) + .thenReturn(existingDevice("Existing device")); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence( + CONFLICTS_INTRO, + "- **Customer**: 'Existing customer'", + "- **Asset**: 'Existing asset'", + "- **Device**: 'Existing device'"); + // the randomized customer title and the entities that do not exist yet are not reported + assertThat(result.getConflictReport()) + .doesNotContain("Customer $random") + .doesNotContain("New device") + .doesNotContain("New asset"); + } + + @Test + void testValidateSolutionReportsConflictingDashboard() throws IOException { + writeEntitiesFile("dashboards.json", "[{\"name\": \"Overview\", \"file\": \"overview.json\"}]"); + + DashboardInfo dashboard = new DashboardInfo(); + dashboard.setTitle("Overview"); + when(dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, "Overview")).thenReturn(dashboard); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Dashboard**: 'Overview'"); + } + + @Test + void testValidateSolutionUsesTheRuleChainNameFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Name in the definition\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Name the install creates\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Name the install creates"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, "Name the install creates")) + .thenReturn(List.of(ruleChain)); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()) + .containsSubsequence(CONFLICTS_INTRO, "- **Rule chain**: 'Name the install creates'"); + } + + @Test + void testValidateSolutionReportsConflictingProfilesAndEdge() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"thermostat\"}]"); + writeEntitiesFile("asset_profiles.json", "[{\"name\": \"building\"}]"); + writeEntitiesFile("edges.json", "[{\"name\": \"Main edge\"}]"); + + DeviceProfile deviceProfile = new DeviceProfile(); + deviceProfile.setName("thermostat"); + AssetProfile assetProfile = new AssetProfile(); + assetProfile.setName("building"); + Edge edge = new Edge(); + edge.setName("Main edge"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "thermostat")).thenReturn(deviceProfile); + when(assetProfileService.findAssetProfileByName(tenantId, "building")).thenReturn(assetProfile); + when(edgeService.findEdgeByTenantIdAndName(tenantId, "Main edge")).thenReturn(edge); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.isPassed()).isFalse(); + assertThat(result.getConflictReport().lines().toList()).containsSubsequence( + "- **Device profile**: 'thermostat'", + "- **Asset profile**: 'building'", + "- **Edge**: 'Main edge'"); + } + + @Test + void testValidateSolutionLooksTheSameNameUpOnce() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]"); + + when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(existingDevice("Sensor")); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: 'Sensor'"); + verify(deviceService, times(1)).findDeviceByTenantIdAndName(tenantId, "Sensor"); + } + + @Test + void testValidateSolutionSkipsRuleChainsWithoutAResolvableName() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"No file\", \"file\": \"missing.json\"}," + + "{\"name\": \"No name inside\", \"file\": \"nameless.json\"}]"); + writeFile("rule_chains/nameless.json", "{\"ruleChain\": {}}"); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(ruleChainService); + } + + @Test + void testValidateSolutionUsesTheRuleChainTypeFromTheRuleChainFile() throws IOException { + writeEntitiesFile("rule_chains.json", "[{\"name\": \"Edge chain\", \"file\": \"rc.json\"}]"); + writeFile("rule_chains/rc.json", "{\"ruleChain\": {\"name\": \"Edge chain\", \"type\": \"EDGE\"}}"); + + RuleChain ruleChain = new RuleChain(); + ruleChain.setName("Edge chain"); + when(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.EDGE, "Edge chain")) + .thenReturn(List.of(ruleChain)); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Rule chain**: 'Edge chain'"); + } + + @Test + void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException { + writeEntitiesFile("devices.json", "null"); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(deviceService); + } + + @ParameterizedTest + @ValueSource(ints = {LISTED_NAMES_PER_TYPE, LISTED_NAMES_PER_TYPE + 1, LISTED_NAMES_PER_TYPE + 2}) + void testValidateSolutionListsAtMostTenNamesOfAType(int conflictCount) throws IOException { + List names = IntStream.rangeClosed(1, conflictCount).mapToObj(i -> "Sensor " + i).toList(); + writeEntitiesFile("devices.json", names.stream() + .map(name -> "{\"name\": \"" + name + "\"}") + .collect(Collectors.joining(",", "[", "]"))); + names.forEach(name -> when(deviceService.findDeviceByTenantIdAndName(tenantId, name)) + .thenReturn(existingDevice(name))); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + int hidden = conflictCount - LISTED_NAMES_PER_TYPE; + String listed = names.stream().limit(LISTED_NAMES_PER_TYPE) + .map(name -> "'" + name + "'").collect(Collectors.joining(", ")); + assertThat(result.getConflictReport().lines().toList()).contains("- **Device**: " + listed + + (hidden > 0 ? " and " + hidden + " more (" + conflictCount + " in total)" : "")); + if (hidden > 0) { + assertThat(result.getConflictReport()).contains(TRUNCATION_NOTE); + } else { + assertThat(result.getConflictReport()).doesNotContain(TRUNCATION_NOTE); + } + } + + /** + * The profile lists are the json file plus every file in the directory of the same name merged into one list, so + * this is where the same name genuinely can appear twice. + */ + @Test + void testValidateSolutionChecksAProfileFromBothSourcesOnce() throws IOException { + writeEntitiesFile("device_profiles.json", "[{\"name\": \"Sensor profile\"}]"); + writeFile("device_profiles/sensor_profile.json", "{\"name\": \"Sensor profile\"}"); + + DeviceProfile profile = new DeviceProfile(); + profile.setName("Sensor profile"); + when(deviceProfileService.findDeviceProfileByName(tenantId, "Sensor profile")).thenReturn(profile); + + SolutionValidationResult result = service.validateSolution(tenantId, tempDir); + + assertThat(result.getConflictReport().lines().toList()).contains("- **Device profile**: 'Sensor profile'"); + verify(deviceProfileService, times(1)).findDeviceProfileByName(tenantId, "Sensor profile"); + } + + @Test + void testValidateSolutionWithoutConflicts() throws IOException { + writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]"); + when(deviceService.findDeviceByTenantIdAndName(tenantId, "New device")).thenReturn(null); + + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + } + + @Test + void testValidateSolutionWithoutEntityFiles() { + assertThat(service.validateSolution(tenantId, tempDir).isPassed()).isTrue(); + verifyNoInteractions(customerService, deviceService, assetService, dashboardService, ruleChainService, + deviceProfileService, assetProfileService, edgeService); + } + + private static Device existingDevice(String name) { + Device device = new Device(); + device.setName(name); + return device; + } + + private void writeFile(String relativePath, String content) throws IOException { + Path file = tempDir.resolve(relativePath); + Files.createDirectories(file.getParent()); + Files.writeString(file, content); + } + + private void writeEntitiesFile(String fileName, String content) throws IOException { + Path entitiesDir = Files.createDirectories(tempDir.resolve("entities")); + Files.writeString(entitiesDir.resolve(fileName), content); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html index e0745f549c..ca5f373996 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.html @@ -130,12 +130,14 @@ @case ('error') {

{{ 'iot-hub.install-error-title' | translate }}

{{ 'iot-hub.install-error-message' | translate:{ name: item.name } }}

- @if (item.type === ItemType.SOLUTION_TEMPLATE) { - - } @else { -
- {{ errorMessage }} -
+ @if (errorMessage) { + @if (item.type === ItemType.SOLUTION_TEMPLATE) { + + } @else { +
+ {{ errorMessage }} +
+ } } } } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts index 89214d628c..4c2fd30ab3 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts @@ -300,7 +300,7 @@ export class TbIotHubInstallDialogComponent extends DialogComponent { if (!result.success) { this.state = 'error'; - this.errorMessage = result.errorMessage || this.translate.instant('iot-hub.install-error', { name: this.item.name }); + this.errorMessage = result.errorMessage || ''; return; } this.handleInstalledDescriptor(result.descriptor); @@ -323,20 +323,31 @@ export class TbIotHubInstallDialogComponent extends DialogComponent !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined; + if (failedDependency) { + message = this.translate.instant('iot-hub.install-dependency-error', + { name: failedDependency.name, error: message }); + } // A failed cascade rolls back the items installed so far. When something was actually being // installed and the rollback came back partial (rolledBack === false), some entities are left // behind — tell the admin so they know manual cleanup may be needed. The willInstall guard // avoids the misleading warning on the "empty plan" failure, where nothing was installed. if (!result.rolledBack && this.planSummary.willInstall > 0) { - message += ' ' + this.translate.instant('iot-hub.install-rollback-partial'); + message = [message, this.translate.instant('iot-hub.install-rollback-partial')] + .filter(Boolean).join('\n\n'); } this.errorMessage = message; return; diff --git a/ui-ngx/src/assets/locale/locale.constant-en_US.json b/ui-ngx/src/assets/locale/locale.constant-en_US.json index f6da912a0a..423e79ba8f 100644 --- a/ui-ngx/src/assets/locale/locale.constant-en_US.json +++ b/ui-ngx/src/assets/locale/locale.constant-en_US.json @@ -4343,6 +4343,7 @@ "goto-main-dashboard": "Go to main dashboard", "install-error-title": "Installation Failed", "install-error-message": "Failed to install '{{name}}'.", + "install-dependency-error": "Failed to install the dependency '{{name}}': {{error}}", "install-plan-title": "Install '{{name}}' and its dependencies", "install-plan-will-install": "{{count}} item(s) will be installed.", "install-plan-will-update": "{{count}} item(s) already installed and will be skipped.",