Uplift Spring Boot to 3.2.2
[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.time.OffsetDateTime;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.stream.Collectors;
47 import lombok.RequiredArgsConstructor;
48 import lombok.extern.slf4j.Slf4j;
49 import org.apache.commons.lang3.StringUtils;
50 import org.onap.cps.api.CpsDataService;
51 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandleQueryService;
52 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
53 import org.onap.cps.ncmp.api.impl.config.embeddedcache.TrustLevelCacheConfig;
54 import org.onap.cps.ncmp.api.impl.events.lcm.LcmEventsCmHandleStateHandler;
55 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
56 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
57 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
58 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateBuilder;
59 import org.onap.cps.ncmp.api.impl.inventory.CompositeStateUtils;
60 import org.onap.cps.ncmp.api.impl.inventory.DataStoreSyncState;
61 import org.onap.cps.ncmp.api.impl.inventory.InventoryPersistence;
62 import org.onap.cps.ncmp.api.impl.inventory.sync.ModuleOperationsUtils;
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.AlternateIdChecker;
68 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
69 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
70 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
71 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
72 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
73 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
74 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
75 import org.onap.cps.ncmp.api.models.DataOperationRequest;
76 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
77 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
78 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
79 import org.onap.cps.spi.FetchDescendantsOption;
80 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
81 import org.onap.cps.spi.exceptions.CpsException;
82 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
83 import org.onap.cps.spi.exceptions.DataValidationException;
84 import org.onap.cps.spi.model.ModuleDefinition;
85 import org.onap.cps.spi.model.ModuleReference;
86 import org.onap.cps.utils.JsonObjectMapper;
87 import org.springframework.beans.factory.annotation.Qualifier;
88 import org.springframework.http.ResponseEntity;
89 import org.springframework.stereotype.Service;
90
91 @Slf4j
92 @Service
93 @RequiredArgsConstructor
94 public class NetworkCmProxyDataServiceImpl implements NetworkCmProxyDataService {
95
96     private static final int DELETE_BATCH_SIZE = 100;
97     private final JsonObjectMapper jsonObjectMapper;
98     private final DmiDataOperations dmiDataOperations;
99     private final NetworkCmProxyDataServicePropertyHandler networkCmProxyDataServicePropertyHandler;
100     private final InventoryPersistence inventoryPersistence;
101     private final CmHandleQueries cmHandleQueries;
102     private final NetworkCmProxyCmHandleQueryService networkCmProxyCmHandleQueryService;
103     private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
104     private final CpsDataService cpsDataService;
105     private final IMap<String, Object> moduleSyncStartedOnCmHandles;
106     @Qualifier(TrustLevelCacheConfig.TRUST_LEVEL_PER_DMI_PLUGIN_BEAN_NAME)
107     private final Map<String, TrustLevel> trustLevelPerDmiPlugin;
108     private final TrustLevelManager trustLevelManager;
109     private final AlternateIdChecker alternateIdChecker;
110
111     @Override
112     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
113         final DmiPluginRegistration dmiPluginRegistration) {
114
115         dmiPluginRegistration.validateDmiPluginRegistration();
116         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
117
118         setTrustLevelPerDmiPlugin(dmiPluginRegistration);
119
120         processRemovedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
121
122         processCreatedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
123
124         processUpdatedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
125
126         processUpgradedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
127
128         return dmiPluginRegistrationResponse;
129     }
130
131     @Override
132     public Object getResourceDataForCmHandle(final String datastoreName,
133                                              final String cmHandleId,
134                                              final String resourceIdentifier,
135                                              final String optionsParamInQuery,
136                                              final String topicParamInQuery,
137                                              final String requestId) {
138         final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(datastoreName, cmHandleId,
139             resourceIdentifier,
140             optionsParamInQuery,
141             topicParamInQuery,
142             requestId);
143         return responseEntity.getBody();
144     }
145
146     @Override
147     public Object getResourceDataForCmHandle(final String datastoreName,
148                                              final String cmHandleId,
149                                              final String resourceIdentifier,
150                                              final FetchDescendantsOption fetchDescendantsOption) {
151         return cpsDataService.getDataNodes(datastoreName, cmHandleId, resourceIdentifier,
152             fetchDescendantsOption).iterator().next();
153     }
154
155     @Override
156     public void executeDataOperationForCmHandles(final String topicParamInQuery,
157                                                  final DataOperationRequest
158                                                      dataOperationRequest,
159                                                  final String requestId) {
160         dmiDataOperations.requestResourceDataFromDmi(topicParamInQuery, dataOperationRequest, requestId);
161     }
162
163     @Override
164     public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
165                                                                  final String resourceIdentifier,
166                                                                  final OperationType operationType,
167                                                                  final String requestData,
168                                                                  final String dataType) {
169         return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier,
170             operationType, requestData, dataType);
171     }
172
173     @Override
174     public Collection<ModuleReference> getYangResourcesModuleReferences(final String cmHandleId) {
175         return inventoryPersistence.getYangResourcesModuleReferences(cmHandleId);
176     }
177
178     @Override
179     public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleId(final String cmHandleId) {
180         return inventoryPersistence.getModuleDefinitionsByCmHandleId(cmHandleId);
181     }
182
183     @Override
184     public Collection<ModuleDefinition> getModuleDefinitionsByCmHandleAndModule(final String cmHandleId,
185                                                                                 final String moduleName,
186                                                                                 final String moduleRevision) {
187         return inventoryPersistence.getModuleDefinitionsByCmHandleAndModule(cmHandleId, moduleName, moduleRevision);
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, final Collection<String> acceptedCmHandleIds) {
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                     if (acceptedCmHandleIds.contains(cmHandle.getCmHandleId())) {
326                         final YangModelCmHandle yangModelCmHandle = YangModelCmHandle.toYangModelCmHandle(
327                                 dmiPluginRegistration.getDmiPlugin(),
328                                 dmiPluginRegistration.getDmiDataPlugin(),
329                                 dmiPluginRegistration.getDmiModelPlugin(),
330                                 cmHandle,
331                                 cmHandle.getModuleSetTag(),
332                                 cmHandle.getAlternateId());
333                         yangModelCmHandles.add(yangModelCmHandle);
334                         initialTrustLevelPerCmHandleId.put(cmHandle.getCmHandleId(),
335                             cmHandle.getRegistrationTrustLevel());
336                     }
337                 });
338         return registerNewCmHandles(yangModelCmHandles, initialTrustLevelPerCmHandleId);
339     }
340
341     protected List<CmHandleRegistrationResponse> parseAndProcessDeletedCmHandlesInRegistration(
342         final List<String> tobeRemovedCmHandles) {
343         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
344             new ArrayList<>(tobeRemovedCmHandles.size());
345         final Collection<YangModelCmHandle> yangModelCmHandles =
346             inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandles);
347         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
348
349         final Set<String> notDeletedCmHandles = new HashSet<>();
350         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
351             try {
352                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
353                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
354                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
355
356             } catch (final RuntimeException batchException) {
357                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
358                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
359                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
360                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
361                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
362                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
363                         notDeletedCmHandles.add(cmHandleId);
364                     }
365                 }
366             }
367         }
368
369         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
370         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
371
372         return cmHandleRegistrationResponses;
373     }
374
375     private void processRemovedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
376                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
377         if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
378             dmiPluginRegistrationResponse.setRemovedCmHandles(
379                 parseAndProcessDeletedCmHandlesInRegistration(dmiPluginRegistration.getRemovedCmHandles()));
380         }
381     }
382
383     private void processCreatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
384                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
385         final Collection<String> acceptedCmHandleIds = alternateIdChecker
386             .getIdsOfCmHandlesWithAcceptableAlternateId(dmiPluginRegistration.getCreatedCmHandles());
387         if (!acceptedCmHandleIds.isEmpty()) {
388             dmiPluginRegistrationResponse.setCreatedCmHandles(
389                 parseAndProcessCreatedCmHandlesInRegistration(dmiPluginRegistration, acceptedCmHandleIds));
390         }
391     }
392
393     private void processUpdatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
394                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
395         if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
396             dmiPluginRegistrationResponse.setUpdatedCmHandles(
397                 networkCmProxyDataServicePropertyHandler
398                     .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
399         }
400     }
401
402     private void processUpgradedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
403                                           final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
404         if (dmiPluginRegistration.getUpgradedCmHandles() != null
405             && !dmiPluginRegistration.getUpgradedCmHandles().getCmHandles().isEmpty()) {
406             dmiPluginRegistrationResponse.setUpgradedCmHandles(
407                 parseAndProcessUpgradedCmHandlesInRegistration(dmiPluginRegistration));
408         }
409     }
410
411
412     protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
413         final DmiPluginRegistration dmiPluginRegistration) {
414
415         final List<String> upgradedCmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
416         final String upgradedModuleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
417         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
418                 = new HashMap<>(upgradedCmHandleIds.size());
419         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses = new ArrayList<>(upgradedCmHandleIds.size());
420
421         for (final String cmHandleId : upgradedCmHandleIds) {
422             try {
423                 final YangModelCmHandle yangModelCmHandle = inventoryPersistence.getYangModelCmHandle(cmHandleId);
424                 if (yangModelCmHandle.getCompositeState().getCmHandleState() == CmHandleState.READY) {
425                     if (moduleUpgradeCanBeSkipped(yangModelCmHandle, upgradedModuleSetTag)) {
426                         cmHandleUpgradeResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
427                     } else {
428                         updateYangModelCmHandleForUpgrade(yangModelCmHandle, upgradedModuleSetTag);
429                         acceptedCmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.LOCKED);
430                     }
431                 } else {
432                     cmHandleUpgradeResponses.add(
433                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_READY));
434                 }
435             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
436                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
437                         cmHandleId, dataNodeNotFoundException.getMessage());
438                 cmHandleUpgradeResponses.add(
439                         CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
440             } catch (final DataValidationException dataValidationException) {
441                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
442                         cmHandleId, dataValidationException.getMessage());
443                 cmHandleUpgradeResponses.add(
444                         CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
445             }
446         }
447         cmHandleUpgradeResponses.addAll(upgradeCmHandles(acceptedCmHandleStatePerCmHandle));
448         return cmHandleUpgradeResponses;
449     }
450
451     private static boolean moduleUpgradeCanBeSkipped(final YangModelCmHandle yangModelCmHandle,
452                                                      final String upgradedModuleSetTag) {
453         if (StringUtils.isBlank(upgradedModuleSetTag)) {
454             return false;
455         }
456         return yangModelCmHandle.getModuleSetTag().equals(upgradedModuleSetTag);
457     }
458
459     private static void updateYangModelCmHandleForUpgrade(final YangModelCmHandle yangModelCmHandle,
460                                                           final String upgradedModuleSetTag) {
461         final String lockReasonWithModuleSetTag = String.format(ModuleOperationsUtils.MODULE_SET_TAG_MESSAGE_FORMAT,
462                 upgradedModuleSetTag);
463         yangModelCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
464                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
465     }
466
467     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
468         try {
469             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
470             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
471         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
472             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
473                 cmHandleId, dataNodeNotFoundException.getMessage());
474             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
475         } catch (final DataValidationException dataValidationException) {
476             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
477                 cmHandleId, dataValidationException.getMessage());
478             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
479         } catch (final Exception exception) {
480             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
481             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
482         }
483     }
484
485     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
486                                           final CmHandleState cmHandleState) {
487         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
488         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
489         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
490     }
491
492     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
493         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
494         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
495             + "']");
496         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
497     }
498
499     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
500         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
501         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
502         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
503     }
504
505     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
506         return cmHandles.stream()
507             .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
508             .collect(Collectors.toSet());
509     }
510
511     // CPS-1239 Robustness cleaning of in progress cache
512     private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
513         if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
514             log.debug("{} removed from in progress map", deletedCmHandleId);
515         }
516     }
517
518     private List<CmHandleRegistrationResponse> registerNewCmHandles(final List<YangModelCmHandle> yangModelCmHandles,
519                                                                     final Map<String, TrustLevel>
520                                                                             initialTrustLevelPerCmHandleId) {
521         final Set<String> cmHandleIds = initialTrustLevelPerCmHandleId.keySet();
522         try {
523             lcmEventsCmHandleStateHandler.initiateStateAdvised(yangModelCmHandles);
524             trustLevelManager.handleInitialRegistrationOfTrustLevels(initialTrustLevelPerCmHandleId);
525             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
526         } catch (final AlreadyDefinedException alreadyDefinedException) {
527             return CmHandleRegistrationResponse.createFailureResponses(
528                     alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST);
529         } catch (final Exception exception) {
530             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
531         }
532     }
533
534     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
535                                                                     cmHandleStatePerCmHandle) {
536         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
537         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
538         try {
539             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
540             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
541         } catch (final Exception e) {
542             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
543             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
544         }
545     }
546
547     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
548         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
549     }
550
551     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
552         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
553             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
554         } else {
555             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
556         }
557     }
558
559
560
561 }