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
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.impl.inventory.sync;
24 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_OPERATIONAL;
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;
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;
57 @RequiredArgsConstructor
58 public class SyncUtils {
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:");
66 * Query data nodes for cm handles with an "ADVISED" cm handle state.
68 * @return cm handles (data nodes) in ADVISED state (empty list if none found)
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;
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".
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
83 public List<YangModelCmHandle> getUnsynchronizedReadyCmHandles() {
84 final List<DataNode> unsynchronizedCmHandles = cmHandleQueries
85 .queryCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
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)));
97 Collections.shuffle(yangModelCmHandles);
99 return yangModelCmHandles;
103 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason MODULE_SYNC_FAILED".
105 * @return a random LOCKED yang model cm handle, return null if not found
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);
115 * Update Composite State attempts counter and set new lock reason and details.
117 * @param lockReasonCategory lock reason category
118 * @param errorMessage error message
120 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
121 final LockReasonCategory lockReasonCategory,
122 final String errorMessage) {
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));
130 compositeState.setLockReason(CompositeState.LockReason.builder()
131 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
132 .lockReasonCategory(lockReasonCategory).build());
137 * Check if a module sync retry is needed.
139 * @param compositeState the composite state currently in the locked state
140 * @return if the retry mechanism should be attempted
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");
153 final int timeInMinutesUntilNextAttempt;
154 if (matcher.find()) {
155 timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
157 timeInMinutesUntilNextAttempt = 1;
158 log.info("First Attempt: no current attempts found.");
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);
166 log.info("Retry due now");
171 * Get the Resourece Data from Node through DMI Passthrough service.
173 * @param cmHandleId cm handle id
174 * @return optional string containing the resource data
176 public String getResourceData(final String cmHandleId) {
177 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
178 PASSTHROUGH_OPERATIONAL.getDatastoreName(),
180 UUID.randomUUID().toString());
181 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
182 return getFirstResource(resourceDataResponseEntity.getBody());
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()));
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());