Merge "Reinstate Spring Boot 3.0 after revert"
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / 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.impl.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.inventory.sync.executor.AsyncTaskExecutor;
36 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
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         while (!moduleSyncWorkQueue.isEmpty()) {
69             if (batchCounter.get() <= asyncTaskExecutor.getAsyncTaskParallelismLevel()) {
70                 final Collection<DataNode> nextBatch = prepareNextBatch();
71                 log.info("Processing module sync batch of {}. {} batch(es) active.",
72                     nextBatch.size(), batchCounter.get());
73                 if (!nextBatch.isEmpty()) {
74                     asyncTaskExecutor.executeTask(() ->
75                             moduleSyncTasks.performModuleSync(nextBatch, batchCounter),
76                         ASYNC_TASK_TIMEOUT_IN_MILLISECONDS);
77                     batchCounter.getAndIncrement();
78                 }
79             } else {
80                 preventBusyWait();
81             }
82         }
83     }
84
85     /**
86      * Find any failed (locked) cm handles and change state back to 'ADVISED'.
87      */
88     @Scheduled(fixedDelayString = "${ncmp.timers.locked-modules-sync.sleep-time-ms:300000}")
89     public void resetPreviouslyFailedCmHandles() {
90         log.info("Processing module sync retry-watchdog waking up.");
91         final List<YangModelCmHandle> failedCmHandles = syncUtils.getModuleSyncFailedCmHandles();
92         log.info("Retrying {} cmHandles", failedCmHandles.size());
93         moduleSyncTasks.resetFailedCmHandles(failedCmHandles);
94     }
95
96     private void preventBusyWait() {
97         try {
98             log.info("Busy waiting now");
99             TimeUnit.MILLISECONDS.sleep(PREVENT_CPU_BURN_WAIT_TIME_MILLIS);
100         } catch (final InterruptedException e) {
101             Thread.currentThread().interrupt();
102         }
103     }
104
105     private void populateWorkQueueIfNeeded() {
106         if (moduleSyncWorkQueue.isEmpty()) {
107             final List<DataNode> advisedCmHandles = syncUtils.getAdvisedCmHandles();
108             log.info("Processing module sync fetched {} advised cm handles from DB", advisedCmHandles.size());
109             for (final DataNode advisedCmHandle : advisedCmHandles) {
110                 if (!moduleSyncWorkQueue.offer(advisedCmHandle)) {
111                     log.warn("Unable to add cm handle {} to the work queue", advisedCmHandle.getLeaves().get("id"));
112                 }
113             }
114             log.info("Work Queue Size : {}", moduleSyncWorkQueue.size());
115         }
116     }
117
118     private Collection<DataNode> prepareNextBatch() {
119         final Collection<DataNode> nextBatchCandidates = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
120         final Collection<DataNode> nextBatch = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
121         moduleSyncWorkQueue.drainTo(nextBatchCandidates, MODULE_SYNC_BATCH_SIZE);
122         log.info("nextBatchCandidates size : {}", nextBatchCandidates.size());
123         for (final DataNode batchCandidate : nextBatchCandidates) {
124             final String cmHandleId = String.valueOf(batchCandidate.getLeaves().get("id"));
125             final boolean alreadyAddedToInProgressMap = VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP.equals(
126                     moduleSyncStartedOnCmHandles.putIfAbsent(cmHandleId, VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP,
127                             SynchronizationCacheConfig.MODULE_SYNC_STARTED_TTL_SECS, TimeUnit.SECONDS));
128             if (alreadyAddedToInProgressMap) {
129                 log.info("module sync for {} already in progress by other instance", cmHandleId);
130             } else {
131                 log.info("Adding cmHandle : {} to current batch", cmHandleId);
132                 nextBatch.add(batchCandidate);
133             }
134         }
135         log.debug("nextBatch size : {}", nextBatch.size());
136         return nextBatch;
137     }
138
139 }