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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.ncmp.api.inventory.sync;
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;
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;
42 @RequiredArgsConstructor
44 public class ModuleSyncWatchdog {
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);
56 private AtomicInteger batchCounter = new AtomicInteger(1);
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
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();
85 * Find any failed (locked) cm handles and change state back to 'ADVISED'.
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 moduleSyncTasks.resetFailedCmHandles(failedCmHandles);
94 private void preventBusyWait() {
96 TimeUnit.MILLISECONDS.sleep(PREVENT_CPU_BURN_WAIT_TIME_MILLIS);
97 } catch (final InterruptedException e) {
98 Thread.currentThread().interrupt();
102 private void populateWorkQueueIfNeeded() {
103 if (moduleSyncWorkQueue.isEmpty()) {
104 final List<DataNode> advisedCmHandles = syncUtils.getAdvisedCmHandles();
105 log.info("Processing module sync fetched {} advised cm handles from DB", advisedCmHandles.size());
106 for (final DataNode advisedCmHandle : advisedCmHandles) {
107 if (!moduleSyncWorkQueue.offer(advisedCmHandle)) {
108 log.warn("Unable to add cm handle {} to the work queue", advisedCmHandle.getLeaves().get("id"));
114 private Collection<DataNode> prepareNextBatch() {
115 final Collection<DataNode> nextBatchCandidates = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
116 final Collection<DataNode> nextBatch = new HashSet<>(MODULE_SYNC_BATCH_SIZE);
117 moduleSyncWorkQueue.drainTo(nextBatchCandidates, MODULE_SYNC_BATCH_SIZE);
118 log.debug("nextBatchCandidates size : {}", nextBatchCandidates.size());
119 for (final DataNode batchCandidate : nextBatchCandidates) {
120 final String cmHandleId = String.valueOf(batchCandidate.getLeaves().get("id"));
121 final boolean alreadyAddedToInProgressMap = VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP.equals(
122 moduleSyncStartedOnCmHandles.putIfAbsent(cmHandleId, VALUE_FOR_HAZELCAST_IN_PROGRESS_MAP,
123 SynchronizationCacheConfig.MODULE_SYNC_STARTED_TTL_SECS, TimeUnit.SECONDS));
124 if (alreadyAddedToInProgressMap) {
125 log.debug("module sync for {} already in progress by other instance", cmHandleId);
127 nextBatch.add(batchCandidate);
130 log.debug("nextBatch size : {}", nextBatch.size());