Merge "Fix PASS/FAIL reporting in performance test summary"
[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.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
28 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_READY;
29 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST;
30 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
31 import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_UPGRADE;
32 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
33 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
34 import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateCmHandleQueryParameters;
35
36 import com.google.common.collect.Lists;
37 import com.hazelcast.map.IMap;
38 import java.text.MessageFormat;
39 import java.time.OffsetDateTime;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.EnumMap;
43 import java.util.HashMap;
44 import java.util.HashSet;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Set;
48 import java.util.stream.Collectors;
49 import lombok.RequiredArgsConstructor;
50 import lombok.extern.slf4j.Slf4j;
51 import org.onap.cps.api.CpsDataService;
52 import org.onap.cps.ncmp.api.NcmpResponseStatus;
53 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandleQueryService;
54 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
55 import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler;
56 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
57 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
58 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
59 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder;
60 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateUtils;
61 import org.onap.cps.ncmp.api.impl.inventory.DataStoreSyncState;
62 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
63 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
64 import org.onap.cps.ncmp.api.impl.operations.OperationType;
65 import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevel;
66 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
67 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
68 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
69 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
70 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
71 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
72 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
73 import org.onap.cps.ncmp.api.models.DataOperationRequest;
74 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
75 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
76 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
77 import org.onap.cps.spi.FetchDescendantsOption;
78 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
79 import org.onap.cps.spi.exceptions.CpsException;
80 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
81 import org.onap.cps.spi.exceptions.DataValidationException;
82 import org.onap.cps.spi.model.ModuleDefinition;
83 import org.onap.cps.spi.model.ModuleReference;
84 import org.onap.cps.utils.JsonObjectMapper;
85 import org.springframework.http.ResponseEntity;
86 import org.springframework.stereotype.Service;
87
88 @Slf4j
89 @Service
90 @RequiredArgsConstructor
91 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
92
93     private static final int DELETE_BATCH_SIZE = 100;
94     private final JsonObjectMapper jsonObjectMapper;
95     private final DmiDataOperations dmiDataOperations;
96     private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
97     private final InventoryPersistence inventoryPersistence;
98     private final CmHandleQueries cmHandleQueries;
99     private final NetworkCmProxyCmHandleQueryService networkCmProxyCmHandleQueryService;
100     private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
101     private final CpsDataService cpsDataService;
102     private final IMap<String, Object> moduleSyncStartedOnCmHandles;
103     private final Map<String, TrustLevel> trustLevelPerCmHandle;
104     private final Map<String, TrustLevel> trustLevelPerDmiPlugin;
105
106     @Override
107     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
108             final DmiPluginRegistration dmiPluginRegistration) {
109         dmiPluginRegistration.validateDmiPluginRegistration();
110         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
111
112         setTrustLevelPerDmiPlugin(dmiPluginRegistration);
113
114         if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
115             dmiPluginRegistrationResponse.setRemovedCmHandles(
116                     parseAndProcessDeletedCmHandlesInRegistration(dmiPluginRegistration.getRemovedCmHandles()));
117         }
118
119         if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
120             dmiPluginRegistrationResponse.setCreatedCmHandles(
121                     parseAndProcessCreatedCmHandlesInRegistration(dmiPluginRegistration));
122             populateTrustLevelPerCmHandleCache(dmiPluginRegistration);
123         }
124         if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
125             dmiPluginRegistrationResponse.setUpdatedCmHandles(
126                     networkCmProxyDataServicePropertyHandler
127                             .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
128         }
129         if (dmiPluginRegistration.getUpgradedCmHandles() != null
130                 && !dmiPluginRegistration.getUpgradedCmHandles().getCmHandles().isEmpty()) {
131             dmiPluginRegistrationResponse.setUpgradedCmHandles(
132                     parseAndProcessUpgradedCmHandlesInRegistration(dmiPluginRegistration));
133         }
134
135         return dmiPluginRegistrationResponse;
136     }
137
138     @Override
139     public Object getResourceDataForCmHandle(final String datastoreName,
140                                              final String cmHandleId,
141                                              final String resourceIdentifier,
142                                              final String optionsParamInQuery,
143                                              final String topicParamInQuery,
144                                              final String requestId) {
145         final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(datastoreName, cmHandleId,
146                 resourceIdentifier,
147                 optionsParamInQuery,
148                 topicParamInQuery,
149                 requestId);
150         return responseEntity.getBody();
151     }
152
153     @Override
154     public Object getResourceDataForCmHandle(final String datastoreName,
155                                              final String cmHandleId,
156                                              final String resourceIdentifier,
157                                              final FetchDescendantsOption fetchDescendantsOption) {
158         return cpsDataService.getDataNodes(datastoreName, cmHandleId, resourceIdentifier,
159                 fetchDescendantsOption).iterator().next();
160     }
161
162     @Override
163     public void executeDataOperationForCmHandles(final String topicParamInQuery,
164                                                  final DataOperationRequest
165                                                          dataOperationRequest,
166                                                  final String requestId) {
167         dmiDataOperations.requestResourceDataFromDmi(topicParamInQuery, dataOperationRequest, requestId);
168     }
169
170     @Override
171     public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
172                                                                  final String resourceIdentifier,
173                                                                  final OperationType operationType,
174                                                                  final String requestData,
175                                                                  final String dataType) {
176         return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier,
177                 operationType, requestData, dataType);
178     }
179
180     @Override
181     public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
182         return inventoryPersistence.getYangResourcesModuleReferences(cmHandleId);
183     }
184
185     @Override
186     public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
187         return inventoryPersistence.getModuleDefinitionsByCmHandleId(cmHandleId);
188     }
189
190     /**
191      * Retrieve cm handles with details for the given query parameters.
192      *
193      * @param cmHandleQueryApiParameters cm handle query parameters
194      * @return cm handles with details
195      */
196     @Override
197     public Collection<NcmpServiceCmHandle> executeCmHandleSearch(
198             final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
199         final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
200                 cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
201         validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
202         return networkCmProxyCmHandleQueryService.queryCmHandles(cmHandleQueryServiceParameters);
203     }
204
205     /**
206      * Retrieve cm handle ids for the given query parameters.
207      *
208      * @param cmHandleQueryApiParameters cm handle query parameters
209      * @return cm handle ids
210      */
211     @Override
212     public Collection<String> executeCmHandleIdSearch(final CmHandleQueryApiParameters cmHandleQueryApiParameters) {
213         final CmHandleQueryServiceParameters cmHandleQueryServiceParameters = jsonObjectMapper.convertToValueType(
214                 cmHandleQueryApiParameters, CmHandleQueryServiceParameters.class);
215         validateCmHandleQueryParameters(cmHandleQueryServiceParameters, CmHandleQueryConditions.ALL_CONDITION_NAMES);
216         return networkCmProxyCmHandleQueryService.queryCmHandleIds(cmHandleQueryServiceParameters);
217     }
218
219     /**
220      * Set the data sync enabled flag, along with the data sync state
221      * based on the data sync enabled boolean for the cm handle id provided.
222      *
223      * @param cmHandleId      cm handle id
224      * @param dataSyncEnabledTargetValue data sync enabled flag
225      */
226     @Override
227     public void setDataSyncEnabled(final String cmHandleId, final Boolean dataSyncEnabledTargetValue) {
228         final CompositeState compositeState = inventoryPersistence.getCmHandleState(cmHandleId);
229         if (dataSyncEnabledTargetValue.equals(compositeState.getDataSyncEnabled())) {
230             log.info("Data-Sync Enabled flag is already: {} ", dataSyncEnabledTargetValue);
231             return;
232         }
233         if (CmHandleState.READY.equals(compositeState.getCmHandleState())) {
234             final DataStoreSyncState dataStoreSyncState = compositeState.getDataStores()
235                     .getOperationalDataStore().getDataStoreSyncState();
236             if (Boolean.FALSE.equals(dataSyncEnabledTargetValue)
237                     && DataStoreSyncState.SYNCHRONIZED.equals(dataStoreSyncState)) {
238                 // TODO : This is hard-coded for onap dmi that need to be addressed
239                 cpsDataService.deleteDataNode(NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME, cmHandleId,
240                         "/netconf-state", OffsetDateTime.now());
241             }
242             CompositeStateUtils.setDataSyncEnabledFlagWithDataSyncState(dataSyncEnabledTargetValue, compositeState);
243             inventoryPersistence.saveCmHandleState(cmHandleId, compositeState);
244         } else {
245             throw new CpsException("State mismatch exception.", "Cm-Handle not in READY state. Cm handle state is: "
246                     + compositeState.getCmHandleState());
247         }
248     }
249
250     /**
251      * Get all cm handle IDs by DMI plugin identifier.
252      *
253      * @param dmiPluginIdentifier DMI plugin identifier
254      * @return set of cm handle IDs
255      */
256     @Override
257     public Collection<String> getAllCmHandleIdsByDmiPluginIdentifier(final String dmiPluginIdentifier) {
258         return cmHandleQueries.getCmHandleIdsByDmiPluginIdentifier(dmiPluginIdentifier);
259     }
260
261     /**
262      * Get all cm handle IDs by various properties.
263      *
264      * @param cmHandleQueryServiceParameters cm handle query parameters
265      * @return set of cm handle IDs
266      */
267     @Override
268     public Collection<String> executeCmHandleIdSearchForInventory(
269             final CmHandleQueryServiceParameters cmHandleQueryServiceParameters) {
270         validateCmHandleQueryParameters(cmHandleQueryServiceParameters, InventoryQueryConditions.ALL_CONDITION_NAMES);
271         return networkCmProxyCmHandleQueryService.queryCmHandleIdsForInventory(cmHandleQueryServiceParameters);
272     }
273
274     /**
275      * Retrieve cm handle details for a given cm handle.
276      *
277      * @param cmHandleId cm handle identifier
278      * @return cm handle details
279      */
280     @Override
281     public NcmpServiceCmHandle getNcmpServiceCmHandle(final String cmHandleId) {
282         return YangDataConverter.convertYangModelCmHandleToNcmpServiceCmHandle(
283                 inventoryPersistence.getYangModelCmHandle(cmHandleId));
284     }
285
286     /**
287      * Get cm handle public properties for a given cm handle id.
288      *
289      * @param cmHandleId cm handle identifier
290      * @return cm handle public properties
291      */
292     @Override
293     public Map<String, String> getCmHandlePublicProperties(final String cmHandleId) {
294         final YangModelCmHandle yangModelCmHandle = inventoryPersistence.getYangModelCmHandle(cmHandleId);
295         final List<YangModelCmHandle.Property> yangModelPublicProperties = yangModelCmHandle.getPublicProperties();
296         final Map<String, String> cmHandlePublicProperties = new HashMap<>();
297         YangDataConverter.asPropertiesMap(yangModelPublicProperties, cmHandlePublicProperties);
298         return cmHandlePublicProperties;
299     }
300
301     /**
302      * Get cm handle composite state for a given cm handle id.
303      *
304      * @param cmHandleId cm handle identifier
305      * @return cm handle state
306      */
307     @Override
308     public CompositeState getCmHandleCompositeState(final String cmHandleId) {
309         return inventoryPersistence.getYangModelCmHandle(cmHandleId).getCompositeState();
310     }
311
312     /**
313      * THis method registers a cm handle and initiates modules sync.
314      *
315      * @param dmiPluginRegistration dmi plugin registration information.
316      * @return cm-handle registration response for create cm-handle requests.
317      */
318     public List<CmHandleRegistrationResponse> parseAndProcessCreatedCmHandlesInRegistration(
319             final DmiPluginRegistration dmiPluginRegistration) {
320         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>();
321         dmiPluginRegistration.getCreatedCmHandles()
322                 .forEach(cmHandle -> {
323                     final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
324                             dmiPluginRegistration.getDmiPlugin(),
325                             dmiPluginRegistration.getDmiDataPlugin(),
326                             dmiPluginRegistration.getDmiModelPlugin(),
327                             cmHandle,
328                             cmHandle.getModuleSetTag());
329                     cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.ADVISED);
330                 });
331         return registerNewCmHandles(cmHandleStatePerCmHandle);
332     }
333
334     protected List<CmHandleRegistrationResponse> parseAndProcessDeletedCmHandlesInRegistration(
335             final List<String> tobeRemovedCmHandles) {
336         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
337                 new ArrayList<>(tobeRemovedCmHandles.size());
338         final Collection<YangModelCmHandle> yangModelCmHandles =
339                 inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
340
341         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
342
343         final Set<String> notDeletedCmHandles = new HashSet<>();
344         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
345             try {
346                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
347                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
348                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
349
350             } catch (final RuntimeException batchException) {
351                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
352                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
353                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
354                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
355                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
356                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
357                         notDeletedCmHandles.add(cmHandleId);
358                     }
359                 }
360             }
361         }
362
363         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
364         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
365
366         return cmHandleRegistrationResponses;
367     }
368
369     protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
370             final DmiPluginRegistration dmiPluginRegistration) {
371
372         final List<String> upgradedCmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
373
374         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
375                 = new HashMap<>(upgradedCmHandleIds.size());
376
377         final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus
378                 = new EnumMap<>(NcmpResponseStatus.class);
379         final List<String> nonExistingCmHandleIds = new ArrayList<>();
380         final List<String> nonReadyCmHandleIds = new ArrayList<>();
381         final List<String> invalidCmHandleIds = new ArrayList<>();
382
383         upgradedCmHandleIds.forEach(cmHandleId -> {
384             try {
385                 if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
386                     final YangModelCmHandle yangModelCmHandleWithUpgradeDetails
387                             = createYangModelCmHandle(dmiPluginRegistration, cmHandleId);
388                     acceptedCmHandleStatePerCmHandle.put(yangModelCmHandleWithUpgradeDetails, CmHandleState.LOCKED);
389                 } else {
390                     nonReadyCmHandleIds.add(cmHandleId);
391                 }
392             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
393                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
394                         cmHandleId, dataNodeNotFoundException.getMessage());
395                 nonExistingCmHandleIds.add(cmHandleId);
396             } catch (final DataValidationException dataValidationException) {
397                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
398                         cmHandleId, dataValidationException.getMessage());
399                 invalidCmHandleIds.add(cmHandleId);
400             }
401         });
402         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_READY, nonReadyCmHandleIds);
403         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_FOUND, nonExistingCmHandleIds);
404         failedCmHandlesPerResponseStatus.put(CM_HANDLE_INVALID_ID, invalidCmHandleIds);
405         return mergeAllCmHandleResponses(acceptedCmHandleStatePerCmHandle, failedCmHandlesPerResponseStatus);
406     }
407
408     private static YangModelCmHandle createYangModelCmHandle(final DmiPluginRegistration dmiPluginRegistration,
409                                                              final String cmHandleId) {
410         final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
411         ncmpServiceCmHandle.setCmHandleId(cmHandleId);
412         final String moduleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
413         final String lockReasonWithModuleSetTag = MessageFormat.format("ModuleSetTag: {0}", moduleSetTag);
414         ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
415                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
416         return YangModelCmHandle.toYangModelCmHandle(dmiPluginRegistration.getDmiPlugin(),
417                 dmiPluginRegistration.getDmiDataPlugin(), dmiPluginRegistration.getDmiModelPlugin(),
418                 ncmpServiceCmHandle, moduleSetTag);
419     }
420
421     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
422         try {
423             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
424             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
425         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
426             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
427                 cmHandleId, dataNodeNotFoundException.getMessage());
428             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
429         } catch (final DataValidationException dataValidationException) {
430             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
431                 cmHandleId, dataValidationException.getMessage());
432             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
433         } catch (final Exception exception) {
434             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
435             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
436         }
437     }
438
439     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
440                                           final CmHandleState cmHandleState) {
441         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
442         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
443         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
444     }
445
446     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
447         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
448         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
449                 + "']");
450         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
451     }
452
453     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
454         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
455         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
456         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
457     }
458
459     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
460         return cmHandles.stream()
461                 .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
462                 .collect(Collectors.toSet());
463     }
464
465     // CPS-1239 Robustness cleaning of in progress cache
466     private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
467         if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
468             log.debug("{} removed from in progress map", deletedCmHandleId);
469         }
470     }
471
472     private List<CmHandleRegistrationResponse> registerNewCmHandles(final Map<YangModelCmHandle, CmHandleState>
473                                                                             cmHandleStatePerCmHandle) {
474         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
475         try {
476             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
477             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
478         } catch (final AlreadyDefinedException alreadyDefinedException) {
479             return CmHandleRegistrationResponse.createFailureResponses(
480                     alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST);
481         } catch (final Exception exception) {
482             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
483         }
484     }
485
486     private List<CmHandleRegistrationResponse> mergeAllCmHandleResponses(
487             final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle,
488             final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus) {
489         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses
490                 = upgradeCmHandles(acceptedCmHandleStatePerCmHandle);
491         failedCmHandlesPerResponseStatus.forEach((ncmpResponseStatus, cmHandleIds) ->
492             cmHandleIds.forEach(cmHandleId -> cmHandleUpgradeResponses.add(CmHandleRegistrationResponse
493                 .createFailureResponse(cmHandleId, ncmpResponseStatus))));
494         return cmHandleUpgradeResponses;
495     }
496
497     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
498                                                                         cmHandleStatePerCmHandle) {
499         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
500         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
501         try {
502             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
503             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
504         } catch (final Exception e) {
505             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
506             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
507         }
508     }
509
510     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
511         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
512     }
513
514     private void populateTrustLevelPerCmHandleCache(final DmiPluginRegistration dmiPluginRegistration) {
515         for (final NcmpServiceCmHandle cmHandle: dmiPluginRegistration.getCreatedCmHandles()) {
516             if (cmHandle.getRegistrationTrustLevel() == null) {
517                 if (trustLevelPerCmHandle.containsKey(cmHandle.getCmHandleId())) {
518                     log.warn("CmHandle : {}, Already exists, Initial trustLevel ignored.", cmHandle.getCmHandleId());
519                 } else {
520                     trustLevelPerCmHandle.put(cmHandle.getCmHandleId(), TrustLevel.COMPLETE);
521                 }
522             } else {
523                 trustLevelPerCmHandle.put(cmHandle.getCmHandleId(), cmHandle.getRegistrationTrustLevel());
524             }
525         }
526     }
527
528     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
529         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
530             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
531         } else {
532             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
533         }
534     }
535
536 }