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