Browse Source

IoT Hub: fixed device package installs leaving entities behind after an error or cancel (#16724)

* IoT Hub device packages: the update service becomes DevicePackageService, ready to install too

* IoT Hub device packages: an install saves its entities and the installed item in one transaction

* IoT Hub device packages: an install keeps only entities the user chose, and its errors read for install too

* IoT Hub device packages: an install from a customer or a device group puts its device and dashboard there, in the same transaction

* IoT Hub device packages: an install never moves an overwritten device to another owner

* IoT Hub device install: the wizard checks every step first, asks about all conflicts at once and installs in one request

* IoT Hub device install: an overwritten device takes the package's credentials, a cancelled check installs nothing, one install is one request

* IoT Hub device install: no second check or install from the step header, Retry checks the package again, messages and comments fit install and update

* IoT Hub device packages: install and update share one plan, review and result path, with neutral names

* IoT Hub device install: the plan looks like the update review, with a footer to confirm warnings and no jump to Verify

* IoT Hub device install: the rows after an install say Created, Used existing, Overwritten or Created copy

* IoT Hub device install: no overwrite of a device or gateway, Use existing keeps the step attributes, Try again asks again about the failed choice

- At install a name conflict on a device or gateway offers only Use existing; the
  server rejects an install that overwrites one. An overwrite keeps the device's
  credentials, which are applied only to a created device.
- Use existing at install writes the step's server and shared attributes after
  commit, as the browser install did.
- Try again at install keeps the conflict choices except the one of the failed step.
- The provisioning step label is translated; ca_ES and ar_AE get the install texts.
- Tests check that the audit log, the Hub install report and the attributes run
  after commit.

* IoT Hub device packages: a test pins that an overwrite keeps the device's credentials

* IoT Hub device install dialog: cleanup after review

* IoT Hub device install: the conflict check resolves names from the plan, an install overwrite sends the version

- The pre-check resolves each step's template with the names the plan gives the
  entities of earlier steps (alias -> name, in step order), not with outputs left
  from a failed attempt, so a dashboard titled ${device.name} is checked under the
  device's planned name and the first check and Try again agree. Placeholders known
  only after the install, e.g. ${device.id}, stay. An update still resolves with the
  installed entities. The request sent to the server is unchanged.
- The pre-check keeps the version of the entity it found (rule chain, dashboard,
  converter, integration), and an install overwrite sends it as expectedVersion, so
  the server rejects an entity changed between the check and the install.
- The conflict message names the existing entity, as a step's name can differ from it.
- The duplicate-key comment says the check runs before the plan is sent, and the
  server checks too.

* IoT Hub device install: a device profile overwrite sends the profile's version

The names lookup has no version, so the pre-check reads the matched profile once and keeps its version for expectedVersion.

* IoT Hub device install: a device overwrite sends the device's version

The device lookup of the pre-check now keeps the version, as the other lookups do, and the state key comment says the duplicate check runs before the plan is sent.

* IoT Hub device install: pass the preview outputs instead of swapping entityOutputs

preCheckTemplates passes its preview outputs to resolveTemplateJson instead of temporarily replacing entityOutputs. Drops duplicated comments and redundant optional chaining in templateNameOf.

---------

Co-authored-by: Viacheslav Klimov <vklimov@thingsboard.io>
Co-authored-by: Vladyslav_Prykhodko <vprykhodko@thingsboard.io>
pull/16704/head
Shvaika Dmytro 3 weeks ago
committed by GitHub
parent
commit
aa7085f410
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 24
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 375
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
  3. 2
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  4. 30
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
  5. 10
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
  6. 9
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
  7. 600
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java
  8. 27
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  9. 169
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html
  10. 16
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss
  11. 992
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  12. 4
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts
  13. 8
      ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts
  14. 21
      ui-ngx/src/app/shared/models/iot-hub/iot-hub-installed-item.models.ts
  15. 21
      ui-ngx/src/assets/locale/locale.constant-ar_AE.json
  16. 21
      ui-ngx/src/assets/locale/locale.constant-ca_ES.json
  17. 3
      ui-ngx/src/assets/locale/locale.constant-da_DK.json
  18. 3
      ui-ngx/src/assets/locale/locale.constant-de_DE.json
  19. 3
      ui-ngx/src/assets/locale/locale.constant-el_GR.json
  20. 18
      ui-ngx/src/assets/locale/locale.constant-en_US.json
  21. 3
      ui-ngx/src/assets/locale/locale.constant-es_ES.json
  22. 3
      ui-ngx/src/assets/locale/locale.constant-fr_FR.json
  23. 3
      ui-ngx/src/assets/locale/locale.constant-hi_IN.json
  24. 3
      ui-ngx/src/assets/locale/locale.constant-it_IT.json
  25. 3
      ui-ngx/src/assets/locale/locale.constant-ja_JP.json
  26. 3
      ui-ngx/src/assets/locale/locale.constant-ko_KR.json
  27. 3
      ui-ngx/src/assets/locale/locale.constant-lt_LT.json
  28. 3
      ui-ngx/src/assets/locale/locale.constant-nl_BE.json
  29. 3
      ui-ngx/src/assets/locale/locale.constant-nl_NL.json
  30. 3
      ui-ngx/src/assets/locale/locale.constant-no_NO.json
  31. 3
      ui-ngx/src/assets/locale/locale.constant-pl_PL.json
  32. 3
      ui-ngx/src/assets/locale/locale.constant-pt_BR.json
  33. 3
      ui-ngx/src/assets/locale/locale.constant-sl_SI.json
  34. 3
      ui-ngx/src/assets/locale/locale.constant-tr_TR.json
  35. 3
      ui-ngx/src/assets/locale/locale.constant-uk_UA.json
  36. 3
      ui-ngx/src/assets/locale/locale.constant-zh_CN.json
  37. 3
      ui-ngx/src/assets/locale/locale.constant-zh_TW.json

24
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -39,9 +39,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.DevicePackageEntityState;
import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService;
import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest;
import org.thingsboard.server.service.iot_hub.DeviceUpdateResult;
import org.thingsboard.server.service.iot_hub.DevicePackageService;
import org.thingsboard.server.service.iot_hub.DevicePackageRequest;
import org.thingsboard.server.service.iot_hub.DevicePackageResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan;
@ -58,7 +58,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController {
private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService;
private final DevicePackageService devicePackageService;
private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService;
@ -103,21 +103,29 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/device/install")
@ResponseBody
public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions();
return devicePackageService.install(getCurrentUser(), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody
public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody
public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DeviceUpdateRequest request) throws ThingsboardException {
public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")

375
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java

@ -16,10 +16,13 @@ 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.Customer;
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.GroupEntity;
import org.thingsboard.server.common.data.HasCustomerId;
import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion;
@ -30,14 +33,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti
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.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.EntityGroupId;
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.group.EntityGroup;
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;
@ -66,6 +72,7 @@ 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.install.ProjectInfo;
import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@ -86,18 +93,17 @@ 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.
* Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the
* templates of the version and sends the entity of each step; this service checks the plan, saves every entity
* and 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 {
public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService {
// 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(
@ -110,7 +116,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
"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 static final String UNEXPECTED_ERROR = "Failed to save the device package";
private final IotHubInstalledItemService installedItemService;
private final IotHubRestClient iotHubRestClient;
@ -129,6 +135,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private final AttributesService attributesService;
private final TelemetrySubscriptionService telemetryService;
private final TransactionTemplate transactionTemplate;
private final ProjectInfo projectInfo;
@Override
public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) {
@ -162,33 +169,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
@Override
public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) {
public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Installing device package version {}", tenantId, request.getVersionId());
DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> {
if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) {
throw new IllegalArgumentException("Invalid install request");
}
Placement placement = placement(tenantId, request);
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
if (versionInfo == null) {
throw new IllegalArgumentException("Failed to get version info from IoT Hub");
}
// The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation
DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor();
validateInstallSteps(request);
validate(tenantId, previous, request);
return transactionTemplate.execute(status -> {
Applied applied = applySteps(tenantId, previous, request, null, placement);
IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText()));
installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
installedItem.setItemName(versionInfo.get("name").asText());
installedItem.setItemType("DEVICE");
installedItem.setVersion(versionInfo.get("version").asText());
installedItem.setDescriptor(applied.descriptor());
installedItemService.save(tenantId, installedItem);
return applied;
});
});
if (result.isSuccess()) {
reportInstall(user, request.getVersionId());
log.info("[{}] Installed device package version {}", tenantId, request.getVersionId());
}
return result;
}
@Override
public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId());
Applied applied;
try {
DevicePackageResult result = apply(user, "update of " + installedItemId, () -> {
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));
validate(tenantId, devicePackage.descriptor(), request);
return transactionTemplate.execute(status -> {
IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE);
installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
installedItem.setItemName(versionInfo.get("name").asText());
installedItem.setVersion(versionInfo.get("version").asText());
installedItem.setDescriptor(applied.descriptor());
installedItemService.save(tenantId, installedItem);
return applied;
});
});
if (result.isSuccess()) {
log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId());
}
return result;
}
/** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */
private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) {
TenantId tenantId = user.getTenantId();
Applied applied;
try {
applied = change.apply();
} catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey);
log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause());
return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey);
} 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);
log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e);
return DevicePackageResult.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);
log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e);
return DevicePackageResult.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());
return DevicePackageResult.success(applied.descriptor(), applied.outputs());
}
/** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */
private void reportInstall(SecurityUser user, String versionId) {
TenantId tenantId = user.getTenantId();
try {
InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(),
projectInfo.getProjectVersion(), projectInfo.getProductType());
iotHubRestClient.reportVersionInstalled(versionId, report);
} catch (Exception e) {
log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage());
}
}
/**
* At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or
* gateway is never overwritten: its credentials are what its firmware uses.
*/
private static void validateInstallSteps(DevicePackageRequest request) {
if (request.getSteps() == null) {
return;
}
for (DevicePackageRequest.Step step : request.getSteps()) {
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution()))
|| (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) {
throw new IllegalArgumentException("Invalid install step: " + step.getName());
}
}
}
/**
* The customer and the device group the install was opened from; each must be the tenant's. The group's own
* permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources.
*/
private Placement placement(TenantId tenantId, DevicePackageRequest request) {
CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId())
? new CustomerId(request.getCustomerId()) : null;
if (customerId != null && !isTenantsCustomer(tenantId, customerId)) {
throw new IllegalArgumentException("Invalid install request");
}
if (request.getEntityGroupId() == null) {
return new Placement(customerId, customerId, null);
}
EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId()));
EntityId owner = group != null ? group.getOwnerId() : null;
boolean tenants = owner != null && (tenantId.equals(owner)
|| (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId()))));
if (group == null || group.getType() != EntityType.DEVICE || !tenants) {
throw new IllegalArgumentException("Invalid install request");
}
// As a device saved into a group: with no customer given, a new one goes to the group's customer
CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId;
return new Placement(customerId, deviceCustomerId, group);
}
private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) {
Customer customer = customerService.findCustomerById(tenantId, customerId);
return customer != null && tenantId.equals(customer.getTenantId());
}
/**
* Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without
* a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale.
*/
private static void assignCustomer(GroupEntity<?> entity, CustomerId customerId, GroupEntity<?> current, DevicePackageRequest.Step step) {
if (customerId != null) {
entity.setOwnerId(customerId);
}
if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) {
throw new IllegalArgumentException(step.getName() + " belongs to another owner");
}
}
/** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */
private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception {
validatePlan(ownedIds(previous), request);
checkFeatures(tenantId, request);
validateIntegrations(tenantId, request);
}
private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) {
@ -201,50 +343,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
/**
* The update may only change what the package owns, or what the user confirmed. The device and the gateway,
* The device package may only change what it owns, or what the user confirmed. Its own device and gateway,
* whose credentials the firmware uses, are never changed.
*/
private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) {
private void validatePlan(Set<UUID> ownedIds, DevicePackageRequest request) {
if (request.getSteps() == null || request.getSteps().isEmpty()) {
throw new IllegalArgumentException("The update has no steps");
throw new IllegalArgumentException("The device package has no steps");
}
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor());
// A form's values are saved under its key too, so an entity step may not share it
Set<String> stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>();
for (DeviceUpdateRequest.Step step : request.getSteps()) {
for (DevicePackageRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
throw new IllegalArgumentException("Invalid update step: " + step.getName());
throw new IllegalArgumentException("Invalid step: " + step.getName());
}
if (!stateKeys.add(step.stateKey())) {
throw new IllegalArgumentException("Duplicate update step: " + step.stateKey());
throw new IllegalArgumentException("Duplicate step: " + step.stateKey());
}
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());
throw new IllegalArgumentException("No entity for step: " + step.getName());
}
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId());
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed()
if (step.getAction() == DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.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());
if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) {
throw new IllegalArgumentException("No entity data for 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
private void checkFeatures(TenantId tenantId, DevicePackageRequest request) {
boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER")));
if (savesIntegrations) {
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
@ -252,13 +393,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
/** 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) {
private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception {
for (DevicePackageRequest.Step step : request.getSteps()) {
if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) {
continue;
}
ObjectNode body = step.getEntity().deepCopy();
// Converters this update creates have no id yet; the configuration doesn't depend on them
// Converters the request 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);
@ -274,9 +415,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
}
private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) {
IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
DeviceInstalledItemDescriptor previous = devicePackage.descriptor();
/**
* Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the
* same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null.
*/
private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId,
Placement placement) {
Set<UUID> ownedIds = ownedIds(previous);
Map<String, ObjectNode> aliasOutputs = new HashMap<>();
Map<String, ObjectNode> outputs = new LinkedHashMap<>();
@ -291,21 +435,22 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
List<EntityId> stepEntityIds = new ArrayList<>();
Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous);
List<SavedEntity> saved = new ArrayList<>();
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>();
List<SavedEntity> grouped = new ArrayList<>();
List<DevicePackageRequest.Step> connectorSteps = new ArrayList<>();
List<StepAttributes> attributes = new ArrayList<>();
DashboardId dashboardId = null;
for (DeviceUpdateRequest.Step step : request.getSteps()) {
for (DevicePackageRequest.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) {
if (step.getAction() != DevicePackageRequest.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);
StepResult result = applyStep(tenantId, step, entity, placement);
ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.stateKey(), output);
@ -317,7 +462,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
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();
String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum();
if (checksum != null) {
state.put("checksum", checksum);
}
@ -343,8 +488,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
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
if (placement.entityGroup() != null && result.saved() != null && result.saved().created()
&& result.entityId().getEntityType() == EntityType.DEVICE) {
entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId());
grouped.add(result.saved());
}
// The step's attributes go with the entity it saved; at install also onto an entity the user chose to
// use, as the install always did. Written after commit
boolean install = installedVersionId == null;
if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) {
attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes()));
}
} catch (StepFailure e) {
@ -356,7 +508,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
// An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps
// it changes: the other steps and the forms keep their install state
if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) {
if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) {
previous.getInstallState().forEach((key, value) -> {
if (value instanceof ObjectNode state) {
installState.putIfAbsent(key, state);
@ -376,15 +528,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
carryMetadataStates(previous, tracked, state);
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);
return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped);
}
/** The checksums the installed device packages recorded, by entity. */
@ -422,7 +569,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* 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) {
private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest 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())
@ -432,11 +579,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return installedItem;
}
private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException {
private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) 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 "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement);
case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement);
case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity);
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity);
case "INTEGRATION" -> saveIntegration(tenantId, step, entity);
@ -444,16 +591,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
};
}
private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(profile, id, current, step);
// The tenant's default profile stays the default one
@ -466,31 +613,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null;
Device device;
boolean created = false;
if (step.getAction() == DeviceUpdateRequest.Action.CREATE) {
if (step.getAction() == DevicePackageRequest.Action.CREATE) {
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
template.setId(null);
template.setVersion(null);
assignCustomer(template, placement.deviceCustomerId(), null, step);
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
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
// On update, another device the user chose to overwrite; it keeps its credentials. The package's own
// device never changes, and an install never overwrites one
Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId);
prepareOverwrite(template, id, current, step);
assignCustomer(template, placement.customerId(), current, step);
device = deviceService.saveDevice(template);
created = true;
}
}
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId());
if (created && step.getCredentials() != null && step.getCredentials().isObject()) {
if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) {
credentials = applyCredentials(tenantId, credentials, step.getCredentials());
}
ObjectNode output = output(device.getId(), device.getName());
@ -500,7 +650,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
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;
SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null;
return new StepResult(device.getId(), output, null, saved);
}
@ -520,16 +670,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials);
}
private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
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) {
if (step.getAction() == DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(dashboard, id, current, step);
// The dashboard keeps its owner and the customers it is assigned to
@ -537,25 +687,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
dashboard.setCustomerId(current.getCustomerId());
}
dashboard.setAssignedCustomers(current.getAssignedCustomers());
assignCustomer(dashboard, placement.customerId(), current, step);
} else {
dashboard.setId(null);
dashboard.setVersion(null);
assignCustomer(dashboard, placement.customerId(), null, step);
}
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 {
private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(ruleChain, id, current, step);
// A rule chain the tenant made its root one stays the root
@ -578,17 +730,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(converter, id, current, step);
} else {
@ -599,10 +751,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
}
private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) {
private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.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) {
if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step);
Integration merged = withMergedMetadata(current, step.getMetadata());
if (merged != null) {
@ -613,7 +765,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
integration.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) {
if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step);
prepareOverwrite(integration, id, current, step);
// The devices keep sending to the same endpoint
@ -668,7 +820,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
/**
* 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.
* A copy: the integration may be the cache's own instance, which a rolled back install or update must not change.
*/
private static Integration withMergedMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) {
@ -698,7 +850,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* 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) {
private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.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()); }
@ -715,9 +867,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
((HasVersion) entity).setVersion(currentVersion);
}
private <T> T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) {
private <T> T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) {
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) {
throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again.");
throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again.");
}
return current;
}
@ -745,9 +897,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* 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) {
private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.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));
return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE));
}
private static ObjectNode output(EntityId id, String name) {
@ -775,7 +927,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
}
/** Replaces ${<alias>.<property>} of entities this update has saved, e.g. the id of a converter it created. */
/** Replaces ${<alias>.<property>} of entities the request 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;
@ -834,17 +986,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
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. */
/**
* What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install
* or update.
*/
private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) {
for (SavedEntity saved : applied.saved()) {
try {
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(),
CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null;
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId,
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);
log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e);
}
}
for (SavedEntity saved : applied.grouped()) {
try {
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(),
ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName());
} catch (Exception e) {
log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e);
}
}
for (StepAttributes step : applied.attributes()) {
@ -855,7 +1019,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e);
}
}
for (DeviceUpdateRequest.Step step : applied.connectorSteps()) {
for (DevicePackageRequest.Step step : applied.connectorSteps()) {
try {
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity());
} catch (Exception e) {
@ -905,7 +1069,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
*/
static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) {
return "Someone changed it while you were reviewing the update. Check the update again.";
return "Someone changed it meanwhile. Check the package again.";
}
if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException
|| e instanceof SubscriptionException) {
@ -961,8 +1125,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return ids;
}
private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) {
DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class);
private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) {
DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class);
if (entity != null) {
copy.setEntity(entity);
}
@ -972,6 +1136,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) {
}
@FunctionalInterface
private interface PackageChange {
Applied apply() throws Exception;
}
private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) {
}
@ -982,8 +1151,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}
private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved,
List<DeviceUpdateRequest.Step> connectorSteps, List<StepAttributes> attributes,
Map<String, ObjectNode> aliasOutputs) {
List<DevicePackageRequest.Step> connectorSteps, List<StepAttributes> attributes,
Map<String, ObjectNode> aliasOutputs, EntityGroup entityGroup, List<SavedEntity> grouped) {
}
/**
* Where an install opened from a customer's or a device group's page puts its entities. A new device follows the
* group's customer when no customer is given, as a device saved into a group does; an update has none.
*/
private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) {
static final Placement NONE = new Placement(null, null, null);
}
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */

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

@ -421,7 +421,7 @@ public class DefaultIotHubService implements IotHubService {
String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) {
// Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService
// Updated in one transaction from the install wizard of the new version, see DevicePackageService
throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
}
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();

30
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java

@ -10,28 +10,33 @@ 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.
* The install or update of a device package as the install wizard planned it: the entity of each install step
* of the version being installed, already resolved from its template, and what to do with it. The server applies
* all of it in one transaction, together with the installed item, or nothing.
*/
@Data
public class DeviceUpdateRequest {
public class DevicePackageRequest {
private String versionId;
// The version installed when the wizard planned the update; the update fails if the package changed since
// Update only: the version installed when the wizard planned the update, which fails if the package changed since
private UUID fromVersionId;
// The install method of the new version's steps; the installed one when not set
// The install method of the steps; an update without it keeps the installed one
private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it
private Map<String, JsonNode> installState;
// Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard
// go to, and the group the created device or gateway is added to. An update ignores them
private UUID customerId;
private UUID entityGroupId;
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
// Taken as it is: an update's 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
// A new entity: one the package installs, a step new in this version or deleted since install, or a copy
// next to one with the same name
CREATE
}
@ -51,13 +56,13 @@ public class DeviceUpdateRequest {
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.
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity the
// request 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.
// they may keep ${<alias>.<property>} of an entity the request creates.
private JsonNode serverAttributes;
private JsonNode sharedAttributes;
// The resolution the install state records for it
@ -65,7 +70,8 @@ public class DeviceUpdateRequest {
// 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
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later
// update checks that converter against ThingsBoard's default one
private boolean defaultConverter;
/**

10
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java

@ -17,7 +17,7 @@ import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeviceUpdateResult {
public class DevicePackageResult {
private boolean success;
private String errorMessage;
@ -26,12 +26,12 @@ public class DeviceUpdateResult {
// By install state key of the step: 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 DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DevicePackageResult(true, null, null, descriptor, outputs);
}
public static DeviceUpdateResult error(String errorMessage, String failedStep) {
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null);
public static DevicePackageResult error(String errorMessage, String failedStep) {
return new DevicePackageResult(false, errorMessage, failedStep, null, null);
}
}

9
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java

@ -7,13 +7,16 @@ 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 {
/** Installs a device package, or updates an installed one to another version of its item. */
public interface DevicePackageService {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId);
/** Installs the version in one transaction, together with its installed item, or nothing. */
DevicePackageResult install(SecurityUser user, DevicePackageRequest request);
/** 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);
DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request);
}

600
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateServiceTest.java → application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java

@ -8,6 +8,7 @@ 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.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ -16,12 +17,17 @@ 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.springframework.web.client.RestClientException;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
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.User;
import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
@ -30,23 +36,29 @@ 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.EntityGroupId;
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.id.UserId;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.security.DeviceCredentials;
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.customer.CustomerService;
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.group.EntityGroupService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.dao.subscription.PlatformFeature;
@ -54,6 +66,7 @@ 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.install.ProjectInfo;
import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@ -62,20 +75,25 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
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.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class DefaultDevicePackageUpdateServiceTest {
class DefaultDevicePackageServiceTest {
private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID());
private final SecurityUser user = mock(SecurityUser.class);
@ -119,18 +137,30 @@ class DefaultDevicePackageUpdateServiceTest {
private TelemetrySubscriptionService telemetryService;
@Mock
private IotHubService iotHubService;
@Mock
private ProjectInfo projectInfo;
@Mock
private CustomerService customerService;
@Mock
private EntityGroupService entityGroupService;
@InjectMocks
private DefaultDevicePackageUpdateService service;
private DefaultDevicePackageService service;
private IotHubInstalledItem installedItem;
// Set when the transaction callback threw, so the transaction would roll back
private final List<RuntimeException> rolledBack = new ArrayList<>();
private boolean inTransaction;
private final List<String> savedInTransaction = new ArrayList<>();
// What must run after commit: the audit log, the Hub install report and the attributes, each marked if it ran inside
private final List<String> afterCommitCalls = new ArrayList<>();
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(service, "entityService", entityService);
ReflectionTestUtils.setField(service, "logEntityActionService", logEntityActionService);
ReflectionTestUtils.setField(service, "customerService", customerService);
ReflectionTestUtils.setField(service, "entityGroupService", entityGroupService);
when(user.getTenantId()).thenReturn(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
@ -158,11 +188,14 @@ class DefaultDevicePackageUpdateServiceTest {
when(iotHubRestClient.getVersionInfo(versionId)).thenReturn(versionInfo);
when(transactionTemplate.execute(any())).thenAnswer(invocation -> {
inTransaction = true;
try {
return invocation.<TransactionCallback<?>>getArgument(0).doInTransaction(null);
} catch (RuntimeException e) {
rolledBack.add(e);
throw e;
} finally {
inTransaction = false;
}
});
when(packageEntities.checksum(any(), any())).thenReturn("checksum");
@ -184,7 +217,7 @@ class DefaultDevicePackageUpdateServiceTest {
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(
DevicePackageResult result = service.update(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"))));
@ -218,10 +251,10 @@ class DefaultDevicePackageUpdateServiceTest {
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));
DevicePackageRequest request = request(keep("Dashboard", "DASHBOARD", dashboardId));
request.setSelectedInstallMethod("INTEGRATION_CHIRPSTACK");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -237,10 +270,10 @@ class DefaultDevicePackageUpdateServiceTest {
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);
DevicePackageRequest.Step overview = keep("Overview", "DASHBOARD", dashboardId);
overview.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(overview));
DevicePackageResult result = service.update(user, installedItem.getId(), request(overview));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -256,7 +289,7 @@ class DefaultDevicePackageUpdateServiceTest {
((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)));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -266,10 +299,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void useExistingOfAPackageEntity_staysThePackages() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
DevicePackageRequest.Step step = keep("Overview", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -282,10 +315,10 @@ class DefaultDevicePackageUpdateServiceTest {
// 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);
DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -295,9 +328,9 @@ class DefaultDevicePackageUpdateServiceTest {
@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"));
DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@ -327,10 +360,10 @@ class DefaultDevicePackageUpdateServiceTest {
// 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);
DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setResolution("use-existing");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -343,9 +376,9 @@ class DefaultDevicePackageUpdateServiceTest {
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"));
DevicePackageRequest.Step step = overwrite("Dashboard", "DASHBOARD", dashboardId, 9L, JacksonUtil.newObjectNode().put("title", "Dashboard"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@ -358,7 +391,7 @@ class DefaultDevicePackageUpdateServiceTest {
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)));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getUsedExistingEntityIds()).containsExactly(dashboardId);
@ -377,13 +410,13 @@ class DefaultDevicePackageUpdateServiceTest {
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);
DevicePackageRequest.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));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Integration> saved = ArgumentCaptor.forClass(Integration.class);
@ -411,7 +444,7 @@ class DefaultDevicePackageUpdateServiceTest {
integration.setId(integrationId);
when(entityService.fetchEntity(tenantId, integrationId)).thenReturn(Optional.of(integration));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -438,11 +471,11 @@ class DefaultDevicePackageUpdateServiceTest {
current.setConfiguration(configuration);
when(integrationService.findIntegrationById(tenantId, tenantsIntegrationId)).thenReturn(current);
when(integrationService.saveIntegration(any())).thenAnswer(i -> i.getArgument(0));
DeviceUpdateRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId);
DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", tenantsIntegrationId);
step.setResolution("use-existing");
step.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) installedItem.getDescriptor();
@ -465,10 +498,10 @@ class DefaultDevicePackageUpdateServiceTest {
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);
DevicePackageRequest.Step step = keep("TTN", "INTEGRATION", integrationId);
step.setMetadata(JacksonUtil.newObjectNode().put("profile.lansitec-badge", "Badge"));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(step));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
verify(integrationService, never()).saveIntegration(any());
@ -476,12 +509,12 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void twoStepsWithOneKey_areRejected() {
DeviceUpdateRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
DevicePackageRequest.Step first = keep("Overview", "DASHBOARD", dashboardId);
first.setId("main-dashboard");
DeviceUpdateRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
DevicePackageRequest.Step second = keep("Details", "DASHBOARD", dashboardId);
second.setId("main-dashboard");
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(first, second));
DevicePackageResult result = service.update(user, installedItem.getId(), request(first, second));
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@ -489,25 +522,25 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void twoStepsOfOneTypeAndName_areRejected() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
keep("Dashboard", "DASHBOARD", dashboardId), keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: DASHBOARD:Dashboard");
verify(transactionTemplate, never()).execute(any());
}
@Test
void stepWithTheKeyOfAForm_isRejected() {
DeviceUpdateRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
DevicePackageRequest.Step step = keep("Dashboard", "DASHBOARD", dashboardId);
step.setId("Settings");
DeviceUpdateRequest request = request(step);
DevicePackageRequest request = request(step);
request.setInstallState(Map.of("Settings", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("interval", 10))));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Duplicate update step: Settings");
assertThat(result.getErrorMessage()).isEqualTo("Duplicate step: Settings");
verify(transactionTemplate, never()).execute(any());
}
@ -532,14 +565,14 @@ class DefaultDevicePackageUpdateServiceTest {
legacy.set("metadata", JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
installed.setInstallState(Map.of("${integrationName}", legacy, "${profileName}", stateOf(profileId, "created"),
"Configuration", JacksonUtil.newObjectNode().set("formValues", JacksonUtil.newObjectNode().put("integrationName", "TTN my-app"))));
DeviceUpdateRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
DevicePackageRequest.Step uplink = keep("${integrationName}", "UPLINK_CONVERTER", converterId);
uplink.setDefaultConverter(true);
DeviceUpdateRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
DevicePackageRequest.Step ttn = keep("${integrationName}", "INTEGRATION", integrationId);
ttn.setMetadata(JacksonUtil.newObjectNode().put("profile.milesight-iot-am308", "AM308"));
DeviceUpdateRequest request = request(uplink, ttn);
DevicePackageRequest request = request(uplink, ttn);
request.setInstallState(Map.of("Configuration", installed.getInstallState().get("Configuration")));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@ -563,7 +596,7 @@ class DefaultDevicePackageUpdateServiceTest {
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(
DevicePackageResult result = service.update(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"))));
@ -580,12 +613,12 @@ class DefaultDevicePackageUpdateServiceTest {
void entityChangedSinceTheCheck_isAVersionConflict() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(8L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).contains("Check the update again");
assertThat(result.getErrorMessage()).contains("Check the package again");
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
}
@ -608,7 +641,7 @@ class DefaultDevicePackageUpdateServiceTest {
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(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN")),
overwrite("TTN", "INTEGRATION", integrationId, 2L, integration)));
@ -640,12 +673,12 @@ class DefaultDevicePackageUpdateServiceTest {
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,
DevicePackageRequest.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));
DevicePackageResult result = service.update(user, installedItem.getId(), request(step));
assertThat(result.isSuccess()).isTrue();
JsonNode state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState().get("UPLINK_CONVERTER:Uplink");
@ -672,14 +705,14 @@ class DefaultDevicePackageUpdateServiceTest {
ObjectNode versionInfo = JacksonUtil.newObjectNode().put("itemId", itemId.toString()).put("name", "AM308").put("version", "1.0.0");
when(iotHubRestClient.getVersionInfo(installedVersionId.toString())).thenReturn(versionInfo);
// ThingsBoard's default converter changed: only the converter step is sent
DeviceUpdateRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
DevicePackageRequest.Step step = overwrite("Uplink data converter", "UPLINK_CONVERTER", converterId, 4L,
JacksonUtil.newObjectNode().put("name", "Uplink").set("configuration", JacksonUtil.newObjectNode().put("tbelDecoder", "return {};")));
step.setId("uplink");
step.setDefaultConverter(true);
DeviceUpdateRequest request = request(step);
DevicePackageRequest request = request(step);
request.setVersionId(installedVersionId.toString());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
Map<String, JsonNode> state = ((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState();
@ -697,7 +730,7 @@ class DefaultDevicePackageUpdateServiceTest {
void updateToAnotherVersion_dropsTheInstallStateOfTheStepsItLeavesOut() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(9L));
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("Dashboard", "DASHBOARD", dashboardId)));
assertThat(result.isSuccess()).isTrue();
assertThat(((DeviceInstalledItemDescriptor) installedItem.getDescriptor()).getInstallState()).containsOnlyKeys("DASHBOARD:Dashboard");
@ -707,7 +740,7 @@ class DefaultDevicePackageUpdateServiceTest {
void overwritingAnEntityOfAnotherPackage_needsAConfirmation() {
DashboardId foreign = new DashboardId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("Dashboard", "DASHBOARD", foreign, 1L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
@ -716,7 +749,7 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void theDeviceIsNeverOverwritten() {
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
overwrite("AM308", "DEVICE", deviceId, 1L, JacksonUtil.newObjectNode().put("name", "d"))));
assertThat(result.isSuccess()).isFalse();
@ -729,7 +762,7 @@ class DefaultDevicePackageUpdateServiceTest {
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)));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId)));
assertThat(result.isSuccess()).isFalse();
verify(transactionTemplate, never()).execute(any());
@ -743,7 +776,7 @@ class DefaultDevicePackageUpdateServiceTest {
updated.setItemVersionId(UUID.fromString(versionId));
when(installedItemService.findByIdForUpdate(tenantId, installedItem.getId())).thenReturn(updated);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
@ -754,10 +787,10 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void planOfAnotherInstalledVersion_isRejected() {
DeviceUpdateRequest request = request(keep("AM308", "DEVICE", deviceId));
DevicePackageRequest request = request(keep("AM308", "DEVICE", deviceId));
request.setFromVersionId(UUID.randomUUID());
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request);
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isFalse();
verify(installedItemService, never()).save(any(), any());
@ -768,7 +801,7 @@ class DefaultDevicePackageUpdateServiceTest {
doThrow(new SubscriptionException("Integrations feature is disabled!", SubscriptionErrorCode.FEATURE_DISABLED))
.when(subscriptionService).checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
DeviceUpdateResult result = service.apply(user, installedItem.getId(), request(
DevicePackageResult result = service.update(user, installedItem.getId(), request(
create("Uplink", "UPLINK_CONVERTER", JacksonUtil.newObjectNode().put("name", "Uplink for TTN"))));
assertThat(result.isSuccess()).isFalse();
@ -780,10 +813,10 @@ class DefaultDevicePackageUpdateServiceTest {
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"));
DevicePackageRequest.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));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
@ -829,12 +862,12 @@ class DefaultDevicePackageUpdateServiceTest {
@Test
void userMessage_showsValidationMessagesAndHidesInternalOnes() {
assertThat(DefaultDevicePackageUpdateService.userMessage(new DataValidationException("Rule chains limit reached")))
assertThat(DefaultDevicePackageService.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");
assertThat(DefaultDevicePackageService.userMessage(new EntityVersionMismatchException(EntityType.DASHBOARD, null)))
.contains("Check the package again");
assertThat(DefaultDevicePackageService.userMessage(new IllegalStateException("could not execute statement; SQL [n/a]")))
.isEqualTo("Failed to save the device package");
}
@Test
@ -842,12 +875,431 @@ class DefaultDevicePackageUpdateServiceTest {
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));
ObjectNode resolved = (ObjectNode) DefaultDevicePackageService.resolvePlaceholders(node, Map.of("device", device));
assertThat(resolved.get("a").asText()).isEqualTo("123");
assertThat(resolved.get("b").asText()).isEqualTo("x 123 ${gateway.id}");
}
@Test
void installSavesTheEntitiesAndTheInstalledItemInOneTransaction() {
mockInstall();
DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId);
integrationStep.setResolution("use-existing");
DevicePackageResult result = service.install(user, request(
create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")),
integrationStep,
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
assertThat(result.isSuccess()).isTrue();
verify(transactionTemplate).execute(any());
assertThat(savedInTransaction).containsExactly("DEVICE_PROFILE", "DASHBOARD", "INSTALLED_ITEM");
ArgumentCaptor<IotHubInstalledItem> saved = ArgumentCaptor.forClass(IotHubInstalledItem.class);
verify(installedItemService).save(eq(tenantId), saved.capture());
IotHubInstalledItem item = saved.getValue();
assertThat(item.getTenantId()).isEqualTo(tenantId);
assertThat(item.getItemId()).isEqualTo(itemId);
assertThat(item.getItemVersionId()).isEqualTo(UUID.fromString(versionId));
assertThat(item.getVersion()).isEqualTo("1.0.1");
assertThat(item.getItemName()).isEqualTo("AM308");
assertThat(item.getItemType()).isEqualTo("DEVICE");
DeviceInstalledItemDescriptor descriptor = (DeviceInstalledItemDescriptor) item.getDescriptor();
assertThat(descriptor.getCreatedEntityIds()).containsExactly(profileId, integrationId, dashboardId);
assertThat(descriptor.getUsedExistingEntityIds()).containsExactly(integrationId);
assertThat(descriptor.getDashboardId()).isEqualTo(dashboardId);
Map<String, JsonNode> state = descriptor.getInstallState();
assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("entityOutput").get("id").asText()).isEqualTo(profileId.getId().toString());
assertThat(state.get("DEVICE_PROFILE:AM308 profile").get("checksum").isTextual()).isTrue();
assertThat(state.get("DASHBOARD:Dashboard").get("entityOutput").get("id").asText()).isEqualTo(dashboardId.getId().toString());
assertThat(state.get("DASHBOARD:Dashboard").get("checksum").isTextual()).isTrue();
assertThat(state.get("INTEGRATION:TTN").get("entityOutput").get("id").asText()).isEqualTo(integrationId.getId().toString());
assertThat(state.get("INTEGRATION:TTN").get("resolution").asText()).isEqualTo("use-existing");
assertThat(result.getDescriptor()).isSameAs(descriptor);
assertThat(result.getOutputs()).containsOnlyKeys("DEVICE_PROFILE:AM308 profile", "INTEGRATION:TTN", "DASHBOARD:Dashboard");
assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "REPORT");
}
@Test
void installFailureOnALaterStepSavesNothing() {
mockInstall();
when(dashboardService.saveDashboard(any(Dashboard.class))).thenThrow(new DataValidationException("Dashboards limit reached"));
DevicePackageResult result = service.install(user, request(
create("AM308 profile", "DEVICE_PROFILE", JacksonUtil.newObjectNode().put("name", "milesight-iot-am308")),
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("DASHBOARD:Dashboard");
assertThat(result.getErrorMessage()).isEqualTo("Dashboards limit reached");
assertThat(rolledBack).hasSize(1);
verify(installedItemService, never()).save(any(), any());
verifyNoInteractions(logEntityActionService, telemetryService);
verify(iotHubRestClient, never()).reportVersionInstalled(any(), any());
}
@Test
void installOverwriteOfAnExistingEntityNeedsAConfirmation() {
mockInstall();
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
DevicePackageResult result = service.install(user, request(
overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Overwriting an entity of another package needs a confirmation: Dashboard");
verify(transactionTemplate, never()).execute(any());
verify(dashboardService, never()).saveDashboard(any(Dashboard.class));
verify(installedItemService, never()).save(any(), any());
}
@Test
void installWithBadIntegrationCredentialsSavesNothing() throws Exception {
mockInstall();
doThrow(new ExecutionException(new IllegalStateException("Wrong API key")))
.when(tbIntegrationService).validateIntegrationConfiguration(eq(tenantId), any());
DevicePackageResult result = service.install(user, request(
create("TTN", "INTEGRATION", JacksonUtil.newObjectNode().put("name", "TTN").put("type", "TTN"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("INTEGRATION:TTN");
assertThat(result.getErrorMessage()).isEqualTo("Wrong API key");
verify(transactionTemplate, never()).execute(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void installWhenHubIsUnavailableSavesNothing() {
mockInstall();
when(iotHubRestClient.getVersionInfo(versionId)).thenThrow(new RestClientException("Connection refused"));
DevicePackageResult result = service.install(user, request(
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("IoT Hub is unavailable. Try again later.");
verify(transactionTemplate, never()).execute(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void installReportsToTheHubAfterCommitAndIgnoresAReportFailure() {
mockInstall();
doAnswer(i -> {
recordAfterCommit("REPORT");
throw new RestClientException("Connection refused");
}).when(iotHubRestClient).reportVersionInstalled(eq(versionId), any());
DevicePackageResult result = service.install(user, request(
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
assertThat(result.isSuccess()).isTrue();
InOrder order = inOrder(installedItemService, logEntityActionService, iotHubRestClient);
order.verify(installedItemService).save(eq(tenantId), any());
order.verify(logEntityActionService).logEntityAction(eq(tenantId), eq(dashboardId), any(), any(), eq(ActionType.ADDED), eq(user));
order.verify(iotHubRestClient).reportVersionInstalled(eq(versionId), any());
assertThat(afterCommitCalls).containsExactly("AUDIT", "REPORT");
}
@Test
void installRejectsAFromVersion() {
mockInstall();
DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
request.setFromVersionId(installedVersionId);
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
verify(transactionTemplate, never()).execute(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void installKeepStepMustUseExisting() {
mockInstall();
DevicePackageRequest.Step integrationStep = keep("TTN", "INTEGRATION", integrationId);
integrationStep.setResolution("created");
DevicePackageResult result = service.install(user, request(integrationStep));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: TTN");
verify(transactionTemplate, never()).execute(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void installRejectsAMalformedVersionId() {
mockInstall();
DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
request.setVersionId("not-a-uuid");
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
verify(iotHubRestClient, never()).getVersionInfo(any());
verify(transactionTemplate, never()).execute(any());
}
@Test
void installAssignsTheCustomerToTheDeviceAndTheDashboard() {
mockInstall();
CustomerId customerId = customerOf(tenantId);
DevicePackageRequest request = request(
create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
request.setCustomerId(customerId.getId());
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Device> device = ArgumentCaptor.forClass(Device.class);
verify(deviceService).saveDevice(device.capture());
assertThat(device.getValue().getCustomerId()).isEqualTo(customerId);
ArgumentCaptor<Dashboard> dashboard = ArgumentCaptor.forClass(Dashboard.class);
verify(dashboardService).saveDashboard(dashboard.capture());
assertThat(dashboard.getValue().getCustomerId()).isEqualTo(customerId);
}
@Test
void installAddsTheDeviceToTheEntityGroup() {
mockInstall();
EntityGroup group = new EntityGroup();
group.setId(new EntityGroupId(UUID.randomUUID()));
group.setType(EntityType.DEVICE);
group.setName("Warehouse sensors");
group.setOwnerId(tenantId);
when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group);
DevicePackageRequest request = request(
create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
request.setEntityGroupId(group.getId().getId());
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isTrue();
verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId);
verify(entityGroupService, never()).addEntityToEntityGroup(any(), any(), eq(dashboardId));
assertThat(savedInTransaction).contains("ENTITY_GROUP");
verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), any(), eq(ActionType.ADDED_TO_ENTITY_GROUP),
eq(user), eq(deviceId.toString()), eq(group.getId().toString()), eq("Warehouse sensors"));
assertThat(afterCommitCalls).containsExactly("AUDIT", "AUDIT", "AUDIT", "REPORT");
}
@Test
void installRejectsACustomerOfAnotherTenant() {
mockInstall();
CustomerId customerId = customerOf(TenantId.fromUUID(UUID.randomUUID()));
DevicePackageRequest request = request(create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "d")));
request.setCustomerId(customerId.getId());
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Invalid install request");
verify(transactionTemplate, never()).execute(any());
verify(installedItemService, never()).save(any(), any());
}
@Test
void updateIgnoresCustomerAndEntityGroup() {
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard(7L));
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> i.getArgument(0));
DevicePackageRequest request = request(overwrite("Dashboard", "DASHBOARD", dashboardId, 7L, JacksonUtil.newObjectNode().put("title", "d")));
request.setCustomerId(UUID.randomUUID());
request.setEntityGroupId(UUID.randomUUID());
DevicePackageResult result = service.update(user, installedItem.getId(), request);
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Dashboard> dashboard = ArgumentCaptor.forClass(Dashboard.class);
verify(dashboardService).saveDashboard(dashboard.capture());
assertThat(dashboard.getValue().getCustomerId()).isNull();
verifyNoInteractions(customerService, entityGroupService);
}
@Test
void updateOverwriteOfACustomerDeviceThatChangesItsOwnerFails() {
DeviceId otherId = new DeviceId(UUID.randomUUID());
Device current = new Device(otherId);
current.setTenantId(tenantId);
current.setName("AM308 spare");
current.setCustomerId(customerOf(tenantId));
when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current);
DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare"));
step.setConfirmed(true);
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getFailedStep()).isEqualTo("DEVICE:AM308 spare");
assertThat(result.getErrorMessage()).isEqualTo("AM308 spare belongs to another owner");
verify(deviceService, never()).saveDevice(any(Device.class));
verify(installedItemService, never()).save(any(), any());
}
@Test
void updateOverwriteOfAnotherDeviceKeepsItsCredentials() {
DeviceId otherId = new DeviceId(UUID.randomUUID());
Device current = new Device(otherId);
current.setTenantId(tenantId);
current.setName("AM308 spare");
when(deviceService.findDeviceById(tenantId, otherId)).thenReturn(current);
when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> i.getArgument(0));
DeviceCredentials credentials = new DeviceCredentials();
credentials.setDeviceId(otherId);
credentials.setCredentialsId("existing-token");
when(deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, otherId)).thenReturn(credentials);
DevicePackageRequest.Step step = overwrite("AM308 spare", "DEVICE", otherId, null, JacksonUtil.newObjectNode().put("name", "AM308 spare"));
step.setConfirmed(true);
step.setCredentials(JacksonUtil.newObjectNode().put("credentialsType", "ACCESS_TOKEN").put("credentialsId", "package-token"));
DevicePackageResult result = service.update(user, installedItem.getId(), request(keep("AM308", "DEVICE", deviceId), step));
assertThat(result.isSuccess()).isTrue();
verify(deviceService).saveDevice(any(Device.class));
verify(deviceCredentialsService, never()).updateDeviceCredentials(any(), any());
assertThat(result.getOutputs().get("DEVICE:AM308 spare").get("token").asText()).isEqualTo("existing-token");
}
@Test
void installRejectsAnOverwriteOfADeviceOrGateway() {
mockInstall();
for (String type : new String[]{"DEVICE", "GATEWAY"}) {
DevicePackageRequest.Step step = overwrite("AM308", type, deviceId, 1L, JacksonUtil.newObjectNode().put("name", "AM308"));
step.setConfirmed(true);
DevicePackageResult result = service.install(user, request(step));
assertThat(result.isSuccess()).isFalse();
assertThat(result.getErrorMessage()).isEqualTo("Invalid install step: AM308");
}
verify(transactionTemplate, never()).execute(any());
verify(deviceService, never()).saveDevice(any(Device.class));
verify(installedItemService, never()).save(any(), any());
}
@Test
void installWritesStepAttributesOnAUsedExistingEntityAfterCommit() {
mockInstall();
DevicePackageRequest.Step deviceStep = keep("AM308", "DEVICE", deviceId);
deviceStep.setResolution("use-existing");
deviceStep.setServerAttributes(JacksonUtil.newObjectNode().put("model", "AM308"));
deviceStep.setSharedAttributes(JacksonUtil.newObjectNode().put("deviceId", "${device.id}"));
DevicePackageResult result = service.install(user, request(deviceStep,
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard"))));
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<AttributesSaveRequest> saved = ArgumentCaptor.forClass(AttributesSaveRequest.class);
verify(telemetryService, times(2)).saveAttributes(saved.capture());
assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getEntityId).containsOnly(deviceId);
assertThat(saved.getAllValues()).extracting(AttributesSaveRequest::getScope).containsExactly(AttributeScope.SERVER_SCOPE, AttributeScope.SHARED_SCOPE);
assertThat(saved.getAllValues().get(0).getEntries().get(0).getValueAsString()).isEqualTo("AM308");
assertThat(saved.getAllValues().get(1).getEntries().get(0).getValueAsString()).isEqualTo(deviceId.getId().toString());
// The kept device isn't saved, so only the dashboard is audited
assertThat(afterCommitCalls).containsExactly("AUDIT", "ATTRIBUTES", "ATTRIBUTES", "REPORT");
}
@Test
void installIntoACustomerGroupGivesTheDeviceTheGroupsCustomer() {
mockInstall();
CustomerId groupCustomer = customerOf(tenantId);
EntityGroup group = new EntityGroup();
group.setId(new EntityGroupId(UUID.randomUUID()));
group.setType(EntityType.DEVICE);
group.setName("Customer sensors");
group.setOwnerId(groupCustomer);
when(entityGroupService.findEntityGroupById(tenantId, group.getId())).thenReturn(group);
DevicePackageRequest request = request(
create("AM308", "DEVICE", JacksonUtil.newObjectNode().put("name", "AM308")),
create("Dashboard", "DASHBOARD", JacksonUtil.newObjectNode().put("title", "AM308 dashboard")));
request.setEntityGroupId(group.getId().getId());
DevicePackageResult result = service.install(user, request);
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<Device> device = ArgumentCaptor.forClass(Device.class);
verify(deviceService).saveDevice(device.capture());
assertThat(device.getValue().getCustomerId()).isEqualTo(groupCustomer);
ArgumentCaptor<Dashboard> dashboard = ArgumentCaptor.forClass(Dashboard.class);
verify(dashboardService).saveDashboard(dashboard.capture());
assertThat(dashboard.getValue().getOwnerId()).isEqualTo(tenantId);
verify(entityGroupService).addEntityToEntityGroup(tenantId, group.getId(), deviceId);
verify(logEntityActionService).logEntityAction(eq(tenantId), eq(deviceId), any(Device.class), eq(groupCustomer), eq(ActionType.ADDED), eq(user));
}
private CustomerId customerOf(TenantId owner) {
Customer customer = new Customer(new CustomerId(UUID.randomUUID()));
customer.setTenantId(owner);
when(customerService.findCustomerById(tenantId, customer.getId())).thenReturn(customer);
return customer.getId();
}
/** The new entities get these ids; each save records that it ran inside the transaction. */
private void mockInstall() {
when(user.getId()).thenReturn(new UserId(UUID.randomUUID()));
when(projectInfo.getProjectVersion()).thenReturn("4.4.1");
when(projectInfo.getProductType()).thenReturn("PE");
when(deviceProfileService.saveDeviceProfile(any())).thenAnswer(i -> {
recordSave("DEVICE_PROFILE");
DeviceProfile profile = i.getArgument(0);
profile.setId(profileId);
return profile;
});
when(dashboardService.saveDashboard(any(Dashboard.class))).thenAnswer(i -> {
recordSave("DASHBOARD");
Dashboard dashboard = i.getArgument(0);
dashboard.setId(dashboardId);
return dashboard;
});
when(deviceService.saveDevice(any(Device.class))).thenAnswer(i -> {
recordSave("DEVICE");
Device device = i.getArgument(0);
device.setId(deviceId);
return device;
});
doAnswer(i -> {
recordSave("ENTITY_GROUP");
return null;
}).when(entityGroupService).addEntityToEntityGroup(any(), any(), any());
when(installedItemService.save(any(), any())).thenAnswer(i -> {
recordSave("INSTALLED_ITEM");
return i.getArgument(1);
});
Integration integration = new Integration();
integration.setId(integrationId);
integration.setTenantId(tenantId);
integration.setName("TTN my-app");
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(integration);
doAnswer(i -> {
recordAfterCommit("AUDIT");
return null;
}).when(logEntityActionService).logEntityAction(any(TenantId.class), any(EntityId.class), any(HasName.class), nullable(CustomerId.class),
any(ActionType.class), any(User.class), any(Object[].class));
doAnswer(i -> {
recordAfterCommit("REPORT");
return null;
}).when(iotHubRestClient).reportVersionInstalled(any(), any());
doAnswer(i -> {
recordAfterCommit("ATTRIBUTES");
return null;
}).when(telemetryService).saveAttributes(any(AttributesSaveRequest.class));
}
private void recordSave(String what) {
if (inTransaction) {
savedInTransaction.add(what);
}
}
private void recordAfterCommit(String what) {
afterCommitCalls.add(inTransaction ? what + " in transaction" : what);
}
private IotHubInstalledItem otherPackage(Map<String, JsonNode> installState) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setInstallState(installState);
@ -875,35 +1327,35 @@ class DefaultDevicePackageUpdateServiceTest {
return dashboard;
}
private DeviceUpdateRequest request(DeviceUpdateRequest.Step... steps) {
DeviceUpdateRequest request = new DeviceUpdateRequest();
private DevicePackageRequest request(DevicePackageRequest.Step... steps) {
DevicePackageRequest request = new DevicePackageRequest();
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);
private static DevicePackageRequest.Step keep(String name, String type, EntityId id) {
DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.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);
private static DevicePackageRequest.Step overwrite(String name, String type, EntityId id, Long version, ObjectNode entity) {
DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.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);
private static DevicePackageRequest.Step create(String name, String type, ObjectNode entity) {
DevicePackageRequest.Step step = step(name, type, DevicePackageRequest.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();
private static DevicePackageRequest.Step step(String name, String type, DevicePackageRequest.Action action) {
DevicePackageRequest.Step step = new DevicePackageRequest.Step();
step.setName(name);
step.setType(type);
step.setAction(action);

27
ui-ngx/src/app/core/http/iot-hub-api.service.ts

@ -14,7 +14,7 @@ import {
MpItemVersionView
} from '@shared/models/iot-hub/iot-hub-version.models';
import { CreatorView } from '@shared/models/iot-hub/iot-hub-creator.models';
import { DevicePackageEntityState, DeviceUpdateRequest, DeviceUpdateResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { DevicePackageEntityState, DevicePackageRequest, DevicePackageResult, IotHubInstalledItem, IotHubInstalledItemKeptEntities, InstallItemVersionResult, InstallPlan, InstallPlanResult, UpdateItemVersionResult, ItemPublishedVersionInfo } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { ItemType, ItemTypeFilterInfo, WidgetCategory } from '@shared/models/iot-hub/iot-hub-item.models';
import { InterceptorHttpParams } from '@core/interceptors/interceptor-http-params';
import { InterceptorConfig } from '@core/interceptors/interceptor-config';
@ -180,18 +180,6 @@ export class IotHubApiService {
);
}
public registerDeviceInstall(
versionId: string,
descriptor: { type?: string; createdEntityIds: { entityType: string; id: string }[]; usedExistingEntityIds?: { entityType: string; id: string }[]; dashboardId?: { entityType: string; id: string }; selectedInstallMethod?: string; installState?: Record<string, any> },
config?: IotHubRequestConfig
): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>(
`/api/iot-hub/device/register?versionId=${versionId}`,
{ type: 'DEVICE', ...descriptor },
{ params: this.buildParams(config) }
);
}
public installItemVersion(versionId: string, config?: IotHubRequestConfig, data?: any): Observable<InstallItemVersionResult> {
return this.http.post<InstallItemVersionResult>(
`/api/iot-hub/versions/${versionId}/install`,
@ -287,14 +275,23 @@ export class IotHubApiService {
}
/** Applies a device package update in one transaction: all of it, or nothing. */
public updateDevicePackage(installedItemId: string, request: DeviceUpdateRequest, config?: IotHubRequestConfig): Observable<DeviceUpdateResult> {
return this.http.post<DeviceUpdateResult>(
public updateDevicePackage(installedItemId: string, request: DevicePackageRequest, config?: IotHubRequestConfig): Observable<DevicePackageResult> {
return this.http.post<DevicePackageResult>(
`/api/iot-hub/installedItems/${installedItemId}/deviceUpdate`,
request,
{ params: this.buildParams(config) }
);
}
/** Installs a device package in one transaction: all of its entities and the installed item, or nothing. */
public installDevicePackage(request: DevicePackageRequest, config?: IotHubRequestConfig): Observable<DevicePackageResult> {
return this.http.post<DevicePackageResult>(
`/api/iot-hub/device/install`,
request,
{ params: this.buildParams(config) }
);
}
public getInstalledItemKeptEntities(installedItemId: string, config?: IotHubRequestConfig): Observable<IotHubInstalledItemKeptEntities> {
return this.http.get<IotHubInstalledItemKeptEntities>(
`/api/iot-hub/installedItems/${installedItemId}/keptEntities`,

169
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.html

@ -62,93 +62,7 @@
}
@case ('progress') {
@if (data.update) {
<ng-container *ngTemplateOutlet="updateRows; context: { $implicit: ws }"></ng-container>
} @else {
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@if (i > 0) {
<div class="tb-progress-divider"></div>
}
@if (ep.status === 'conflict' || ep.status === 'error') {
<div class="tb-progress-row tb-progress-row-alert">
<div class="flex min-w-0 flex-1 items-start gap-4">
<div class="tb-progress-icon">
<mat-icon class="tb-progress-warning">warning</mat-icon>
</div>
<div class="flex min-w-0 flex-1 flex-col">
<span class="tb-progress-label tb-progress-label-active">
{{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }}
</span>
@if (ep.status === 'conflict') {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
</span>
}
@if (ep.status === 'error' && ep.errorMessage) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-error">{{ ep.errorMessage }}</span>
}
</div>
</div>
<div class="flex shrink-0 gap-2">
@if (ep.status === 'conflict') {
@if (ep.conflictType === 'use-or-overwrite') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="resolveConflict(ws, ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }}
</button>
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="resolveConflict(ws, ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="resolveConflict(ws, ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }}
</button>
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="resolveConflict(ws, ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
}
@if (ep.status === 'error') {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="retryEntitySteps(ws)">
{{ 'action.retry' | translate }}
</button>
}
</div>
</div>
} @else {
<div class="tb-progress-row"
[class.tb-progress-row-active]="ep.status === 'running'">
<div class="tb-progress-icon">
@switch (ep.status) {
@case ('pending') {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
}
@case ('running') {
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success">check_circle</mat-icon>
}
}
</div>
<span class="tb-progress-label"
[class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="ep.status === 'pending'">
{{ ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name) }}
</span>
<span class="tb-progress-status">
@if (ep.status === 'success') {
<span class="tb-progress-status-done">{{ 'iot-hub.done' | translate }}</span>
}
@if (ep.status === 'running') {
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
</span>
</div>
}
}
</div>
}
<ng-container *ngTemplateOutlet="packageRows; context: { $implicit: ws }"></ng-container>
}
}
</div>
@ -156,18 +70,17 @@
<!-- Update: an entity someone changed since install, which the user can save before the update overwrites it -->
<ng-template #modifiedHint let-ep>
@let hint = textWithLink('iot-hub.device-update-modified');
{{ hint.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ hint.link }}</a>{{ hint.after }}
{{ modifiedHintText.before }}<a class="tb-progress-link" href="#" (click)="$event.preventDefault(); downloadCurrentEntity(ep)">{{ modifiedHintText.link }}</a>{{ modifiedHintText.after }}
</ng-template>
<!-- Update: the package's entities and what the update does with them -->
<ng-template #updateRows let-ws>
<!-- The package's entities and what the install or update does with them; review mode shows them done -->
<ng-template #packageRows let-ws>
<div class="flex flex-col p-6">
@for (ep of ws.entitySteps; track ep.step.name; let i = $index) {
@for (ep of ws.entitySteps; track ep.step; let i = $index) {
@if (i > 0) {
<div class="tb-progress-divider"></div>
}
@let plan = updatePlanOf(ep);
@let plan = planOf(ep);
@let label = ('iot-hub.device-install-step-type-' + ep.step.type | translate) + ' — ' + (ep.resolvedName || ep.step.name);
@if (ws.reviewing && plan && !plan.confirmed) {
<div class="tb-progress-row tb-progress-row-alert">
@ -182,7 +95,7 @@
}
@if (plan.existing) {
<span class="tb-progress-alert-msg tb-progress-alert-msg-warning">
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate) } }}
{{ 'iot-hub.device-install-conflict-exists' | translate:{ type: ('iot-hub.device-install-step-type-' + ep.step.type | translate), name: plan.existing.name } }}
</span>
}
@if (plan.shared) {
@ -198,19 +111,21 @@
<div class="flex shrink-0 gap-2">
@if (plan.existing) {
@if (ep.step.type === 'DASHBOARD') {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'create-copy')">
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmWarning(ep, 'create-copy')">
{{ 'iot-hub.device-install-create-copy' | translate }}
</button>
} @else {
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmUpdateWarning(ep, 'use-existing')">
<button class="tb-progress-action-btn tb-progress-action-primary" (click)="confirmWarning(ep, 'use-existing')">
{{ 'iot-hub.device-install-use-existing' | translate }}
</button>
}
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
@if (canOverwriteExisting(ep)) {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmWarning(ep, 'overwrite')">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
} @else {
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmUpdateWarning(ep)">
<button class="tb-progress-action-btn tb-progress-action-warning" (click)="confirmWarning(ep)">
{{ 'iot-hub.device-install-overwrite' | translate }}
</button>
}
@ -237,7 +152,7 @@
<mat-spinner diameter="24"></mat-spinner>
}
@case ('success') {
<mat-icon class="tb-progress-success tb-update-reveal">check_circle</mat-icon>
<mat-icon class="tb-progress-success tb-package-reveal">check_circle</mat-icon>
}
@default {
<div class="tb-progress-pending-circle">{{ i + 1 }}</div>
@ -249,7 +164,8 @@
<span class="tb-progress-label tb-progress-label-fit"
[class.tb-progress-label-active]="ep.status === 'running'"
[class.tb-progress-label-pending]="!ws.reviewing && (ep.status === 'pending' || ep.status === 'skipped')">{{ label }}</span>
@if (plan?.action === 'create' && plan.resolution !== 'use-existing') {
<!-- Update: an entity the installed version doesn't have; at install every entity is new -->
@if (data.update && plan?.action === 'create' && plan.resolution !== 'use-existing') {
<span class="tb-progress-new">{{ 'iot-hub.device-update-new' | translate }}</span>
}
</div>
@ -274,10 +190,10 @@
<span class="tb-progress-status-progress">{{ 'iot-hub.in-progress' | translate }}</span>
}
@case ('success') {
<span class="tb-progress-status-done tb-update-reveal">{{ updateOutcomeOf(plan) | translate }}</span>
<span class="tb-progress-status-done tb-package-reveal">{{ appliedOutcomeOf(plan) | translate }}</span>
}
@case ('skipped') {
<span class="tb-progress-status-progress">{{ 'iot-hub.device-update-skipped' | translate }}</span>
<span class="tb-progress-status-progress">{{ 'iot-hub.device-package-skipped' | translate }}</span>
}
@default {
<!-- A resolved name conflict shows the choice: Use existing, Overwrite or Create copy -->
@ -335,7 +251,7 @@
<!-- Review mode: tabs -->
<div mat-dialog-content>
<mat-tab-group (selectedIndexChange)="onTabChanged($event)">
@for (ws of wizardSteps; track ws.label) {
@for (ws of wizardSteps; track ws) {
<mat-tab [label]="ws.label">
<ng-template matTabContent>
<ng-container *ngTemplateOutlet="stepContent; context: { $implicit: ws }"></ng-container>
@ -359,8 +275,8 @@
<mat-icon>done</mat-icon>
</ng-template>
@for (ws of wizardSteps; track ws.label) {
<mat-step [editable]="true"
@for (ws of wizardSteps; track ws) {
<mat-step [editable]="!isBusy"
[completed]="ws.completed && !ws.formGroup?.invalid"
[stepControl]="ws.type === 'form' ? ws.formGroup : null">
<ng-template matStepLabel>{{ ws.label }}</ng-template>
@ -378,24 +294,24 @@
}
</ng-template>
@if (data.update && currentWizardStep?.type === 'progress') {
@if (currentWizardStep?.type === 'progress') {
@let step = currentWizardStep;
@if (hasUpdateError(step)) {
<div class="tb-update-banner tb-update-banner-error">
@if (hasPackageError(step)) {
<div class="tb-package-banner tb-package-banner-error">
<mat-icon>error</mat-icon>
<span>{{ step.progressError }}</span>
</div>
} @else if (step.reviewing && !step.checking && unconfirmedUpdateWarnings(step) > 0) {
<div class="tb-update-banner tb-update-banner-warning">
} @else if (step.reviewing && !step.checking && unconfirmedWarnings(step) > 0) {
<div class="tb-package-banner tb-package-banner-warning">
<mat-icon>warning</mat-icon>
<span>{{ 'iot-hub.device-update-confirm-warnings' | translate:{ count: unconfirmedUpdateWarnings(step) } }}</span>
<span>{{ 'iot-hub.device-package-confirm-warnings' | translate:{ count: unconfirmedWarnings(step), action: (applyActionKey | translate) } }}</span>
</div>
}
}
<mat-dialog-actions>
@if (!isFirstWizardStep) {
<button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isUpdating || currentWizardStep?.checking" (click)="previousStep()">{{ 'action.back' | translate }}</button>
<button mat-stroked-button [disabled]="connectionChecking(currentWizardStep) || isBusy" (click)="previousStep()">{{ 'action.back' | translate }}</button>
}
<span class="flex-1"></span>
@if (currentWizardStep; as step) {
@ -432,13 +348,13 @@
</button>
}
@case ('progress') {
@if (data.update && (step.reviewing || step.updating || step.progressError)) {
@if (step.progressError && !step.updating) {
<button mat-button (click)="done()">{{ 'action.close' | translate }}</button>
<button mat-flat-button color="primary" (click)="retryUpdate(step)">
{{ 'iot-hub.device-update-try-again' | translate }}
@if (step.reviewing || step.applying || step.progressError) {
@if (step.progressError && !step.applying) {
<button mat-button (click)="cancel()">{{ 'action.close' | translate }}</button>
<button mat-flat-button color="primary" (click)="retry(step)">
{{ 'iot-hub.device-package-try-again' | translate }}
</button>
} @else if (step.updating) {
} @else if (step.applying) {
<button mat-button disabled>{{ 'action.cancel' | translate }}</button>
<button mat-stroked-button color="primary" disabled>
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}
@ -446,19 +362,14 @@
} @else {
<button mat-button (click)="cancel()">{{ 'action.cancel' | translate }}</button>
<button mat-flat-button color="primary"
[disabled]="step.checking || unconfirmedUpdateWarnings(step) > 0"
(click)="runUpdate(step)">
{{ 'action.update' | translate }}
[disabled]="step.checking || unconfirmedWarnings(step) > 0"
(click)="apply(step)">
{{ applyActionKey | translate }}
</button>
}
} @else if (step.progressError) {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-flat-button color="primary" (click)="retryEntitySteps(step)">
{{ 'action.retry' | translate }}
</button>
} @else if (step.progressDone && isLastWizardStep) {
<ng-container *ngTemplateOutlet="finishActions"></ng-container>
} @else if (!step.progressError) {
} @else {
<ng-container *ngTemplateOutlet="closeOrCancel"></ng-container>
<button mat-stroked-button color="primary" [disabled]="!step.progressDone" (click)="nextStep()">
{{ 'action.next' | translate }}@if (nextWizardStepLabel) {: {{ nextWizardStepLabel }}}

16
ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.scss

@ -356,17 +356,17 @@
color: #198038;
}
// Update: the outcome of a row shows in when the row gets it
.tb-update-reveal {
// The outcome of a row shows in when the row gets it
.tb-package-reveal {
display: inline-block;
animation: tb-update-reveal 200ms ease-out;
animation: tb-package-reveal 200ms ease-out;
@media (prefers-reduced-motion: reduce) {
animation: none;
}
}
@keyframes tb-update-reveal {
@keyframes tb-package-reveal {
from {
opacity: 0;
transform: scale(0.6);
@ -392,8 +392,8 @@
color: rgba(0, 0, 0, 0.54);
}
// Update: above the actions, so the list doesn't move when it goes away
.tb-update-banner {
// Above the actions, so the list doesn't move when it goes away
.tb-package-banner {
display: flex;
align-items: center;
gap: 12px;
@ -411,7 +411,7 @@
height: 20px;
}
&.tb-update-banner-warning {
&.tb-package-banner-warning {
background: rgba(246, 103, 22, 0.08);
color: #b5470b;
@ -420,7 +420,7 @@
}
}
&.tb-update-banner-error {
&.tb-package-banner-error {
background: rgba(211, 47, 47, 0.06);
color: #c62828;
}

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

File diff suppressed because it is too large

4
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-default-converter.ts

@ -6,7 +6,7 @@ import { Converter, ConverterConfigV2, ConverterType, getTargetField, getTargetT
import { IntegrationType } from '@shared/models/integration.models';
import { ScriptLanguage } from '@shared/models/rule-node.models';
import { isEqual } from '@core/utils';
import { DeviceInstalledItemDescriptor, DeviceUpdateRequest, IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-item.models';
import { DeviceInstalledItemDescriptor, DevicePackageRequest, 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';
@ -104,7 +104,7 @@ export const loadOwnDefaultConverterIds = async (iotHubApiService: IotHubApiServ
* the converter step: the server keeps the other steps, the forms and the integration's metadata as they are.
* expectedVersion is the converter's version the user reviewed.
*/
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DeviceUpdateRequest => {
export const defaultConverterUpdateRequest = (update: DefaultConverterUpdate, expectedVersion?: number): DevicePackageRequest => {
const descriptor = update.installedItem.descriptor as DeviceInstalledItemDescriptor;
return {
versionId: update.installedItem.itemVersionId,

8
ui-ngx/src/app/shared/models/iot-hub/device-package.models.ts

@ -355,10 +355,8 @@ export interface EntityStepOutput {
baseUrl?: string;
}
// skipped: a step of an update that failed, so nothing was changed
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'conflict' | 'skipped';
export type ConflictType = 'use-or-overwrite' | 'overwrite-or-copy';
// skipped: a step of an install or update that failed, so nothing was changed
export type EntityStepStatus = 'pending' | 'running' | 'success' | 'error' | 'skipped';
export interface EntityStepProgress {
step: DeviceInstallStep;
@ -366,7 +364,5 @@ export interface EntityStepProgress {
resolvedName?: string;
entityOutput?: EntityStepOutput;
errorMessage?: string;
existingEntity?: EntityStepOutput;
conflictType?: ConflictType;
resolution?: string;
}

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

@ -48,8 +48,8 @@ export interface DevicePackageEntityState {
shared: boolean;
}
/** A step of a device package update, with its entity resolved from the template of the new version. */
export interface DeviceUpdateStep {
/** A step of a device package install or update, with its entity resolved from the template of the version being installed. */
export interface DevicePackageStep {
name: string;
type: string;
action: 'KEEP' | 'OVERWRITE' | 'CREATE';
@ -58,7 +58,7 @@ export interface DeviceUpdateStep {
confirmed?: boolean;
entity?: any;
credentials?: any;
// OVERWRITE and CREATE: the attributes the saved entity gets, as at install
// OVERWRITE and CREATE: the attributes the saved entity gets
serverAttributes?: any;
sharedAttributes?: any;
resolution?: string;
@ -71,18 +71,21 @@ export interface DeviceUpdateStep {
defaultConverter?: boolean;
}
export interface DeviceUpdateRequest {
export interface DevicePackageRequest {
versionId: string;
// The version installed when the update was planned: the server refuses the update if the package changed since
// Update only: the version installed when the update was planned; the server refuses it if the package changed since
fromVersionId?: string;
// The install method of the new version's steps
// The install method of the steps
selectedInstallMethod?: string;
installState: Record<string, any>;
steps: DeviceUpdateStep[];
steps: DevicePackageStep[];
// Install only: the owner of the device, gateway and dashboard, and the group the created device joins
customerId?: string;
entityGroupId?: string;
}
/** All of the update was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */
export interface DeviceUpdateResult {
/** All of the request was applied, or none of it: failedStep is the install state key of the step that failed, if one did. */
export interface DevicePackageResult {
success: boolean;
errorMessage?: string;
failedStep?: string;

21
ui-ngx/src/assets/locale/locale.constant-ar_AE.json

@ -6538,9 +6538,6 @@
"step-configuration": "التكوين",
"step-provisioning": "التزويد",
"device-install-step-error": "فشل",
"device-install-step-pending": "قيد الانتظار",
"device-install-step-running": "جارٍ الإنشاء...",
"device-install-step-success": "تم الإنشاء",
"device-install-step-type-DASHBOARD": "لوحة المعلومات",
"device-install-step-type-DEVICE": "جهاز",
"device-install-step-type-DEVICE_PROFILE": "ملف تعريف الجهاز",
@ -6552,7 +6549,7 @@
"device-install-step-type-INTEGRATION": "التكامل",
"use-secret": "استخدام سر",
"use-plain-text": "استخدام نص عادي",
"device-install-conflict-exists": "يوجد {{type}} بهذا الاسم بالفعل",
"device-install-conflict-exists": "يوجد {{type}} بالاسم \"{{name}}\" بالفعل",
"device-install-use-existing": "استخدام الموجود",
"device-install-transport-host-step": "الاتصال",
"device-install-thingsboard-connection": "الاتصال بمنصة ThingsBoard",
@ -6586,20 +6583,18 @@
"device-installing-title": "جارٍ تثبيت \"{{name}}\"",
"device-update-title": "تحديث \"{{name}}\"",
"device-update-step": "تحديث",
"device-update-no-conflicts": "لا توجد تعارضات",
"device-update-new": "جديد",
"device-update-shared": "تستخدمه حزم أخرى. يؤثر التحديث عليها.",
"device-update-new-default-converter": "يتوفر في منصة ThingsBoard إصدار جديد من المحوّل الافتراضي الذي تستخدمه هذه الحزمة.",
"device-update-modified": "يحتوي على تغييرات محلية. يمكنك تنزيل الإصدار الحالي <a>من هنا</a>.",
"device-install-unexpected-error": "حدث خطأ ما. حاول مرة أخرى.",
"device-update-existing-use-existing": "موجود بالفعل. سيتم استخدام العنصر الموجود.",
"device-update-existing-overwrite": "موجود بالفعل. ستتم الكتابة فوقه.",
"device-update-existing-create-copy": "موجود بالفعل. سيتم إنشاء نسخة.",
"device-update-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"تحديث\"",
"device-update-skipped": "لم يتغير",
"device-update-updated": "تم التحديث",
"device-update-created": "تم الإنشاء",
"device-update-try-again": "إعادة المحاولة",
"device-package-will-create": "سيتم الإنشاء",
"device-install-nothing-installed": "لم يتم تثبيت أي شيء.",
"device-package-confirm-warnings": "أكّد {count, plural, one {تحذيرًا واحدًا} two {تحذيرين} few {# تحذيرات} many {# تحذيرًا} other {# تحذير} } لتمكين زر \"{action}\"",
"device-package-skipped": "لم يتغير",
"device-package-updated": "تم التحديث",
"device-package-created": "تم الإنشاء",
"device-package-try-again": "إعادة المحاولة",
"done": "تم",
"in-progress": "قيد التنفيذ",
"item-detail": "عنصر IoT Hub",

21
ui-ngx/src/assets/locale/locale.constant-ca_ES.json

@ -6540,9 +6540,6 @@
"step-configuration": "Configuració",
"step-provisioning": "Aprovisionament",
"device-install-step-error": "Ha fallat",
"device-install-step-pending": "Pendent",
"device-install-step-running": "S'està creant...",
"device-install-step-success": "Creat",
"device-install-step-type-DASHBOARD": "Tauler",
"device-install-step-type-DEVICE": "Dispositiu",
"device-install-step-type-DEVICE_PROFILE": "Perfil de dispositiu",
@ -6554,7 +6551,7 @@
"device-install-step-type-INTEGRATION": "Integració",
"use-secret": "Utilitza un secret",
"use-plain-text": "Utilitza text pla",
"device-install-conflict-exists": "{{type}}: aquest nom ja existeix",
"device-install-conflict-exists": "{{type}}: el nom \"{{name}}\" ja existeix",
"device-install-use-existing": "Utilitza l'existent",
"device-install-transport-host-step": "Connexió",
"device-install-thingsboard-connection": "Connexió amb ThingsBoard",
@ -6588,20 +6585,18 @@
"device-installing-title": "S'està instal·lant \"{{name}}\"",
"device-update-title": "Actualitza \"{{name}}\"",
"device-update-step": "Actualització",
"device-update-no-conflicts": "Sense conflictes",
"device-update-new": "Nou",
"device-update-shared": "L'utilitzen altres paquets. L'actualització els afecta.",
"device-update-new-default-converter": "ThingsBoard té una versió nova del convertidor per defecte que utilitza aquest paquet.",
"device-update-modified": "Té canvis locals. Podeu baixar la versió actual <a>aquí</a>.",
"device-install-unexpected-error": "S'ha produït un error. Torneu-ho a provar.",
"device-update-existing-use-existing": "Ja existeix. S'utilitzarà l'existent.",
"device-update-existing-overwrite": "Ja existeix. Se sobreescriurà.",
"device-update-existing-create-copy": "Ja existeix. Se'n crearà una còpia.",
"device-update-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó Actualitza",
"device-update-skipped": "Sense canvis",
"device-update-updated": "Actualitzat",
"device-update-created": "Creat",
"device-update-try-again": "Torna-ho a provar",
"device-package-will-create": "Es crearà",
"device-install-nothing-installed": "No s'ha instal·lat res.",
"device-package-confirm-warnings": "Confirmeu { count, plural, one {1 avís} other {# avisos} } per activar el botó {action}",
"device-package-skipped": "Sense canvis",
"device-package-updated": "Actualitzat",
"device-package-created": "Creat",
"device-package-try-again": "Torna-ho a provar",
"done": "Fet",
"in-progress": "En curs",
"item-detail": "Element de l'IoT Hub",

3
ui-ngx/src/assets/locale/locale.constant-da_DK.json

@ -6488,9 +6488,6 @@
"step-configuration": "Konfiguration",
"step-provisioning": "Klargøring",
"device-install-step-error": "Mislykket",
"device-install-step-pending": "Afventer",
"device-install-step-running": "Opretter...",
"device-install-step-success": "Oprettet",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Enhed",
"device-install-step-type-DEVICE_PROFILE": "Enhedsprofil",

3
ui-ngx/src/assets/locale/locale.constant-de_DE.json

@ -6486,9 +6486,6 @@
"step-configuration": "Konfiguration",
"step-provisioning": "Provisionierung",
"device-install-step-error": "Fehlgeschlagen",
"device-install-step-pending": "Ausstehend",
"device-install-step-running": "Wird erstellt...",
"device-install-step-success": "Erstellt",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Gerät",
"device-install-step-type-DEVICE_PROFILE": "Geräteprofil",

3
ui-ngx/src/assets/locale/locale.constant-el_GR.json

@ -6500,9 +6500,6 @@
"step-configuration": "Διαμόρφωση",
"step-provisioning": "Παροχή",
"device-install-step-error": "Αποτυχία",
"device-install-step-pending": "Σε εκκρεμότητα",
"device-install-step-running": "Δημιουργία...",
"device-install-step-success": "Δημιουργήθηκε",
"device-install-step-type-DASHBOARD": "Πίνακας ελέγχου",
"device-install-step-type-DEVICE": "Συσκευή",
"device-install-step-type-DEVICE_PROFILE": "Προφίλ συσκευής",

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

@ -6550,9 +6550,6 @@
"step-configuration": "Configuration",
"step-provisioning": "Provisioning",
"device-install-step-error": "Failed",
"device-install-step-pending": "Pending",
"device-install-step-running": "Creating...",
"device-install-step-success": "Created",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Device",
"device-install-step-type-DEVICE_PROFILE": "Device Profile",
@ -6564,7 +6561,7 @@
"device-install-step-type-INTEGRATION": "Integration",
"use-secret": "Use Secret",
"use-plain-text": "Use plain text",
"device-install-conflict-exists": "{{type}} with this name already exists",
"device-install-conflict-exists": "{{type}} named \"{{name}}\" already exists",
"device-install-use-existing": "Use existing",
"device-install-transport-host-step": "Connection",
"device-install-thingsboard-connection": "ThingsBoard connection",
@ -6599,7 +6596,7 @@
"device-update-title": "Update \"{{name}}\"",
"device-update-step": "Update",
"device-update-will-update": "Will be updated",
"device-update-will-create": "Will be created",
"device-package-will-create": "Will be created",
"device-update-no-changes": "No changes",
"device-update-new": "New",
"device-update-shared": "Used by other packages. The update affects them.",
@ -6609,11 +6606,12 @@
"device-update-modified": "Has local changes. You can download the current version <a>here</a>.",
"device-install-unexpected-error": "Something went wrong. Try again.",
"device-install-duplicate-step": "Two install steps of this device package have the same key: {{key}}. Report it to the package's creator.",
"device-update-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable Update",
"device-update-skipped": "Unchanged",
"device-update-updated": "Updated",
"device-update-created": "Created",
"device-update-try-again": "Try again",
"device-install-nothing-installed": "Nothing was installed.",
"device-package-confirm-warnings": "Confirm { count, plural, =1 {1 warning} other {# warnings} } to enable {action}",
"device-package-skipped": "Unchanged",
"device-package-updated": "Updated",
"device-package-created": "Created",
"device-package-try-again": "Try again",
"done": "Done",
"in-progress": "In progress",
"item-detail": "IoT Hub item",

3
ui-ngx/src/assets/locale/locale.constant-es_ES.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuración",
"step-provisioning": "Aprovisionamiento",
"device-install-step-error": "Fallido",
"device-install-step-pending": "Pendiente",
"device-install-step-running": "Creando...",
"device-install-step-success": "Creado",
"device-install-step-type-DASHBOARD": "Tablero",
"device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Perfil de dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-fr_FR.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuration",
"step-provisioning": "Provisionnement",
"device-install-step-error": "Échoué",
"device-install-step-pending": "En attente",
"device-install-step-running": "Création...",
"device-install-step-success": "Créé",
"device-install-step-type-DASHBOARD": "Tableau de bord",
"device-install-step-type-DEVICE": "Appareil",
"device-install-step-type-DEVICE_PROFILE": "Profil d’appareil",

3
ui-ngx/src/assets/locale/locale.constant-hi_IN.json

@ -6526,9 +6526,6 @@
"step-configuration": "कॉन्फ़िगरेशन",
"step-provisioning": "प्रोविज़निंग",
"device-install-step-error": "विफल",
"device-install-step-pending": "लंबित",
"device-install-step-running": "बनाया जा रहा है...",
"device-install-step-success": "बनाया गया",
"device-install-step-type-DASHBOARD": "डैशबोर्ड",
"device-install-step-type-DEVICE": "डिवाइस",
"device-install-step-type-DEVICE_PROFILE": "डिवाइस प्रोफ़ाइल",

3
ui-ngx/src/assets/locale/locale.constant-it_IT.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configurazione",
"step-provisioning": "Provisioning",
"device-install-step-error": "Non riuscito",
"device-install-step-pending": "In attesa",
"device-install-step-running": "Creazione in corso...",
"device-install-step-success": "Creato",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Profilo dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-ja_JP.json

@ -6486,9 +6486,6 @@
"step-configuration": "設定",
"step-provisioning": "プロビジョニング",
"device-install-step-error": "失敗",
"device-install-step-pending": "待機中",
"device-install-step-running": "作成中...",
"device-install-step-success": "作成済み",
"device-install-step-type-DASHBOARD": "ダッシュボード",
"device-install-step-type-DEVICE": "デバイス",
"device-install-step-type-DEVICE_PROFILE": "デバイスプロファイル",

3
ui-ngx/src/assets/locale/locale.constant-ko_KR.json

@ -6518,9 +6518,6 @@
"step-configuration": "구성",
"step-provisioning": "프로비저닝",
"device-install-step-error": "실패",
"device-install-step-pending": "대기 중",
"device-install-step-running": "생성 중...",
"device-install-step-success": "생성됨",
"device-install-step-type-DASHBOARD": "대시보드",
"device-install-step-type-DEVICE": "장치",
"device-install-step-type-DEVICE_PROFILE": "장치 프로필",

3
ui-ngx/src/assets/locale/locale.constant-lt_LT.json

@ -6526,9 +6526,6 @@
"step-configuration": "Konfigūracija",
"step-provisioning": "Paruošimas",
"device-install-step-error": "Nepavyko",
"device-install-step-pending": "Laukiama",
"device-install-step-running": "Kuriama...",
"device-install-step-success": "Sukurta",
"device-install-step-type-DASHBOARD": "Skydelis",
"device-install-step-type-DEVICE": "Įrenginys",
"device-install-step-type-DEVICE_PROFILE": "Įrenginio profilis",

3
ui-ngx/src/assets/locale/locale.constant-nl_BE.json

@ -6526,9 +6526,6 @@
"step-configuration": "Configuratie",
"step-provisioning": "Provisioning",
"device-install-step-error": "Mislukt",
"device-install-step-pending": "In afwachting",
"device-install-step-running": "Aanmaken...",
"device-install-step-success": "Aangemaakt",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Apparaat",
"device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel",

3
ui-ngx/src/assets/locale/locale.constant-nl_NL.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuratie",
"step-provisioning": "Provisioning",
"device-install-step-error": "Mislukt",
"device-install-step-pending": "In afwachting",
"device-install-step-running": "Aanmaken...",
"device-install-step-success": "Aangemaakt",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Apparaat",
"device-install-step-type-DEVICE_PROFILE": "Apparaatprofiel",

3
ui-ngx/src/assets/locale/locale.constant-no_NO.json

@ -6500,9 +6500,6 @@
"step-configuration": "Konfigurasjon",
"step-provisioning": "Klargjøring",
"device-install-step-error": "Mislyktes",
"device-install-step-pending": "Venter",
"device-install-step-running": "Oppretter...",
"device-install-step-success": "Opprettet",
"device-install-step-type-DASHBOARD": "Dashbord",
"device-install-step-type-DEVICE": "Enhet",
"device-install-step-type-DEVICE_PROFILE": "Enhetsprofil",

3
ui-ngx/src/assets/locale/locale.constant-pl_PL.json

@ -6526,9 +6526,6 @@
"step-configuration": "Konfiguracja",
"step-provisioning": "Aprowizacja",
"device-install-step-error": "Niepowodzenie",
"device-install-step-pending": "Oczekuje",
"device-install-step-running": "Tworzenie...",
"device-install-step-success": "Utworzono",
"device-install-step-type-DASHBOARD": "Pulpit",
"device-install-step-type-DEVICE": "Urządzenie",
"device-install-step-type-DEVICE_PROFILE": "Profil urządzenia",

3
ui-ngx/src/assets/locale/locale.constant-pt_BR.json

@ -6486,9 +6486,6 @@
"step-configuration": "Configuração",
"step-provisioning": "Provisionamento",
"device-install-step-error": "Falhou",
"device-install-step-pending": "Pendente",
"device-install-step-running": "Criando...",
"device-install-step-success": "Criado",
"device-install-step-type-DASHBOARD": "Dashboard",
"device-install-step-type-DEVICE": "Dispositivo",
"device-install-step-type-DEVICE_PROFILE": "Perfil do dispositivo",

3
ui-ngx/src/assets/locale/locale.constant-sl_SI.json

@ -6516,9 +6516,6 @@
"step-configuration": "Konfiguracija",
"step-provisioning": "Priprava",
"device-install-step-error": "Ni uspelo",
"device-install-step-pending": "Na čakanju",
"device-install-step-running": "Ustvarjanje...",
"device-install-step-success": "Ustvarjeno",
"device-install-step-type-DASHBOARD": "Nadzorna plošča",
"device-install-step-type-DEVICE": "Naprava",
"device-install-step-type-DEVICE_PROFILE": "Profil naprave",

3
ui-ngx/src/assets/locale/locale.constant-tr_TR.json

@ -6488,9 +6488,6 @@
"step-configuration": "Yapılandırma",
"step-provisioning": "Sağlama",
"device-install-step-error": "Başarısız",
"device-install-step-pending": "Beklemede",
"device-install-step-running": "Oluşturuluyor...",
"device-install-step-success": "Oluşturuldu",
"device-install-step-type-DASHBOARD": "Pano",
"device-install-step-type-DEVICE": "Cihaz",
"device-install-step-type-DEVICE_PROFILE": "Cihaz profili",

3
ui-ngx/src/assets/locale/locale.constant-uk_UA.json

@ -6486,9 +6486,6 @@
"step-configuration": "Конфігурація",
"step-provisioning": "Реєстрація",
"device-install-step-error": "Не вдалося",
"device-install-step-pending": "Очікує",
"device-install-step-running": "Створення...",
"device-install-step-success": "Створено",
"device-install-step-type-DASHBOARD": "Дашборд",
"device-install-step-type-DEVICE": "Пристрій",
"device-install-step-type-DEVICE_PROFILE": "Профіль пристрою",

3
ui-ngx/src/assets/locale/locale.constant-zh_CN.json

@ -6488,9 +6488,6 @@
"step-configuration": "配置",
"step-provisioning": "预配",
"device-install-step-error": "失败",
"device-install-step-pending": "等待中",
"device-install-step-running": "正在创建...",
"device-install-step-success": "已创建",
"device-install-step-type-DASHBOARD": "仪表板",
"device-install-step-type-DEVICE": "设备",
"device-install-step-type-DEVICE_PROFILE": "设备配置",

3
ui-ngx/src/assets/locale/locale.constant-zh_TW.json

@ -9357,9 +9357,6 @@
"step-configuration": "設定",
"step-provisioning": "佈建",
"device-install-step-error": "失敗",
"device-install-step-pending": "等待中",
"device-install-step-running": "正在建立…",
"device-install-step-success": "已建立",
"device-install-step-type-DASHBOARD": "儀表板",
"device-install-step-type-DEVICE": "裝置",
"device-install-step-type-DEVICE_PROFILE": "裝置設定檔",

Loading…
Cancel
Save