Define Initial Data Sync Enabled Flag and state
[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.List;
25 import java.util.function.Consumer;
26 import lombok.RequiredArgsConstructor;
27 import lombok.extern.slf4j.Slf4j;
28 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
29 import org.onap.cps.ncmp.api.inventory.CmHandleState;
30 import org.onap.cps.ncmp.api.inventory.CompositeState;
31 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState;
32 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
33 import org.onap.cps.ncmp.api.inventory.LockReasonCategory;
34 import org.springframework.beans.factory.annotation.Value;
35 import org.springframework.scheduling.annotation.Scheduled;
36 import org.springframework.stereotype.Component;
37
38 @Slf4j
39 @RequiredArgsConstructor
40 @Component
41 public class ModuleSyncWatchdog {
42
43     private final InventoryPersistence inventoryPersistence;
44
45     private final SyncUtils syncUtils;
46
47     private final ModuleSyncService moduleSyncService;
48
49     @Value("${data-sync.cache.enabled:false}")
50     private boolean isGlobalDataSyncCacheEnabled;
51
52     /**
53      * Execute Cm Handle poll which changes the cm handle state from 'ADVISED' to 'READY'.
54      */
55     @Scheduled(fixedDelayString = "${timers.advised-modules-sync.sleep-time-ms:30000}")
56     public void executeAdvisedCmHandlePoll() {
57         YangModelCmHandle advisedCmHandle = syncUtils.getAnAdvisedCmHandle();
58         while (advisedCmHandle != null) {
59             final String cmHandleId = advisedCmHandle.getId();
60             final CompositeState compositeState = inventoryPersistence.getCmHandleState(cmHandleId);
61             try {
62                 moduleSyncService.deleteSchemaSetIfExists(advisedCmHandle);
63                 moduleSyncService.syncAndCreateSchemaSetAndAnchor(advisedCmHandle);
64                 setCompositeStateToReadyWithInitialDataStoreSyncState().accept(compositeState);
65             } catch (final Exception e) {
66                 setCompositeStateToLocked().accept(compositeState);
67                 syncUtils.updateLockReasonDetailsAndAttempts(compositeState,
68                         LockReasonCategory.LOCKED_MODULE_SYNC_FAILED, e.getMessage());
69             }
70             inventoryPersistence.saveCmHandleState(cmHandleId, compositeState);
71             log.debug("{} is now in {} state", cmHandleId, compositeState.getCmHandleState().name());
72             advisedCmHandle = syncUtils.getAnAdvisedCmHandle();
73         }
74         log.debug("No Cm-Handles currently found in an ADVISED state");
75     }
76
77     /**
78      * Execute Cm Handle poll which changes the cm handle state from 'LOCKED' to 'ADVISED'.
79      */
80     @Scheduled(fixedDelayString = "${timers.locked-modules-sync.sleep-time-ms:300000}")
81     public void executeLockedCmHandlePoll() {
82         final List<YangModelCmHandle> lockedCmHandles = syncUtils.getModuleSyncFailedCmHandles();
83         for (final YangModelCmHandle lockedCmHandle : lockedCmHandles) {
84             final CompositeState compositeState = lockedCmHandle.getCompositeState();
85             final boolean isReadyForRetry = syncUtils.isReadyForRetry(compositeState);
86             if (isReadyForRetry) {
87                 setCompositeStateToAdvisedAndRetainOldLockReasonDetails(compositeState);
88                 log.debug("Locked cm handle {} is being resynced", lockedCmHandle.getId());
89                 inventoryPersistence.saveCmHandleState(lockedCmHandle.getId(), compositeState);
90             }
91         }
92     }
93
94     private Consumer<CompositeState> setCompositeStateToLocked() {
95         return compositeState -> {
96             compositeState.setCmHandleState(CmHandleState.LOCKED);
97             compositeState.setLastUpdateTimeNow();
98         };
99     }
100
101     private Consumer<CompositeState> setCompositeStateToReadyWithInitialDataStoreSyncState() {
102         return compositeState -> {
103             compositeState.setDataSyncEnabled(isGlobalDataSyncCacheEnabled);
104             compositeState.setCmHandleState(CmHandleState.READY);
105             final CompositeState.Operational operational = getDataStoreSyncState(compositeState.getDataSyncEnabled());
106             final CompositeState.DataStores dataStores = CompositeState.DataStores.builder()
107                     .operationalDataStore(operational)
108                     .build();
109             compositeState.setDataStores(dataStores);
110         };
111     }
112
113     private void setCompositeStateToAdvisedAndRetainOldLockReasonDetails(final CompositeState compositeState) {
114         compositeState.setCmHandleState(CmHandleState.ADVISED);
115         compositeState.setLastUpdateTimeNow();
116         final String oldLockReasonDetails = compositeState.getLockReason().getDetails();
117         final CompositeState.LockReason lockReason = CompositeState.LockReason.builder()
118                 .details(oldLockReasonDetails).build();
119         compositeState.setLockReason(lockReason);
120     }
121
122     private CompositeState.Operational getDataStoreSyncState(final boolean dataSyncEnabled) {
123         final DataStoreSyncState dataStoreSyncState = dataSyncEnabled
124             ? DataStoreSyncState.UNSYNCHRONIZED : DataStoreSyncState.NONE_REQUESTED;
125         return CompositeState.Operational.builder().dataStoreSyncState(dataStoreSyncState).build();
126     }
127
128 }