Refactoring persistence classes
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / impl / inventory / sync / SyncUtils.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 static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_OPERATIONAL;
25
26 import com.fasterxml.jackson.databind.JsonNode;
27 import java.time.Duration;
28 import java.time.OffsetDateTime;
29 import java.time.format.DateTimeFormatter;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.UUID;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38 import java.util.stream.Collectors;
39 import lombok.RequiredArgsConstructor;
40 import lombok.extern.slf4j.Slf4j;
41 import org.onap.cps.ncmp.api.impl.inventory.CmHandleQueries;
42 import org.onap.cps.ncmp.api.impl.inventory.CmHandleState;
43 import org.onap.cps.ncmp.api.impl.inventory.CompositeState;
44 import org.onap.cps.ncmp.api.impl.inventory.DataStoreSyncState;
45 import org.onap.cps.ncmp.api.impl.inventory.LockReasonCategory;
46 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
47 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
48 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
49 import org.onap.cps.spi.FetchDescendantsOption;
50 import org.onap.cps.spi.model.DataNode;
51 import org.onap.cps.utils.JsonObjectMapper;
52 import org.springframework.http.ResponseEntity;
53 import org.springframework.stereotype.Service;
54
55 @Slf4j
56 @Service
57 @RequiredArgsConstructor
58 public class SyncUtils {
59
60     private final CmHandleQueries cmHandleQueries;
61     private final DmiDataOperations dmiDataOperations;
62     private final JsonObjectMapper jsonObjectMapper;
63     private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
64
65     /**
66      * Query data nodes for cm handles with an "ADVISED" cm handle state.
67      *
68      * @return cm handles (data nodes) in ADVISED state (empty list if none found)
69      */
70     public List<DataNode> getAdvisedCmHandles() {
71         final List<DataNode> advisedCmHandlesAsDataNodes = cmHandleQueries.queryCmHandlesByState(CmHandleState.ADVISED);
72         log.debug("Total number of fetched advised cm handle(s) is (are) {}", advisedCmHandlesAsDataNodes.size());
73         return advisedCmHandlesAsDataNodes;
74     }
75
76     /**
77      * First query data nodes for cm handles with CM Handle Operational Sync State in "UNSYNCHRONIZED" and
78      * randomly select a CM Handle and query the data nodes for CM Handle State in "READY".
79      *
80      * @return a randomized yang model cm handle list with State in READY and Operation Sync State in "UNSYNCHRONIZED",
81      *         return empty list if not found
82      */
83     public List<YangModelCmHandle> getUnsynchronizedReadyCmHandles() {
84         final List<DataNode> unsynchronizedCmHandles = cmHandleQueries
85                 .queryCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
86
87         final List<YangModelCmHandle> yangModelCmHandles = new ArrayList<>();
88         for (final DataNode unsynchronizedCmHandle : unsynchronizedCmHandles) {
89             final String cmHandleId = unsynchronizedCmHandle.getLeaves().get("id").toString();
90             if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
91                 yangModelCmHandles.addAll(
92                         convertCmHandlesDataNodesToYangModelCmHandles(
93                                 Collections.singletonList(unsynchronizedCmHandle)));
94             }
95         }
96
97         Collections.shuffle(yangModelCmHandles);
98
99         return yangModelCmHandles;
100     }
101
102     /**
103      * Query data nodes for cm handles with an "LOCKED" cm handle state with reason MODULE_SYNC_FAILED".
104      *
105      * @return a random LOCKED yang model cm handle, return null if not found
106      */
107     public List<YangModelCmHandle> getModuleSyncFailedCmHandles() {
108         final List<DataNode> lockedCmHandlesAsDataNodeList = cmHandleQueries.queryCmHandleDataNodesByCpsPath(
109                 "//lock-reason[@reason=\"MODULE_SYNC_FAILED\"]",
110                 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
111         return convertCmHandlesDataNodesToYangModelCmHandles(lockedCmHandlesAsDataNodeList);
112     }
113
114     /**
115      * Update Composite State attempts counter and set new lock reason and details.
116      *
117      * @param lockReasonCategory lock reason category
118      * @param errorMessage       error message
119      */
120     public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
121                                                    final LockReasonCategory lockReasonCategory,
122                                                    final String errorMessage) {
123         int attempt = 1;
124         if (compositeState.getLockReason() != null) {
125             final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
126             if (matcher.find()) {
127                 attempt = 1 + Integer.parseInt(matcher.group(1));
128             }
129         }
130         compositeState.setLockReason(CompositeState.LockReason.builder()
131                 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
132                 .lockReasonCategory(lockReasonCategory).build());
133     }
134
135
136     /**
137      * Check if a module sync retry is needed.
138      *
139      * @param compositeState the composite state currently in the locked state
140      * @return if the retry mechanism should be attempted
141      */
142     public boolean needsModuleSyncRetry(final CompositeState compositeState) {
143         final OffsetDateTime time =
144                 OffsetDateTime.parse(compositeState.getLastUpdateTime(),
145                         DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
146         final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
147         final boolean failedDuringModuleSync = LockReasonCategory.MODULE_SYNC_FAILED
148                 == compositeState.getLockReason().getLockReasonCategory();
149         if (!failedDuringModuleSync) {
150             log.info("Locked for other reason");
151             return false;
152         }
153         final int timeInMinutesUntilNextAttempt;
154         if (matcher.find()) {
155             timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
156         } else {
157             timeInMinutesUntilNextAttempt = 1;
158             log.info("First Attempt: no current attempts found.");
159         }
160         final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
161         if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
162             log.info("Time until next attempt is {} minutes: ",
163                 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
164             return false;
165         }
166         log.info("Retry due now");
167         return true;
168     }
169
170     /**
171      * Get the Resourece Data from Node through DMI Passthrough service.
172      *
173      * @param cmHandleId cm handle id
174      * @return optional string containing the resource data
175      */
176     public String getResourceData(final String cmHandleId) {
177         final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
178                 PASSTHROUGH_OPERATIONAL.getDatastoreName(),
179                 cmHandleId,
180                 UUID.randomUUID().toString());
181         if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
182             return getFirstResource(resourceDataResponseEntity.getBody());
183         }
184         return null;
185     }
186
187     private String getFirstResource(final Object responseBody) {
188         final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
189         final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
190         final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
191         final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
192         return jsonObjectMapper.asJsonString(Map.of(firstElement.getKey(), firstElement.getValue()));
193     }
194
195     private static List<YangModelCmHandle> convertCmHandlesDataNodesToYangModelCmHandles(
196             final List<DataNode> cmHandlesAsDataNodeList) {
197         return cmHandlesAsDataNodeList.stream()
198                 .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
199                         cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());
200     }
201 }