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.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 CmHandleQueries cmHandleQueries;
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 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();
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 randomized yang model cm handle list with State in READY and Operation Sync State in "UNSYNCHRONIZED",
87 * return empty list if not found
89 public List<YangModelCmHandle> getUnsynchronizedReadyCmHandles() {
90 final List<DataNode> unsynchronizedCmHandles = cmHandleQueries
91 .queryCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
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)));
103 Collections.shuffle(yangModelCmHandles);
105 return yangModelCmHandles;
109 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MODULE_SYNC_FAILED".
111 * @return a random LOCKED yang model cm handle, return null if not found
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);
121 * Update Composite State attempts counter and set new lock reason and details.
123 * @param lockReasonCategory lock reason category
124 * @param errorMessage error message
126 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
127 final LockReasonCategory lockReasonCategory,
128 final String errorMessage) {
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));
136 compositeState.setLockReason(CompositeState.LockReason.builder()
137 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
138 .lockReasonCategory(lockReasonCategory).build());
143 * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
145 * @param compositeState the composite state currently in the locked state
146 * @return if the retry mechanism should be attempted
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)));
157 log.debug("First Attempt: no current attempts found.");
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);
164 return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
168 * Get the Resourece Data from Node through DMI Passthrough service.
170 * @param cmHandleId cm handle id
171 * @return optional string containing the resource data
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());
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()));
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());