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 com.google.common.collect.ImmutableMap;
26 import java.security.SecureRandom;
27 import java.util.Collections;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.UUID;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import java.util.stream.Collectors;
35 import lombok.RequiredArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37 import org.onap.cps.ncmp.api.impl.operations.DmiDataOperations;
38 import org.onap.cps.ncmp.api.impl.operations.DmiOperations;
39 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
40 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
41 import org.onap.cps.ncmp.api.inventory.CmHandleState;
42 import org.onap.cps.ncmp.api.inventory.CompositeState;
43 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
44 import org.onap.cps.ncmp.api.inventory.LockReasonCategory;
45 import org.onap.cps.ncmp.api.inventory.SyncState;
46 import org.onap.cps.spi.FetchDescendantsOption;
47 import org.onap.cps.spi.model.DataNode;
48 import org.onap.cps.utils.JsonObjectMapper;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.stereotype.Service;
54 @RequiredArgsConstructor
55 public class SyncUtils {
57 private static final SecureRandom secureRandom = new SecureRandom();
59 private final InventoryPersistence inventoryPersistence;
61 private final DmiDataOperations dmiDataOperations;
63 private final JsonObjectMapper jsonObjectMapper;
65 private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
68 * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
70 * @return a random yang model cm handle with an ADVISED state, return null if not found
72 public YangModelCmHandle getAnAdvisedCmHandle() {
73 final List<DataNode> advisedCmHandles = inventoryPersistence.getCmHandlesByState(CmHandleState.ADVISED);
74 if (advisedCmHandles.isEmpty()) {
77 final int randomElementIndex = secureRandom.nextInt(advisedCmHandles.size());
78 final String cmHandleId = advisedCmHandles.get(randomElementIndex).getLeaves()
79 .get("id").toString();
80 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
84 * First query data nodes for cm handles with CM Handle Operational Sync State in "UNSYNCHRONIZED" and
85 * randomly select a CM Handle and query the data nodes for CM Handle State in "READY".
87 * @return a random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
88 * return null if not found
90 public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
91 final List<DataNode> unSynchronizedCmHandles = inventoryPersistence
92 .getCmHandlesByOperationalSyncState(SyncState.UNSYNCHRONIZED);
93 if (unSynchronizedCmHandles.isEmpty()) {
96 Collections.shuffle(unSynchronizedCmHandles);
97 for (final DataNode cmHandle : unSynchronizedCmHandles) {
98 final String cmHandleId = cmHandle.getLeaves().get("id").toString();
99 final List<DataNode> readyCmHandles = inventoryPersistence
100 .getCmHandlesByIdAndState(cmHandleId, CmHandleState.READY);
101 if (!readyCmHandles.isEmpty()) {
102 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
109 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MISBEHAVING".
111 * @return a random yang model cm handle with an ADVISED state, return null if not found
113 public List<YangModelCmHandle> getLockedMisbehavingYangModelCmHandles() {
114 final List<DataNode> lockedCmHandleAsDataNodeList = inventoryPersistence.getCmHandleDataNodesByCpsPath(
115 "//lock-reason[@reason=\"LOCKED_MISBEHAVING\"]/ancestor::cm-handles",
116 FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
117 return lockedCmHandleAsDataNodeList.stream()
118 .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
119 cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());
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());
144 * Get the Resourece Data from Node through DMI Passthrough service.
146 * @param cmHandleId cm handle id
147 * @return optional string containing the resource data
149 public String getResourceData(final String cmHandleId) {
150 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
151 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
152 UUID.randomUUID().toString());
153 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
154 return getFirstResource(resourceDataResponseEntity.getBody());
159 private String getFirstResource(final Object responseBody) {
160 final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
161 final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
162 final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
163 final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
164 return jsonObjectMapper.asJsonString(ImmutableMap.of(firstElement.getKey(), firstElement.getValue()));