Browse Source
IoT Hub: update a device package in place instead of deleting its devicepull/16536/head
committed by
GitHub
42 changed files with 4130 additions and 188 deletions
@ -0,0 +1,947 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ArrayNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import com.fasterxml.jackson.databind.node.TextNode; |
|||
import com.google.gson.JsonParser; |
|||
import lombok.RequiredArgsConstructor; |
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.springframework.stereotype.Service; |
|||
import org.springframework.transaction.support.TransactionTemplate; |
|||
import org.springframework.web.client.RestClientException; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.rule.engine.api.AttributesSaveRequest; |
|||
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.Device; |
|||
import org.thingsboard.server.common.data.DeviceProfile; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.HasName; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.HasVersion; |
|||
import org.thingsboard.server.common.data.audit.ActionType; |
|||
import org.thingsboard.server.common.data.converter.Converter; |
|||
import org.thingsboard.server.common.data.converter.ConverterType; |
|||
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; |
|||
import org.thingsboard.server.common.data.exception.ThingsboardException; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
import org.thingsboard.server.common.data.id.DeviceProfileId; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
import org.thingsboard.server.common.data.id.IntegrationId; |
|||
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; |
|||
import org.thingsboard.server.common.data.id.RuleChainId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; |
|||
import org.thingsboard.server.common.data.kv.AttributeKvEntry; |
|||
import org.thingsboard.server.common.data.page.PageData; |
|||
import org.thingsboard.server.common.data.page.PageLink; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.common.data.rule.RuleChainMetaData; |
|||
import org.thingsboard.server.common.data.security.DeviceCredentials; |
|||
import org.thingsboard.server.common.data.security.DeviceCredentialsType; |
|||
import org.thingsboard.server.common.data.subscription.SubscriptionException; |
|||
import org.thingsboard.server.dao.attributes.AttributesService; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceCredentialsService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
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.dao.subscription.PlatformFeature; |
|||
import org.thingsboard.server.dao.subscription.SubscriptionService; |
|||
import org.thingsboard.server.exception.DataValidationException; |
|||
import org.thingsboard.server.exception.EntitiesLimitExceededException; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; |
|||
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; |
|||
import org.thingsboard.server.service.rule.TbRuleChainService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.HashMap; |
|||
import java.util.HashSet; |
|||
import java.util.Iterator; |
|||
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.concurrent.ExecutionException; |
|||
import java.util.concurrent.TimeoutException; |
|||
import java.util.regex.Matcher; |
|||
import java.util.regex.Pattern; |
|||
|
|||
/** |
|||
* Applies an update of an installed device package in one transaction. The install wizard resolves the templates |
|||
* of the new version (the same way it installs them) and sends the entity of each step; this service checks the |
|||
* plan, saves every entity and the new version of the installed item together, and rolls all of it back on a |
|||
* failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a |
|||
* rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, |
|||
* are written after commit too. |
|||
*/ |
|||
@Service |
|||
@TbCoreComponent |
|||
@Slf4j |
|||
@RequiredArgsConstructor |
|||
public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { |
|||
|
|||
// Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id}
|
|||
private static final Map<String, String> STEP_ALIASES = Map.of( |
|||
"DEVICE_PROFILE", "deviceProfile", |
|||
"DEVICE", "device", |
|||
"GATEWAY", "gateway", |
|||
"DASHBOARD", "dashboard", |
|||
"RULE_CHAIN", "ruleChain", |
|||
"UPLINK_CONVERTER", "uplinkConverter", |
|||
"DOWNLINK_CONVERTER", "downlinkConverter", |
|||
"INTEGRATION", "integration"); |
|||
private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); |
|||
private static final String UNEXPECTED_ERROR = "Failed to update the device package"; |
|||
|
|||
private final IotHubInstalledItemService installedItemService; |
|||
private final IotHubRestClient iotHubRestClient; |
|||
private final IotHubService iotHubService; |
|||
private final DevicePackageEntities packageEntities; |
|||
private final DeviceProfileService deviceProfileService; |
|||
private final DeviceService deviceService; |
|||
private final DeviceCredentialsService deviceCredentialsService; |
|||
private final DashboardService dashboardService; |
|||
private final RuleChainService ruleChainService; |
|||
private final TbRuleChainService tbRuleChainService; |
|||
private final ConverterService converterService; |
|||
private final IntegrationService integrationService; |
|||
private final TbIntegrationService tbIntegrationService; |
|||
private final SubscriptionService subscriptionService; |
|||
private final AttributesService attributesService; |
|||
private final TelemetrySubscriptionService telemetryService; |
|||
private final TransactionTemplate transactionTemplate; |
|||
|
|||
@Override |
|||
public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) { |
|||
TenantId tenantId = user.getTenantId(); |
|||
DeviceInstalledItemDescriptor descriptor = findDevicePackage(tenantId, installedItemId).descriptor(); |
|||
Set<UUID> sharedIds = new HashSet<>(); |
|||
iotHubService.findKeptEntities(tenantId, installedItemId).getEntities().forEach(e -> sharedIds.add(e.getEntityId().getId())); |
|||
Map<UUID, EntityId> createdIds = createdIds(descriptor); |
|||
Map<UUID, Set<String>> recordedChecksums = recordedChecksums(tenantId); |
|||
|
|||
List<DevicePackageEntityState> states = new ArrayList<>(); |
|||
if (descriptor.getInstallState() == null) { |
|||
return states; |
|||
} |
|||
descriptor.getInstallState().forEach((stepName, state) -> { |
|||
EntityId entityId = DevicePackageEntities.entityIdOf(state, createdIds); |
|||
if (entityId == null || !DevicePackageEntities.CHECKSUM_TYPES.contains(entityId.getEntityType())) { |
|||
return; |
|||
} |
|||
DevicePackageEntities.Snapshot snapshot = packageEntities.load(tenantId, entityId); |
|||
JsonNode storedChecksum = state.get("checksum"); |
|||
// Changed by someone else only when no installed package recorded the current checksum: an update of another
|
|||
// package that shares the entity, e.g. a converter, records it only in its own row
|
|||
Boolean modified = snapshot == null || storedChecksum == null || !storedChecksum.isTextual() ? null : |
|||
!storedChecksum.asText().equals(snapshot.checksum()) |
|||
&& !recordedChecksums.getOrDefault(entityId.getId(), Set.of()).contains(snapshot.checksum()); |
|||
states.add(new DevicePackageEntityState(stepName, entityId, snapshot != null, |
|||
snapshot != null ? snapshot.version() : null, modified, sharedIds.contains(entityId.getId()))); |
|||
}); |
|||
return states; |
|||
} |
|||
|
|||
@Override |
|||
public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { |
|||
TenantId tenantId = user.getTenantId(); |
|||
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); |
|||
Applied applied; |
|||
try { |
|||
DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); |
|||
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); |
|||
if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { |
|||
throw new IllegalArgumentException("The version belongs to another item"); |
|||
} |
|||
validatePlan(devicePackage, request); |
|||
checkFeatures(tenantId, request); |
|||
validateIntegrations(tenantId, request); |
|||
applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); |
|||
} catch (StepFailure e) { |
|||
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepName, e.getCause()); |
|||
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepName); |
|||
} catch (RestClientException e) { |
|||
log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); |
|||
return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); |
|||
} catch (Exception e) { |
|||
log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); |
|||
return DeviceUpdateResult.error(userMessage(e), null); |
|||
} |
|||
afterCommit(user, tenantId, applied); |
|||
log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); |
|||
return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); |
|||
} |
|||
|
|||
private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { |
|||
IotHubInstalledItem installedItem = installedItemService.findById(tenantId, installedItemId); |
|||
if (installedItem == null || !"DEVICE".equals(installedItem.getItemType()) |
|||
|| !(installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor)) { |
|||
throw new IllegalArgumentException("Installed device package not found"); |
|||
} |
|||
return new DevicePackage(installedItem, descriptor); |
|||
} |
|||
|
|||
/** |
|||
* The update may only change what the package owns, or what the user confirmed. The device and the gateway, |
|||
* whose credentials the firmware uses, are never changed. |
|||
*/ |
|||
private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { |
|||
if (request.getSteps() == null || request.getSteps().isEmpty()) { |
|||
throw new IllegalArgumentException("The update has no steps"); |
|||
} |
|||
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor()); |
|||
Set<String> stateKeys = new HashSet<>(); |
|||
for (DeviceUpdateRequest.Step step : request.getSteps()) { |
|||
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { |
|||
throw new IllegalArgumentException("Invalid update step: " + step.getName()); |
|||
} |
|||
// The key of the step's install state
|
|||
if (!stateKeys.add(step.getId() != null ? step.getId() : step.getName())) { |
|||
throw new IllegalArgumentException("Duplicate update step: " + step.getName()); |
|||
} |
|||
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); |
|||
switch (step.getAction()) { |
|||
case KEEP, OVERWRITE -> { |
|||
if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { |
|||
throw new IllegalArgumentException("No entity for update step: " + step.getName()); |
|||
} |
|||
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() |
|||
&& !"GATEWAY_CONNECTOR".equals(step.getType())) { |
|||
throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); |
|||
} |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { |
|||
throw new IllegalArgumentException("The device and its credentials don't change on update"); |
|||
} |
|||
} |
|||
case CREATE -> { |
|||
} |
|||
} |
|||
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { |
|||
throw new IllegalArgumentException("No entity data for update step: " + step.getName()); |
|||
} |
|||
} |
|||
} |
|||
|
|||
/** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ |
|||
private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { |
|||
boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP |
|||
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); |
|||
if (savesIntegrations) { |
|||
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); |
|||
} |
|||
} |
|||
|
|||
/** The configuration of an integration is checked by a remote call, so before the transaction. */ |
|||
private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { |
|||
for (DeviceUpdateRequest.Step step : request.getSteps()) { |
|||
if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
continue; |
|||
} |
|||
ObjectNode body = step.getEntity().deepCopy(); |
|||
// Converters this update creates have no id yet; the configuration doesn't depend on them
|
|||
body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); |
|||
Integration integration = JacksonUtil.treeToValue(body, Integration.class); |
|||
integration.setTenantId(tenantId); |
|||
try { |
|||
tbIntegrationService.validateIntegrationConfiguration(tenantId, integration); |
|||
} catch (ExecutionException e) { |
|||
// What the integration reports, e.g. wrong credentials, is what the user has to fix
|
|||
Throwable cause = e.getCause() != null ? e.getCause() : e; |
|||
throw new StepFailure(step.getName(), new IllegalArgumentException(cause.getMessage(), cause)); |
|||
} catch (TimeoutException e) { |
|||
throw new StepFailure(step.getName(), new IllegalStateException("Timeout to validate the integration configuration")); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { |
|||
IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); |
|||
DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); |
|||
Set<UUID> ownedIds = ownedIds(previous); |
|||
Map<String, ObjectNode> aliasOutputs = new HashMap<>(); |
|||
Map<String, ObjectNode> outputs = new LinkedHashMap<>(); |
|||
Map<String, ObjectNode> installState = new LinkedHashMap<>(); |
|||
if (request.getInstallState() != null) { |
|||
request.getInstallState().forEach((key, value) -> { |
|||
if (value != null && value.has("formValues")) { |
|||
installState.put(key, JacksonUtil.newObjectNode().set("formValues", value.get("formValues"))); |
|||
} |
|||
}); |
|||
} |
|||
List<EntityId> stepEntityIds = new ArrayList<>(); |
|||
Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous); |
|||
List<SavedEntity> saved = new ArrayList<>(); |
|||
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>(); |
|||
List<StepAttributes> attributes = new ArrayList<>(); |
|||
// The checksums of the entities this update overwrote, which other packages may record too
|
|||
DashboardId dashboardId = null; |
|||
|
|||
for (DeviceUpdateRequest.Step step : request.getSteps()) { |
|||
try { |
|||
if ("GATEWAY_CONNECTOR".equals(step.getType())) { |
|||
// A connector lives in the gateway's attributes, which aren't transactional: saved after commit
|
|||
if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { |
|||
connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); |
|||
} |
|||
continue; |
|||
} |
|||
JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; |
|||
StepResult result = applyStep(tenantId, step, entity); |
|||
ObjectNode output = result.output(); |
|||
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); |
|||
outputs.put(step.getName(), output); |
|||
ObjectNode state = JacksonUtil.newObjectNode(); |
|||
state.set("entityOutput", output); |
|||
// The package's own entity stays the package's, whatever the request says, so later versions update it
|
|||
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); |
|||
String resolution = step.getResolution() == null || (owned && "use-existing".equals(step.getResolution())) ? "created" : step.getResolution(); |
|||
state.put("resolution", resolution); |
|||
// A kept entity keeps the checksum of what the package left: the current one would take the
|
|||
// user's changes for the package's, and the next update would overwrite them without a warning
|
|||
String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); |
|||
if (checksum != null) { |
|||
state.put("checksum", checksum); |
|||
} |
|||
if (step.isDefaultConverter()) { |
|||
state.put("defaultConverter", true); |
|||
} |
|||
installState.put(step.getId() != null ? step.getId() : step.getName(), state); |
|||
if (!"use-existing".equals(resolution)) { |
|||
stepEntityIds.add(result.entityId()); |
|||
} else { |
|||
usedExistingIds.putIfAbsent(result.entityId().getId(), result.entityId()); |
|||
} |
|||
if (result.entityId() instanceof DashboardId id) { |
|||
dashboardId = id; |
|||
} |
|||
if (result.saved() != null) { |
|||
saved.add(result.saved()); |
|||
} |
|||
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { |
|||
// As at install, the step's attributes go with the entity it saved; written after commit
|
|||
attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); |
|||
} |
|||
} catch (StepFailure e) { |
|||
throw e; |
|||
} catch (Exception e) { |
|||
throw new StepFailure(step.getName(), e); |
|||
} |
|||
} |
|||
|
|||
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); |
|||
// The new version may not offer the method the package was installed with
|
|||
descriptor.setSelectedInstallMethod(request.getSelectedInstallMethod() != null ? request.getSelectedInstallMethod() : previous.getSelectedInstallMethod()); |
|||
descriptor.setCreatedEntityIds(createdEntityIds(tenantId, previous, stepEntityIds)); |
|||
// Carried over like createdEntityIds, so an entity the user chose to use stays theirs after a version drops its step
|
|||
Set<UUID> tracked = createdIds(descriptor).keySet(); |
|||
descriptor.setUsedExistingEntityIds(usedExistingIds.values().stream().filter(id -> tracked.contains(id.getId())).toList()); |
|||
descriptor.setDashboardId(dashboardId != null ? dashboardId : existingDashboard(tenantId, previous)); |
|||
Map<String, JsonNode> state = new LinkedHashMap<>(installState); |
|||
descriptor.setInstallState(state); |
|||
|
|||
installedItem.setItemVersionId(UUID.fromString(request.getVersionId())); |
|||
installedItem.setItemName(versionInfo.get("name").asText()); |
|||
installedItem.setVersion(versionInfo.get("version").asText()); |
|||
installedItem.setDescriptor(descriptor); |
|||
installedItemService.save(tenantId, installedItem); |
|||
// Resolved once every entity is saved: attributes may refer to a later step's entity
|
|||
List<StepAttributes> resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), |
|||
resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); |
|||
return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); |
|||
} |
|||
|
|||
/** The checksums the installed device packages recorded, by entity. */ |
|||
private Map<UUID, Set<String>> recordedChecksums(TenantId tenantId) { |
|||
Map<UUID, Set<String>> checksums = new HashMap<>(); |
|||
PageLink pageLink = new PageLink(100); |
|||
PageData<IotHubInstalledItem> page; |
|||
do { |
|||
page = installedItemService.findByTenantId(tenantId, List.of("DEVICE"), null, pageLink); |
|||
for (IotHubInstalledItem item : page.getData()) { |
|||
if (item.getDescriptor() instanceof DeviceInstalledItemDescriptor descriptor && descriptor.getInstallState() != null) { |
|||
descriptor.getInstallState().values().forEach(state -> { |
|||
UUID id = toUuid(state.path("entityOutput").path("id").asText()); |
|||
JsonNode checksum = state.get("checksum"); |
|||
if (id != null && checksum != null && checksum.isTextual()) { |
|||
checksums.computeIfAbsent(id, k -> new HashSet<>()).add(checksum.asText()); |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
pageLink = pageLink.nextPageLink(); |
|||
} while (page.hasNext()); |
|||
return checksums; |
|||
} |
|||
|
|||
private static UUID toUuid(String id) { |
|||
try { |
|||
return UUID.fromString(id); |
|||
} catch (IllegalArgumentException e) { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then |
|||
* fails: the plan was made for the version installed before. Without it both would create the new entities. |
|||
*/ |
|||
private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { |
|||
IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); |
|||
UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); |
|||
if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) |
|||
|| !Objects.equals(devicePackage.installedItem().getItemVersionId(), installedItem.getItemVersionId())) { |
|||
throw new IllegalArgumentException("The package was updated meanwhile. Check the update again."); |
|||
} |
|||
return installedItem; |
|||
} |
|||
|
|||
private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { |
|||
return switch (step.getType()) { |
|||
case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); |
|||
case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); |
|||
case "DASHBOARD" -> saveDashboard(tenantId, step, entity); |
|||
case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); |
|||
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); |
|||
case "INTEGRATION" -> saveIntegration(tenantId, step, entity); |
|||
default -> throw new IllegalArgumentException("Unsupported step type: " + step.getType()); |
|||
}; |
|||
} |
|||
|
|||
private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; |
|||
DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
existing(tenantId, current, step); |
|||
return kept(id, current.getName()); |
|||
} |
|||
DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); |
|||
profile.setTenantId(tenantId); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
existing(tenantId, current, step); |
|||
prepareOverwrite(profile, id, current, step); |
|||
// The tenant's default profile stays the default one
|
|||
profile.setDefault(current.isDefault()); |
|||
} else { |
|||
profile.setId(null); |
|||
profile.setVersion(null); |
|||
} |
|||
DeviceProfile result = deviceProfileService.saveDeviceProfile(profile); |
|||
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); |
|||
} |
|||
|
|||
private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; |
|||
Device device; |
|||
boolean created = false; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { |
|||
Device template = JacksonUtil.treeToValue(entity, Device.class); |
|||
template.setTenantId(tenantId); |
|||
template.setId(null); |
|||
template.setVersion(null); |
|||
device = deviceService.saveDevice(template); |
|||
created = true; |
|||
} else { |
|||
Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; |
|||
device = existing(tenantId, current, step); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
// Another device the user chose to overwrite; the package's own device never changes
|
|||
Device template = JacksonUtil.treeToValue(entity, Device.class); |
|||
template.setTenantId(tenantId); |
|||
prepareOverwrite(template, id, current, step); |
|||
device = deviceService.saveDevice(template); |
|||
created = true; |
|||
} |
|||
} |
|||
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); |
|||
if (created && step.getCredentials() != null && step.getCredentials().isObject()) { |
|||
credentials = applyCredentials(tenantId, credentials, step.getCredentials()); |
|||
} |
|||
ObjectNode output = output(device.getId(), device.getName()); |
|||
if (credentials != null) { |
|||
output.put("token", credentials.getCredentialsId()); |
|||
} |
|||
if ("GATEWAY".equals(step.getType())) { |
|||
output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); |
|||
} |
|||
SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; |
|||
return new StepResult(device.getId(), output, null, saved); |
|||
} |
|||
|
|||
private DeviceCredentials applyCredentials(TenantId tenantId, DeviceCredentials credentials, JsonNode template) { |
|||
JsonNode type = template.get("credentialsType"); |
|||
if (type != null && type.isTextual()) { |
|||
credentials.setCredentialsType(DeviceCredentialsType.valueOf(type.asText())); |
|||
} |
|||
JsonNode value = template.get("credentialsValue"); |
|||
if (value != null && !value.isNull()) { |
|||
credentials.setCredentialsValue(value.isTextual() ? value.asText() : value.toString()); |
|||
} |
|||
JsonNode credentialsId = template.get("credentialsId"); |
|||
if (credentialsId != null && credentialsId.isTextual()) { |
|||
credentials.setCredentialsId(credentialsId.asText()); |
|||
} |
|||
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); |
|||
} |
|||
|
|||
private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; |
|||
Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
existing(tenantId, current, step); |
|||
return kept(id, current.getTitle()); |
|||
} |
|||
Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); |
|||
dashboard.setTenantId(tenantId); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
existing(tenantId, current, step); |
|||
prepareOverwrite(dashboard, id, current, step); |
|||
// The dashboard keeps its owner and the customers it is assigned to
|
|||
if (dashboard.getCustomerId() == null) { |
|||
dashboard.setCustomerId(current.getCustomerId()); |
|||
} |
|||
dashboard.setAssignedCustomers(current.getAssignedCustomers()); |
|||
} else { |
|||
dashboard.setId(null); |
|||
dashboard.setVersion(null); |
|||
} |
|||
Dashboard result = dashboardService.saveDashboard(dashboard); |
|||
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); |
|||
} |
|||
|
|||
private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { |
|||
RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; |
|||
RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
existing(tenantId, current, step); |
|||
return kept(id, current.getName()); |
|||
} |
|||
JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; |
|||
RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); |
|||
ruleChain.setTenantId(tenantId); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
existing(tenantId, current, step); |
|||
prepareOverwrite(ruleChain, id, current, step); |
|||
// A rule chain the tenant made its root one stays the root
|
|||
ruleChain.setRoot(current.isRoot()); |
|||
} else { |
|||
ruleChain.setId(null); |
|||
ruleChain.setVersion(null); |
|||
ruleChain.setRoot(false); |
|||
} |
|||
RuleChain result = ruleChainService.saveRuleChain(ruleChain); |
|||
if (entity.has("metadata") && entity.get("metadata").isObject()) { |
|||
RuleChainMetaData metadata = JacksonUtil.treeToValue(entity.get("metadata"), RuleChainMetaData.class); |
|||
metadata.setRuleChainId(result.getId()); |
|||
metadata.setVersion(result.getVersion()); |
|||
if (!ruleChainService.saveRuleChainMetaData(tenantId, metadata, tbRuleChainService::updateRuleNodeConfiguration).isSuccess()) { |
|||
throw new IllegalStateException("Failed to save the rule chain metadata"); |
|||
} |
|||
result = ruleChainService.findRuleChainById(tenantId, result.getId()); |
|||
} |
|||
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); |
|||
} |
|||
|
|||
private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; |
|||
Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
existing(tenantId, current, step); |
|||
return kept(id, current.getName()); |
|||
} |
|||
Converter converter = JacksonUtil.treeToValue(entity, Converter.class); |
|||
converter.setTenantId(tenantId); |
|||
converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
existing(tenantId, current, step); |
|||
prepareOverwrite(converter, id, current, step); |
|||
} else { |
|||
converter.setId(null); |
|||
converter.setVersion(null); |
|||
} |
|||
Converter result = converterService.saveConverter(converter); |
|||
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); |
|||
} |
|||
|
|||
private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; |
|||
Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; |
|||
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { |
|||
existing(tenantId, current, step); |
|||
Integration merged = withMergedMetadata(current, step.getMetadata()); |
|||
if (merged != null) { |
|||
Integration result = integrationService.saveIntegration(merged); |
|||
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); |
|||
} |
|||
return new StepResult(id, integrationOutput(current), null, null); |
|||
} |
|||
Integration integration = JacksonUtil.treeToValue(entity, Integration.class); |
|||
integration.setTenantId(tenantId); |
|||
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { |
|||
existing(tenantId, current, step); |
|||
prepareOverwrite(integration, id, current, step); |
|||
// The devices keep sending to the same endpoint
|
|||
integration.setRoutingKey(current.getRoutingKey()); |
|||
} else { |
|||
integration.setId(null); |
|||
integration.setVersion(null); |
|||
if (integration.getRoutingKey() == null) { |
|||
integration.setRoutingKey(UUID.randomUUID().toString()); |
|||
} |
|||
} |
|||
Integration result = integrationService.saveIntegration(integration); |
|||
return savedResult(tenantId, result.getId(), result, step, integrationOutput(result)); |
|||
} |
|||
|
|||
/** |
|||
* A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. |
|||
* A copy: the integration may be the cache's own instance, which a rolled back update must not change. |
|||
*/ |
|||
private static Integration withMergedMetadata(Integration integration, JsonNode entries) { |
|||
if (entries == null || !entries.isObject() || entries.isEmpty()) { |
|||
return null; |
|||
} |
|||
Integration copy = new Integration(integration); |
|||
ObjectNode configuration = copy.getConfiguration() instanceof ObjectNode current ? current : JacksonUtil.newObjectNode(); |
|||
JsonNode before = configuration.get("metadata"); |
|||
ObjectNode metadata = before instanceof ObjectNode current ? current.deepCopy() : JacksonUtil.newObjectNode(); |
|||
entries.fields().forEachRemaining(entry -> { |
|||
if (entry.getValue() == null || entry.getValue().isNull()) { |
|||
metadata.remove(entry.getKey()); |
|||
} else { |
|||
metadata.put(entry.getKey(), entry.getValue().asText()); |
|||
} |
|||
}); |
|||
if (metadata.equals(before) || (metadata.isEmpty() && before == null)) { |
|||
return null; |
|||
} |
|||
configuration.set("metadata", metadata); |
|||
copy.setConfiguration(configuration); |
|||
return copy; |
|||
} |
|||
|
|||
|
|||
/** |
|||
* The overwritten entity keeps its id and its current name (the user may have renamed it). The version the |
|||
* user reviewed makes the save fail if someone changed the entity since. |
|||
*/ |
|||
private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { |
|||
switch (entity) { |
|||
case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } |
|||
case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } |
|||
case Dashboard d -> { d.setId((DashboardId) id); d.setTitle(((Dashboard) current).getTitle()); } |
|||
case RuleChain r -> { r.setId((RuleChainId) id); r.setName(((RuleChain) current).getName()); } |
|||
case Converter c -> { c.setId((ConverterId) id); c.setName(((Converter) current).getName()); } |
|||
case Integration i -> { i.setId((IntegrationId) id); i.setName(((Integration) current).getName()); } |
|||
default -> throw new IllegalArgumentException("Unsupported entity: " + entity.getClass().getSimpleName()); |
|||
} |
|||
Long currentVersion = ((HasVersion) current).getVersion(); |
|||
if (step.getExpectedVersion() != null && !step.getExpectedVersion().equals(currentVersion)) { |
|||
throw new EntityVersionMismatchException(id.getEntityType(), null); |
|||
} |
|||
((HasVersion) entity).setVersion(currentVersion); |
|||
} |
|||
|
|||
private <T> T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { |
|||
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { |
|||
throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); |
|||
} |
|||
return current; |
|||
} |
|||
|
|||
private StepResult kept(EntityId id, String name) { |
|||
return new StepResult(id, output(id, name), null, null); |
|||
} |
|||
|
|||
/** The checksum the installed version recorded for the entity, under whichever step it was installed with. */ |
|||
private static String previousChecksum(DeviceInstalledItemDescriptor previous, UUID entityId) { |
|||
if (previous.getInstallState() == null || entityId == null) { |
|||
return null; |
|||
} |
|||
for (JsonNode state : previous.getInstallState().values()) { |
|||
JsonNode checksum = state.get("checksum"); |
|||
if (entityId.toString().equals(state.path("entityOutput").path("id").asText()) && checksum != null && checksum.isTextual()) { |
|||
return checksum.asText(); |
|||
} |
|||
} |
|||
return null; |
|||
} |
|||
|
|||
/** |
|||
* The checksum is of the entity the save returned: a profile or an integration read back by id inside the |
|||
* transaction may come from the cache, which is evicted only after commit. A rule chain is read back with |
|||
* its metadata, which isn't cached. |
|||
*/ |
|||
private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { |
|||
String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); |
|||
return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); |
|||
} |
|||
|
|||
private static ObjectNode output(EntityId id, String name) { |
|||
ObjectNode output = JacksonUtil.newObjectNode(); |
|||
output.put("id", id.getId().toString()); |
|||
output.put("name", name); |
|||
return output; |
|||
} |
|||
|
|||
/** With what the install instructions resolve: ${integration.routingKey}, ${integration.httpEndpoint}, ${integration.baseUrl}. */ |
|||
private static ObjectNode integrationOutput(Integration integration) { |
|||
ObjectNode output = output(integration.getId(), integration.getName()); |
|||
output.put("routingKey", integration.getRoutingKey()); |
|||
JsonNode configuration = integration.getConfiguration() != null ? integration.getConfiguration() : JacksonUtil.newObjectNode(); |
|||
JsonNode client = configuration.path("clientConfiguration"); |
|||
putText(output, "httpEndpoint", client.path("httpEndpoint"), configuration.path("httpEndpoint")); |
|||
putText(output, "baseUrl", client.path("baseUrl"), configuration.path("baseUrl")); |
|||
return output; |
|||
} |
|||
|
|||
private static void putText(ObjectNode output, String key, JsonNode first, JsonNode second) { |
|||
JsonNode value = first.isTextual() ? first : second; |
|||
if (value.isTextual()) { |
|||
output.put(key, value.asText()); |
|||
} |
|||
} |
|||
|
|||
/** Replaces ${<alias>.<property>} of entities this update has saved, e.g. the id of a converter it created. */ |
|||
static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) { |
|||
if (node == null) { |
|||
return null; |
|||
} |
|||
if (node.isTextual()) { |
|||
String text = node.asText(); |
|||
Matcher matcher = ENTITY_PLACEHOLDER.matcher(text); |
|||
StringBuilder resolved = new StringBuilder(); |
|||
boolean changed = false; |
|||
while (matcher.find()) { |
|||
ObjectNode output = aliasOutputs.get(matcher.group(1)); |
|||
JsonNode value = output != null ? output.get(matcher.group(2)) : null; |
|||
String replacement = value != null && !value.isNull() ? value.asText() : matcher.group(); |
|||
changed |= value != null && !value.isNull(); |
|||
matcher.appendReplacement(resolved, Matcher.quoteReplacement(replacement)); |
|||
} |
|||
matcher.appendTail(resolved); |
|||
return changed ? TextNode.valueOf(resolved.toString()) : node; |
|||
} |
|||
if (node.isObject()) { |
|||
ObjectNode copy = JacksonUtil.newObjectNode(); |
|||
for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) { |
|||
Map.Entry<String, JsonNode> field = it.next(); |
|||
copy.set(field.getKey(), resolvePlaceholders(field.getValue(), aliasOutputs)); |
|||
} |
|||
return copy; |
|||
} |
|||
if (node.isArray()) { |
|||
ArrayNode copy = JacksonUtil.newArrayNode(); |
|||
node.forEach(item -> copy.add(resolvePlaceholders(item, aliasOutputs))); |
|||
return copy; |
|||
} |
|||
return node; |
|||
} |
|||
|
|||
/** |
|||
* The ids the package tracks: the entities of this version's steps, and those of the installed version this one |
|||
* no longer uses, so deleting the package still deletes them. Entities deleted since are dropped. |
|||
*/ |
|||
private List<EntityId> createdEntityIds(TenantId tenantId, DeviceInstalledItemDescriptor previous, List<EntityId> stepEntityIds) { |
|||
List<EntityId> ids = new ArrayList<>(stepEntityIds); |
|||
Set<UUID> known = new HashSet<>(); |
|||
ids.forEach(id -> known.add(id.getId())); |
|||
if (previous.getCreatedEntityIds() != null) { |
|||
for (EntityId id : previous.getCreatedEntityIds()) { |
|||
if (known.add(id.getId()) && entityService.fetchEntity(tenantId, id).isPresent()) { |
|||
ids.add(id); |
|||
} |
|||
} |
|||
} |
|||
return ids; |
|||
} |
|||
|
|||
private DashboardId existingDashboard(TenantId tenantId, DeviceInstalledItemDescriptor previous) { |
|||
DashboardId id = previous.getDashboardId(); |
|||
return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; |
|||
} |
|||
|
|||
/** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ |
|||
private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { |
|||
for (SavedEntity saved : applied.saved()) { |
|||
try { |
|||
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), |
|||
saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); |
|||
if (saved.id().getEntityType() != EntityType.DEVICE) { |
|||
autoCommit(user, saved.id()); |
|||
} |
|||
} catch (Exception e) { |
|||
log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); |
|||
} |
|||
} |
|||
for (StepAttributes step : applied.attributes()) { |
|||
try { |
|||
saveAttributes(tenantId, step.entityId(), AttributeScope.SERVER_SCOPE, step.server()); |
|||
saveAttributes(tenantId, step.entityId(), AttributeScope.SHARED_SCOPE, step.shared()); |
|||
} catch (Exception e) { |
|||
log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); |
|||
} |
|||
} |
|||
for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { |
|||
try { |
|||
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); |
|||
} catch (Exception e) { |
|||
log.warn("[{}] Failed to save the gateway connector of device package step [{}]", tenantId, step.getName(), e); |
|||
} |
|||
} |
|||
} |
|||
|
|||
private void saveConnector(TenantId tenantId, ObjectNode gateway, JsonNode connector) throws Exception { |
|||
if (gateway == null || connector == null || !connector.has("name")) { |
|||
return; |
|||
} |
|||
DeviceId gatewayId = new DeviceId(UUID.fromString(gateway.get("id").asText())); |
|||
String name = connector.get("name").asText(); |
|||
List<String> active = new ArrayList<>(); |
|||
for (AttributeKvEntry entry : attributesService.find(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, List.of("active_connectors")).get()) { |
|||
JsonNode value = JacksonUtil.toJsonNode(entry.getValueAsString()); |
|||
if (value != null && value.isArray()) { |
|||
value.forEach(v -> active.add(v.asText())); |
|||
} |
|||
} |
|||
if (!active.contains(name)) { |
|||
active.add(name); |
|||
} |
|||
ObjectNode attributes = JacksonUtil.newObjectNode(); |
|||
attributes.set("active_connectors", JacksonUtil.valueToTree(active)); |
|||
attributes.set(name, connector); |
|||
saveAttributes(tenantId, gatewayId, AttributeScope.SHARED_SCOPE, attributes); |
|||
} |
|||
|
|||
private void saveAttributes(TenantId tenantId, EntityId entityId, AttributeScope scope, JsonNode attributes) { |
|||
if (attributes == null || !attributes.isObject() || attributes.isEmpty()) { |
|||
return; |
|||
} |
|||
List<AttributeKvEntry> entries = JsonConverter.convertToAttributes(JsonParser.parseString(attributes.toString())); |
|||
telemetryService.saveAttributes(AttributesSaveRequest.builder() |
|||
.tenantId(tenantId) |
|||
.entityId(entityId) |
|||
.scope(scope) |
|||
.entries(entries) |
|||
.build()); |
|||
} |
|||
|
|||
/** |
|||
* The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database |
|||
* error, as a common message, with the details in the log. |
|||
*/ |
|||
static String userMessage(Throwable e) { |
|||
if (e instanceof EntityVersionMismatchException) { |
|||
return "Someone changed it while you were reviewing the update. Check the update again."; |
|||
} |
|||
if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException |
|||
|| e instanceof SubscriptionException) { |
|||
return e.getMessage(); |
|||
} |
|||
if (e instanceof ThingsboardException te && te.getErrorCode() != ThingsboardErrorCode.GENERAL) { |
|||
return te.getMessage(); |
|||
} |
|||
return UNEXPECTED_ERROR; |
|||
} |
|||
|
|||
private static boolean isKnownType(String type) { |
|||
return type != null && (STEP_ALIASES.containsKey(type) || "GATEWAY_CONNECTOR".equals(type)); |
|||
} |
|||
|
|||
/** |
|||
* The entities the package owns: those it created, not the ones the user chose to use as they were. The install adds |
|||
* those to createdEntityIds too, so they are subtracted; an entity of a step a later version dropped stays owned. |
|||
*/ |
|||
private static Set<UUID> ownedIds(DeviceInstalledItemDescriptor descriptor) { |
|||
Set<UUID> ids = new HashSet<>(createdIds(descriptor).keySet()); |
|||
ids.removeAll(usedExistingIds(descriptor).keySet()); |
|||
return ids; |
|||
} |
|||
|
|||
/** |
|||
* The entities the user chose to use as they were. An install made before the descriptor kept them has them only in |
|||
* its install state, which the first update carries over into the descriptor. |
|||
*/ |
|||
private static Map<UUID, EntityId> usedExistingIds(DeviceInstalledItemDescriptor descriptor) { |
|||
Map<UUID, EntityId> ids = new LinkedHashMap<>(); |
|||
if (descriptor.getUsedExistingEntityIds() != null) { |
|||
descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id)); |
|||
return ids; |
|||
} |
|||
Map<UUID, EntityId> createdIds = createdIds(descriptor); |
|||
if (descriptor.getInstallState() != null) { |
|||
descriptor.getInstallState().values().forEach(state -> { |
|||
UUID id = toUuid(state.path("entityOutput").path("id").asText()); |
|||
if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) { |
|||
ids.put(id, createdIds.get(id)); |
|||
} |
|||
}); |
|||
} |
|||
return ids; |
|||
} |
|||
|
|||
private static Map<UUID, EntityId> createdIds(DeviceInstalledItemDescriptor descriptor) { |
|||
Map<UUID, EntityId> ids = new HashMap<>(); |
|||
if (descriptor.getCreatedEntityIds() != null) { |
|||
descriptor.getCreatedEntityIds().forEach(id -> ids.put(id.getId(), id)); |
|||
} |
|||
return ids; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { |
|||
DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); |
|||
if (entity != null) { |
|||
copy.setEntity(entity); |
|||
} |
|||
return copy; |
|||
} |
|||
|
|||
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { |
|||
} |
|||
|
|||
private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { |
|||
} |
|||
|
|||
private record SavedEntity(EntityId id, Object entity, boolean created) { |
|||
} |
|||
|
|||
private record StepAttributes(String stepName, EntityId entityId, JsonNode server, JsonNode shared) { |
|||
} |
|||
|
|||
private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved, |
|||
List<DeviceUpdateRequest.Step> connectorSteps, List<StepAttributes> attributes, |
|||
Map<String, ObjectNode> aliasOutputs) { |
|||
} |
|||
|
|||
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ |
|||
private static class StepFailure extends RuntimeException { |
|||
|
|||
private final String stepName; |
|||
|
|||
StepFailure(String stepName, Throwable cause) { |
|||
super(cause.getMessage(), cause); |
|||
this.stepName = stepName; |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,119 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.RequiredArgsConstructor; |
|||
import org.springframework.stereotype.Component; |
|||
import org.thingsboard.server.common.data.EntityType; |
|||
import org.thingsboard.server.common.data.HasTenantId; |
|||
import org.thingsboard.server.common.data.HasVersion; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
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.RuleChainId; |
|||
import org.thingsboard.server.common.data.id.TenantId; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.rule.RuleChain; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
import org.thingsboard.server.dao.integration.IntegrationService; |
|||
import org.thingsboard.server.dao.rule.RuleChainService; |
|||
import org.thingsboard.server.queue.util.TbCoreComponent; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
import java.util.Set; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The entities of a device package whose content an update overwrites, and their checksums. A device, a gateway |
|||
* and a gateway connector don't have one: an update never changes them. |
|||
*/ |
|||
@Component |
|||
@TbCoreComponent |
|||
@RequiredArgsConstructor |
|||
public class DevicePackageEntities { |
|||
|
|||
static final Set<EntityType> CHECKSUM_TYPES = Set.of(EntityType.DEVICE_PROFILE, EntityType.DASHBOARD, |
|||
EntityType.RULE_CHAIN, EntityType.CONVERTER, EntityType.INTEGRATION); |
|||
|
|||
private final DeviceProfileService deviceProfileService; |
|||
private final DashboardService dashboardService; |
|||
private final RuleChainService ruleChainService; |
|||
private final ConverterService converterService; |
|||
private final IntegrationService integrationService; |
|||
|
|||
/** The entity of the tenant, null when there is none, e.g. it was deleted. A rule chain comes with its metadata. */ |
|||
public Snapshot load(TenantId tenantId, EntityId entityId) { |
|||
Object entity = switch (entityId.getEntityType()) { |
|||
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, (DeviceProfileId) entityId); |
|||
case DASHBOARD -> dashboardService.findDashboardById(tenantId, (DashboardId) entityId); |
|||
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, (RuleChainId) entityId); |
|||
case CONVERTER -> converterService.findConverterById(tenantId, (ConverterId) entityId); |
|||
case INTEGRATION -> integrationService.findIntegrationById(tenantId, (IntegrationId) entityId); |
|||
default -> throw new IllegalArgumentException("Unsupported entity type: " + entityId.getEntityType()); |
|||
}; |
|||
if (entity == null || !tenantId.equals(((HasTenantId) entity).getTenantId())) { |
|||
return null; |
|||
} |
|||
Object metadata = entity instanceof RuleChain ruleChain ? ruleChainService.loadRuleChainMetaData(tenantId, ruleChain.getId()) : null; |
|||
return new Snapshot(entity, metadata); |
|||
} |
|||
|
|||
public String checksum(TenantId tenantId, EntityId entityId) { |
|||
Snapshot snapshot = load(tenantId, entityId); |
|||
return snapshot != null ? snapshot.checksum() : null; |
|||
} |
|||
|
|||
/** |
|||
* Adds the checksum of each entity the install state names, so that an update can tell whether someone changed |
|||
* it since. Entities the user kept at install are left out: an update never overwrites them. |
|||
*/ |
|||
public void addChecksums(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) { |
|||
if (descriptor.getInstallState() == null || descriptor.getCreatedEntityIds() == null) { |
|||
return; |
|||
} |
|||
Map<UUID, EntityId> createdIds = new HashMap<>(); |
|||
descriptor.getCreatedEntityIds().forEach(id -> createdIds.put(id.getId(), id)); |
|||
descriptor.getInstallState().forEach((stepName, state) -> { |
|||
EntityId entityId = entityIdOf(state, createdIds); |
|||
if (entityId != null && CHECKSUM_TYPES.contains(entityId.getEntityType()) && state.isObject()) { |
|||
String checksum = checksum(tenantId, entityId); |
|||
if (checksum != null) { |
|||
((ObjectNode) state).put("checksum", checksum); |
|||
} |
|||
} |
|||
}); |
|||
} |
|||
|
|||
/** The package entity an install-state step recorded, with its type from the ids the package created. */ |
|||
static EntityId entityIdOf(JsonNode state, Map<UUID, EntityId> createdIds) { |
|||
JsonNode id = state != null ? state.path("entityOutput").path("id") : null; |
|||
if (id == null || !id.isTextual() || "use-existing".equals(state.path("resolution").asText())) { |
|||
return null; |
|||
} |
|||
try { |
|||
return createdIds.get(UUID.fromString(id.asText())); |
|||
} catch (IllegalArgumentException e) { |
|||
return null; |
|||
} |
|||
} |
|||
|
|||
public record Snapshot(Object entity, Object metadata) { |
|||
|
|||
public Long version() { |
|||
return ((HasVersion) entity).getVersion(); |
|||
} |
|||
|
|||
public String checksum() { |
|||
return metadata != null ? EntityChecksum.of(entity, metadata) : EntityChecksum.of(entity); |
|||
} |
|||
|
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,27 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.id.EntityId; |
|||
|
|||
/** An entity of an installed device package as an update finds it, before it changes anything. */ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DevicePackageEntityState { |
|||
|
|||
private String stepName; |
|||
private EntityId entityId; |
|||
private boolean exists; |
|||
// Sent back with the update, which fails if someone changed the entity in between
|
|||
private Long version; |
|||
// Changed since the package installed or last updated it; null when the install state has no checksum of it
|
|||
// (installed before checksums were kept)
|
|||
private Boolean modified; |
|||
// Other installed device packages use it, so overwriting it affects them
|
|||
private boolean shared; |
|||
|
|||
} |
|||
@ -0,0 +1,19 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
|
|||
import java.util.List; |
|||
|
|||
/** Updates an installed device package to another version of its item. */ |
|||
public interface DevicePackageUpdateService { |
|||
|
|||
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */ |
|||
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId); |
|||
|
|||
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ |
|||
DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); |
|||
|
|||
} |
|||
@ -0,0 +1,71 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import lombok.Data; |
|||
|
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.UUID; |
|||
|
|||
/** |
|||
* The update of an installed device package as the install wizard planned it: the entity of each install step |
|||
* of the new version, already resolved from its template, and what to do with it. The server applies all of it |
|||
* in one transaction, together with the new version of the installed item, or nothing. |
|||
*/ |
|||
@Data |
|||
public class DeviceUpdateRequest { |
|||
|
|||
private String versionId; |
|||
// The version installed when the wizard planned the update; the update fails if the package changed since
|
|||
private UUID fromVersionId; |
|||
// The install method of the new version's steps; the installed one when not set
|
|||
private String selectedInstallMethod; |
|||
// The form values of the install state, by step: the server adds the entities to it
|
|||
private Map<String, JsonNode> installState; |
|||
private List<Step> steps; |
|||
|
|||
public enum Action { |
|||
// Taken as it is: the new version doesn't change it, or the user kept an entity they had
|
|||
KEEP, |
|||
// Takes the entity from the step
|
|||
OVERWRITE, |
|||
// A new entity: new in this version, deleted since install, or a copy next to one with the same name
|
|||
CREATE |
|||
} |
|||
|
|||
@Data |
|||
public static class Step { |
|||
private String name; |
|||
// The package step's id, which keys its install state; the name when not set
|
|||
private String id; |
|||
// InstallStepType of the package: DEVICE_PROFILE, DEVICE, GATEWAY, GATEWAY_CONNECTOR, DASHBOARD, RULE_CHAIN,
|
|||
// UPLINK_CONVERTER, DOWNLINK_CONVERTER, INTEGRATION
|
|||
private String type; |
|||
private Action action; |
|||
// KEEP and OVERWRITE: the entity
|
|||
private UUID entityId; |
|||
// OVERWRITE: the version the user reviewed; a different one means someone changed the entity since
|
|||
private Long expectedVersion; |
|||
// The user confirmed overwriting an entity of another package or one they didn't install with this package
|
|||
private boolean confirmed; |
|||
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this
|
|||
// update creates is left for the server, which knows its id only once it is created.
|
|||
private JsonNode entity; |
|||
// DEVICE and GATEWAY: the credentials template, if any
|
|||
private JsonNode credentials; |
|||
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
|
|||
// they may keep ${<alias>.<property>} of an entity this update creates.
|
|||
private JsonNode serverAttributes; |
|||
private JsonNode sharedAttributes; |
|||
// The resolution the install state records for it
|
|||
private String resolution; |
|||
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
|
|||
// integration, e.g. one the package took as it was; null removes an entry
|
|||
private JsonNode metadata; |
|||
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check
|
|||
private boolean defaultConverter; |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,37 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import lombok.AllArgsConstructor; |
|||
import lombok.Data; |
|||
import lombok.NoArgsConstructor; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
|
|||
import java.util.Map; |
|||
|
|||
/** |
|||
* Either everything was applied, or nothing was: on a failure the transaction was rolled back and failedStep |
|||
* names the step that failed, if one did. |
|||
*/ |
|||
@Data |
|||
@NoArgsConstructor |
|||
@AllArgsConstructor |
|||
public class DeviceUpdateResult { |
|||
|
|||
private boolean success; |
|||
private String errorMessage; |
|||
private String failedStep; |
|||
private DeviceInstalledItemDescriptor descriptor; |
|||
// By step name: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
|
|||
private Map<String, ObjectNode> outputs; |
|||
|
|||
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { |
|||
return new DeviceUpdateResult(true, null, null, descriptor, outputs); |
|||
} |
|||
|
|||
public static DeviceUpdateResult error(String errorMessage, String failedStep) { |
|||
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,116 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ArrayNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.rule.RuleChainMetaData; |
|||
import org.thingsboard.server.common.data.rule.RuleNode; |
|||
|
|||
import java.nio.charset.StandardCharsets; |
|||
import java.security.MessageDigest; |
|||
import java.security.NoSuchAlgorithmException; |
|||
import java.util.ArrayList; |
|||
import java.util.HexFormat; |
|||
import java.util.Iterator; |
|||
import java.util.List; |
|||
import java.util.Set; |
|||
|
|||
/** |
|||
* The checksum of an entity as the server stores it, kept in the install state of a device package. A different |
|||
* checksum later means someone changed the entity, even a widget resized. The fields the server sets, and the name, |
|||
* which an update keeps, don't count, nor do the debug settings, which the user turns on without changing what the |
|||
* entity does, and whether a profile is the default one, which changes when another profile becomes the default. |
|||
*/ |
|||
final class EntityChecksum { |
|||
|
|||
private static final Set<String> SKIPPED_KEYS = Set.of("id", "name", "title", "version", "createdTime", "tenantId", |
|||
"customerId", "ownerId", "assignedCustomers", "externalId", "ruleChainId", "resources", "debugMode", "debugSettings", "default"); |
|||
|
|||
private EntityChecksum() { |
|||
} |
|||
|
|||
/** A rule chain is checked with its metadata: pass both. */ |
|||
static String of(Object... parts) { |
|||
StringBuilder canonical = new StringBuilder(); |
|||
for (Object part : parts) { |
|||
JsonNode node = part instanceof RuleChainMetaData metadata ? ruleChainContent(metadata) : JacksonUtil.valueToTree(part); |
|||
if (part instanceof Integration && node.get("configuration") instanceof ObjectNode configuration) { |
|||
// Device packages on one integration add their entries to its metadata: that is no change to the integration
|
|||
configuration.remove("metadata"); |
|||
} |
|||
appendCanonical(canonical, node, true); |
|||
canonical.append('|'); |
|||
} |
|||
try { |
|||
byte[] hash = MessageDigest.getInstance("SHA-256").digest(canonical.toString().getBytes(StandardCharsets.UTF_8)); |
|||
return HexFormat.of().formatHex(hash); |
|||
} catch (NoSuchAlgorithmException e) { |
|||
throw new IllegalStateException(e); |
|||
} |
|||
} |
|||
|
|||
/** |
|||
* What a rule chain does, as the IoT Hub checksum of a rule chain item takes it: the nodes' type, name and |
|||
* configuration, and the connections. Node ids, layout and debug settings change without the user changing |
|||
* what the rule chain does, e.g. when it is saved again. |
|||
*/ |
|||
private static JsonNode ruleChainContent(RuleChainMetaData metadata) { |
|||
ObjectNode content = JacksonUtil.newObjectNode(); |
|||
ArrayNode nodes = content.putArray("nodes"); |
|||
if (metadata.getNodes() != null) { |
|||
for (RuleNode node : metadata.getNodes()) { |
|||
ObjectNode n = nodes.addObject(); |
|||
n.put("type", node.getType()); |
|||
n.put("name", node.getName()); |
|||
n.set("configuration", node.getConfiguration()); |
|||
n.put("singletonMode", node.isSingletonMode()); |
|||
n.put("queueName", node.getQueueName()); |
|||
} |
|||
} |
|||
content.set("connections", JacksonUtil.valueToTree(metadata.getConnections())); |
|||
content.set("ruleChainConnections", JacksonUtil.valueToTree(metadata.getRuleChainConnections())); |
|||
content.set("firstNodeIndex", JacksonUtil.valueToTree(metadata.getFirstNodeIndex())); |
|||
return content; |
|||
} |
|||
|
|||
/** JSON with the keys sorted, so the same entity always gives the same text. */ |
|||
private static void appendCanonical(StringBuilder out, JsonNode node, boolean topLevel) { |
|||
if (node == null || node.isNull() || node.isMissingNode()) { |
|||
out.append("null"); |
|||
} else if (node.isObject()) { |
|||
List<String> keys = new ArrayList<>(); |
|||
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) { |
|||
String key = it.next(); |
|||
if (!topLevel || !SKIPPED_KEYS.contains(key)) { |
|||
keys.add(key); |
|||
} |
|||
} |
|||
keys.sort(null); |
|||
out.append('{'); |
|||
for (int i = 0; i < keys.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
out.append(JacksonUtil.toString(keys.get(i))).append(':'); |
|||
appendCanonical(out, node.get(keys.get(i)), false); |
|||
} |
|||
out.append('}'); |
|||
} else if (node.isArray()) { |
|||
out.append('['); |
|||
for (int i = 0; i < node.size(); i++) { |
|||
if (i > 0) { |
|||
out.append(','); |
|||
} |
|||
appendCanonical(out, node.get(i), false); |
|||
} |
|||
out.append(']'); |
|||
} else { |
|||
out.append(node.toString()); |
|||
} |
|||
} |
|||
|
|||
} |
|||
@ -0,0 +1,748 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
package org.thingsboard.server.service.iot_hub; |
|||
|
|||
import com.fasterxml.jackson.databind.JsonNode; |
|||
import com.fasterxml.jackson.databind.node.ObjectNode; |
|||
import org.junit.jupiter.api.BeforeEach; |
|||
import org.junit.jupiter.api.Test; |
|||
import org.junit.jupiter.api.extension.ExtendWith; |
|||
import org.mockito.ArgumentCaptor; |
|||
import org.mockito.InjectMocks; |
|||
import org.mockito.Mock; |
|||
import org.mockito.junit.jupiter.MockitoExtension; |
|||
import org.mockito.junit.jupiter.MockitoSettings; |
|||
import org.mockito.quality.Strictness; |
|||
import org.springframework.test.util.ReflectionTestUtils; |
|||
import org.springframework.transaction.support.TransactionCallback; |
|||
import org.springframework.transaction.support.TransactionTemplate; |
|||
import org.thingsboard.common.util.JacksonUtil; |
|||
import org.thingsboard.server.common.data.Dashboard; |
|||
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.AttributeScope; |
|||
import org.thingsboard.server.common.data.converter.Converter; |
|||
import org.thingsboard.server.common.data.debug.DebugSettings; |
|||
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException; |
|||
import org.thingsboard.server.common.data.id.ConverterId; |
|||
import org.thingsboard.server.common.data.id.CustomerId; |
|||
import org.thingsboard.server.common.data.id.DashboardId; |
|||
import org.thingsboard.server.common.data.id.DeviceId; |
|||
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.TenantId; |
|||
import org.thingsboard.server.common.data.integration.Integration; |
|||
import org.thingsboard.server.common.data.page.PageData; |
|||
import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; |
|||
import org.thingsboard.server.common.data.subscription.SubscriptionException; |
|||
import org.thingsboard.rule.engine.api.AttributesSaveRequest; |
|||
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; |
|||
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; |
|||
import org.thingsboard.server.dao.converter.ConverterService; |
|||
import org.thingsboard.server.dao.dashboard.DashboardService; |
|||
import org.thingsboard.server.dao.device.DeviceCredentialsService; |
|||
import org.thingsboard.server.dao.device.DeviceProfileService; |
|||
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.subscription.PlatformFeature; |
|||
import org.thingsboard.server.dao.subscription.SubscriptionService; |
|||
import org.thingsboard.server.exception.DataValidationException; |
|||
import org.thingsboard.server.service.entitiy.TbLogEntityActionService; |
|||
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; |
|||
import org.thingsboard.server.service.security.model.SecurityUser; |
|||
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
import java.util.Map; |
|||
import java.util.Optional; |
|||
import java.util.UUID; |
|||
|
|||
import static org.assertj.core.api.Assertions.assertThat; |
|||
import static org.mockito.ArgumentMatchers.any; |
|||
import static org.mockito.Mockito.mock; |
|||
import static org.mockito.ArgumentMatchers.eq; |
|||
import static org.mockito.Mockito.doThrow; |
|||
import static org.mockito.Mockito.never; |
|||
import static org.mockito.Mockito.verify; |
|||
import static org.mockito.Mockito.verifyNoInteractions; |
|||
import static org.mockito.Mockito.when; |
|||
|
|||
@ExtendWith(MockitoExtension.class) |
|||
@MockitoSettings(strictness = Strictness.LENIENT) |
|||
class DefaultDevicePackageUpdateServiceTest { |
|||
|
|||
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); |
|||
private final SecurityUser user = mock(SecurityUser.class); |
|||
private final UUID itemId = UUID.randomUUID(); |
|||
private final String versionId = UUID.randomUUID().toString(); |
|||
private final UUID installedVersionId = UUID.randomUUID(); |
|||
private final DeviceProfileId profileId = new DeviceProfileId(UUID.randomUUID()); |
|||
private final DashboardId dashboardId = new DashboardId(UUID.randomUUID()); |
|||
private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); |
|||
private final IntegrationId integrationId = new IntegrationId(UUID.randomUUID()); |
|||
|
|||
@Mock |
|||
private IotHubInstalledItemService installedItemService; |
|||
@Mock |
|||
private IotHubRestClient iotHubRestClient; |
|||
@Mock |
|||
private DevicePackageEntities packageEntities; |
|||
@Mock |
|||
private DeviceProfileService deviceProfileService; |
|||
@Mock |
|||
private DashboardService dashboardService; |
|||
@Mock |
|||
private DeviceService deviceService; |
|||
@Mock |
|||
private DeviceCredentialsService deviceCredentialsService; |
|||
@Mock |
|||
private ConverterService converterService; |
|||
@Mock |
|||
private IntegrationService integrationService; |
|||
@Mock |
|||
private TransactionTemplate transactionTemplate; |
|||
@Mock |
|||
private EntityService entityService; |
|||
@Mock |
|||
private TbLogEntityActionService logEntityActionService; |
|||
@Mock |
|||
private TbIntegrationService tbIntegrationService; |
|||
@Mock |
|||
private SubscriptionService subscriptionService; |
|||
@Mock |
|||
private TelemetrySubscriptionService telemetryService; |
|||
@Mock |
|||
private IotHubService iotHubService; |
|||
|
|||
@InjectMocks |
|||
private DefaultDevicePackageUpdateService service; |
|||
|
|||
private IotHubInstalledItem installedItem; |
|||
// Set when the transaction callback threw, so the transaction would roll back
|
|||
private final List<RuntimeException> rolledBack = new ArrayList<>(); |
|||
|
|||
@BeforeEach |
|||
void setUp() { |
|||
ReflectionTestUtils.setField(service, "entityService", entityService); |
|||
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService); |
|||
when(user.getTenantId()).thenReturn(tenantId); |
|||
|
|||
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); |
|||
descriptor.setSelectedInstallMethod("INTEGRATION_TTN"); |
|||
descriptor.setCreatedEntityIds(List.of(profileId, deviceId, dashboardId, integrationId)); |
|||
descriptor.setDashboardId(dashboardId); |
|||
// The package created these entities
|
|||
descriptor.setInstallState(Map.of("Profile", stateOf(profileId, "created"), "AM308", stateOf(deviceId, "created"), |
|||
"Dashboard", stateOf(dashboardId, "created"), "Integration", stateOf(integrationId, "created"))); |
|||
installedItem = new IotHubInstalledItem(); |
|||
installedItem.setId(new IotHubInstalledItemId(UUID.randomUUID())); |
|||
installedItem.setTenantId(tenantId); |
|||
installedItem.setItemId(itemId); |
|||
installedItem.setItemType("DEVICE"); |
|||
installedItem.setVersion("1.0.0"); |
|||
installedItem.setItemVersionId(installedVersionId); |
|||
installedItem.setDescriptor(descriptor); |
|||
when(installedItemService.findById(tenantId, installedItem.getId())).thenReturn(installedItem); |
|||
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(installedItem); |
|||
|
|||
ObjectNode versionInfo = JacksonUtil.newObjectNode(); |
|||
versionInfo.put("itemId", itemId.toString()); |
|||
versionInfo.put("name", "AM308"); |
|||
versionInfo.put("version", "1.0.1"); |
|||
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo); |
|||
|
|||
when(transactionTemplate.execute(any())).thenAnswer(invocation -> { |
|||
try { |
|||
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null); |
|||
} catch (RuntimeException e) { |
|||
rolledBack.add(e); |
|||
throw e; |
|||
} |
|||
}); |
|||
when(packageEntities.checksum(any(), any())).thenReturn("checksum"); |
|||
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.empty()); |
|||
Device device = new Device(deviceId); |
|||
device.setTenantId(tenantId); |
|||
device.setName("AM308"); |
|||
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())).thenReturn(new PageData<>()); |
|||
} |
|||
|
|||
@Test |
|||
void overwritesTheEntitiesAndRecordsTheNewVersionInOneTransaction() { |
|||
DeviceProfile profile = profile(3L, "AM308 renamed"); |
|||
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile); |
|||
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); |
|||
Dashboard dashboard = dashboard(7L); |
|||
dashboard.setCustomerId(new CustomerId(UUID.randomUUID())); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "milesight-iot-am308").put("description", "new")), |
|||
keep("AM308", "DEVICE", deviceId), |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "Template title")))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<DeviceProfile> savedProfile = ArgumentCaptor.forClass(DeviceProfile.class); |
|||
verify(deviceProfileService).saveDeviceProfile(savedProfile.capture()); |
|||
// Same id, the name the user gave it, the version they reviewed
|
|||
assertThat(savedProfile.getValue().getId()).isEqualTo(profileId); |
|||
assertThat(savedProfile.getValue().getName()).isEqualTo("AM308 renamed"); |
|||
assertThat(savedProfile.getValue().getDescription()).isEqualTo("new"); |
|||
assertThat(savedProfile.getValue().getVersion()).isEqualTo(3L); |
|||
ArgumentCaptor<Dashboard> savedDashboard = ArgumentCaptor.forClass(Dashboard.class); |
|||
verify(dashboardService).saveDashboard(savedDashboard.capture()); |
|||
assertThat(savedDashboard.getValue().getCustomerId()).isEqualTo(dashboard.getCustomerId()); |
|||
|
|||
verify(installedItemService).save(tenantId, installedItem); |
|||
assertThat(installedItem.getVersion()).isEqualTo("1.0.1"); |
|||
assertThat(installedItem.getItemVersionId()).isEqualTo(UUID.fromString(versionId)); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
// Of the saved dashboard, not read back by id: inside the transaction that may come from the cache
|
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()) |
|||
.isEqualTo(EntityChecksum.of(savedDashboard.getValue())); |
|||
assertThat(descriptor.getCreatedEntityIds()).contains(profileId, deviceId, dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntity_keepsTheChecksumThePackageLeft() { |
|||
// The user changed the dashboard since: its current checksum must not become the package's
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId)); |
|||
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("checksum").asText()).isEqualTo("installed"); |
|||
assertThat(descriptor.getSelectedInstallMethod()).isEqualTo("INTEGRATION_CHIRPSTACK"); |
|||
verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntityOfAStepWithAnId_keepsItsChecksumUnderTheId() { |
|||
// Installed by a version whose step had no id: the entry is under the step's name
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "installed").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", dashboardId.getId().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId); |
|||
overview.setId("main-dashboard"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("main-dashboard").get("checksum").asText()).isEqualTo("installed"); |
|||
assertThat(descriptor.getInstallState()).doesNotContainKeys("Dashboard", "Overview"); |
|||
} |
|||
|
|||
@Test |
|||
void keptEntity_doesNotTakeTheChecksumOfAnotherEntity() { |
|||
// The entry under the step's key was recorded for an entity deleted since
|
|||
ObjectNode dashboardState = JacksonUtil.newObjectNode().put("checksum", "of-the-deleted-one").put("resolution", "created"); |
|||
dashboardState.set("entityOutput", JacksonUtil.newObjectNode().put("id", UUID.randomUUID().toString())); |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", dashboardState)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").has("checksum")).isFalse(); |
|||
} |
|||
|
|||
@Test |
|||
void useExistingOfAPackageEntity_staysThePackages() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Overview").get("resolution").asText()).isEqualTo("created"); |
|||
assertThat(descriptor.getCreatedEntityIds()).contains(dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void useExistingAtInstall_staysUseExisting() { |
|||
// At install the user picked their own dashboard: the install adds it to createdEntityIds too
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("use-existing"); |
|||
} |
|||
|
|||
@Test |
|||
void overwritingAnEntityUsedAtInstall_needsAConfirmation() { |
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void sharedEntityOverwrittenByAnotherPackage_isNotChangedBySomeoneElse() { |
|||
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)); |
|||
// 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)); |
|||
IotHubInstalledItem other = otherPackage(Map.of("Dashboard", stateOf(dashboardId, "created").put("checksum", snapshot.checksum()))); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())) |
|||
.thenReturn(new PageData<>(List.of(installedItem, other), 1, 2, false)); |
|||
|
|||
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isFalse(); |
|||
|
|||
shared.setConfiguration(JacksonUtil.newObjectNode().put("description", "Changed by hand")); |
|||
assertThat(service.check(user, installedItem.getId()).get(0).getModified()).isTrue(); |
|||
} |
|||
|
|||
@Test |
|||
void entityOfAStepAVersionDropped_staysThePackages() { |
|||
// v2 dropped the dashboard step: the install state no longer has it, createdEntityIds does
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of()); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId); |
|||
step.setResolution("use-existing"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
assertThat(descriptor.getInstallState().get("Dashboard").get("resolution").asText()).isEqualTo("created"); |
|||
} |
|||
|
|||
@Test |
|||
void entityUsedAtInstall_staysTheUsersAfterAVersionDropsItsStep() { |
|||
// Recorded at install; the step is gone from the install state since
|
|||
DeviceInstalledItemDescriptor installed = (DeviceInstalledItemDescriptor) installedItem.getDescriptor(); |
|||
installed.setUsedExistingEntityIds(List.of(dashboardId)); |
|||
installed.setInstallState(Map.of()); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void entitiesUsedAtInstall_areCarriedIntoTheDescriptor() { |
|||
// Installed before the descriptor kept them: the install state has them
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("Dashboard", stateOf(dashboardId, "use-existing"))); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L)); |
|||
when(entityService.fetchEntity(any(), any())).thenReturn(Optional.of(dashboard(9L))); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId); |
|||
} |
|||
|
|||
@Test |
|||
void keptIntegration_getsTheStepsMetadataEntries() { |
|||
// Taken as it was at install: other packages' entries stay, the step's are merged, a null one is removed
|
|||
((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).setInstallState(Map.of("TTN", stateOf(integrationId, "use-existing"))); |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.other-model", "Other").put("profile.milesight-iot-am308", "AM308")); |
|||
current.setConfiguration(configuration); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); |
|||
step.setResolution("use-existing"); |
|||
ObjectNode entries = JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"); |
|||
entries.putNull("profile.milesight-iot-am308"); |
|||
step.setMetadata(entries); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class); |
|||
verify(integrationService).saveIntegration(saved.capture()); |
|||
JsonNode metadata = saved.getValue().getConfiguration().get("metadata"); |
|||
assertThat(metadata.get("profile.other-model").asText()).isEqualTo("Other"); |
|||
assertThat(metadata.get("profile.lansitec-badge").asText()).isEqualTo("Badge"); |
|||
assertThat(metadata.has("profile.milesight-iot-am308")).isFalse(); |
|||
// A copy is saved: the integration read, possibly the cache's own instance, stays as it is until the commit
|
|||
assertThat(saved.getValue()).isNotSameAs(current); |
|||
assertThat(current.getConfiguration().get("metadata").has("profile.lansitec-badge")).isFalse(); |
|||
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("TTN").get("resolution").asText()) |
|||
.isEqualTo("use-existing"); |
|||
} |
|||
|
|||
@Test |
|||
void keptIntegrationWithTheEntriesItHas_isNotSaved() { |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode(); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); |
|||
current.setConfiguration(configuration); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", integrationId); |
|||
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
verify(integrationService, never()).saveIntegration(any()); |
|||
} |
|||
|
|||
@Test |
|||
void twoStepsWithOneKey_areRejected() { |
|||
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId); |
|||
first.setId("main-dashboard"); |
|||
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId); |
|||
second.setId("main-dashboard"); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second)); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void failedStep_rollsBackAndReportsTheStep() { |
|||
when(deviceProfileService.findDeviceProfileById(tenantId, profileId)).thenReturn(profile(3L, "AM308")); |
|||
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> i.getArgument(0)); |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308 profile", "DEVICE_PROFILE", profileId, 3L, JacksonUtil.newObjectNode().put("name", "p")), |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getFailedStep()).isEqualTo("Dashboard"); |
|||
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached"); |
|||
assertThat(rolledBack).hasSize(1); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
verifyNoInteractions(logEntityActionService); |
|||
assertThat(installedItem.getVersion()).isEqualTo("1.0.0"); |
|||
} |
|||
|
|||
@Test |
|||
void entityChangedSinceTheCheck_isAVersionConflict() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L)); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getFailedStep()).isEqualTo("Dashboard"); |
|||
assertThat(result.getErrorMessage()).contains("Check the update again"); |
|||
verify(dashboardService, never()).saveDashboard(any(Dashboard.class)); |
|||
} |
|||
|
|||
@Test |
|||
void integrationGetsTheIdOfTheConverterCreatedInTheSameUpdate() throws Exception { |
|||
ConverterId converterId = new ConverterId(UUID.randomUUID()); |
|||
when(converterService.saveConverter(any())).thenAnswer(i -> { |
|||
Converter converter = i.getArgument(0); |
|||
converter.setId(converterId); |
|||
return converter; |
|||
}); |
|||
Integration current = new Integration(); |
|||
current.setId(integrationId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("TTN my-app"); |
|||
current.setRoutingKey("routing-key"); |
|||
current.setVersion(2L); |
|||
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(current); |
|||
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0)); |
|||
ObjectNode integration = JacksonUtil.newObjectNode().put("name", "Template name").put("type", "TTN").put("edgeTemplate", true); |
|||
integration.set("defaultConverterId", JacksonUtil.newObjectNode().put("entityType", "CONVERTER").put("id", "${uplinkConverter.id}")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")), |
|||
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration))); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class); |
|||
verify(integrationService).saveIntegration(saved.capture()); |
|||
assertThat(saved.getValue().getDefaultConverterId()).isEqualTo(converterId); |
|||
// The devices keep sending to the same endpoint
|
|||
assertThat(saved.getValue().getRoutingKey()).isEqualTo("routing-key"); |
|||
assertThat(saved.getValue().getName()).isEqualTo("TTN my-app"); |
|||
assertThat(result.getOutputs().get("TTN").get("routingKey").asText()).isEqualTo("routing-key"); |
|||
} |
|||
|
|||
@Test |
|||
void overwrittenSharedConverter_isRecordedAsDefaultAndOnlyThePackagesOwnRowIsWritten() { |
|||
ConverterId converterId = new ConverterId(UUID.randomUUID()); |
|||
Converter current = new Converter(converterId); |
|||
current.setTenantId(tenantId); |
|||
current.setName("Uplink data converter for TTN my-app"); |
|||
current.setVersion(4L); |
|||
when(converterService.findConverterById(tenantId, converterId)).thenReturn(current); |
|||
when(converterService.saveConverter(any())).thenAnswer(i -> i.getArgument(0)); |
|||
// The package that created the converter records its checksum; one that took it as it was records none
|
|||
ObjectNode created = JacksonUtil.newObjectNode().put("checksum", "before").put("resolution", "created"); |
|||
created.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); |
|||
ObjectNode usedExisting = JacksonUtil.newObjectNode().put("resolution", "use-existing"); |
|||
usedExisting.set("entityOutput", JacksonUtil.newObjectNode().put("id", converterId.getId().toString())); |
|||
IotHubInstalledItem creator = otherPackage(Map.of("Uplink", created)); |
|||
IotHubInstalledItem taker = otherPackage(Map.of("Uplink", usedExisting)); |
|||
when(installedItemService.findByTenantId(any(), any(), any(), any())) |
|||
.thenReturn(new PageData<>(List.of(installedItem, creator, taker), 1, 3, false)); |
|||
DeviceUpdateRequest.Step step = overwrite("Uplink", "UPLINK_CONVERTER", converterId, 4L, |
|||
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};"))); |
|||
step.setConfirmed(true); |
|||
step.setDefaultConverter(true); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("Uplink"); |
|||
assertThat(state.get("defaultConverter").asBoolean()).isTrue(); |
|||
// The other packages keep what they recorded: check() takes the checksum of any installed package
|
|||
assertThat(created.get("checksum").asText()).isEqualTo("before"); |
|||
verify(installedItemService, never()).save(tenantId, creator); |
|||
verify(installedItemService, never()).save(tenantId, taker); |
|||
} |
|||
|
|||
@Test |
|||
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() { |
|||
DashboardId foreign = new DashboardId(UUID.randomUUID()); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void theDeviceIsNeverOverwritten() { |
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).isEqualTo("The device and its credentials don't change on update"); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void versionOfAnotherItem_isRejected() { |
|||
ObjectNode other = JacksonUtil.newObjectNode().put("itemId", UUID.randomUUID().toString()); |
|||
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(other); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void anotherUpdateCommittedMeanwhile_failsWithoutChanges() { |
|||
// E.g. a second click: it waits for the first one's lock and finds the package on another version
|
|||
IotHubInstalledItem updated = new IotHubInstalledItem(); |
|||
updated.setId(installedItem.getId()); |
|||
updated.setItemVersionId(UUID.fromString(versionId)); |
|||
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).contains("Check the update again"); |
|||
verify(converterService, never()).saveConverter(any()); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void planOfAnotherInstalledVersion_isRejected() { |
|||
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId)); |
|||
request.setFromVersionId(UUID.randomUUID()); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
verify(installedItemService, never()).save(any(), any()); |
|||
} |
|||
|
|||
@Test |
|||
void integrationsNotInThePlan_areRefused() { |
|||
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED)) |
|||
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request( |
|||
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")))); |
|||
|
|||
assertThat(result.isSuccess()).isFalse(); |
|||
assertThat(result.getErrorMessage()).isEqualTo("Integrations feature is disabled!"); |
|||
verify(transactionTemplate, never()).execute(any()); |
|||
} |
|||
|
|||
@Test |
|||
void attributesOfAnOverwrittenEntity_areSavedAfterCommit() { |
|||
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L)); |
|||
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0)); |
|||
DeviceUpdateRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")); |
|||
step.setServerAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}")); |
|||
|
|||
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step)); |
|||
|
|||
assertThat(result.isSuccess()).isTrue(); |
|||
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class); |
|||
verify(telemetryService).saveAttributes(saved.capture()); |
|||
assertThat(saved.getValue().getEntityId()).isEqualTo(dashboardId); |
|||
assertThat(saved.getValue().getScope()).isEqualTo(AttributeScope.SERVER_SCOPE); |
|||
assertThat(saved.getValue().getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString()); |
|||
} |
|||
|
|||
@Test |
|||
void checksum_ignoresDebugSettingsAndTheDefaultProfile() { |
|||
Converter converter = new Converter(); |
|||
converter.setName("Uplink"); |
|||
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {};")); |
|||
String installed = EntityChecksum.of(converter); |
|||
converter.setDebugMode(true); |
|||
converter.setDebugSettings(DebugSettings.all()); |
|||
assertThat(EntityChecksum.of(converter)).isEqualTo(installed); |
|||
converter.setConfiguration(JacksonUtil.newObjectNode().put("decoder", "return {a: 1};")); |
|||
assertThat(EntityChecksum.of(converter)).isNotEqualTo(installed); |
|||
|
|||
DeviceProfile profile = profile(1L, "AM308"); |
|||
String profileChecksum = EntityChecksum.of(profile); |
|||
profile.setDefault(true); |
|||
assertThat(EntityChecksum.of(profile)).isEqualTo(profileChecksum); |
|||
} |
|||
|
|||
@Test |
|||
void checksum_ignoresTheMetadataOfAnIntegration() { |
|||
Integration integration = new Integration(); |
|||
integration.setName("TTN my-app"); |
|||
ObjectNode configuration = JacksonUtil.newObjectNode().put("host", "eu1.cloud.thethings.network"); |
|||
configuration.set("metadata", JacksonUtil.newObjectNode()); |
|||
integration.setConfiguration(configuration); |
|||
String installed = EntityChecksum.of(integration); |
|||
// Another package on the integration adds its profile name
|
|||
((ObjectNode) configuration.get("metadata")).put("profile.milesight-iot-am308", "AM308"); |
|||
assertThat(EntityChecksum.of(integration)).isEqualTo(installed); |
|||
assertThat(integration.getConfiguration().get("metadata").has("profile.milesight-iot-am308")).isTrue(); |
|||
configuration.put("host", "nam1.cloud.thethings.network"); |
|||
assertThat(EntityChecksum.of(integration)).isNotEqualTo(installed); |
|||
} |
|||
|
|||
@Test |
|||
void userMessage_showsValidationMessagesAndHidesInternalOnes() { |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached"))) |
|||
.isEqualTo("Rule chains limit reached"); |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null))) |
|||
.contains("Check the update again"); |
|||
assertThat(DefaultDevicePackageUpdateService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]"))) |
|||
.isEqualTo("Failed to update the device package"); |
|||
} |
|||
|
|||
@Test |
|||
void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() { |
|||
ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); |
|||
ObjectNode node = JacksonUtil.newObjectNode().put("a", "${device.id}").put("b", "x ${device.id} ${gateway.id}"); |
|||
|
|||
ObjectNode resolved = (ObjectNode) DefaultDevicePackageUpdateService.resolvePlaceholders(node, Map.of("device", device)); |
|||
|
|||
assertThat(resolved.get("a").asText()).isEqualTo("123"); |
|||
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}"); |
|||
} |
|||
|
|||
private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) { |
|||
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor(); |
|||
descriptor.setInstallState(installState); |
|||
IotHubInstalledItem item = new IotHubInstalledItem(); |
|||
item.setId(new IotHubInstalledItemId(UUID.randomUUID())); |
|||
item.setTenantId(tenantId); |
|||
item.setItemType("DEVICE"); |
|||
item.setDescriptor(descriptor); |
|||
return item; |
|||
} |
|||
|
|||
private DeviceProfile profile(Long version, String name) { |
|||
DeviceProfile profile = new DeviceProfile(profileId); |
|||
profile.setTenantId(tenantId); |
|||
profile.setName(name); |
|||
profile.setVersion(version); |
|||
return profile; |
|||
} |
|||
|
|||
private Dashboard dashboard(Long version) { |
|||
Dashboard dashboard = new Dashboard(dashboardId); |
|||
dashboard.setTenantId(tenantId); |
|||
dashboard.setTitle("AM308 dashboard"); |
|||
dashboard.setVersion(version); |
|||
return dashboard; |
|||
} |
|||
|
|||
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) { |
|||
DeviceUpdateRequest request = new DeviceUpdateRequest(); |
|||
request.setVersionId(versionId); |
|||
request.setSteps(List.of(steps)); |
|||
return request; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step keep(String name, String type, EntityId id) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.KEEP); |
|||
step.setEntityId(id.getId()); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.OVERWRITE); |
|||
step.setEntityId(id.getId()); |
|||
step.setExpectedVersion(version); |
|||
step.setEntity(entity); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step create(String name, String type, ObjectNode entity) { |
|||
DeviceUpdateRequest.Step step = step(name, type, DeviceUpdateRequest.Action.CREATE); |
|||
step.setEntity(entity); |
|||
return step; |
|||
} |
|||
|
|||
private static DeviceUpdateRequest.Step step(String name, String type, DeviceUpdateRequest.Action action) { |
|||
DeviceUpdateRequest.Step step = new DeviceUpdateRequest.Step(); |
|||
step.setName(name); |
|||
step.setType(type); |
|||
step.setAction(action); |
|||
return step; |
|||
} |
|||
|
|||
|
|||
private static ObjectNode stateOf(EntityId id, String resolution) { |
|||
ObjectNode state = JacksonUtil.newObjectNode().put("resolution", resolution); |
|||
state.set("entityOutput", JacksonUtil.newObjectNode().put("id", id.getId().toString())); |
|||
return state; |
|||
} |
|||
|
|||
} |
|||
File diff suppressed because it is too large
@ -0,0 +1,84 @@ |
|||
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
|
|||
// SPDX-License-Identifier: Apache-2.0
|
|||
import { firstValueFrom } from 'rxjs'; |
|||
import { ResourcesService } from '@core/services/resources.service'; |
|||
import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetTemplateUrl } from '@shared/models/converter.models'; |
|||
import { IntegrationType } from '@shared/models/integration.models'; |
|||
import { ScriptLanguage } from '@shared/models/rule-node.models'; |
|||
import { isEqual } from '@core/utils'; |
|||
import { DeviceInstalledItemDescriptor, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models'; |
|||
import { IotHubApiService } from '@core/http/iot-hub-api.service'; |
|||
import { PageLink } from '@shared/models/page/page-link'; |
|||
import { PageData } from '@shared/models/page/page-data'; |
|||
|
|||
const DEFAULT_CONVERTERS_V2_CONFIGURATION_URL = '/assets/converters/default-converters-v2-configuration.json'; |
|||
|
|||
// The settings of a default converter that decide what it does: the script is compared on its own
|
|||
const V2_CONFIGURATION_KEYS: (keyof ConverterConfigV2)[] = |
|||
['type', 'name', 'profile', 'label', 'customer', 'group', 'attributes', 'telemetry', 'updateOnlyKeys']; |
|||
|
|||
/** |
|||
* The uplink converter ThingsBoard creates for a new integration of this type, as a device package step with |
|||
* "default": true installs it. Null when ThingsBoard has no default converter settings for the type. |
|||
*/ |
|||
export const loadDefaultUplinkConverter = async (resourcesService: ResourcesService, integrationType: IntegrationType, |
|||
scriptLang: ScriptLanguage, name: string): Promise<Partial<Converter> | null> => { |
|||
const configurations = await firstValueFrom( |
|||
resourcesService.loadJsonResource<Record<string, ConverterConfigV2>>(DEFAULT_CONVERTERS_V2_CONFIGURATION_URL)); |
|||
const configuration = configurations?.[integrationType]; |
|||
if (!configuration) { |
|||
return null; |
|||
} |
|||
const script = await firstValueFrom(resourcesService.loadJsonResource<string>( |
|||
getTargetTemplateUrl(ConverterType.UPLINK, scriptLang, integrationType, 2))); |
|||
return { |
|||
name, |
|||
type: ConverterType.UPLINK, |
|||
integrationType, |
|||
converterVersion: 2, |
|||
edgeTemplate: false, |
|||
// As the device packages had it: the debug events help to find out why a LoRaWAN device sends nothing
|
|||
debugSettings: { failuresEnabled: true, allEnabled: true, allEnabledUntil: 0 }, |
|||
configuration: { |
|||
...configuration, |
|||
scriptLang, |
|||
decoder: null, |
|||
tbelDecoder: null, |
|||
encoder: null, |
|||
tbelEncoder: null, |
|||
[getTargetField(ConverterType.UPLINK, scriptLang)]: script |
|||
}, |
|||
additionalInfo: { description: '' } |
|||
}; |
|||
}; |
|||
|
|||
/** True when the converter does something else than the default one: another script or other settings. */ |
|||
export const differsFromDefaultConverter = (converter: Converter, defaultConverter: Partial<Converter>): boolean => { |
|||
const field = getTargetField(ConverterType.UPLINK, converter.configuration.scriptLang); |
|||
const script = (value: string) => (value ?? '').trimEnd(); |
|||
return script(converter.configuration[field]) !== script(defaultConverter.configuration[field]) || |
|||
V2_CONFIGURATION_KEYS.some(key => !isEqual(converter.configuration[key] ?? null, defaultConverter.configuration[key] ?? null)); |
|||
}; |
|||
|
|||
/** |
|||
* The converters device packages installed themselves as their default converter, not ones they took as they were, of |
|||
* all installed device packages: only such a converter is ThingsBoard's default one, which a new ThingsBoard version |
|||
* may change. The installed items table and the update dialog both decide by it. |
|||
*/ |
|||
export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiService): Promise<Set<string>> => { |
|||
const ids = new Set<string>(); |
|||
let pageLink = new PageLink(100); |
|||
let page: PageData<IotHubInstalledItem>; |
|||
do { |
|||
page = await firstValueFrom(iotHubApiService.getInstalledItems(pageLink, 'DEVICE', undefined, { ignoreLoading: true })); |
|||
for (const item of page.data) { |
|||
for (const state of Object.values((item.descriptor as DeviceInstalledItemDescriptor)?.installState ?? {})) { |
|||
if (state?.defaultConverter && state.entityOutput?.id && state.resolution !== 'use-existing') { |
|||
ids.add(state.entityOutput.id); |
|||
} |
|||
} |
|||
} |
|||
pageLink = pageLink.nextPageLink(); |
|||
} while (page.hasNext); |
|||
return ids; |
|||
}; |
|||
Loading…
Reference in new issue