Merge "[k6] Refactor k6 tests for CM handle searches"
[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 ModuleOperationsUtils moduleOperationsUtils;
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
92                 = moduleOperationsUtils.getCmHandlesThatFailedModelSyncOrUpgrade();
93         log.info("Retrying {} cmHandles", failedCmHandles.size());
94         moduleSyncTasks.resetFailedCmHandles(failedCmHandles);
95     }
96
97     private void preventBusyWait() {
98         try {
99             log.info("Busy waiting now");
100             TimeUnit.MILLISECONDS.sleep(PREVENT_CPU_BURN_WAIT_TIME_MILLIS);
101         } catch (final InterruptedException e) {
102             Thread.currentThread().interrupt();
103         }
104     }
105
106     private void populateWorkQueueIfNeeded() {
107         if (moduleSyncWorkQueue.isEmpty()) {
108             final List<DataNode> advisedCmHandles = moduleOperationsUtils.getAdvisedCmHandles();
109             log.info("Processing module sync fetched {} advised cm handles from DB", advisedCmHandles.size());
110             for (final DataNode advisedCmHandle : advisedCmHandles) {
111                 if (!moduleSyncWorkQueue.offer(advisedCmHandle)) {
112                     log.warn("Unable to add cm handle {} to the work queue", advisedCmHandle.getLeaves().get("id"));
113                 }
114             }
115             log.info("Work Queue Size : {}", moduleSyncWorkQueue.size());
116         }
117     }
118
119     private Collection<DataNode> prepareNextBatch() {
120         final Collection<DataNode> nextBatchCandidates = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
121         final Collection<DataNode> nextBatch = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
122         moduleSyncWorkQueue.drainTo(nextBatchCandidates, MODULE_SYNC_BATCH_SIZE);
123         log.info("nextBatchCandidates size : {}", nextBatchCandidates.size());
124         for (final DataNode batchCandidate : nextBatchCandidates) {
125             final String cmHandleId = String.valueOf(batchCandidate.getLeaves().get("id"));
126             final boolean alreadyAddedToInProgressMap = VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP.equals(
127                     moduleSyncStartedOnCmHandles.putIfAbsent(cmHandleId, VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP,
128                             SynchronizationCacheConfig.MODULE_SYNC_STARTED_TTL_SECS, TimeUnit.SECONDS));
129             if (alreadyAddedToInProgressMap) {
130                 log.info("module sync for {} already in progress by other instance", cmHandleId);
131             } else {
132                 log.info("Adding cmHandle : {} to current batch", cmHandleId);
133                 nextBatch.add(batchCandidate);
134             }
135         }
136         log.debug("nextBatch size : {}", nextBatch.size());
137         return nextBatch;
138     }
139
140 }