Browse Source

IoT Hub: a device package update keeps the device's entity group and customer (PROD-9245)

The PE part of thingsboard-pe#5291 for 4.4.0.x, by hand: the update opens the wizard of the new version with the entity
group (the first one other than All) and the customer of the installed version's device, and the server keeps them in
the install state ($placement) when it removes the entities, so a retry after the device is gone still creates the new
one there. 4.4.1 does not need it: its update keeps the same device.
pull/16625/head
dpinkevych 3 weeks ago
parent
commit
cd704379fc
  1. 7
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  2. 28
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  3. 11
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java
  4. 34
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  5. 5
      ui-ngx/src/app/core/http/iot-hub-api.service.ts
  6. 4
      ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts
  7. 46
      ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

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

@ -101,9 +101,12 @@ public class IotHubController extends BaseController {
@PostMapping("/installedItems/{installedItemId}/device/removeEntities")
@ResponseBody
public void removeDevicePackageEntities(@PathVariable UUID installedItemId,
@RequestParam String versionId) throws ThingsboardException {
@RequestParam String versionId,
@RequestParam(required = false) UUID entityGroupId,
@RequestParam(required = false) UUID customerId) throws ThingsboardException {
checkAllPermissions();
iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId);
iotHubService.removeDevicePackageEntities(getCurrentUser(), new IotHubInstalledItemId(installedItemId), versionId,
entityGroupId, customerId);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")

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

@ -4,6 +4,7 @@
package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@ -800,7 +801,8 @@ public class DefaultIotHubService implements IotHubService {
}
@Override
public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) {
public void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId,
UUID entityGroupId, UUID customerId) {
TenantId tenantId = user.getTenantId();
IotHubInstalledItem installedItem = findDevicePackage(tenantId, installedItemId);
// Checked before anything is removed: the registration of the new version checks the same and would fail.
@ -832,9 +834,23 @@ public class DefaultIotHubService implements IotHubService {
}
// Keep what the user entered in the forms (the wizard of the new version starts from it), drop the outputs of
// the removed entities: their ids, links and tokens no longer exist.
if (descriptor.getInstallState() != null) {
descriptor.setInstallState(stripEntityOutputs(descriptor.getInstallState()));
Map<String, JsonNode> installState = descriptor.getInstallState() != null
? stripEntityOutputs(descriptor.getInstallState()) : null;
// PE: where the removed device was, so that a retry still creates the new one there.
if (entityGroupId != null || customerId != null) {
if (installState == null) {
installState = new LinkedHashMap<>();
}
ObjectNode placement = JacksonUtil.newObjectNode();
if (entityGroupId != null) {
placement.put("entityGroupId", entityGroupId.toString());
}
if (customerId != null) {
placement.put("customerId", customerId.toString());
}
installState.put(PLACEMENT_STATE, placement);
}
descriptor.setInstallState(installState);
iotHubInstalledItemService.save(tenantId, installedItem);
} catch (RuntimeException e) {
// Without the cause: BaseController answers 400 for an IncorrectParameterException cause, and a 400 tells the
@ -849,11 +865,15 @@ public class DefaultIotHubService implements IotHubService {
log.info("[{}] Removed the entities of device package {} for its update", tenantId, installedItem.getItemName());
}
private static final String PLACEMENT_STATE = "$placement";
private static Map<String, JsonNode> stripEntityOutputs(Map<String, JsonNode> installState) {
Map<String, JsonNode> stripped = new LinkedHashMap<>();
installState.forEach((step, state) -> {
JsonNode formValues = state != null ? state.get("formValues") : null;
if (formValues != null) {
if (PLACEMENT_STATE.equals(step) && state != null) {
stripped.put(step, state);
} else if (formValues != null) {
stripped.put(step, JacksonUtil.newObjectNode().set("formValues", formValues));
}
});

11
application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubService.java

@ -10,6 +10,8 @@ import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.UUID;
public interface IotHubService {
InstallItemVersionResult installItemVersion(SecurityUser user, String versionId, JsonNode data, HttpServletRequest request);
@ -31,8 +33,15 @@ public interface IotHubService {
* Refused with an {@link IllegalArgumentException} (a 400), before anything is removed, when the item is not a device
* package, {@code versionId} (the version to install) is not a version of that item, or IoT Hub does not answer. A failure once removing started is an
* {@link IllegalStateException}: entities may already be removed.
* PE: the entity group and the customer of the removed device are kept in the install state ({@code $placement}),
* so the new version's device is created there even when the update is retried after the device is gone.
*/
void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId);
void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId,
UUID entityGroupId, UUID customerId);
default void removeDevicePackageEntities(SecurityUser user, IotHubInstalledItemId installedItemId, String versionId) {
removeDevicePackageEntities(user, installedItemId, versionId, null, null);
}
void deleteInstalledItem(SecurityUser user, IotHubInstalledItemId installedItemId);

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

@ -504,6 +504,40 @@ class DefaultIotHubServiceTest {
verify(iotHubInstalledItemService, never()).deleteById(any(), any());
}
@Test
void removeDevicePackageEntities_keepsThePlacementOfTheRemovedDeviceForARetry() throws Exception {
mockTenant();
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(tenantId);
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.<EntityId>of(device.getId()));
descriptor.setInstallState(new LinkedHashMap<>(Map.of(
"Configuration", JacksonUtil.toJsonNode("{\"formValues\":{\"gatewayName\":\"GW\"}}"))));
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("DEVICE");
item.setItemId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
String newVersionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(newVersionId))
.thenReturn(version(newVersionId, item.getItemId().toString(), "DEVICE", "Gateway", "1.0.2"));
when(deviceService.findDeviceById(tenantId, device.getId())).thenReturn(device);
UUID entityGroupId = UUID.randomUUID();
UUID customerId = UUID.randomUUID();
service.removeDevicePackageEntities(user, item.getId(), newVersionId, entityGroupId, customerId);
verify(tbDeviceService).delete(device, user);
assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement");
assertThat(descriptor.getInstallState().get("$placement").get("entityGroupId").asText()).isEqualTo(entityGroupId.toString());
assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString());
// A retry after the device is gone: the wizard sends the kept placement again, and it stays.
service.removeDevicePackageEntities(user, item.getId(), newVersionId);
assertThat(descriptor.getInstallState()).containsOnlyKeys("Configuration", "$placement");
assertThat(descriptor.getInstallState().get("$placement").get("customerId").asText()).isEqualTo(customerId.toString());
}
@Test
void registerDeviceInstall_replace_updatesTheSameItemToTheNewVersion() {
mockTenant();

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

@ -175,11 +175,12 @@ export class IotHubApiService {
);
}
public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig): Observable<void> {
public removeDevicePackageEntities(installedItemId: string, versionId: string, config?: IotHubRequestConfig,
placement?: { entityGroupId?: string; customerId?: string }): Observable<void> {
return this.http.post<void>(
`/api/iot-hub/installedItems/${installedItemId}/device/removeEntities`,
null,
{ params: this.buildParams(config, { versionId }) }
{ params: this.buildParams(config, { versionId, entityGroupId: placement?.entityGroupId, customerId: placement?.customerId }) }
);
}

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

@ -937,8 +937,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent<TbDeviceInst
}
this.removingReplaced.set(true);
try {
// The server keeps the placement, so that a retry after the device is gone still creates the new one there.
await firstValueFrom(this.iotHubApiService.removeDevicePackageEntities(this.data.replaceInstalledItemId,
this.data.item.id as string, { ignoreLoading: true, ignoreErrors: true }));
this.data.item.id as string, { ignoreLoading: true, ignoreErrors: true },
{ entityGroupId: this.data.entityGroupId, customerId: this.data.customerId }));
this.replacedEntitiesRemoved = true;
this.replacedEntitiesMayBeGone = true;
return true;

46
ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts

@ -3,7 +3,7 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Observable, of, EMPTY } from 'rxjs';
import { Observable, of, EMPTY, forkJoin } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { DialogService } from '@core/services/dialog.service';
@ -24,6 +24,10 @@ import { TbDeviceInstallDialogComponent, DeviceInstallDialogData } from './devic
import { TbIotHubInstalledItemsDialogComponent, IotHubInstalledItemsDialogData } from './iot-hub-installed-items-dialog.component';
import { IotHubBuiltInService } from './iot-hub-built-in.service';
import { IotHubApiService } from '@core/http/iot-hub-api.service';
import { DeviceService } from '@core/http/device.service';
import { EntityGroupService } from '@core/http/entity-group.service';
import { EntityType } from '@shared/models/entity-type.models';
import { NULL_UUID } from '@shared/models/id/has-uuid';
import { isBuiltInItem } from './iot-hub-utils';
/**
@ -41,7 +45,9 @@ export class IotHubActionsService {
private dialogService: DialogService,
private translate: TranslateService,
private builtInService: IotHubBuiltInService,
private iotHubApiService: IotHubApiService
private iotHubApiService: IotHubApiService,
private deviceService: DeviceService,
private entityGroupService: EntityGroupService
) {}
openItemDetail(item: MpItemVersionView, installedItem?: IotHubInstalledItem, installedItemsCount?: number,
@ -183,11 +189,15 @@ export class IotHubActionsService {
/** The install wizard of the new version updates a device package: it needs the user's input. */
private reinstallDevice(installedItem: IotHubInstalledItem, versionId: string): Observable<string | boolean> {
const descriptor = installedItem.descriptor as DeviceInstalledItemDescriptor;
return this.iotHubApiService.getVersionInfo(versionId).pipe(
switchMap(item => this.openDeviceInstallDialog(item, {
return forkJoin({
item: this.iotHubApiService.getVersionInfo(versionId),
placement: this.findDevicePlacement(descriptor)
}).pipe(
switchMap(({ item, placement }) => this.openDeviceInstallDialog(item, {
replaceInstalledItemId: installedItem.id.id,
selectedInstallMethod: descriptor?.selectedInstallMethod,
installState: descriptor?.installState
installState: descriptor?.installState,
...placement
})),
map(result => result === 'installed' ? 'updated' : false),
// The error itself is shown by the HTTP interceptor; nothing is changed yet.
@ -224,6 +234,32 @@ export class IotHubActionsService {
});
}
/**
* The customer and the entity group of the installed version's device: the new version's device is created there
* too, as the wizard creates it in the group and for the customer it was installed from. With several groups the
* first one other than "All" is taken; nothing when the device cannot be read. When an earlier update already removed
* the device, the placement the server kept for it ($placement in the install state).
*/
private findDevicePlacement(descriptor: DeviceInstalledItemDescriptor): Observable<{ entityGroupId?: string; customerId?: string }> {
const deviceId = descriptor?.createdEntityIds?.find(id => id.entityType === EntityType.DEVICE)?.id;
if (!deviceId) {
const kept = descriptor?.installState?.['$placement'];
return of({ entityGroupId: kept?.entityGroupId, customerId: kept?.customerId });
}
const config = { ignoreLoading: true, ignoreErrors: true };
// Each lookup failing on its own (a deleted device, no access to its groups) only leaves its part out.
return forkJoin({
customerId: this.deviceService.getDevice(deviceId, config).pipe(
map(device => device.customerId && device.customerId.id !== NULL_UUID ? device.customerId.id : undefined),
catchError(() => of(undefined))),
entityGroupId: this.entityGroupService.getEntityGroupIdsForEntityId(EntityType.DEVICE, deviceId, config).pipe(
switchMap(groupIds => groupIds.length
? this.entityGroupService.getEntityGroupsByIds(groupIds.map(groupId => groupId.id), config) : of([])),
map(groups => groups.find(group => !group.groupAll)?.id.id),
catchError(() => of(undefined)))
});
}
private openDeviceInstallDialog(item: MpItemVersionView,
options?: { reviewMode?: boolean; selectedInstallMethod?: string; installState?: any;
entityGroupId?: string; customerId?: string; replaceInstalledItemId?: string}): Observable<any> {

Loading…
Cancel
Save