Distributed datastore solution for Data Sync Watchdog
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / inventory / sync / ModuleSyncWatchdog.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.inventory.sync;
23
24 import java.util.List;
25 import java.util.concurrent.ConcurrentMap;
26 import lombok.RequiredArgsConstructor;
27 import lombok.extern.slf4j.Slf4j;
28 import org.onap.cps.ncmp.api.impl.event.lcm.LcmEventsCmHandleStateHandler;
29 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
30 import org.onap.cps.ncmp.api.inventory.CmHandleState;
31 import org.onap.cps.ncmp.api.inventory.CompositeState;
32 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
33 import org.onap.cps.ncmp.api.inventory.LockReasonCategory;
34 import org.springframework.beans.factory.annotation.Qualifier;
35 import org.springframework.scheduling.annotation.Scheduled;
36 import org.springframework.stereotype.Component;
37
38 @Slf4j
39 @RequiredArgsConstructor
40 @Component
41 public class ModuleSyncWatchdog {
42
43     private static final boolean MODEL_SYNC_IN_PROGRESS = false;
44     private static final boolean MODEL_SYNC_DONE = true;
45
46     private final InventoryPersistence inventoryPersistence;
47
48     private final SyncUtils syncUtils;
49
50     private final ModuleSyncService moduleSyncService;
51
52     @Qualifier("moduleSyncSemaphores")
53     private final ConcurrentMap<String, Boolean> moduleSyncSemaphores;
54
55     private final LcmEventsCmHandleStateHandler lcmEventsCmHandleStateHandler;
56
57     /**
58      * Execute Cm Handle poll which changes the cm handle state from 'ADVISED' to 'READY'.
59      */
60     @Scheduled(fixedDelayString = "${timers.advised-modules-sync.sleep-time-ms:30000}")
61     public void executeAdvisedCmHandlePoll() {
62         syncUtils.getAdvisedCmHandles().forEach(advisedCmHandle -> {
63             final String cmHandleId = advisedCmHandle.getId();
64             if (hasPushedIntoSemaphoreMap(cmHandleId)) {
65                 log.debug("executing module sync on {}", cmHandleId);
66                 final CompositeState compositeState = inventoryPersistence.getCmHandleState(cmHandleId);
67                 try {
68                     moduleSyncService.deleteSchemaSetIfExists(advisedCmHandle);
69                     moduleSyncService.syncAndCreateSchemaSetAndAnchor(advisedCmHandle);
70                     lcmEventsCmHandleStateHandler.updateCmHandleState(advisedCmHandle, CmHandleState.READY);
71                     updateModuleSyncSemaphoreMap(cmHandleId);
72                 } catch (final Exception e) {
73                     syncUtils.updateLockReasonDetailsAndAttempts(compositeState,
74                             LockReasonCategory.LOCKED_MODULE_SYNC_FAILED, e.getMessage());
75                     setCmHandleStateLocked(advisedCmHandle, compositeState.getLockReason());
76                 }
77                 log.debug("{} is now in {} state", cmHandleId, compositeState.getCmHandleState().name());
78             } else {
79                 log.debug("{} already processed by another instance", cmHandleId);
80             }
81         });
82         log.debug("No Cm-Handles currently found in an ADVISED state");
83     }
84
85     /**
86      * Execute Cm Handle poll which changes the cm handle state from 'LOCKED' to 'ADVISED'.
87      */
88     @Scheduled(fixedDelayString = "${timers.locked-modules-sync.sleep-time-ms:300000}")
89     public void executeLockedCmHandlePoll() {
90         final List<YangModelCmHandle> lockedCmHandles = syncUtils.getModuleSyncFailedCmHandles();
91         for (final YangModelCmHandle lockedCmHandle : lockedCmHandles) {
92             final CompositeState compositeState = lockedCmHandle.getCompositeState();
93             final boolean isReadyForRetry = syncUtils.isReadyForRetry(compositeState);
94             if (isReadyForRetry) {
95                 log.debug("Reset cm handle {} state to ADVISED to re-attempt module-sync", lockedCmHandle.getId());
96                 lcmEventsCmHandleStateHandler.updateCmHandleState(lockedCmHandle, CmHandleState.ADVISED);
97             }
98         }
99     }
100
101     private void setCmHandleStateLocked(final YangModelCmHandle advisedCmHandle,
102             final CompositeState.LockReason lockReason) {
103         advisedCmHandle.getCompositeState().setLockReason(lockReason);
104         lcmEventsCmHandleStateHandler.updateCmHandleState(advisedCmHandle, CmHandleState.LOCKED);
105     }
106
107     private void updateModuleSyncSemaphoreMap(final String cmHandleId) {
108         moduleSyncSemaphores.replace(cmHandleId, MODEL_SYNC_DONE);
109     }
110
111     private boolean hasPushedIntoSemaphoreMap(final String cmHandleId) {
112         return moduleSyncSemaphores.putIfAbsent(cmHandleId, MODEL_SYNC_IN_PROGRESS) == null;
113     }
114 }