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.
69 * @return cm handles (data nodes) in ADVISED state (empty list if none found)
71 public List<DataNode> getAdvisedCmHandles() {
72 final List<DataNode> advisedCmHandlesAsDataNodes = cmHandleQueries.queryCmHandlesByState(CmHandleState.ADVISED);
73 log.debug("Total number of fetched advised cm handle(s) is (are) {}", advisedCmHandlesAsDataNodes.size());
74 return advisedCmHandlesAsDataNodes;
78 * First query data nodes for cm handles with CM Handle Operational Sync State in "UNSYNCHRONIZED" and
79 * randomly select a CM Handle and query the data nodes for CM Handle State in "READY".
81 * @return a randomized yang model cm handle list with State in READY and Operation Sync State in "UNSYNCHRONIZED",
82 * return empty list if not found
84 public List<YangModelCmHandle> getUnsynchronizedReadyCmHandles() {
85 final List<DataNode> unsynchronizedCmHandles = cmHandleQueries
86 .queryCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
88 final List<YangModelCmHandle> yangModelCmHandles = new ArrayList<>();
89 for (final DataNode unsynchronizedCmHandle : unsynchronizedCmHandles) {
90 final String cmHandleId = unsynchronizedCmHandle.getLeaves().get("id").toString();
91 if (cmHandleQueries.cmHandleHasState(cmHandleId, CmHandleState.READY)) {
92 yangModelCmHandles.addAll(
93 convertCmHandlesDataNodesToYangModelCmHandles(
94 Collections.singletonList(unsynchronizedCmHandle)));
98 Collections.shuffle(yangModelCmHandles);
100 return yangModelCmHandles;
104 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MODULE_SYNC_FAILED".
106 * @return a random LOCKED yang model cm handle, return null if not found
108 public List<YangModelCmHandle> getModuleSyncFailedCmHandles() {
109 final List<DataNode> lockedCmHandlesAsDataNodeList = cmHandleQueries.queryCmHandleDataNodesByCpsPath(
110 "//lock-reason[@reason=\"LOCKED_MODULE_SYNC_FAILED\"]",
111 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
112 return convertCmHandlesDataNodesToYangModelCmHandles(lockedCmHandlesAsDataNodeList);
116 * Update Composite State attempts counter and set new lock reason and details.
118 * @param lockReasonCategory lock reason category
119 * @param errorMessage error message
121 public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
122 final LockReasonCategory lockReasonCategory,
123 final String errorMessage) {
125 if (compositeState.getLockReason() != null) {
126 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
127 if (matcher.find()) {
128 attempt = 1 + Integer.parseInt(matcher.group(1));
131 compositeState.setLockReason(CompositeState.LockReason.builder()
132 .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
133 .lockReasonCategory(lockReasonCategory).build());
138 * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
140 * @param compositeState the composite state currently in the locked state
141 * @return if the retry mechanism should be attempted
143 public boolean isReadyForRetry(final CompositeState compositeState) {
144 int timeInMinutesUntilNextAttempt = 1;
145 final OffsetDateTime time =
146 OffsetDateTime.parse(compositeState.getLastUpdateTime(),
147 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
148 final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
149 if (matcher.find()) {
150 timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
152 log.debug("First Attempt: no current attempts found.");
154 final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
155 if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
156 log.info("Time until next attempt is {} minutes: ",
157 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
159 return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
163 * Get the Resourece Data from Node through DMI Passthrough service.
165 * @param cmHandleId cm handle id
166 * @return optional string containing the resource data
168 public String getResourceData(final String cmHandleId) {
169 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
170 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
171 UUID.randomUUID().toString());
172 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
173 return getFirstResource(resourceDataResponseEntity.getBody());
178 private String getFirstResource(final Object responseBody) {
179 final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
180 final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
181 final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
182 final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
183 return jsonObjectMapper.asJsonString(Map.of(firstElement.getKey(), firstElement.getValue()));
186 private static List<YangModelCmHandle> convertCmHandlesDataNodesToYangModelCmHandles(
187 final List<DataNode> cmHandlesAsDataNodeList) {
188 return cmHandlesAsDataNodeList.stream()
189 .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
190 cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());