Bug Analysis for LOCKED cmHandles
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / inventory / sync / ModuleSyncTasks.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.api.inventory.sync;
22
23 import com.hazelcast.map.IMap;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.atomic.AtomicInteger;
30 import lombok.RequiredArgsConstructor;
31 import lombok.extern.slf4j.Slf4j;
32 import org.onap.cps.ncmp.api.impl.event.lcm.LcmEventsCmHandleStateHandler;
33 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
34 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
35 import org.onap.cps.ncmp.api.inventory.CmHandleState;
36 import org.onap.cps.ncmp.api.inventory.CompositeState;
37 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
38 import org.onap.cps.ncmp.api.inventory.LockReasonCategory;
39 import org.onap.cps.spi.model.DataNode;
40 import org.springframework.stereotype.Component;
41
42 @RequiredArgsConstructor
43 @Component
44 @Slf4j
45 public class ModuleSyncTasks {
46     private final InventoryPersistence inventoryPersistence;
47     private final SyncUtils syncUtils;
48     private final ModuleSyncService moduleSyncService;
49     private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
50     private final IMap<String, Object> moduleSyncStartedOnCmHandles;
51
52     /**
53      * Perform module sync on a batch of cm handles.
54      *
55      * @param cmHandlesAsDataNodes         a batch of Data nodes representing cm handles to perform module sync on
56      * @param batchCounter                 the number of batches currently being processed, will be decreased when
57      *                                     task is finished or fails
58      * @return completed future to handle post-processing
59      */
60     public CompletableFuture<Void> performModuleSync(final Collection<DataNode> cmHandlesAsDataNodes,
61                                                      final AtomicInteger batchCounter) {
62         try {
63             final Map<YangModelCmHandle, CmHandleState> cmHandelStatePerCmHandle = new HashMap<>();
64             for (final DataNode cmHandleAsDataNode : cmHandlesAsDataNodes) {
65                 final String cmHandleId = String.valueOf(cmHandleAsDataNode.getLeaves().get("id"));
66                 final YangModelCmHandle yangModelCmHandle =
67                         YangDataConverter.convertCmHandleToYangModel(cmHandleAsDataNode, cmHandleId);
68                 final CompositeState compositeState = inventoryPersistence.getCmHandleState(cmHandleId);
69                 try {
70                     moduleSyncService.deleteSchemaSetIfExists(cmHandleId);
71                     moduleSyncService.syncAndCreateSchemaSetAndAnchor(yangModelCmHandle);
72                     cmHandelStatePerCmHandle.put(yangModelCmHandle, CmHandleState.READY);
73                 } catch (final Exception e) {
74                     log.warn("Processing of {} module sync failed.", cmHandleId);
75                     syncUtils.updateLockReasonDetailsAndAttempts(compositeState,
76                             LockReasonCategory.LOCKED_MODULE_SYNC_FAILED, e.getMessage());
77                     setCmHandleStateLocked(yangModelCmHandle, compositeState.getLockReason());
78                     cmHandelStatePerCmHandle.put(yangModelCmHandle, CmHandleState.LOCKED);
79                 }
80                 log.debug("{} is now in {} state", cmHandleId, compositeState.getCmHandleState().name());
81             }
82             lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandelStatePerCmHandle);
83         } finally {
84             batchCounter.getAndDecrement();
85             log.info("Processing module sync batch finished. {} batch(es) active.", batchCounter.get());
86         }
87         return CompletableFuture.completedFuture(null);
88     }
89
90     /**
91      * Reset state to "ADVISED" for any previously failed cm handles.
92      *
93      * @param failedCmHandles previously failed (locked) cm handles
94      */
95     public void resetFailedCmHandles(final List<YangModelCmHandle> failedCmHandles) {
96         final Map<YangModelCmHandle, CmHandleState> cmHandleStatePerCmHandle = new HashMap<>(failedCmHandles.size());
97         for (final YangModelCmHandle failedCmHandle : failedCmHandles) {
98             final CompositeState compositeState = failedCmHandle.getCompositeState();
99             final boolean isReadyForRetry = syncUtils.isReadyForRetry(compositeState);
100             log.info("Retry for cmHandleId : {} is {}", failedCmHandle.getId(), isReadyForRetry);
101             if (isReadyForRetry) {
102                 final String resetCmHandleId = failedCmHandle.getId();
103                 log.debug("Reset cm handle {} state to ADVISED to be re-attempted by module-sync watchdog",
104                         resetCmHandleId);
105                 cmHandleStatePerCmHandle.put(failedCmHandle, CmHandleState.ADVISED);
106                 removeResetCmHandleFromModuleSyncMap(resetCmHandleId);
107             }
108         }
109         lcmEventsCmHandleStateHandler.updateCmHandleStateBatch(cmHandleStatePerCmHandle);
110     }
111
112     private void setCmHandleStateLocked(final YangModelCmHandle advisedCmHandle,
113                                         final CompositeState.LockReason lockReason) {
114         advisedCmHandle.getCompositeState().setLockReason(lockReason);
115     }
116
117     private void removeResetCmHandleFromModuleSyncMap(final String resetCmHandleId) {
118         if (moduleSyncStartedOnCmHandles.remove(resetCmHandleId) != null) {
119             log.info("{} removed from in progress map", resetCmHandleId);
120         }
121     }
122 }