Browse Source

address the second review pass on the install validation

- the dialog no longer mistakes a MISSING plan entry for the failing one:
  such entries carry an error message of their own with no name, so the
  lookup now also requires the WILL_INSTALL status
- the whole dependency sentence lives in the locale bundle as one key
  with a name and an error parameter, instead of a fragment glued to the
  server message, and the partial rollback warning is appended as its own
  paragraph by the dialog rather than relying on the details ending with
  a blank line
- a rule chain is validated under the type from the rule chain file too,
  so an EDGE chain is no longer looked up among the CORE ones
- names are deduplicated before the lookup rather than when formatting,
  so a template repeating a name queries once
- the entity type and the name come from the definition itself for the
  five lists that carry both, which removes the pairing hazard
- ExceptionUtil.getMessage replaces the hand-rolled fallback, and the
  single-use firstOrNull helper is inlined
- the dashboard check moved after the device one to match the provision
  order the comment claims, and the unreachable empty-list guard is gone
- tests cover both profile types, edges, the rule chain type and its two
  unresolvable-name branches, the deduplicated lookup and a json file
  holding null
pull/16117/head
dpinkevych 3 months ago
parent
commit
f8b190691a
Failed to extract signature
  1. 10
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  2. 130
      application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java
  3. 88
      application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java
  4. 14
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts
  5. 2
      ui-ngx/src/assets/locale/locale.constant-en_US.json

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

@ -20,8 +20,8 @@ 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.StringUtils;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.DeviceProfile;
@ -1007,15 +1007,13 @@ public class DefaultIotHubService implements IotHubService {
} catch (Exception e) {
log.error("[{}] Cascade install failed at entry {} ({}): {}", tenantId,
entry.getName(), entry.getVersionId(), e.getMessage(), e);
// an exception without a message would leave both the entry and the result blank,
// and the dialog would have nothing to name the failing entry by
String failure = StringUtils.isEmpty(e.getMessage()) ? e.getClass().getSimpleName() : e.getMessage();
resultEntry.setErrorMessage(failure);
String failureMessage = ExceptionUtil.getMessage(e);
resultEntry.setErrorMessage(failureMessage);
resultEntries.add(resultEntry);
boolean rolledBack = rollbackInstalledItems(user, rollbackIds);
result.setSuccess(false);
result.setRolledBack(rolledBack);
result.setErrorMessage(failure);
result.setErrorMessage(failureMessage);
result.setEntries(resultEntries);
result.setMissingItemIds(missingItemIds);
return result;

130
application/src/main/java/org/thingsboard/server/service/solutions/DefaultSolutionService.java

@ -126,6 +126,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;
@ -183,7 +184,7 @@ 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_NAME_PLACEHOLDER_PREFIX = "$random";
private static final String RANDOM_PLACEHOLDER = "$random";
@Value("${ui.solution_templates.docs_base_url:https://thingsboard.io/docs}")
private String docsBaseUrl;
@ -323,32 +324,23 @@ public class DefaultSolutionService implements SolutionService {
// Insertion ordered, so that the reported sections keep the order the entities are provisioned in.
Map<EntityType, List<HasName>> conflicts = new LinkedHashMap<>();
collectConflicts(conflicts, EntityType.RULE_CHAIN, ruleChains, definition -> ruleChainName(tempDir, definition),
name -> firstOrNull(ruleChainService.findTenantRuleChainsByTypeAndName(tenantId, RuleChainType.CORE, name)));
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, EntityType.CUSTOMER, customers, CustomerDefinition::getName,
title -> isRandomizedAtInstall(title) ? null : customerService.findCustomerByTenantIdAndTitle(tenantId, title).orElse(null));
collectConflicts(conflicts, EntityType.DASHBOARD, dashboards, DashboardDefinition::getName,
title -> dashboardService.findFirstDashboardInfoByTenantIdAndName(tenantId, title));
collectConflicts(conflicts, EntityType.ASSET, assets, AssetDefinition::getName,
name -> assetService.findAssetByTenantIdAndName(tenantId, name));
collectConflicts(conflicts, EntityType.DEVICE, devices, DeviceDefinition::getName,
name -> deviceService.findDeviceByTenantIdAndName(tenantId, name));
collectConflicts(conflicts, EntityType.EDGE, edges, EdgeDefinition::getName,
name -> edgeService.findEdgeByTenantIdAndName(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 null;
}
StringBuilder details = new StringBuilder(CONFLICTS_INTRO).append(BLANK_LINE);
conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType,
entities.stream().map(HasName::getName).map(DefaultSolutionService::quoted).toList()));
// the dialog appends its own sentences to these details, so the list has to end with a blank line
details.append(System.lineSeparator());
conflicts.forEach((entityType, entities) -> appendConflicts(details, entityType, entities));
SolutionInstallResponse solutionInstallResponse = new SolutionInstallResponse();
solutionInstallResponse.setSuccess(false);
@ -356,65 +348,91 @@ public class DefaultSolutionService implements SolutionService {
return solutionInstallResponse;
}
/**
* 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<EntityType, List<HasName>> conflicts, List<? extends EntityDefinition> definitions,
Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (EntityDefinition definition : definitions) {
if (checked.add(definition.getName())) {
collectConflict(conflicts, definition.getEntityType(), definition.getName(), lookup);
}
}
}
private <T> void collectConflicts(Map<EntityType, List<HasName>> conflicts, EntityType entityType, List<T> definitions,
Function<T, String> nameExtractor, Function<String, ? extends HasName> lookup) {
Set<String> checked = new HashSet<>();
for (T definition : definitions) {
String name = nameExtractor.apply(definition);
if (StringUtils.isEmpty(name)) {
if (checked.add(name)) {
collectConflict(conflicts, entityType, name, lookup);
}
}
}
private void collectConflict(Map<EntityType, List<HasName>> conflicts, EntityType entityType, String name,
Function<String, ? extends HasName> lookup) {
if (StringUtils.isEmpty(name)) {
return;
}
HasName existing = lookup.apply(name);
if (existing != null) {
conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing);
}
}
/**
* 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<EntityType, List<HasName>> conflicts, TenantId tenantId, Path tempDir,
List<ReferenceableEntityDefinition> definitions) {
Set<String> 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;
}
HasName existing = lookup.apply(name);
if (existing != null) {
conflicts.computeIfAbsent(entityType, key -> new ArrayList<>()).add(existing);
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, so those are looked up as is - skipping them
* here would let the install die on a DB constraint again.
* every other entity are used as written, placeholder included, and must be looked up as is.
*/
private static boolean isRandomizedAtInstall(String name) {
return name.contains(RANDOM_NAME_PLACEHOLDER_PREFIX);
private static boolean isRandomizedCustomerTitle(String title) {
return title.contains(RANDOM_PLACEHOLDER);
}
/**
* 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.
*/
private void appendConflicts(StringBuilder details, EntityType entityType, List<String> conflictDescriptions) {
if (conflictDescriptions.isEmpty()) {
return;
}
private void appendConflicts(StringBuilder details, EntityType entityType, List<HasName> entities) {
details.append("- **").append(entityType.getNormalName()).append("**: ")
.append(conflictDescriptions.stream().distinct().collect(Collectors.joining(", "))).append(System.lineSeparator());
}
private static String quoted(String value) {
return "'" + value + "'";
}
/**
* The provisioned rule chain takes its name from the rule chain file, not from the name in rule_chains.json,
* so the conflict has to be looked up under the name the install will actually create.
*/
private String ruleChainName(Path tempDir, ReferenceableEntityDefinition definition) {
if (StringUtils.isEmpty(definition.getFile())) {
return null;
}
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
return null;
}
JsonNode ruleChain = JacksonUtil.toJsonNode(ruleChainPath).get("ruleChain");
return ruleChain != null && ruleChain.hasNonNull("name") ? ruleChain.get("name").asText() : null;
}
private static <T> T firstOrNull(Collection<T> data) {
return data == null || data.isEmpty() ? null : data.iterator().next();
.append(entities.stream().map(entity -> "'" + entity.getName() + "'").collect(Collectors.joining(", ")))
.append(System.lineSeparator());
}
private SolutionInstallResponse doInstallSolution(User user, TenantId tenantId, String solutionId, Path tempDir, HttpServletRequest request) {

88
application/src/test/java/org/thingsboard/server/service/solutions/DefaultSolutionServiceTest.java

@ -24,13 +24,19 @@ 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.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.solution.SolutionInstallResponse;
@ -42,6 +48,8 @@ import java.util.Optional;
import java.util.UUID;
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;
@ -63,6 +71,12 @@ class DefaultSolutionServiceTest {
private DashboardService dashboardService;
@Mock
private RuleChainService ruleChainService;
@Mock
private DeviceProfileService deviceProfileService;
@Mock
private AssetProfileService assetProfileService;
@Mock
private EdgeService edgeService;
@InjectMocks
private DefaultSolutionService service;
@ -95,8 +109,6 @@ class DefaultSolutionServiceTest {
CONFLICTS_INTRO,
"- **Customer**: 'Existing customer'",
"- **Device**: 'Existing device'");
// the dialog appends its own sentences, so the details have to end with a blank line
assertThat(result.getDetails()).endsWith(System.lineSeparator() + System.lineSeparator());
// the randomized customer title and the entities that do not exist yet are not reported
assertThat(result.getDetails())
.doesNotContain("Customer $random")
@ -136,6 +148,78 @@ class DefaultSolutionServiceTest {
.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);
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
assertThat(result).isNotNull();
assertThat(result.getDetails().lines().toList()).containsSubsequence(
"- **Device profile**: 'thermostat'",
"- **Asset profile**: 'building'",
"- **Edge**: 'Main edge'");
}
@Test
void testValidateSolutionLooksTheSameNameUpOnce() throws IOException {
writeEntitiesFile("devices.json", "[{\"name\": \"Sensor\"}, {\"name\": \"Sensor\"}]");
Device device = new Device();
device.setName("Sensor");
when(deviceService.findDeviceByTenantIdAndName(tenantId, "Sensor")).thenReturn(device);
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
assertThat(result.getDetails().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)).isNull();
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));
SolutionInstallResponse result = service.validateSolution(tenantId, tempDir);
assertThat(result.getDetails().lines().toList()).contains("- **Rule chain**: 'Edge chain'");
}
@Test
void testValidateSolutionTreatsAJsonNullFileAsEmpty() throws IOException {
writeEntitiesFile("devices.json", "null");
assertThat(service.validateSolution(tenantId, tempDir)).isNull();
verifyNoInteractions(deviceService);
}
@Test
void testValidateSolutionWithoutConflicts() throws IOException {
writeEntitiesFile("devices.json", "[{\"name\": \"New device\"}]");

14
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-install-dialog.component.ts

@ -346,19 +346,21 @@ export class TbIotHubInstallDialogComponent extends DialogComponent<TbIotHubInst
this.state = 'error';
const serverError = result.errorMessage;
let message = serverError || this.translate.instant('iot-hub.install-error', { name: this.item.name });
// The title already names the item being installed, so only a failing dependency has to be named
// here - and only when the server reported the failure, since the fallback above names the root.
const failedDependency = serverError
? (result.entries ?? []).find(entry => !entry.root && entry.errorMessage) : undefined;
// The title already names the item being installed, so only a failing dependency has to be named here, and
// only when the server reported the failure - the fallback above names the root. A missing entry carries an
// error message of its own, so the failing one is the entry the cascade actually tried to install.
const failedDependency = serverError ? (result.entries ?? []).find(
entry => !entry.root && entry.errorMessage && entry.status === InstallPlanEntryStatus.WILL_INSTALL) : undefined;
if (failedDependency) {
message = this.translate.instant('iot-hub.install-dependency-error', { name: failedDependency.name }) + ' ' + message;
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 += '\n\n' + this.translate.instant('iot-hub.install-rollback-partial');
}
this.errorMessage = message;
return;

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

@ -4337,7 +4337,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}}':",
"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.",

Loading…
Cancel
Save