CPS-1553 :REST endpoint to accept collection of cm handles for GET operation
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / NetworkCmProxyDataServiceImpl.java
1 /*
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
12  *
13  *        http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  *  SPDX-License-Identifier: Apache-2.0
22  *  ============LICENSE_END=========================================================
23  */
24
25 package org.onap.cps.ncmp.api.impl;
26
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;
29
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;
38 import java.util.Map;
39 import java.util.Set;
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;
76
77 @Slf4j
78 @Service
79 @RequiredArgsConstructor
80 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
81
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;
92
93     @Override
94     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
95             final DmiPluginRegistration dmiPluginRegistration) {
96         dmiPluginRegistration.validateDmiPluginRegistration();
97         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
98
99         if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
100             dmiPluginRegistrationResponse.setRemovedCmHandles(
101                     parseAndRemoveCmHandlesInDmiRegistration(dmiPluginRegistration.getRemovedCmHandles()));
102         }
103
104         if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
105             dmiPluginRegistrationResponse.setCreatedCmHandles(
106                     parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(dmiPluginRegistration));
107         }
108         if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
109             dmiPluginRegistrationResponse.setUpdatedCmHandles(
110                     networkCmProxyDataServicePropertyHandler
111                             .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
112         }
113         return dmiPluginRegistrationResponse;
114     }
115
116     @Override
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,
124                 resourceIdentifier,
125                 optionsParamInQuery,
126                 topicParamInQuery,
127                 requestId);
128         return responseEntity.getBody();
129     }
130
131     @Override
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();
138     }
139
140     @Override
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,
148                 resourceIdentifier,
149                 optionsParamInQuery,
150                 topicParamInQuery,
151                 requestId);
152         return responseEntity.getBody();
153     }
154
155     @Override
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);
163     }
164
165     @Override
166     public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
167         return inventoryPersistence.getYangResourcesModuleReferences(cmHandleId);
168     }
169
170     @Override
171     public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
172         return inventoryPersistence.getModuleDefinitionsByCmHandleId(cmHandleId);
173     }
174
175     /**
176      * Retrieve cm handles with details for the given query parameters.
177      *
178      * @param cmHandleQueryApiParameters cm handle query parameters
179      * @return cm handles with details
180      */
181     @Override
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);
188     }
189
190     /**
191      * Retrieve cm handle ids for the given query parameters.
192      *
193      * @param cmHandleQueryApiParameters cm handle query parameters
194      * @return cm handle ids
195      */
196     @Override
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);
202     }
203
204     /**
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.
207      *
208      * @param cmHandleId      cm handle id
209      * @param dataSyncEnabled data sync enabled flag
210      */
211     @Override
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());
220         } else {
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());
226             }
227             CompositeStateUtils.setDataSyncEnabledFlagWithDataSyncState(dataSyncEnabled, compositeState);
228             inventoryPersistence.saveCmHandleState(cmHandleId,
229                     compositeState);
230         }
231     }
232
233     /**
234      * Get all cm handle IDs by DMI plugin identifier.
235      *
236      * @param dmiPluginIdentifier DMI plugin identifier
237      * @return set of cm handle IDs
238      */
239     @Override
240     public Collection<String> getAllCmHandleIdsByDmiPluginIdentifier(final String dmiPluginIdentifier) {
241         return cmHandleQueries.getCmHandleIdsByDmiPluginIdentifier(dmiPluginIdentifier);
242     }
243
244     /**
245      * Get all cm handle IDs by various properties.
246      *
247      * @param cmHandleQueryServiceParameters cm handle query parameters
248      * @return set of cm handle IDs
249      */
250     @Override
251     public Collection<String> executeCmHandleIdSearchForInventory(
252             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
253         validateCmHandleQueryParameters(cmHandleQueryServiceParameters, InventoryQueryConditions.ALL_CONDITION_NAMES);
254         return networkCmProxyCmHandleQueryService.queryCmHandleIdsForInventory(cmHandleQueryServiceParameters);
255     }
256
257     /**
258      * Retrieve cm handle details for a given cm handle.
259      *
260      * @param cmHandleId cm handle identifier
261      * @return cm handle details
262      */
263     @Override
264     public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
265         return YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle(
266                 inventoryPersistence.getYangModelCmHandle(cmHandleId));
267     }
268
269     /**
270      * Get cm handle public properties for a given cm handle id.
271      *
272      * @param cmHandleId cm handle identifier
273      * @return cm handle public properties
274      */
275     @Override
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;
283     }
284
285     /**
286      * Get cm handle composite state for a given cm handle id.
287      *
288      * @param cmHandleId cm handle identifier
289      * @return cm handle state
290      */
291     @Override
292     public CompositeState getCmHandleCompositeState(final String cmHandleId) {
293         return inventoryPersistence.getYangModelCmHandle(cmHandleId).getCompositeState();
294     }
295
296     /**
297      * THis method registers a cm handle and initiates modules sync.
298      *
299      * @param dmiPluginRegistration dmi plugin registration information.
300      * @return cm-handle registration response for create cm-handle requests.
301      */
302     public List<CmHandleRegistrationResponse> parseAndCreateCmHandlesInDmiRegistrationAndSyncModules(
303             final DmiPluginRegistration dmiPluginRegistration) {
304         List<CmHandleRegistrationResponse> cmHandleRegistrationResponses = new ArrayList<>();
305         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>();
306         try {
307             dmiPluginRegistration.getCreatedCmHandles()
308                     .forEach(cmHandle -> {
309                         final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
310                                 dmiPluginRegistration.getDmiPlugin(),
311                                 dmiPluginRegistration.getDmiDataPlugin(),
312                                 dmiPluginRegistration.getDmiModelPlugin(),
313                                 cmHandle);
314                         cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.ADVISED);
315                     });
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));
322         }
323         return cmHandleRegistrationResponses;
324     }
325
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);
332
333         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
334
335         final Set<String> notDeletedCmHandles = new HashSet<>();
336         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
337             try {
338                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
339                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
340                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
341
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);
350                     }
351                 }
352             }
353         }
354
355         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
356         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
357
358         return cmHandleRegistrationResponses;
359     }
360
361     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
362         try {
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);
378         }
379     }
380
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);
386     }
387
388     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
389         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
390         inventoryPersistence.deleteDataNode("/dmi-registry/cm-handles[@id='" + cmHandleId + "']");
391         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
392     }
393
394     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
395         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
396         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
397         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
398     }
399
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());
404     }
405
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);
410         }
411     }
412
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());
417         try {
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);
426         }
427     }
428
429 }