Publish trust level notification event
[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.trustlevel.TrustLevelManager;
67 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
68 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
69 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
70 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
71 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
72 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
73 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
74 import org.onap.cps.ncmp.api.models.DataOperationRequest;
75 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
76 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
77 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
78 import org.onap.cps.spi.FetchDescendantsOption;
79 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
80 import org.onap.cps.spi.exceptions.CpsException;
81 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
82 import org.onap.cps.spi.exceptions.DataValidationException;
83 import org.onap.cps.spi.model.ModuleDefinition;
84 import org.onap.cps.spi.model.ModuleReference;
85 import org.onap.cps.utils.JsonObjectMapper;
86 import org.springframework.http.ResponseEntity;
87 import org.springframework.stereotype.Service;
88
89 @Slf4j
90 @Service
91 @RequiredArgsConstructor
92 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
93
94     private static final int DELETE_BATCH_SIZE = 100;
95     private final JsonObjectMapper jsonObjectMapper;
96     private final DmiDataOperations dmiDataOperations;
97     private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
98     private final InventoryPersistence inventoryPersistence;
99     private final CmHandleQueries cmHandleQueries;
100     private final NetworkCmProxyCmHandleQueryService networkCmProxyCmHandleQueryService;
101     private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
102     private final CpsDataService cpsDataService;
103     private final IMap<String, Object> moduleSyncStartedOnCmHandles;
104     private final Map<String, TrustLevel> trustLevelPerDmiPlugin;
105     private final TrustLevelManager trustLevelManager;
106
107     @Override
108     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
109         final DmiPluginRegistration dmiPluginRegistration) {
110         dmiPluginRegistration.validateDmiPluginRegistration();
111         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
112
113         setTrustLevelPerDmiPlugin(dmiPluginRegistration);
114
115         if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
116             dmiPluginRegistrationResponse.setRemovedCmHandles(
117                 parseAndProcessDeletedCmHandlesInRegistration(dmiPluginRegistration.getRemovedCmHandles()));
118         }
119
120         if (!dmiPluginRegistration.getCreatedCmHandles().isEmpty()) {
121             dmiPluginRegistrationResponse.setCreatedCmHandles(
122                 parseAndProcessCreatedCmHandlesInRegistration(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 List<NcmpServiceCmHandle> cmHandlesToBeCreated = dmiPluginRegistration.getCreatedCmHandles();
321         final Map<String, TrustLevel> initialTrustLevelPerCmHandleId = new HashMap<>(cmHandlesToBeCreated.size());
322         final List<YangModelCmHandle> yangModelCmHandles = new ArrayList<>(cmHandlesToBeCreated.size());
323         cmHandlesToBeCreated
324                 .forEach(cmHandle -> {
325                     final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
326                             dmiPluginRegistration.getDmiPlugin(),
327                             dmiPluginRegistration.getDmiDataPlugin(),
328                             dmiPluginRegistration.getDmiModelPlugin(),
329                             cmHandle,
330                             cmHandle.getModuleSetTag());
331                     yangModelCmHandles.add(yangModelCmHandle);
332                     initialTrustLevelPerCmHandleId.put(cmHandle.getCmHandleId(), cmHandle.getRegistrationTrustLevel());
333                 });
334         return registerNewCmHandles(yangModelCmHandles, initialTrustLevelPerCmHandleId);
335     }
336
337     protected List<CmHandleRegistrationResponse> parseAndProcessDeletedCmHandlesInRegistration(
338         final List<String> tobeRemovedCmHandles) {
339         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
340             new ArrayList<>(tobeRemovedCmHandles.size());
341         final Collection<YangModelCmHandle> yangModelCmHandles =
342             inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
343
344         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
345
346         final Set<String> notDeletedCmHandles = new HashSet<>();
347         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
348             try {
349                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
350                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
351                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
352
353             } catch (final RuntimeException batchException) {
354                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
355                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
356                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
357                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
358                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
359                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
360                         notDeletedCmHandles.add(cmHandleId);
361                     }
362                 }
363             }
364         }
365
366         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
367         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
368
369         return cmHandleRegistrationResponses;
370     }
371
372     protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
373         final DmiPluginRegistration dmiPluginRegistration) {
374
375         final List<String> upgradedCmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
376
377         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
378                 = new HashMap<>(upgradedCmHandleIds.size());
379
380         final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus
381                 = new EnumMap<>(NcmpResponseStatus.class);
382         final List<String> nonExistingCmHandleIds = new ArrayList<>();
383         final List<String> nonReadyCmHandleIds = new ArrayList<>();
384         final List<String> invalidCmHandleIds = new ArrayList<>();
385
386         upgradedCmHandleIds.forEach(cmHandleId -> {
387             try {
388                 if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
389                     final YangModelCmHandle yangModelCmHandleWithUpgradeDetails
390                             = createYangModelCmHandle(dmiPluginRegistration, cmHandleId);
391                     acceptedCmHandleStatePerCmHandle.put(yangModelCmHandleWithUpgradeDetails, CmHandleState.LOCKED);
392                 } else {
393                     nonReadyCmHandleIds.add(cmHandleId);
394                 }
395             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
396                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
397                         cmHandleId, dataNodeNotFoundException.getMessage());
398                 nonExistingCmHandleIds.add(cmHandleId);
399             } catch (final DataValidationException dataValidationException) {
400                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
401                         cmHandleId, dataValidationException.getMessage());
402                 invalidCmHandleIds.add(cmHandleId);
403             }
404         });
405         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_READY, nonReadyCmHandleIds);
406         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_FOUND, nonExistingCmHandleIds);
407         failedCmHandlesPerResponseStatus.put(CM_HANDLE_INVALID_ID, invalidCmHandleIds);
408         return mergeAllCmHandleResponses(acceptedCmHandleStatePerCmHandle, failedCmHandlesPerResponseStatus);
409     }
410
411     private static YangModelCmHandle createYangModelCmHandle(final DmiPluginRegistration dmiPluginRegistration,
412                                                              final String cmHandleId) {
413         final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
414         ncmpServiceCmHandle.setCmHandleId(cmHandleId);
415         final String moduleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
416         final String lockReasonWithModuleSetTag = MessageFormat.format("ModuleSetTag: {0}", moduleSetTag);
417         ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
418                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
419         return YangModelCmHandle.toYangModelCmHandle(dmiPluginRegistration.getDmiPlugin(),
420                 dmiPluginRegistration.getDmiDataPlugin(), dmiPluginRegistration.getDmiModelPlugin(),
421                 ncmpServiceCmHandle, moduleSetTag);
422     }
423
424     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
425         try {
426             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
427             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
428         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
429             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
430                 cmHandleId, dataNodeNotFoundException.getMessage());
431             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
432         } catch (final DataValidationException dataValidationException) {
433             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
434                 cmHandleId, dataValidationException.getMessage());
435             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
436         } catch (final Exception exception) {
437             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
438             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
439         }
440     }
441
442     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
443                                           final CmHandleState cmHandleState) {
444         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
445         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
446         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
447     }
448
449     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
450         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
451         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
452             + "']");
453         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
454     }
455
456     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
457         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
458         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
459         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
460     }
461
462     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
463         return cmHandles.stream()
464             .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
465             .collect(Collectors.toSet());
466     }
467
468     // CPS-1239 Robustness cleaning of in progress cache
469     private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
470         if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
471             log.debug("{} removed from in progress map", deletedCmHandleId);
472         }
473     }
474
475     private List<CmHandleRegistrationResponse> registerNewCmHandles(final List<YangModelCmHandle> yangModelCmHandles,
476                                                                     final Map<String, TrustLevel>
477                                                                             initialTrustLevelPerCmHandleId) {
478         final Set<String> cmHandleIds = initialTrustLevelPerCmHandleId.keySet();
479         try {
480             lcmEventsCmHandleStateHandler.initiateStateAdvised(yangModelCmHandles);
481             trustLevelManager.handleInitialRegistrationOfTrustLevels(initialTrustLevelPerCmHandleId);
482             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
483         } catch (final AlreadyDefinedException alreadyDefinedException) {
484             return CmHandleRegistrationResponse.createFailureResponses(
485                     alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST);
486         } catch (final Exception exception) {
487             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
488         }
489     }
490
491     private List<CmHandleRegistrationResponse> mergeAllCmHandleResponses(
492             final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle,
493             final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus) {
494         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses
495                 = upgradeCmHandles(acceptedCmHandleStatePerCmHandle);
496         failedCmHandlesPerResponseStatus.forEach((ncmpResponseStatus, cmHandleIds) ->
497             cmHandleIds.forEach(cmHandleId -> cmHandleUpgradeResponses.add(CmHandleRegistrationResponse
498                 .createFailureResponse(cmHandleId, ncmpResponseStatus))));
499         return cmHandleUpgradeResponses;
500     }
501
502     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
503                                                                     cmHandleStatePerCmHandle) {
504         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
505         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
506         try {
507             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
508             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
509         } catch (final Exception e) {
510             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
511             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
512         }
513     }
514
515     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
516         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
517     }
518
519     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
520         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
521             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
522         } else {
523             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
524         }
525     }
526
527 }