2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 highstreet technologies GmbH
4 * Modifications Copyright (C) 2021-2023 Nordix Foundation
5 * Modifications Copyright (C) 2021 Pantheon.tech
6 * Modifications Copyright (C) 2021-2022 Bell Canada
7 * Modifications Copyright (C) 2023 TechMahindra Ltd.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * SPDX-License-Identifier: Apache-2.0
22 * ============LICENSE_END=========================================================
25 package org.onap.cps.ncmp.api.impl;
27 import static org.onap.cps.ncmp.api.impl.constants.DmiRegistryConstants.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
28 import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateCmHandleQueryParameters;
30 import com.google.common.collect.Lists;
31 import com.hazelcast.map.IMap;
32 import java.time.OffsetDateTime;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
40 import java.util.stream.Collectors;
41 import lombok.RequiredArgsConstructor;
42 import lombok.extern.slf4j.Slf4j;
43 import org.onap.cps.api.CpsDataService;
44 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandleQueryService;
45 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
46 import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler;
47 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
48 import org.onap.cps.ncmp.api.impl.operations.OperationEnum;
49 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
50 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
51 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
52 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
53 import org.onap.cps.ncmp.api.inventory.CmHandleQueries;
54 import org.onap.cps.ncmp.api.inventory.CmHandleState;
55 import org.onap.cps.ncmp.api.inventory.CompositeState;
56 import org.onap.cps.ncmp.api.inventory.CompositeStateUtils;
57 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState;
58 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
59 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
60 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
61 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
62 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse.RegistrationError;
63 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
64 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
65 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
66 import org.onap.cps.spi.FetchDescendantsOption;
67 import org.onap.cps.spi.exceptions.AlreadyDefinedExceptionBatch;
68 import org.onap.cps.spi.exceptions.CpsException;
69 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
70 import org.onap.cps.spi.exceptions.DataValidationException;
71 import org.onap.cps.spi.model.ModuleDefinition;
72 import org.onap.cps.spi.model.ModuleReference;
73 import org.onap.cps.utils.JsonObjectMapper;
74 import org.springframework.http.ResponseEntity;
75 import org.springframework.stereotype.Service;
79 @RequiredArgsConstructor
80 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
82 private static final int DELETE_BATCH_SIZE = 100;
83 private final JsonObjectMapper jsonObjectMapper;
84 private final DmiDataOperations dmiDataOperations;
85 private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
86 private final InventoryPersistence inventoryPersistence;
87 private final CmHandleQueries cmHandleQueries;
88 private final NetworkCmProxyCmHandleQueryService networkCmProxyCmHandleQueryService;
89 private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
90 private final CpsDataService cpsDataService;
91 private final IMap<String, Object> moduleSyncStartedOnCmHandles;
94 public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
95 final DmiPluginRegistration dmiPluginRegistration) {
96 dmiPluginRegistration.validateDmiPluginRegistration();
97 final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
99 if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
100 dmiPluginRegistrationResponse.setRemovedCmHandles(
101 parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration.getRemovedCmHandles()));
104 if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
105 dmiPluginRegistrationResponse.setCreatedCmHandles(
106 parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration));
108 if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
109 dmiPluginRegistrationResponse.setUpdatedCmHandles(
110 networkCmProxyDataServicePropertyHandler
111 .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
113 return dmiPluginRegistrationResponse;
117 public Object getResourceDataForCmHandle(final String datastoreName,
118 final String cmHandleId,
119 final String resourceIdentifier,
120 final String optionsParamInQuery,
121 final String topicParamInQuery,
122 final String requestId) {
123 final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(datastoreName, cmHandleId,
128 return responseEntity.getBody();
132 public Object getResourceDataForCmHandle(final String datastoreName,
133 final String cmHandleId,
134 final String resourceIdentifier,
135 final FetchDescendantsOption fetchDescendantsOption) {
136 return cpsDataService.getDataNodes(datastoreName, cmHandleId, resourceIdentifier,
137 fetchDescendantsOption).iterator().next();
141 public Object getResourceDataForCmHandleBatch(final String datastoreName,
142 final List<String> cmHandleIds,
143 final String resourceIdentifier,
144 final String optionsParamInQuery,
145 final String topicParamInQuery,
146 final String requestId) {
147 final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(datastoreName, cmHandleIds,
152 return responseEntity.getBody();
156 public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
157 final String resourceIdentifier,
158 final OperationEnum operation,
159 final String requestData,
160 final String dataType) {
161 return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier, operation,
162 requestData, dataType);
166 public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
167 return inventoryPersistence.getYangResourcesModuleReferences(cmHandleId);
171 public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
172 return inventoryPersistence.getModuleDefinitionsByCmHandleId(cmHandleId);
176 * Retrieve cm handles with details for the given query parameters.
178 * @param cmHandleQueryApiParameters cm handle query parameters
179 * @return cm handles with details
182 public Collection<NcmpServiceCmHandle> executeCmHandleSearch(
183 final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
184 final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
185 cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
186 validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
187 return networkCmProxyCmHandleQueryService.queryCmHandles(cmHandleQueryServiceParameters);
191 * Retrieve cm handle ids for the given query parameters.
193 * @param cmHandleQueryApiParameters cm handle query parameters
194 * @return cm handle ids
197 public Collection<String> executeCmHandleIdSearch(final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
198 final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
199 cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
200 validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
201 return networkCmProxyCmHandleQueryService.queryCmHandleIds(cmHandleQueryServiceParameters);
205 * Set the data sync enabled flag, along with the data sync state
206 * based on the data sync enabled boolean for the cm handle id provided.
208 * @param cmHandleId cm handle id
209 * @param dataSyncEnabled data sync enabled flag
212 public void setDataSyncEnabled(final String cmHandleId, final boolean dataSyncEnabled) {
213 final CompositeState compositeState = inventoryPersistence
214 .getCmHandleState(cmHandleId);
215 if (compositeState.getDataSyncEnabled().equals(dataSyncEnabled)) {
216 log.info("Data-Sync Enabled flag is already: {} ", dataSyncEnabled);
217 } else if (compositeState.getCmHandleState() != CmHandleState.READY) {
218 throw new CpsException("State mismatch exception.", "Cm-Handle not in READY state. Cm handle state is: "
219 + compositeState.getCmHandleState());
221 final DataStoreSyncState dataStoreSyncState = compositeState.getDataStores()
222 .getOperationalDataStore().getDataStoreSyncState();
223 if (!dataSyncEnabled && dataStoreSyncState == DataStoreSyncState.SYNCHRONIZED) {
224 cpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId,
225 "/netconf-state", OffsetDateTime.now());
227 CompositeStateUtils.setDataSyncEnabledFlagWithDataSyncState(dataSyncEnabled, compositeState);
228 inventoryPersistence.saveCmHandleState(cmHandleId,
234 * Get all cm handle IDs by DMI plugin identifier.
236 * @param dmiPluginIdentifier DMI plugin identifier
237 * @return set of cm handle IDs
240 public Collection<String> getAllCmHandleIdsByDmiPluginIdentifier(final String dmiPluginIdentifier) {
241 return cmHandleQueries.getCmHandleIdsByDmiPluginIdentifier(dmiPluginIdentifier);
245 * Get all cm handle IDs by various properties.
247 * @param cmHandleQueryServiceParameters cm handle query parameters
248 * @return set of cm handle IDs
251 public Collection<String> executeCmHandleIdSearchForInventory(
252 final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
253 validateCmHandleQueryParameters(cmHandleQueryServiceParameters, InventoryQueryConditions.ALL_CONDITION_NAMES);
254 return networkCmProxyCmHandleQueryService.queryCmHandleIdsForInventory(cmHandleQueryServiceParameters);
258 * Retrieve cm handle details for a given cm handle.
260 * @param cmHandleId cm handle identifier
261 * @return cm handle details
264 public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
265 return YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle(
266 inventoryPersistence.getYangModelCmHandle(cmHandleId));
270 * Get cm handle public properties for a given cm handle id.
272 * @param cmHandleId cm handle identifier
273 * @return cm handle public properties
276 public Map<String, String> getCmHandlePublicProperties(final String cmHandleId) {
277 final YangModelCmHandle yangModelCmHandle =
278 inventoryPersistence.getYangModelCmHandle(cmHandleId);
279 final List<YangModelCmHandle.Property> yangModelPublicProperties = yangModelCmHandle.getPublicProperties();
280 final Map<String, String> cmHandlePublicProperties = new HashMap<>();
281 YangDataConverter.asPropertiesMap(yangModelPublicProperties, cmHandlePublicProperties);
282 return cmHandlePublicProperties;
286 * Get cm handle composite state for a given cm handle id.
288 * @param cmHandleId cm handle identifier
289 * @return cm handle state
292 public CompositeState getCmHandleCompositeState(final String cmHandleId) {
293 return inventoryPersistence.getYangModelCmHandle(cmHandleId).getCompositeState();
297 * THis method registers a cm handle and initiates modules sync.
299 * @param dmiPluginRegistration dmi plugin registration information.
300 * @return cm-handle registration response for create cm-handle requests.
302 public List<CmHandleRegistrationResponse> parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
303 final DmiPluginRegistration dmiPluginRegistration) {
304 List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
305 final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>();
307 dmiPluginRegistration.getCreatedCmHandles()
308 .forEach(cmHandle -> {
309 final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
310 dmiPluginRegistration.getDmiPlugin(),
311 dmiPluginRegistration.getDmiDataPlugin(),
312 dmiPluginRegistration.getDmiModelPlugin(),
314 cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.ADVISED);
316 cmHandleRegistrationResponses = registerNewCmHandles(cmHandleStatePerCmHandle);
317 } catch (final DataValidationException dataValidationException) {
318 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createFailureResponse(dmiPluginRegistration
319 .getCreatedCmHandles().stream()
320 .map(NcmpServiceCmHandle::getCmHandleId).findFirst().orElse(null),
321 RegistrationError.CM_HANDLE_INVALID_ID));
323 return cmHandleRegistrationResponses;
326 protected List<CmHandleRegistrationResponse> parseAndRemoveCmHandlesInDmiRegistration(
327 final List<String> tobeRemovedCmHandles) {
328 final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
329 new ArrayList<>(tobeRemovedCmHandles.size());
330 final Collection<YangModelCmHandle> yangModelCmHandles =
331 inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
333 updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
335 final Set<String> notDeletedCmHandles = new HashSet<>();
336 for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
338 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
339 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
340 cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
342 } catch (final RuntimeException batchException) {
343 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
344 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
345 final CmHandleRegistrationResponse cmHandleRegistrationResponse =
346 deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
347 cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
348 if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
349 notDeletedCmHandles.add(cmHandleId);
355 yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
356 updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
358 return cmHandleRegistrationResponses;
361 private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
363 deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
364 return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
365 } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
366 log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
367 cmHandleId, dataNodeNotFoundException.getMessage());
368 return CmHandleRegistrationResponse.createFailureResponse(cmHandleId,
369 RegistrationError.CM_HANDLE_DOES_NOT_EXIST);
370 } catch (final DataValidationException dataValidationException) {
371 log.error("Unable to de-register cm-handle id: {}, caused by: {}",
372 cmHandleId, dataValidationException.getMessage());
373 return CmHandleRegistrationResponse.createFailureResponse(cmHandleId,
374 RegistrationError.CM_HANDLE_INVALID_ID);
375 } catch (final Exception exception) {
376 log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
377 return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
381 private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
382 final CmHandleState cmHandleState) {
383 final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
384 yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
385 lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
388 private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
389 inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
390 inventoryPersistence.deleteDataNode("/dmi-registry/cm-handles[@id='" + cmHandleId + "']");
391 removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
394 private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
395 inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
396 inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
397 tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
400 private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
401 return cmHandles.stream()
402 .map(cmHandleId -> "/dmi-registry/cm-handles[@id='" + cmHandleId + "']")
403 .collect(Collectors.toSet());
406 // CPS-1239 Robustness cleaning of in progress cache
407 private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
408 if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
409 log.debug("{} removed from in progress map", deletedCmHandleId);
413 private List<CmHandleRegistrationResponse> registerNewCmHandles(final Map<YangModelCmHandle, CmHandleState>
414 cmHandleStatePerCmHandle) {
415 final List<String> cmHandleIds = cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId)
416 .collect(Collectors.toList());
418 lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
419 return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
420 } catch (final AlreadyDefinedExceptionBatch alreadyDefinedExceptionBatch) {
421 return CmHandleRegistrationResponse.createFailureResponses(
422 alreadyDefinedExceptionBatch.getAlreadyDefinedXpaths(),
423 RegistrationError.CM_HANDLE_ALREADY_EXIST);
424 } catch (final Exception exception) {
425 return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);