Merge "Trust level updates with dmi status change"
[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().forEach(cmHandle -> {
322             final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
323                 dmiPluginRegistration.getDmiPlugin(),
324                 dmiPluginRegistration.getDmiDataPlugin(),
325                 dmiPluginRegistration.getDmiModelPlugin(),
326                 cmHandle,
327                 cmHandle.getModuleSetTag());
328             cmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.ADVISED);
329         });
330         return registerNewCmHandles(cmHandleStatePerCmHandle);
331     }
332
333     protected List<CmHandleRegistrationResponse> parseAndProcessDeletedCmHandlesInRegistration(
334         final List<String> tobeRemovedCmHandles) {
335         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
336             new ArrayList<>(tobeRemovedCmHandles.size());
337         final Collection<YangModelCmHandle> yangModelCmHandles =
338             inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
339
340         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
341
342         final Set<String> notDeletedCmHandles = new HashSet<>();
343         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
344             try {
345                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
346                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
347                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
348
349             } catch (final RuntimeException batchException) {
350                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
351                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
352                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
353                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
354                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
355                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
356                         notDeletedCmHandles.add(cmHandleId);
357                     }
358                 }
359             }
360         }
361
362         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
363         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
364
365         return cmHandleRegistrationResponses;
366     }
367
368     protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
369         final DmiPluginRegistration dmiPluginRegistration) {
370
371         final List<String> upgradedCmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
372
373         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
374                 = new HashMap<>(upgradedCmHandleIds.size());
375
376         final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus
377                 = new EnumMap<>(NcmpResponseStatus.class);
378         final List<String> nonExistingCmHandleIds = new ArrayList<>();
379         final List<String> nonReadyCmHandleIds = new ArrayList<>();
380         final List<String> invalidCmHandleIds = new ArrayList<>();
381
382         upgradedCmHandleIds.forEach(cmHandleId -> {
383             try {
384                 if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
385                     final YangModelCmHandle yangModelCmHandleWithUpgradeDetails
386                             = createYangModelCmHandle(dmiPluginRegistration, cmHandleId);
387                     acceptedCmHandleStatePerCmHandle.put(yangModelCmHandleWithUpgradeDetails, CmHandleState.LOCKED);
388                 } else {
389                     nonReadyCmHandleIds.add(cmHandleId);
390                 }
391             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
392                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
393                         cmHandleId, dataNodeNotFoundException.getMessage());
394                 nonExistingCmHandleIds.add(cmHandleId);
395             } catch (final DataValidationException dataValidationException) {
396                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
397                         cmHandleId, dataValidationException.getMessage());
398                 invalidCmHandleIds.add(cmHandleId);
399             }
400         });
401         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_READY, nonReadyCmHandleIds);
402         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_FOUND, nonExistingCmHandleIds);
403         failedCmHandlesPerResponseStatus.put(CM_HANDLE_INVALID_ID, invalidCmHandleIds);
404         return mergeAllCmHandleResponses(acceptedCmHandleStatePerCmHandle, failedCmHandlesPerResponseStatus);
405     }
406
407     private static YangModelCmHandle createYangModelCmHandle(final DmiPluginRegistration dmiPluginRegistration,
408                                                              final String cmHandleId) {
409         final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
410         ncmpServiceCmHandle.setCmHandleId(cmHandleId);
411         final String moduleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
412         final String lockReasonWithModuleSetTag = MessageFormat.format("ModuleSetTag: {0}", moduleSetTag);
413         ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
414                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
415         return YangModelCmHandle.toYangModelCmHandle(dmiPluginRegistration.getDmiPlugin(),
416                 dmiPluginRegistration.getDmiDataPlugin(), dmiPluginRegistration.getDmiModelPlugin(),
417                 ncmpServiceCmHandle, moduleSetTag);
418     }
419
420     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
421         try {
422             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
423             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
424         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
425             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
426                 cmHandleId, dataNodeNotFoundException.getMessage());
427             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
428         } catch (final DataValidationException dataValidationException) {
429             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
430                 cmHandleId, dataValidationException.getMessage());
431             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
432         } catch (final Exception exception) {
433             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
434             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
435         }
436     }
437
438     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
439                                           final CmHandleState cmHandleState) {
440         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
441         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
442         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
443     }
444
445     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
446         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
447         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
448             + "']");
449         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
450     }
451
452     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
453         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
454         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
455         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
456     }
457
458     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
459         return cmHandles.stream()
460             .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
461             .collect(Collectors.toSet());
462     }
463
464     // CPS-1239 Robustness cleaning of in progress cache
465     private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
466         if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
467             log.debug("{} removed from in progress map", deletedCmHandleId);
468         }
469     }
470
471     private List<CmHandleRegistrationResponse> registerNewCmHandles(final Map<YangModelCmHandle, CmHandleState>
472                                                                         cmHandleStatePerCmHandle) {
473         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
474         try {
475             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
476             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
477         } catch (final AlreadyDefinedException alreadyDefinedException) {
478             return CmHandleRegistrationResponse.createFailureResponses(
479                     alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST);
480         } catch (final Exception exception) {
481             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
482         }
483     }
484
485     private List<CmHandleRegistrationResponse> mergeAllCmHandleResponses(
486             final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle,
487             final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus) {
488         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses
489                 = upgradeCmHandles(acceptedCmHandleStatePerCmHandle);
490         failedCmHandlesPerResponseStatus.forEach((ncmpResponseStatus, cmHandleIds) ->
491             cmHandleIds.forEach(cmHandleId -> cmHandleUpgradeResponses.add(CmHandleRegistrationResponse
492                 .createFailureResponse(cmHandleId, ncmpResponseStatus))));
493         return cmHandleUpgradeResponses;
494     }
495
496     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
497                                                                     cmHandleStatePerCmHandle) {
498         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
499         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
500         try {
501             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
502             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
503         } catch (final Exception e) {
504             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
505             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
506         }
507     }
508
509     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
510         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
511     }
512
513     private void populateTrustLevelPerCmHandleCache(final DmiPluginRegistration dmiPluginRegistration) {
514         for (final NcmpServiceCmHandle cmHandle: dmiPluginRegistration.getCreatedCmHandles()) {
515             if (cmHandle.getRegistrationTrustLevel() == null) {
516                 if (trustLevelPerCmHandle.containsKey(cmHandle.getCmHandleId())) {
517                     log.warn("CmHandle : {}, Already exists, Initial trustLevel ignored.", cmHandle.getCmHandleId());
518                 } else {
519                     trustLevelPerCmHandle.put(cmHandle.getCmHandleId(), TrustLevel.COMPLETE);
520                 }
521             } else {
522                 trustLevelPerCmHandle.put(cmHandle.getCmHandleId(), cmHandle.getRegistrationTrustLevel());
523             }
524         }
525     }
526
527     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
528         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
529             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
530         } else {
531             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
532         }
533     }
534
535 }