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.security.SecureRandom;
26 import java.time.Duration;
27 import java.time.OffsetDateTime;
28 import java.time.format.DateTimeFormatter;
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 {
59 private static final SecureRandom secureRandom = new SecureRandom();
61 private final InventoryPersistence inventoryPersistence;
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 random yang model cm handle with an ADVISED state, return null if not found
74 public YangModelCmHandle getAnAdvisedCmHandle() {
75 final List<DataNode> advisedCmHandles = inventoryPersistence.getCmHandlesByState(CmHandleState.ADVISED);
76 if (advisedCmHandles.isEmpty()) {
79 final int randomElementIndex = secureRandom.nextInt(advisedCmHandles.size());
80 final String cmHandleId = advisedCmHandles.get(randomElementIndex).getLeaves()
81 .get("id").toString();
82 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
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 = inventoryPersistence
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 = inventoryPersistence
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> lockedCmHandleAsDataNodeList = inventoryPersistence.getCmHandleDataNodesByCpsPath(
117 "//lock-reason[@reason=\"LOCKED_MODULE_SYNC_FAILED\"]/ancestor::cm-handles",
118 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
119 return lockedCmHandleAsDataNodeList.stream()
120 .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
121 cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());
125 * Update Composite State attempts counter and set new lock reason and details.
127 * @param lockReasonCategory lock reason category
128 * @param errorMessage error message
130 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
131 final LockReasonCategory lockReasonCategory,
132 final String errorMessage) {
134 if (compositeState.getLockReason() != null) {
135 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
136 if (matcher.find()) {
137 attempt = 1 + Integer.parseInt(matcher.group(1));
140 compositeState.setLockReason(CompositeState.LockReason.builder()
141 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
142 .lockReasonCategory(lockReasonCategory).build());
147 * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
149 * @param compositeState the composite state currently in the locked state
150 * @return if the retry mechanism should be attempted
152 public boolean isReadyForRetry(final CompositeState compositeState) {
153 int timeInMinutesUntilNextAttempt = 1;
154 final OffsetDateTime time =
155 OffsetDateTime.parse(compositeState.getLastUpdateTime(),
156 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
157 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
158 if (matcher.find()) {
159 timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
161 log.debug("First Attempt: no current attempts found.");
163 final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
164 if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
165 log.info("Time until next attempt is {} minutes: ",
166 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
168 return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
172 * Get the Resourece Data from Node through DMI Passthrough service.
174 * @param cmHandleId cm handle id
175 * @return optional string containing the resource data
177 public String getResourceData(final String cmHandleId) {
178 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
179 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
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()));