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.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.InventoryPersistence;
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;
57 @RequiredArgsConstructor
58 public class SyncUtils {
59 private final InventoryPersistence inventoryPersistence;
61 private final CmHandleQueries cmHandleQueries;
63 private final DmiDataOperations dmiDataOperations;
65 private final JsonObjectMapper jsonObjectMapper;
67 private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
70 * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
72 * @return a randomized yang model cm handle list with ADVISED state, return empty list if not found
74 public List<YangModelCmHandle> getAdvisedCmHandles() {
75 final List<DataNode> advisedCmHandlesAsDataNodeList = new ArrayList<>(
76 cmHandleQueries.getCmHandlesByState(CmHandleState.ADVISED));
77 log.info("Total number of fetched advised cm handle(s) is (are) {}", advisedCmHandlesAsDataNodeList.size());
78 if (advisedCmHandlesAsDataNodeList.isEmpty()) {
79 return Collections.emptyList();
81 Collections.shuffle(advisedCmHandlesAsDataNodeList);
82 return convertCmHandlesDataNodesToYangModelCmHandles(advisedCmHandlesAsDataNodeList);
86 * First query data nodes for cm handles with CM Handle Operational Sync State in "UNSYNCHRONIZED" and
87 * randomly select a CM Handle and query the data nodes for CM Handle State in "READY".
89 * @return a random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
90 * return null if not found
92 public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
93 final List<DataNode> unSynchronizedCmHandles = cmHandleQueries
94 .getCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
95 if (unSynchronizedCmHandles.isEmpty()) {
98 Collections.shuffle(unSynchronizedCmHandles);
99 for (final DataNode cmHandle : unSynchronizedCmHandles) {
100 final String cmHandleId = cmHandle.getLeaves().get("id").toString();
101 final List<DataNode> readyCmHandles = cmHandleQueries
102 .getCmHandlesByIdAndState(cmHandleId, CmHandleState.READY);
103 if (!readyCmHandles.isEmpty()) {
104 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
111 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MODULE_SYNC_FAILED".
113 * @return a random LOCKED yang model cm handle, return null if not found
115 public List<YangModelCmHandle> getModuleSyncFailedCmHandles() {
116 final List<DataNode> lockedCmHandlesAsDataNodeList = cmHandleQueries.getCmHandleDataNodesByCpsPath(
117 "//lock-reason[@reason=\"LOCKED_MODULE_SYNC_FAILED\"]",
118 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
119 return convertCmHandlesDataNodesToYangModelCmHandles(lockedCmHandlesAsDataNodeList);
123 * Update Composite State attempts counter and set new lock reason and details.
125 * @param lockReasonCategory lock reason category
126 * @param errorMessage error message
128 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
129 final LockReasonCategory lockReasonCategory,
130 final String errorMessage) {
132 if (compositeState.getLockReason() != null) {
133 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
134 if (matcher.find()) {
135 attempt = 1 + Integer.parseInt(matcher.group(1));
138 compositeState.setLockReason(CompositeState.LockReason.builder()
139 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
140 .lockReasonCategory(lockReasonCategory).build());
145 * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
147 * @param compositeState the composite state currently in the locked state
148 * @return if the retry mechanism should be attempted
150 public boolean isReadyForRetry(final CompositeState compositeState) {
151 int timeInMinutesUntilNextAttempt = 1;
152 final OffsetDateTime time =
153 OffsetDateTime.parse(compositeState.getLastUpdateTime(),
154 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
155 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
156 if (matcher.find()) {
157 timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
159 log.debug("First Attempt: no current attempts found.");
161 final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
162 if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
163 log.info("Time until next attempt is {} minutes: ",
164 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
166 return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
170 * Get the Resourece Data from Node through DMI Passthrough service.
172 * @param cmHandleId cm handle id
173 * @return optional string containing the resource data
175 public String getResourceData(final String cmHandleId) {
176 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
177 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
178 UUID.randomUUID().toString());
179 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
180 return getFirstResource(resourceDataResponseEntity.getBody());
185 private String getFirstResource(final Object responseBody) {
186 final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
187 final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
188 final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
189 final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
190 return jsonObjectMapper.asJsonString(Map.of(firstElement.getKey(), firstElement.getValue()));
193 private List<YangModelCmHandle> convertCmHandlesDataNodesToYangModelCmHandles(
194 final List<DataNode> cmHandlesAsDataNodeList) {
195 return cmHandlesAsDataNodeList.stream().map(dataNode -> YangDataConverter.convertCmHandleToYangModel(dataNode,
196 dataNode.getLeaves().get("id").toString())).collect(Collectors.toList());