/*
* ============LICENSE_START=======================================================
* Copyright (C) 2021 highstreet technologies GmbH
- * Modifications Copyright (C) 2021-2022 Nordix Foundation
+ * Modifications Copyright (C) 2021-2023 Nordix Foundation
* Modifications Copyright (C) 2021 Pantheon.tech
- * Modifications Copyright (C) 2021 Bell Canada
+ * Modifications Copyright (C) 2021-2022 Bell Canada
+ * Modifications Copyright (C) 2023 TechMahindra Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package org.onap.cps.ncmp.api.impl;
-import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DATASPACE_NAME;
-import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_ANCHOR;
-import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NCMP_DMI_REGISTRY_PARENT;
-import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
-import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NO_TIMESTAMP;
-import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum;
-import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_ALLOWED;
-
-import com.fasterxml.jackson.core.JsonProcessingException;
+import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
+import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_READY;
+import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST;
+import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
+import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_UPGRADE;
+import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
+import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
+import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateCmHandleQueryParameters;
+
+import com.google.common.collect.Lists;
+import com.hazelcast.map.IMap;
+import java.text.MessageFormat;
+import java.time.OffsetDateTime;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
-import java.util.LinkedHashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.UUID;
-import java.util.regex.Pattern;
+import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import org.apache.logging.log4j.util.Strings;
-import org.onap.cps.api.CpsAdminService;
import org.onap.cps.api.CpsDataService;
-import org.onap.cps.api.CpsModuleService;
+import org.onap.cps.ncmp.api.NetworkCmProxyCmHandleQueryService;
import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
-import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException;
+import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler;
+import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
+import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
+import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
+import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder;
+import org.onap.cps.ncmp.api.impl.inventory.CompositeStateUtils;
+import org.onap.cps.ncmp.api.impl.inventory.DataStoreSyncState;
+import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
-import org.onap.cps.ncmp.api.impl.operations.DmiModelOperations;
-import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
-import org.onap.cps.ncmp.api.impl.operations.YangModelCmHandleRetriever;
+import org.onap.cps.ncmp.api.impl.operations.OperationType;
+import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevel;
+import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
+import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
+import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
-import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandlesList;
+import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
+import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
+import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
+import org.onap.cps.ncmp.api.models.DataOperationRequest;
import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
+import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
+import org.onap.cps.ncmp.api.models.UpgradedCmHandles;
+import org.onap.cps.spi.FetchDescendantsOption;
+import org.onap.cps.spi.exceptions.AlreadyDefinedException;
+import org.onap.cps.spi.exceptions.CpsException;
import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
import org.onap.cps.spi.exceptions.DataValidationException;
+import org.onap.cps.spi.model.ModuleDefinition;
import org.onap.cps.spi.model.ModuleReference;
import org.onap.cps.utils.JsonObjectMapper;
-import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
+ private static final int DELETE_BATCH_SIZE = 100;
+ private final JsonObjectMapper jsonObjectMapper;
+ private final DmiDataOperations dmiDataOperations;
+ private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
+ private final InventoryPersistence inventoryPersistence;
+ private final CmHandleQueries cmHandleQueries;
+ private final NetworkCmProxyCmHandleQueryService networkCmProxyCmHandleQueryService;
+ private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
private final CpsDataService cpsDataService;
+ private final IMap<String, Object> moduleSyncStartedOnCmHandles;
+ private final Map<String, TrustLevel> trustLevelPerDmiPlugin;
- private final JsonObjectMapper jsonObjectMapper;
+ @Override
+ public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
+ final DmiPluginRegistration dmiPluginRegistration) {
+ dmiPluginRegistration.validateDmiPluginRegistration();
+ final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
- private final DmiDataOperations dmiDataOperations;
+ if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
+ dmiPluginRegistrationResponse.setRemovedCmHandles(
+ parseAndProcessDeletedCmHandlesInRegistration(dmiPluginRegistration.getRemovedCmHandles()));
+ }
- private final DmiModelOperations dmiModelOperations;
+ if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
+ dmiPluginRegistrationResponse.setCreatedCmHandles(
+ parseAndProcessCreatedCmHandlesInRegistration(dmiPluginRegistration));
+ }
+ if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
+ dmiPluginRegistrationResponse.setUpdatedCmHandles(
+ networkCmProxyDataServicePropertyHandler
+ .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
+ }
+ if (dmiPluginRegistration.getUpgradedCmHandles() != null
+ && !dmiPluginRegistration.getUpgradedCmHandles().getCmHandles().isEmpty()) {
+ dmiPluginRegistrationResponse.setUpgradedCmHandles(
+ parseAndProcessUpgradedCmHandlesInRegistration(dmiPluginRegistration));
+ }
- private final CpsModuleService cpsModuleService;
+ setTrustLevelPerDmiPlugin(dmiPluginRegistration);
- private final CpsAdminService cpsAdminService;
+ return dmiPluginRegistrationResponse;
+ }
- private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
+ @Override
+ public Object getResourceDataForCmHandle(final String datastoreName,
+ final String cmHandleId,
+ final String resourceIdentifier,
+ final String optionsParamInQuery,
+ final String topicParamInQuery,
+ final String requestId) {
+ final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(datastoreName, cmHandleId,
+ resourceIdentifier,
+ optionsParamInQuery,
+ topicParamInQuery,
+ requestId);
+ return responseEntity.getBody();
+ }
- private final YangModelCmHandleRetriever yangModelCmHandleRetriever;
+ @Override
+ public Object getResourceDataForCmHandle(final String datastoreName,
+ final String cmHandleId,
+ final String resourceIdentifier,
+ final FetchDescendantsOption fetchDescendantsOption) {
+ return cpsDataService.getDataNodes(datastoreName, cmHandleId, resourceIdentifier,
+ fetchDescendantsOption).iterator().next();
+ }
- // valid kafka topic name regex
- private static final Pattern TOPIC_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9]([._-](?![._-])|"
- + "[a-zA-Z0-9]){0,120}[a-zA-Z0-9]$");
- private static final String NO_REQUEST_ID = null;
- private static final String NO_TOPIC = null;
+ @Override
+ public void executeDataOperationForCmHandles(final String topicParamInQuery,
+ final DataOperationRequest
+ dataOperationRequest,
+ final String requestId) {
+ dmiDataOperations.requestResourceDataFromDmi(topicParamInQuery, dataOperationRequest, requestId);
+ }
@Override
- public void updateDmiRegistrationAndSyncModule(final DmiPluginRegistration dmiPluginRegistration) {
- dmiPluginRegistration.validateDmiPluginRegistration();
- try {
- if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
- parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration);
- }
- if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
- parseAndUpdateCmHandlesInDmiRegistration(dmiPluginRegistration);
- }
- parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration);
- } catch (final JsonProcessingException | DataNodeNotFoundException e) {
- final String errorMessage = String.format(
- "Error occurred while processing the CM-handle registration request, caused by : [%s]",
- e.getMessage());
- throw new DataValidationException(errorMessage, e.getMessage(), e);
- }
+ public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
+ final String resourceIdentifier,
+ final OperationType operationType,
+ final String requestData,
+ final String dataType) {
+ return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier,
+ operationType, requestData, dataType);
}
@Override
- public Object getResourceDataOperationalForCmHandle(final String cmHandleId,
- final String resourceIdentifier,
- final String acceptParamInHeader,
- final String optionsParamInQuery,
- final String topicParamInQuery) {
-
- return validateTopicNameAndGetResourceData(cmHandleId, resourceIdentifier, acceptParamInHeader,
- DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL, optionsParamInQuery, topicParamInQuery);
+ public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
+ return inventoryPersistence.getYangResourcesModuleReferences(cmHandleId);
}
@Override
- public Object getResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
- final String resourceIdentifier,
- final String acceptParamInHeader,
- final String optionsParamInQuery,
- final String topicParamInQuery) {
- return validateTopicNameAndGetResourceData(cmHandleId, resourceIdentifier, acceptParamInHeader,
- DmiOperations.DataStoreEnum.PASSTHROUGH_RUNNING, optionsParamInQuery, topicParamInQuery);
+ public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
+ return inventoryPersistence.getModuleDefinitionsByCmHandleId(cmHandleId);
}
+ /**
+ * Retrieve cm handles with details for the given query parameters.
+ *
+ * @param cmHandleQueryApiParameters cm handle query parameters
+ * @return cm handles with details
+ */
@Override
- public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
- final String resourceIdentifier,
- final OperationEnum operation,
- final String requestData,
- final String dataType) {
- return handleResponse(
- dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(
- cmHandleId, resourceIdentifier, operation, requestData, dataType),
- "Not able to " + operation + " resource data.");
+ public Collection<NcmpServiceCmHandle> executeCmHandleSearch(
+ final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
+ final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
+ cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
+ validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
+ return networkCmProxyCmHandleQueryService.queryCmHandles(cmHandleQueryServiceParameters);
}
+ /**
+ * Retrieve cm handle ids for the given query parameters.
+ *
+ * @param cmHandleQueryApiParameters cm handle query parameters
+ * @return cm handle ids
+ */
+ @Override
+ public Collection<String> executeCmHandleIdSearch(final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
+ final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
+ cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
+ validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
+ return networkCmProxyCmHandleQueryService.queryCmHandleIds(cmHandleQueryServiceParameters);
+ }
+ /**
+ * Set the data sync enabled flag, along with the data sync state
+ * based on the data sync enabled boolean for the cm handle id provided.
+ *
+ * @param cmHandleId cm handle id
+ * @param dataSyncEnabled data sync enabled flag
+ */
@Override
- public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
- return cpsModuleService.getYangResourcesModuleReferences(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId);
+ public void setDataSyncEnabled(final String cmHandleId, final boolean dataSyncEnabled) {
+ final CompositeState compositeState = inventoryPersistence.getCmHandleState(cmHandleId);
+ if (compositeState.getDataSyncEnabled().equals(dataSyncEnabled)) {
+ log.info("Data-Sync Enabled flag is already: {} ", dataSyncEnabled);
+ } else if (compositeState.getCmHandleState() != CmHandleState.READY) {
+ throw new CpsException("State mismatch exception.", "Cm-Handle not in READY state. Cm handle state is: "
+ + compositeState.getCmHandleState());
+ } else {
+ final DataStoreSyncState dataStoreSyncState = compositeState.getDataStores()
+ .getOperationalDataStore().getDataStoreSyncState();
+ if (!dataSyncEnabled && dataStoreSyncState == DataStoreSyncState.SYNCHRONIZED) {
+ cpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId,
+ "/netconf-state", OffsetDateTime.now());
+ }
+ CompositeStateUtils.setDataSyncEnabledFlagWithDataSyncState(dataSyncEnabled, compositeState);
+ inventoryPersistence.saveCmHandleState(cmHandleId,
+ compositeState);
+ }
+ }
+
+ /**
+ * Get all cm handle IDs by DMI plugin identifier.
+ *
+ * @param dmiPluginIdentifier DMI plugin identifier
+ * @return set of cm handle IDs
+ */
+ @Override
+ public Collection<String> getAllCmHandleIdsByDmiPluginIdentifier(final String dmiPluginIdentifier) {
+ return cmHandleQueries.getCmHandleIdsByDmiPluginIdentifier(dmiPluginIdentifier);
}
/**
- * Retrieve cm handle identifiers for the given list of module names.
+ * Get all cm handle IDs by various properties.
*
- * @param moduleNames module names.
- * @return a collection of anchor identifiers
+ * @param cmHandleQueryServiceParameters cm handle query parameters
+ * @return set of cm handle IDs
*/
@Override
- public Collection<String> executeCmHandleHasAllModulesSearch(final Collection<String> moduleNames) {
- return cpsAdminService.queryAnchorNames(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, moduleNames);
+ public Collection<String> executeCmHandleIdSearchForInventory(
+ final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
+ validateCmHandleQueryParameters(cmHandleQueryServiceParameters, InventoryQueryConditions.ALL_CONDITION_NAMES);
+ return networkCmProxyCmHandleQueryService.queryCmHandleIdsForInventory(cmHandleQueryServiceParameters);
}
/**
* Retrieve cm handle details for a given cm handle.
+ *
* @param cmHandleId cm handle identifier
* @return cm handle details
*/
@Override
public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
- final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
- final YangModelCmHandle yangModelCmHandle =
- yangModelCmHandleRetriever.getDmiServiceNamesAndProperties(cmHandleId);
- final List<YangModelCmHandle.Property> dmiProperties = yangModelCmHandle.getDmiProperties();
- final List<YangModelCmHandle.Property> publicProperties = yangModelCmHandle.getPublicProperties();
- ncmpServiceCmHandle.setCmHandleID(yangModelCmHandle.getId());
- setDmiProperties(dmiProperties, ncmpServiceCmHandle);
- setPublicProperties(publicProperties, ncmpServiceCmHandle);
- return ncmpServiceCmHandle;
+ return YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle(
+ inventoryPersistence.getYangModelCmHandle(cmHandleId));
}
- private void setDmiProperties(final List<YangModelCmHandle.Property> dmiProperties,
- final NcmpServiceCmHandle ncmpServiceCmHandle) {
- final Map<String, String> dmiPropertiesMap = new LinkedHashMap<>(dmiProperties.size());
- asPropertiesMap(dmiProperties, dmiPropertiesMap);
- ncmpServiceCmHandle.setDmiProperties(dmiPropertiesMap);
- }
-
- private void setPublicProperties(final List<YangModelCmHandle.Property> publicProperties,
- final NcmpServiceCmHandle ncmpServiceCmHandle) {
- final Map<String, String> publicPropertiesMap = new LinkedHashMap<>();
- asPropertiesMap(publicProperties, publicPropertiesMap);
- ncmpServiceCmHandle.setPublicProperties(publicPropertiesMap);
+ /**
+ * Get cm handle public properties for a given cm handle id.
+ *
+ * @param cmHandleId cm handle identifier
+ * @return cm handle public properties
+ */
+ @Override
+ public Map<String, String> getCmHandlePublicProperties(final String cmHandleId) {
+ final YangModelCmHandle yangModelCmHandle = inventoryPersistence.getYangModelCmHandle(cmHandleId);
+ final List<YangModelCmHandle.Property> yangModelPublicProperties = yangModelCmHandle.getPublicProperties();
+ final Map<String, String> cmHandlePublicProperties = new HashMap<>();
+ YangDataConverter.asPropertiesMap(yangModelPublicProperties, cmHandlePublicProperties);
+ return cmHandlePublicProperties;
}
- private void asPropertiesMap(final List<YangModelCmHandle.Property> properties,
- final Map<String, String> propertiesMap) {
- for (final YangModelCmHandle.Property property: properties) {
- propertiesMap.put(property.getName(), property.getValue());
- }
+ /**
+ * Get cm handle composite state for a given cm handle id.
+ *
+ * @param cmHandleId cm handle identifier
+ * @return cm handle state
+ */
+ @Override
+ public CompositeState getCmHandleCompositeState(final String cmHandleId) {
+ return inventoryPersistence.getYangModelCmHandle(cmHandleId).getCompositeState();
}
/**
* THis method registers a cm handle and initiates modules sync.
*
* @param dmiPluginRegistration dmi plugin registration information.
- * @throws JsonProcessingException thrown if json is malformed or missing.
+ * @return cm-handle registration response for create cm-handle requests.
*/
- public void parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
- final DmiPluginRegistration dmiPluginRegistration) throws JsonProcessingException {
- final YangModelCmHandlesList createdYangModelCmHandlesList =
- getUpdatedYangModelCmHandlesList(dmiPluginRegistration,
- dmiPluginRegistration.getCreatedCmHandles());
- registerAndSyncNewCmHandles(createdYangModelCmHandlesList);
+ public List<CmHandleRegistrationResponse> parseAndProcessCreatedCmHandlesInRegistration(
+ final DmiPluginRegistration dmiPluginRegistration) {
+ final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>();
+ dmiPluginRegistration.getCreatedCmHandles()
+ .forEach(cmHandle -> {
+ final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
+ dmiPluginRegistration.getDmiPlugin(),
+ dmiPluginRegistration.getDmiDataPlugin(),
+ dmiPluginRegistration.getDmiModelPlugin(),
+ cmHandle,
+ cmHandle.getModuleSetTag());
+ cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.ADVISED);
+ });
+ return registerNewCmHandles(cmHandleStatePerCmHandle);
}
- private static Object handleResponse(final ResponseEntity<?> responseEntity,
- final String exceptionMessage) {
- if (responseEntity.getStatusCode().is2xxSuccessful()) {
- return responseEntity.getBody();
- } else {
- throw new ServerNcmpException(exceptionMessage,
- "DMI status code: " + responseEntity.getStatusCodeValue()
- + ", DMI response body: " + responseEntity.getBody());
- }
- }
+ protected List<CmHandleRegistrationResponse> parseAndProcessDeletedCmHandlesInRegistration(
+ final List<String> tobeRemovedCmHandles) {
+ final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
+ new ArrayList<>(tobeRemovedCmHandles.size());
+ final Collection<YangModelCmHandle> yangModelCmHandles =
+ inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
- private void parseAndUpdateCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
- networkCmProxyDataServicePropertyHandler.updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles());
- }
+ updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
- private YangModelCmHandlesList getUpdatedYangModelCmHandlesList(
- final DmiPluginRegistration dmiPluginRegistration,
- final List<NcmpServiceCmHandle> updatedCmHandles) {
- return YangModelCmHandlesList.toYangModelCmHandlesList(
- dmiPluginRegistration.getDmiPlugin(),
- dmiPluginRegistration.getDmiDataPlugin(),
- dmiPluginRegistration.getDmiModelPlugin(),
- updatedCmHandles);
- }
+ final Set<String> notDeletedCmHandles = new HashSet<>();
+ for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
+ try {
+ batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
+ tobeRemovedCmHandleBatch.forEach(cmHandleId ->
+ cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
+
+ } catch (final RuntimeException batchException) {
+ log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
+ for (final String cmHandleId : tobeRemovedCmHandleBatch) {
+ final CmHandleRegistrationResponse cmHandleRegistrationResponse =
+ deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
+ cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
+ if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
+ notDeletedCmHandles.add(cmHandleId);
+ }
+ }
+ }
+ }
- private void registerAndSyncNewCmHandles(final YangModelCmHandlesList yangModelCmHandlesList) {
- final String cmHandleJsonData = jsonObjectMapper.asJsonString(yangModelCmHandlesList);
- cpsDataService.saveListElements(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR, NCMP_DMI_REGISTRY_PARENT,
- cmHandleJsonData, NO_TIMESTAMP);
+ yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
+ updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
- for (final YangModelCmHandle yangModelCmHandle : yangModelCmHandlesList.getYangModelCmHandles()) {
- syncModulesAndCreateAnchor(yangModelCmHandle);
- }
+ return cmHandleRegistrationResponses;
}
- protected void syncModulesAndCreateAnchor(final YangModelCmHandle yangModelCmHandle) {
- syncAndCreateSchemaSet(yangModelCmHandle);
- createAnchor(yangModelCmHandle);
- }
+ protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
+ final DmiPluginRegistration dmiPluginRegistration) {
- private void parseAndRemoveCmHandlesInDmiRegistration(final DmiPluginRegistration dmiPluginRegistration) {
- for (final String cmHandle : dmiPluginRegistration.getRemovedCmHandles()) {
- try {
- attemptToDeleteSchemaSetWithCascade(cmHandle);
- cpsDataService.deleteListOrListElement(NCMP_DATASPACE_NAME, NCMP_DMI_REGISTRY_ANCHOR,
- "/dmi-registry/cm-handles[@id='" + cmHandle + "']", NO_TIMESTAMP);
- } catch (final DataNodeNotFoundException e) {
- log.warn("Datanode {} not deleted message {}", cmHandle, e.getMessage());
+ final UpgradedCmHandles upgradedCmHandles = dmiPluginRegistration.getUpgradedCmHandles();
+ final String moduleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
+ final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle =
+ new HashMap<>(upgradedCmHandles.getCmHandles().size());
+ final Collection<String> notReadyCmHandles = new ArrayList<>(upgradedCmHandles.getCmHandles().size());
+ final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
+ final String formattedModuleSetTag = MessageFormat.format("new moduleSetTag: {0}", moduleSetTag);
+
+ upgradedCmHandles.getCmHandles().forEach(cmHandleId -> {
+ if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
+ ncmpServiceCmHandle.setCmHandleId(cmHandleId);
+ ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder()
+ .withCmHandleState(CmHandleState.READY)
+ .withLockReason(MODULE_UPGRADE, formattedModuleSetTag).build());
+ final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
+ dmiPluginRegistration.getDmiPlugin(),
+ dmiPluginRegistration.getDmiDataPlugin(),
+ dmiPluginRegistration.getDmiModelPlugin(),
+ ncmpServiceCmHandle,
+ moduleSetTag);
+ cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.LOCKED);
+ } else {
+ notReadyCmHandles.add(cmHandleId);
}
- }
+ });
+
+ final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses
+ = upgradeCmHandles(cmHandleStatePerCmHandle);
+ cmHandleRegistrationResponses.addAll(CmHandleRegistrationResponse.createFailureResponses(notReadyCmHandles,
+ CM_HANDLES_NOT_READY));
+ return cmHandleRegistrationResponses;
}
- private void attemptToDeleteSchemaSetWithCascade(final String schemaSetName) {
+ private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
try {
- cpsModuleService.deleteSchemaSet(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, schemaSetName,
- CASCADE_DELETE_ALLOWED);
- } catch (final Exception e) {
- log.warn("Schema set {} delete failed, reason {}", schemaSetName, e.getMessage());
+ deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
+ return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
+ } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
+ log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
+ cmHandleId, dataNodeNotFoundException.getMessage());
+ return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
+ } catch (final DataValidationException dataValidationException) {
+ log.error("Unable to de-register cm-handle id: {}, caused by: {}",
+ cmHandleId, dataValidationException.getMessage());
+ return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
+ } catch (final Exception exception) {
+ log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
+ return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
}
}
- private void syncAndCreateSchemaSet(final YangModelCmHandle yangModelCmHandle) {
- final Collection<ModuleReference> moduleReferencesFromCmHandle =
- dmiModelOperations.getModuleReferences(yangModelCmHandle);
+ private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
+ final CmHandleState cmHandleState) {
+ final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
+ yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
+ lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
+ }
+
+ private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
+ inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
+ inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
+ + "']");
+ removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
+ }
- final Collection<ModuleReference> identifiedNewModuleReferencesFromCmHandle = cpsModuleService
- .identifyNewModuleReferences(moduleReferencesFromCmHandle);
+ private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
+ inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
+ inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
+ tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
+ }
- final Collection<ModuleReference> existingModuleReferencesFromCmHandle =
- moduleReferencesFromCmHandle.stream().filter(moduleReferenceFromCmHandle ->
- !identifiedNewModuleReferencesFromCmHandle.contains(moduleReferenceFromCmHandle)
- ).collect(Collectors.toList());
+ private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
+ return cmHandles.stream()
+ .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
+ .collect(Collectors.toSet());
+ }
- final Map<String, String> newModuleNameToContentMap;
- if (identifiedNewModuleReferencesFromCmHandle.isEmpty()) {
- newModuleNameToContentMap = new HashMap<>();
- } else {
- newModuleNameToContentMap = dmiModelOperations.getNewYangResourcesFromDmi(yangModelCmHandle,
- identifiedNewModuleReferencesFromCmHandle);
+ // CPS-1239 Robustness cleaning of in progress cache
+ private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
+ if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
+ log.debug("{} removed from in progress map", deletedCmHandleId);
}
- cpsModuleService
- .createSchemaSetFromModules(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, yangModelCmHandle.getId(),
- newModuleNameToContentMap, existingModuleReferencesFromCmHandle);
}
- private void createAnchor(final YangModelCmHandle yangModelCmHandle) {
- cpsAdminService.createAnchor(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, yangModelCmHandle.getId(),
- yangModelCmHandle.getId());
+ private List<CmHandleRegistrationResponse> registerNewCmHandles(final Map<YangModelCmHandle, CmHandleState>
+ cmHandleStatePerCmHandle) {
+ final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
+ try {
+ lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
+ return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
+ } catch (final AlreadyDefinedException alreadyDefinedException) {
+ return CmHandleRegistrationResponse.createFailureResponses(
+ alreadyDefinedException.getAlreadyDefinedObjectNames(),
+ CM_HANDLE_ALREADY_EXIST);
+ } catch (final Exception exception) {
+ return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
+ }
}
- private static boolean isValidTopicName(final String topicName) {
- return Strings.isNotEmpty(topicName) && TOPIC_NAME_PATTERN.matcher(topicName).matches();
+ private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
+ cmHandleStatePerCmHandle) {
+ final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
+ log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
+ try {
+ lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
+ return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
+ } catch (final Exception exception) {
+ return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
+ }
}
- private Map<String, Object> buildDmiResponse(final String requestId) {
- final Map<String, Object> dmiResponseMap = new HashMap<>();
- dmiResponseMap.put("requestId", requestId);
- return dmiResponseMap;
+ private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
+ return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
}
- private Object validateTopicNameAndGetResourceData(final String cmHandleId,
- final String resourceIdentifier,
- final String acceptParamInHeader,
- final DmiOperations.DataStoreEnum dataStore,
- final String optionsParamInQuery,
- final String topicParamInQuery) {
- final boolean processAsynchronously = isValidTopicName(topicParamInQuery);
- if (processAsynchronously) {
- final String resourceDataRequestId = UUID.randomUUID().toString();
- return ResponseEntity.status(HttpStatus.OK)
- .body(buildDmiResponse(resourceDataRequestId));
+ private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
+ if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
+ trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
+ } else {
+ trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
}
- final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(
- cmHandleId, resourceIdentifier, optionsParamInQuery, acceptParamInHeader,
- dataStore, NO_REQUEST_ID, NO_TOPIC);
- return handleResponse(responseEntity, "Not able to get resource data.");
}
-}
\ No newline at end of file
+
+}