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