Merge "Use DB for checking Alternate IDs"
[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.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.inventory.sync.ModuleOperationsUtils;
64 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
65 import org.onap.cps.ncmp.api.impl.operations.OperationType;
66 import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevel;
67 import org.onap.cps.ncmp.api.impl.trustlevel.TrustLevelManager;
68 import org.onap.cps.ncmp.api.impl.utils.AlternateIdChecker;
69 import org.onap.cps.ncmp.api.impl.utils.CmHandleQueryConditions;
70 import org.onap.cps.ncmp.api.impl.utils.InventoryQueryConditions;
71 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
72 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
73 import org.onap.cps.ncmp.api.models.CmHandleQueryApiParameters;
74 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters;
75 import org.onap.cps.ncmp.api.models.CmHandleRegistrationResponse;
76 import org.onap.cps.ncmp.api.models.DataOperationRequest;
77 import org.onap.cps.ncmp.api.models.DmiPluginRegistration;
78 import org.onap.cps.ncmp.api.models.DmiPluginRegistrationResponse;
79 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle;
80 import org.onap.cps.spi.FetchDescendantsOption;
81 import org.onap.cps.spi.exceptions.AlreadyDefinedException;
82 import org.onap.cps.spi.exceptions.CpsException;
83 import org.onap.cps.spi.exceptions.DataNodeNotFoundException;
84 import org.onap.cps.spi.exceptions.DataValidationException;
85 import org.onap.cps.spi.model.ModuleDefinition;
86 import org.onap.cps.spi.model.ModuleReference;
87 import org.onap.cps.utils.JsonObjectMapper;
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     private final Map<String, TrustLevel> trustLevelPerDmiPlugin;
107     private final TrustLevelManager trustLevelManager;
108     private final AlternateIdChecker alternateIdChecker;
109     private final Map<String, Collection<ModuleReference>> moduleSetTagCache;
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         final Set<String> moduleSetTags = yangModelCmHandles.stream().map(YangModelCmHandle::getModuleSetTag)
348                 .collect(Collectors.toSet());
349         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
350
351         final Set<String> notDeletedCmHandles = new HashSet<>();
352         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandles, DELETE_BATCH_SIZE)) {
353             try {
354                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
355                 moduleSetTags.forEach(moduleSetTagCache::remove);
356                 log.debug("Removed module set tags: {}", moduleSetTags);
357                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
358                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
359
360             } catch (final RuntimeException batchException) {
361                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
362                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
363                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
364                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
365                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
366                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
367                         notDeletedCmHandles.add(cmHandleId);
368                     }
369                 }
370             }
371         }
372
373         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
374         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
375
376         return cmHandleRegistrationResponses;
377     }
378
379     private void processRemovedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
380                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
381         if (!dmiPluginRegistration.getRemovedCmHandles().isEmpty()) {
382             dmiPluginRegistrationResponse.setRemovedCmHandles(
383                 parseAndProcessDeletedCmHandlesInRegistration(dmiPluginRegistration.getRemovedCmHandles()));
384         }
385     }
386
387     private void processCreatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
388                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
389         final Collection<String> acceptedCmHandleIds = alternateIdChecker
390             .getIdsOfCmHandlesWithAcceptableAlternateId(dmiPluginRegistration.getCreatedCmHandles());
391         if (!acceptedCmHandleIds.isEmpty()) {
392             dmiPluginRegistrationResponse.setCreatedCmHandles(
393                 parseAndProcessCreatedCmHandlesInRegistration(dmiPluginRegistration, acceptedCmHandleIds));
394         }
395     }
396
397     private void processUpdatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
398                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
399         if (!dmiPluginRegistration.getUpdatedCmHandles().isEmpty()) {
400             dmiPluginRegistrationResponse.setUpdatedCmHandles(
401                 networkCmProxyDataServicePropertyHandler
402                     .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
403         }
404     }
405
406     private void processUpgradedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
407                                           final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
408         if (dmiPluginRegistration.getUpgradedCmHandles() != null
409             && !dmiPluginRegistration.getUpgradedCmHandles().getCmHandles().isEmpty()) {
410             dmiPluginRegistrationResponse.setUpgradedCmHandles(
411                 parseAndProcessUpgradedCmHandlesInRegistration(dmiPluginRegistration));
412         }
413     }
414
415
416     protected List<CmHandleRegistrationResponse> parseAndProcessUpgradedCmHandlesInRegistration(
417         final DmiPluginRegistration dmiPluginRegistration) {
418
419         final List<String> upgradedCmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
420
421         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
422                 = new HashMap<>(upgradedCmHandleIds.size());
423
424         final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus
425                 = new EnumMap<>(NcmpResponseStatus.class);
426         final List<String> nonExistingCmHandleIds = new ArrayList<>();
427         final List<String> nonReadyCmHandleIds = new ArrayList<>();
428         final List<String> invalidCmHandleIds = new ArrayList<>();
429
430         upgradedCmHandleIds.forEach(cmHandleId -> {
431             try {
432                 if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
433                     final YangModelCmHandle yangModelCmHandleWithUpgradeDetails
434                             = createYangModelCmHandle(dmiPluginRegistration, cmHandleId);
435                     acceptedCmHandleStatePerCmHandle.put(yangModelCmHandleWithUpgradeDetails, CmHandleState.LOCKED);
436                 } else {
437                     nonReadyCmHandleIds.add(cmHandleId);
438                 }
439             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
440                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
441                         cmHandleId, dataNodeNotFoundException.getMessage());
442                 nonExistingCmHandleIds.add(cmHandleId);
443             } catch (final DataValidationException dataValidationException) {
444                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
445                         cmHandleId, dataValidationException.getMessage());
446                 invalidCmHandleIds.add(cmHandleId);
447             }
448         });
449         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_READY, nonReadyCmHandleIds);
450         failedCmHandlesPerResponseStatus.put(CM_HANDLES_NOT_FOUND, nonExistingCmHandleIds);
451         failedCmHandlesPerResponseStatus.put(CM_HANDLE_INVALID_ID, invalidCmHandleIds);
452         return mergeAllCmHandleResponses(acceptedCmHandleStatePerCmHandle, failedCmHandlesPerResponseStatus);
453     }
454
455     private static YangModelCmHandle createYangModelCmHandle(final DmiPluginRegistration dmiPluginRegistration,
456                                                              final String cmHandleId) {
457         final NcmpServiceCmHandle ncmpServiceCmHandle = new NcmpServiceCmHandle();
458         ncmpServiceCmHandle.setCmHandleId(cmHandleId);
459         final String moduleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
460         final String lockReasonWithModuleSetTag = MessageFormat.format(
461                 ModuleOperationsUtils.MODULE_SET_TAG_MESSAGE_FORMAT, moduleSetTag);
462         ncmpServiceCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
463                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
464         return YangModelCmHandle.toYangModelCmHandle(dmiPluginRegistration.getDmiPlugin(),
465                 dmiPluginRegistration.getDmiDataPlugin(), dmiPluginRegistration.getDmiModelPlugin(),
466                 ncmpServiceCmHandle, moduleSetTag, ncmpServiceCmHandle.getAlternateId());
467     }
468
469     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
470         try {
471             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
472             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
473         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
474             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
475                 cmHandleId, dataNodeNotFoundException.getMessage());
476             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
477         } catch (final DataValidationException dataValidationException) {
478             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
479                 cmHandleId, dataValidationException.getMessage());
480             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
481         } catch (final Exception exception) {
482             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
483             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
484         }
485     }
486
487     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
488                                           final CmHandleState cmHandleState) {
489         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
490         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
491         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
492     }
493
494     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
495         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
496         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId
497             + "']");
498         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
499     }
500
501     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> tobeRemovedCmHandles) {
502         inventoryPersistence.deleteSchemaSetsWithCascade(tobeRemovedCmHandles);
503         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(tobeRemovedCmHandles));
504         tobeRemovedCmHandles.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
505     }
506
507     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
508         return cmHandles.stream()
509             .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
510             .collect(Collectors.toSet());
511     }
512
513     // CPS-1239 Robustness cleaning of in progress cache
514     private void removeDeletedCmHandleFromModuleSyncMap(final String deletedCmHandleId) {
515         if (moduleSyncStartedOnCmHandles.remove(deletedCmHandleId) != null) {
516             log.debug("{} removed from in progress map", deletedCmHandleId);
517         }
518     }
519
520     private List<CmHandleRegistrationResponse> registerNewCmHandles(final List<YangModelCmHandle> yangModelCmHandles,
521                                                                     final Map<String, TrustLevel>
522                                                                             initialTrustLevelPerCmHandleId) {
523         final Set<String> cmHandleIds = initialTrustLevelPerCmHandleId.keySet();
524         try {
525             lcmEventsCmHandleStateHandler.initiateStateAdvised(yangModelCmHandles);
526             trustLevelManager.handleInitialRegistrationOfTrustLevels(initialTrustLevelPerCmHandleId);
527             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
528         } catch (final AlreadyDefinedException alreadyDefinedException) {
529             return CmHandleRegistrationResponse.createFailureResponses(
530                     alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST);
531         } catch (final Exception exception) {
532             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, exception);
533         }
534     }
535
536     private List<CmHandleRegistrationResponse> mergeAllCmHandleResponses(
537             final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle,
538             final Map<NcmpResponseStatus, List<String>> failedCmHandlesPerResponseStatus) {
539         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses
540                 = upgradeCmHandles(acceptedCmHandleStatePerCmHandle);
541         failedCmHandlesPerResponseStatus.forEach((ncmpResponseStatus, cmHandleIds) ->
542             cmHandleIds.forEach(cmHandleId -> cmHandleUpgradeResponses.add(CmHandleRegistrationResponse
543                 .createFailureResponse(cmHandleId, ncmpResponseStatus))));
544         return cmHandleUpgradeResponses;
545     }
546
547     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
548                                                                     cmHandleStatePerCmHandle) {
549         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
550         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
551         try {
552             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
553             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
554         } catch (final Exception e) {
555             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
556             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
557         }
558     }
559
560     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
561         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
562     }
563
564     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
565         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
566             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
567         } else {
568             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
569         }
570     }
571
572
573
574 }