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