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
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.inventory.sync;
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;
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.CmHandleState;
44 import org.onap.cps.ncmp.api.inventory.CompositeState;
45 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState;
46 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
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;
56 @RequiredArgsConstructor
57 public class SyncUtils {
58 private final InventoryPersistence inventoryPersistence;
60 private final DmiDataOperations dmiDataOperations;
62 private final JsonObjectMapper jsonObjectMapper;
64 private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
67 * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
69 * @return a randomized yang model cm handle list with ADVISED state, return empty list if not found
71 public List<YangModelCmHandle> getAdvisedCmHandles() {
72 final List<DataNode> advisedCmHandlesAsDataNodeList = new ArrayList<>(
73 inventoryPersistence.getCmHandlesByState(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();
78 Collections.shuffle(advisedCmHandlesAsDataNodeList);
79 return convertCmHandlesDataNodesToYangModelCmHandles(advisedCmHandlesAsDataNodeList);
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".
86 * @return a random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
87 * return null if not found
89 public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
90 final List<DataNode> unSynchronizedCmHandles = inventoryPersistence
91 .getCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
92 if (unSynchronizedCmHandles.isEmpty()) {
95 Collections.shuffle(unSynchronizedCmHandles);
96 for (final DataNode cmHandle : unSynchronizedCmHandles) {
97 final String cmHandleId = cmHandle.getLeaves().get("id").toString();
98 final List<DataNode> readyCmHandles = inventoryPersistence
99 .getCmHandlesByIdAndState(cmHandleId, CmHandleState.READY);
100 if (!readyCmHandles.isEmpty()) {
101 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
108 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MODULE_SYNC_FAILED".
110 * @return a random LOCKED yang model cm handle, return null if not found
112 public List<YangModelCmHandle> getModuleSyncFailedCmHandles() {
113 final List<DataNode> lockedCmHandlesAsDataNodeList = inventoryPersistence.getCmHandleDataNodesByCpsPath(
114 "//lock-reason[@reason=\"LOCKED_MODULE_SYNC_FAILED\"]/ancestor::cm-handles",
115 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
116 return convertCmHandlesDataNodesToYangModelCmHandles(lockedCmHandlesAsDataNodeList);
120 * Update Composite State attempts counter and set new lock reason and details.
122 * @param lockReasonCategory lock reason category
123 * @param errorMessage error message
125 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
126 final LockReasonCategory lockReasonCategory,
127 final String errorMessage) {
129 if (compositeState.getLockReason() != null) {
130 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
131 if (matcher.find()) {
132 attempt = 1 + Integer.parseInt(matcher.group(1));
135 compositeState.setLockReason(CompositeState.LockReason.builder()
136 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
137 .lockReasonCategory(lockReasonCategory).build());
142 * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
144 * @param compositeState the composite state currently in the locked state
145 * @return if the retry mechanism should be attempted
147 public boolean isReadyForRetry(final CompositeState compositeState) {
148 int timeInMinutesUntilNextAttempt = 1;
149 final OffsetDateTime time =
150 OffsetDateTime.parse(compositeState.getLastUpdateTime(),
151 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
152 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
153 if (matcher.find()) {
154 timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
156 log.debug("First Attempt: no current attempts found.");
158 final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
159 if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
160 log.info("Time until next attempt is {} minutes: ",
161 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
163 return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
167 * Get the Resourece Data from Node through DMI Passthrough service.
169 * @param cmHandleId cm handle id
170 * @return optional string containing the resource data
172 public String getResourceData(final String cmHandleId) {
173 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
174 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
175 UUID.randomUUID().toString());
176 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
177 return getFirstResource(resourceDataResponseEntity.getBody());
182 private String getFirstResource(final Object responseBody) {
183 final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
184 final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
185 final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
186 final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
187 return jsonObjectMapper.asJsonString(Map.of(firstElement.getKey(), firstElement.getValue()));
190 private List<YangModelCmHandle> convertCmHandlesDataNodesToYangModelCmHandles(
191 final List<DataNode> cmHandlesAsDataNodeList) {
192 return cmHandlesAsDataNodeList.stream().map(dataNode -> YangDataConverter.convertCmHandleToYangModel(dataNode,
193 dataNode.getLeaves().get("id").toString())).collect(Collectors.toList());