e5398374d9ed32db2fe49dc26a1445a79e8f09d9
[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-2023 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 com.hazelcast.map.IMap;
25 import java.util.Collection;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.concurrent.BlockingQueue;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicInteger;
31 import lombok.Getter;
32 import lombok.RequiredArgsConstructor;
33 import lombok.extern.slf4j.Slf4j;
34 import org.onap.cps.ncmp.api.impl.config.embeddedcache.SynchronizationCacheConfig;
35 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
36 import org.onap.cps.ncmp.api.inventory.sync.executor.AsyncTaskExecutor;
37 import org.onap.cps.spi.model.DataNode;
38 import org.springframework.scheduling.annotation.Scheduled;
39 import org.springframework.stereotype.Service;
40
41 @Slf4j
42 @RequiredArgsConstructor
43 @Service
44 public class ModuleSyncWatchdog {
45
46     private final SyncUtils syncUtils;
47     private final BlockingQueue<DataNode> moduleSyncWorkQueue;
48     private final IMap<String, Object> moduleSyncStartedOnCmHandles;
49     private final ModuleSyncTasks moduleSyncTasks;
50     private final AsyncTaskExecutor asyncTaskExecutor;
51     private static final int MODULE_SYNC_BATCH_SIZE = 100;
52     private static final long PREVENT_CPU_BURN_WAIT_TIME_MILLIS = 10;
53     private static final String VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP = "Started";
54     private static final long ASYNC_TASK_TIMEOUT_IN_MILLISECONDS = TimeUnit.MINUTES.toMillis(5);
55     @Getter
56     private AtomicInteger batchCounter = new AtomicInteger(1);
57
58     /**
59      * Check DB for any cm handles in 'ADVISED' state.
60      * Queue and create batches to process them asynchronously.
61      * This method will only finish when there are no more 'ADVISED' cm handles in the DB.
62      * This method wil be triggered on a configurable interval
63      */
64     @Scheduled(fixedDelayString = "${ncmp.timers.advised-modules-sync.sleep-time-ms:5000}")
65     public void moduleSyncAdvisedCmHandles() {
66         log.info("Processing module sync watchdog waking up.");
67         populateWorkQueueIfNeeded();
68         final int asyncTaskParallelismLevel = asyncTaskExecutor.getAsyncTaskParallelismLevel();
69         while (!moduleSyncWorkQueue.isEmpty()) {
70             if (batchCounter.get() <= asyncTaskParallelismLevel) {
71                 final Collection<DataNode> nextBatch = prepareNextBatch();
72                 log.debug("Processing module sync batch of {}. {} batch(es) active.",
73                         nextBatch.size(), batchCounter.get());
74                 asyncTaskExecutor.executeTask(() ->
75                                 moduleSyncTasks.performModuleSync(nextBatch, batchCounter),
76                         ASYNC_TASK_TIMEOUT_IN_MILLISECONDS);
77                 batchCounter.getAndIncrement();
78             } else {
79                 preventBusyWait();
80             }
81         }
82     }
83
84     /**
85      * Find any failed (locked) cm handles and change state back to 'ADVISED'.
86      */
87     @Scheduled(fixedDelayString = "${ncmp.timers.locked-modules-sync.sleep-time-ms:300000}")
88     public void resetPreviouslyFailedCmHandles() {
89         log.info("Processing module sync retry-watchdog waking up.");
90         final List<YangModelCmHandle> failedCmHandles = syncUtils.getModuleSyncFailedCmHandles();
91         log.info("Retrying {} cmHandles", failedCmHandles.size());
92         moduleSyncTasks.resetFailedCmHandles(failedCmHandles);
93     }
94
95     private void preventBusyWait() {
96         try {
97             log.info("Busy waiting now");
98             TimeUnit.MILLISECONDS.sleep(PREVENT_CPU_BURN_WAIT_TIME_MILLIS);
99         } catch (final InterruptedException e) {
100             Thread.currentThread().interrupt();
101         }
102     }
103
104     private void populateWorkQueueIfNeeded() {
105         if (moduleSyncWorkQueue.isEmpty()) {
106             final List<DataNode> advisedCmHandles = syncUtils.getAdvisedCmHandles();
107             log.info("Processing module sync fetched {} advised cm handles from DB", advisedCmHandles.size());
108             for (final DataNode advisedCmHandle : advisedCmHandles) {
109                 if (!moduleSyncWorkQueue.offer(advisedCmHandle)) {
110                     log.warn("Unable to add cm handle {} to the work queue", advisedCmHandle.getLeaves().get("id"));
111                 }
112             }
113             log.info("Work Queue Size : {}", moduleSyncWorkQueue.size());
114         }
115     }
116
117     private Collection<DataNode> prepareNextBatch() {
118         final Collection<DataNode> nextBatchCandidates = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
119         final Collection<DataNode> nextBatch = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
120         moduleSyncWorkQueue.drainTo(nextBatchCandidates, MODULE_SYNC_BATCH_SIZE);
121         log.debug("nextBatchCandidates size : {}", nextBatchCandidates.size());
122         for (final DataNode batchCandidate : nextBatchCandidates) {
123             final String cmHandleId = String.valueOf(batchCandidate.getLeaves().get("id"));
124             final boolean alreadyAddedToInProgressMap = VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP.equals(
125                     moduleSyncStartedOnCmHandles.putIfAbsent(cmHandleId, VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP,
126                             SynchronizationCacheConfig.MODULE_SYNC_STARTED_TTL_SECS, TimeUnit.SECONDS));
127             if (alreadyAddedToInProgressMap) {
128                 log.info("module sync for {} already in progress by other instance", cmHandleId);
129             } else {
130                 nextBatch.add(batchCandidate);
131             }
132         }
133         log.debug("nextBatch size : {}", nextBatch.size());
134         return nextBatch;
135     }
136
137 }