c15df9c869730ed7701594c455bdac77adae16db
[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.ALTERNATE_ID_ALREADY_ASSOCIATED;
28 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_FOUND;
29 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLES_NOT_READY;
30 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_ALREADY_EXIST;
31 import static org.onap.cps.ncmp.api.NcmpResponseStatus.CM_HANDLE_INVALID_ID;
32 import static org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory.MODULE_UPGRADE;
33 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NCMP_DMI_REGISTRY_PARENT;
34 import static org.onap.cps.ncmp.api.impl.ncmppersistence.NcmpPersistence.NFP_OPERATIONAL_DATASTORE_DATASPACE_NAME;
35 import static org.onap.cps.ncmp.api.impl.utils.RestQueryParametersValidator.validateCmHandleQueryParameters;
36
37 import com.google.common.collect.Lists;
38 import com.hazelcast.map.IMap;
39 import java.time.OffsetDateTime;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.HashMap;
43 import java.util.HashSet;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import java.util.stream.Collectors;
48 import lombok.RequiredArgsConstructor;
49 import lombok.extern.slf4j.Slf4j;
50 import org.apache.commons.lang3.StringUtils;
51 import org.onap.cps.api.CpsDataService;
52 import org.onap.cps.ncmp.api.NetworkCmProxyCmHandleQueryService;
53 import org.onap.cps.ncmp.api.NetworkCmProxyDataService;
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.CmResourceAddress;
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
110     @Override
111     public DmiPluginRegistrationResponse updateDmiRegistrationAndSyncModule(
112         final DmiPluginRegistration dmiPluginRegistration) {
113
114         dmiPluginRegistration.validateDmiPluginRegistration();
115         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse = new DmiPluginRegistrationResponse();
116
117         setTrustLevelPerDmiPlugin(dmiPluginRegistration);
118
119         processRemovedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
120
121         processCreatedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
122
123         processUpdatedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
124
125         processUpgradedCmHandles(dmiPluginRegistration, dmiPluginRegistrationResponse);
126
127         return dmiPluginRegistrationResponse;
128     }
129
130     @Override
131     public Object getResourceDataForCmHandle(final CmResourceAddress cmResourceAddress,
132                                              final String optionsParamInQuery,
133                                              final String topicParamInQuery,
134                                              final String requestId,
135                                              final String authorization) {
136         final ResponseEntity<?> responseEntity = dmiDataOperations.getResourceDataFromDmi(cmResourceAddress,
137             optionsParamInQuery,
138             topicParamInQuery,
139             requestId,
140             authorization);
141         return responseEntity.getBody();
142     }
143
144     @Override
145     public Object getResourceDataForCmHandle(final CmResourceAddress cmResourceAddress,
146                                              final FetchDescendantsOption fetchDescendantsOption) {
147         return cpsDataService.getDataNodes(cmResourceAddress.datastoreName(),
148                                            cmResourceAddress.cmHandleId(),
149                                            cmResourceAddress.resourceIdentifier(),
150                                            fetchDescendantsOption).iterator().next();
151     }
152
153     @Override
154     public void executeDataOperationForCmHandles(final String topicParamInQuery,
155                                                  final DataOperationRequest dataOperationRequest,
156                                                  final String requestId,
157                                                  final String authorization) {
158         dmiDataOperations.requestResourceDataFromDmi(topicParamInQuery, dataOperationRequest, requestId,
159                 authorization);
160     }
161
162     @Override
163     public Object writeResourceDataPassThroughRunningForCmHandle(final String cmHandleId,
164                                                                  final String resourceIdentifier,
165                                                                  final OperationType operationType,
166                                                                  final String requestData,
167                                                                  final String dataType,
168                                                                  final String authorization) {
169         return dmiDataOperations.writeResourceDataPassThroughRunningFromDmi(cmHandleId, resourceIdentifier,
170             operationType, requestData, dataType, authorization);
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     protected void processRemovedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
313                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
314         final List<String> tobeRemovedCmHandleIds = dmiPluginRegistration.getRemovedCmHandles();
315         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
316             new ArrayList<>(tobeRemovedCmHandleIds.size());
317         final Collection<YangModelCmHandle> yangModelCmHandles =
318             inventoryPersistence.getYangModelCmHandles(tobeRemovedCmHandleIds);
319         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETING);
320
321         final Set<String> notDeletedCmHandles = new HashSet<>();
322         for (final List<String> tobeRemovedCmHandleBatch : Lists.partition(tobeRemovedCmHandleIds, DELETE_BATCH_SIZE)) {
323             try {
324                 batchDeleteCmHandlesFromDbAndModuleSyncMap(tobeRemovedCmHandleBatch);
325                 tobeRemovedCmHandleBatch.forEach(cmHandleId ->
326                     cmHandleRegistrationResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId)));
327
328             } catch (final RuntimeException batchException) {
329                 log.error("Unable to de-register cm-handle batch, retrying on each cm handle");
330                 for (final String cmHandleId : tobeRemovedCmHandleBatch) {
331                     final CmHandleRegistrationResponse cmHandleRegistrationResponse =
332                         deleteCmHandleAndGetCmHandleRegistrationResponse(cmHandleId);
333                     cmHandleRegistrationResponses.add(cmHandleRegistrationResponse);
334                     if (cmHandleRegistrationResponse.getStatus() != CmHandleRegistrationResponse.Status.SUCCESS) {
335                         notDeletedCmHandles.add(cmHandleId);
336                     }
337                 }
338             }
339         }
340         yangModelCmHandles.removeIf(yangModelCmHandle -> notDeletedCmHandles.contains(yangModelCmHandle.getId()));
341         updateCmHandleStateBatch(yangModelCmHandles, CmHandleState.DELETED);
342         dmiPluginRegistrationResponse.setRemovedCmHandles(cmHandleRegistrationResponses);
343     }
344
345     protected void processCreatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
346                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
347         final List<NcmpServiceCmHandle> ncmpServiceCmHandles = dmiPluginRegistration.getCreatedCmHandles();
348         final List<CmHandleRegistrationResponse> failedCmHandleRegistrationResponses = new ArrayList<>();
349
350         try {
351             final Collection<String> rejectedCmHandleIds
352                 = checkAlternateIds(ncmpServiceCmHandles, failedCmHandleRegistrationResponses);
353
354             final Collection<String> succeededCmHandleIds = persistCmHandlesWithState(dmiPluginRegistration,
355                 dmiPluginRegistrationResponse, ncmpServiceCmHandles, rejectedCmHandleIds);
356
357             processTrustLevels(ncmpServiceCmHandles, succeededCmHandleIds);
358
359         } catch (final AlreadyDefinedException alreadyDefinedException) {
360             failedCmHandleRegistrationResponses.addAll(CmHandleRegistrationResponse.createFailureResponsesFromXpaths(
361                 alreadyDefinedException.getAlreadyDefinedObjectNames(), CM_HANDLE_ALREADY_EXIST));
362         } catch (final Exception exception) {
363             final Collection<String> cmHandleIds =
364                 ncmpServiceCmHandles.stream().map(NcmpServiceCmHandle::getCmHandleId).collect(Collectors.toList());
365             failedCmHandleRegistrationResponses.addAll(CmHandleRegistrationResponse
366                 .createFailureResponses(cmHandleIds, exception));
367         }
368         final List<CmHandleRegistrationResponse> mergedCmHandleRegistrationResponses
369             = new ArrayList<>(failedCmHandleRegistrationResponses);
370         mergedCmHandleRegistrationResponses.addAll(dmiPluginRegistrationResponse.getCreatedCmHandles());
371
372         dmiPluginRegistrationResponse.setCreatedCmHandles(mergedCmHandleRegistrationResponses);
373     }
374
375     protected void processUpdatedCmHandles(final DmiPluginRegistration dmiPluginRegistration,
376                                          final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
377         dmiPluginRegistrationResponse.setUpdatedCmHandles(networkCmProxyDataServicePropertyHandler
378             .updateCmHandleProperties(dmiPluginRegistration.getUpdatedCmHandles()));
379     }
380
381     protected void processUpgradedCmHandles(
382         final DmiPluginRegistration dmiPluginRegistration,
383         final DmiPluginRegistrationResponse dmiPluginRegistrationResponse) {
384
385         final List<String> cmHandleIds = dmiPluginRegistration.getUpgradedCmHandles().getCmHandles();
386         final String upgradedModuleSetTag = dmiPluginRegistration.getUpgradedCmHandles().getModuleSetTag();
387         final Map<YangModelCmHandle, CmHandleState> acceptedCmHandleStatePerCmHandle
388             = new HashMap<>(cmHandleIds.size());
389         final List<CmHandleRegistrationResponse> cmHandleUpgradeResponses = new ArrayList<>(cmHandleIds.size());
390
391         for (final String cmHandleId : cmHandleIds) {
392             try {
393                 final YangModelCmHandle yangModelCmHandle = inventoryPersistence.getYangModelCmHandle(cmHandleId);
394                 if (yangModelCmHandle.getCompositeState().getCmHandleState() == CmHandleState.READY) {
395                     if (moduleUpgradeCanBeSkipped(yangModelCmHandle, upgradedModuleSetTag)) {
396                         cmHandleUpgradeResponses.add(CmHandleRegistrationResponse.createSuccessResponse(cmHandleId));
397                     } else {
398                         updateYangModelCmHandleForUpgrade(yangModelCmHandle, upgradedModuleSetTag);
399                         acceptedCmHandleStatePerCmHandle.put(yangModelCmHandle, CmHandleState.LOCKED);
400                     }
401                 } else {
402                     cmHandleUpgradeResponses.add(
403                             CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_READY));
404                 }
405             } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
406                 log.error("Unable to find data node for cm handle id : {} , caused by : {}",
407                         cmHandleId, dataNodeNotFoundException.getMessage());
408                 cmHandleUpgradeResponses.add(
409                         CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND));
410             } catch (final DataValidationException dataValidationException) {
411                 log.error("Unable to upgrade cm handle id: {}, caused by : {}",
412                         cmHandleId, dataValidationException.getMessage());
413                 cmHandleUpgradeResponses.add(
414                         CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID));
415             }
416         }
417         cmHandleUpgradeResponses.addAll(upgradeCmHandles(acceptedCmHandleStatePerCmHandle));
418         dmiPluginRegistrationResponse.setUpgradedCmHandles(cmHandleUpgradeResponses);
419     }
420
421     private Collection<String> checkAlternateIds(
422         final List<NcmpServiceCmHandle> cmHandlesToBeCreated,
423         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses) {
424         final Collection<String> rejectedCmHandleIds = alternateIdChecker
425             .getIdsOfCmHandlesWithRejectedAlternateId(cmHandlesToBeCreated, AlternateIdChecker.Operation.CREATE);
426         cmHandleRegistrationResponses.addAll(CmHandleRegistrationResponse.createFailureResponses(
427             rejectedCmHandleIds, ALTERNATE_ID_ALREADY_ASSOCIATED));
428         return rejectedCmHandleIds;
429     }
430
431     private List<String> persistCmHandlesWithState(final DmiPluginRegistration dmiPluginRegistration,
432                                                    final DmiPluginRegistrationResponse dmiPluginRegistrationResponse,
433                                                    final List<NcmpServiceCmHandle> cmHandlesToBeCreated,
434                                                    final Collection<String> rejectedCmHandleIds) {
435         final List<String> succeededCmHandleIds = new ArrayList<>(cmHandlesToBeCreated.size());
436         final List<YangModelCmHandle> yangModelCmHandlesToRegister = new ArrayList<>(cmHandlesToBeCreated.size());
437         final List<CmHandleRegistrationResponse> cmHandleRegistrationResponses =
438             new ArrayList<>(cmHandlesToBeCreated.size());
439         for (final NcmpServiceCmHandle ncmpServiceCmHandle: cmHandlesToBeCreated) {
440             if (!rejectedCmHandleIds.contains(ncmpServiceCmHandle.getCmHandleId())) {
441                 yangModelCmHandlesToRegister.add(getYangModelCmHandle(dmiPluginRegistration, ncmpServiceCmHandle));
442                 cmHandleRegistrationResponses.add(
443                     CmHandleRegistrationResponse.createSuccessResponse(ncmpServiceCmHandle.getCmHandleId()));
444                 succeededCmHandleIds.add(ncmpServiceCmHandle.getCmHandleId());
445             }
446         }
447         lcmEventsCmHandleStateHandler.initiateStateAdvised(yangModelCmHandlesToRegister);
448         dmiPluginRegistrationResponse.setCreatedCmHandles(cmHandleRegistrationResponses);
449         return succeededCmHandleIds;
450     }
451
452     private YangModelCmHandle getYangModelCmHandle(final DmiPluginRegistration dmiPluginRegistration,
453                                                    final NcmpServiceCmHandle ncmpServiceCmHandle) {
454         return YangModelCmHandle.toYangModelCmHandle(
455             dmiPluginRegistration.getDmiPlugin(),
456             dmiPluginRegistration.getDmiDataPlugin(),
457             dmiPluginRegistration.getDmiModelPlugin(),
458             ncmpServiceCmHandle,
459             ncmpServiceCmHandle.getModuleSetTag(),
460             ncmpServiceCmHandle.getAlternateId(),
461             ncmpServiceCmHandle.getDataProducerIdentifier());
462     }
463
464     private void processTrustLevels(final Collection<NcmpServiceCmHandle> cmHandlesToBeCreated,
465                                     final Collection<String> succeededCmHandleIds) {
466         final Map<String, TrustLevel> initialTrustLevelPerCmHandleId = new HashMap<>(cmHandlesToBeCreated.size());
467         for (final NcmpServiceCmHandle ncmpServiceCmHandle: cmHandlesToBeCreated) {
468             if (succeededCmHandleIds.contains(ncmpServiceCmHandle.getCmHandleId())) {
469                 initialTrustLevelPerCmHandleId.put(ncmpServiceCmHandle.getCmHandleId(),
470                     ncmpServiceCmHandle.getRegistrationTrustLevel());
471             }
472         }
473         trustLevelManager.handleInitialRegistrationOfTrustLevels(initialTrustLevelPerCmHandleId);
474     }
475
476     private static boolean moduleUpgradeCanBeSkipped(final YangModelCmHandle yangModelCmHandle,
477                                                      final String upgradedModuleSetTag) {
478         if (StringUtils.isBlank(upgradedModuleSetTag)) {
479             return false;
480         }
481         return yangModelCmHandle.getModuleSetTag().equals(upgradedModuleSetTag);
482     }
483
484     private static void updateYangModelCmHandleForUpgrade(final YangModelCmHandle yangModelCmHandle,
485                                                           final String upgradedModuleSetTag) {
486         final String lockReasonWithModuleSetTag = String.format(ModuleOperationsUtils.MODULE_SET_TAG_MESSAGE_FORMAT,
487                 upgradedModuleSetTag);
488         yangModelCmHandle.setCompositeState(new CompositeStateBuilder().withCmHandleState(CmHandleState.READY)
489                 .withLockReason(MODULE_UPGRADE, lockReasonWithModuleSetTag).build());
490     }
491
492     private CmHandleRegistrationResponse deleteCmHandleAndGetCmHandleRegistrationResponse(final String cmHandleId) {
493         try {
494             deleteCmHandleFromDbAndModuleSyncMap(cmHandleId);
495             return CmHandleRegistrationResponse.createSuccessResponse(cmHandleId);
496         } catch (final DataNodeNotFoundException dataNodeNotFoundException) {
497             log.error("Unable to find dataNode for cmHandleId : {} , caused by : {}",
498                 cmHandleId, dataNodeNotFoundException.getMessage());
499             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLES_NOT_FOUND);
500         } catch (final DataValidationException dataValidationException) {
501             log.error("Unable to de-register cm-handle id: {}, caused by: {}",
502                 cmHandleId, dataValidationException.getMessage());
503             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, CM_HANDLE_INVALID_ID);
504         } catch (final Exception exception) {
505             log.error("Unable to de-register cm-handle id : {} , caused by : {}", cmHandleId, exception.getMessage());
506             return CmHandleRegistrationResponse.createFailureResponse(cmHandleId, exception);
507         }
508     }
509
510     private void updateCmHandleStateBatch(final Collection<YangModelCmHandle> yangModelCmHandles,
511                                           final CmHandleState cmHandleState) {
512         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(yangModelCmHandles.size());
513         yangModelCmHandles.forEach(yangModelCmHandle -> cmHandleStatePerCmHandle.put(yangModelCmHandle, cmHandleState));
514         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
515     }
516
517     private void deleteCmHandleFromDbAndModuleSyncMap(final String cmHandleId) {
518         inventoryPersistence.deleteSchemaSetWithCascade(cmHandleId);
519         inventoryPersistence.deleteDataNode(NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']");
520         removeDeletedCmHandleFromModuleSyncMap(cmHandleId);
521     }
522
523     private void batchDeleteCmHandlesFromDbAndModuleSyncMap(final Collection<String> cmHandleIds) {
524         inventoryPersistence.deleteSchemaSetsWithCascade(cmHandleIds);
525         inventoryPersistence.deleteDataNodes(mapCmHandleIdsToXpaths(cmHandleIds));
526         cmHandleIds.forEach(this::removeDeletedCmHandleFromModuleSyncMap);
527     }
528
529     private Collection<String> mapCmHandleIdsToXpaths(final Collection<String> cmHandles) {
530         return cmHandles.stream()
531             .map(cmHandleId -> NCMP_DMI_REGISTRY_PARENT + "/cm-handles[@id='" + cmHandleId + "']")
532             .collect(Collectors.toSet());
533     }
534
535     // CPS-1239 Robustness cleaning of in progress cache
536     private void removeDeletedCmHandleFromModuleSyncMap(final String cmHandleId) {
537         if (moduleSyncStartedOnCmHandles.remove(cmHandleId) != null) {
538             log.debug("{} removed from in progress map", cmHandleId);
539         }
540     }
541
542     private List<CmHandleRegistrationResponse> upgradeCmHandles(final Map<YangModelCmHandle, CmHandleState>
543                                                                     cmHandleStatePerCmHandle) {
544         final List<String> cmHandleIds = getCmHandleIds(cmHandleStatePerCmHandle);
545         log.info("Moving cm handles : {} into locked (for upgrade) state.", cmHandleIds);
546         try {
547             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
548             return CmHandleRegistrationResponse.createSuccessResponses(cmHandleIds);
549         } catch (final Exception e) {
550             log.error("Unable to update cmHandleIds : {} , caused by : {}", cmHandleIds, e.getMessage());
551             return CmHandleRegistrationResponse.createFailureResponses(cmHandleIds, e);
552         }
553     }
554
555     private static List<String> getCmHandleIds(final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle) {
556         return cmHandleStatePerCmHandle.keySet().stream().map(YangModelCmHandle::getId).toList();
557     }
558
559     private void setTrustLevelPerDmiPlugin(final DmiPluginRegistration dmiPluginRegistration) {
560         if (DmiPluginRegistration.isNullEmptyOrBlank(dmiPluginRegistration.getDmiDataPlugin())) {
561             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiPlugin(), TrustLevel.COMPLETE);
562         } else {
563             trustLevelPerDmiPlugin.put(dmiPluginRegistration.getDmiDataPlugin(), TrustLevel.COMPLETE);
564         }
565     }
566
567 }