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