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.model.DataNode;
47 import org.onap.cps.utils.JsonObjectMapper;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.stereotype.Service;
53 @RequiredArgsConstructor
54 public class SyncUtils {
56 private static final SecureRandom secureRandom = new SecureRandom();
58 private final InventoryPersistence inventoryPersistence;
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 random yang model cm handle with an ADVISED state, return null if not found
71 public YangModelCmHandle getAnAdvisedCmHandle() {
72 final List<DataNode> advisedCmHandles = inventoryPersistence.getCmHandlesByState(CmHandleState.ADVISED);
73 if (advisedCmHandles.isEmpty()) {
76 final int randomElementIndex = secureRandom.nextInt(advisedCmHandles.size());
77 final String cmHandleId = advisedCmHandles.get(randomElementIndex).getLeaves()
78 .get("id").toString();
79 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
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 random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
87 * return null if not found
89 public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
90 final List<DataNode> unSynchronizedCmHandles = inventoryPersistence
91 .getCmHandlesByOperationalSyncState(SyncState.UNSYNCHRONIZED);
92 if (unSynchronizedCmHandles.isEmpty()) {
95 Collections.shuffle(unSynchronizedCmHandles);
96 for (final DataNode cmHandle : unSynchronizedCmHandles) {
97 final String cmHandleId = cmHandle.getLeaves().get("id").toString();
98 final List<DataNode> readyCmHandles = inventoryPersistence
99 .getCmHandlesByIdAndState(cmHandleId, CmHandleState.READY);
100 if (!readyCmHandles.isEmpty()) {
101 return inventoryPersistence.getYangModelCmHandle(cmHandleId);
108 * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MISBEHAVING".
110 * @return a random yang model cm handle with an ADVISED state, return null if not found
112 public List<YangModelCmHandle> getLockedMisbehavingYangModelCmHandles() {
113 final List<DataNode> lockedCmHandleAsDataNodeList = inventoryPersistence.getCmHandleDataNodesByCpsPath(
114 "//lock-reason[@reason=\"LOCKED_MISBEHAVING\"]/ancestor::cm-handles");
115 return lockedCmHandleAsDataNodeList.stream()
116 .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
117 cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());
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());
142 * Get the Resourece Data from Node through DMI Passthrough service.
144 * @param cmHandleId cm handle id
145 * @return optional string containing the resource data
147 public String getResourceData(final String cmHandleId) {
148 final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
149 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
150 UUID.randomUUID().toString());
151 if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
152 return getFirstResource(resourceDataResponseEntity.getBody());
157 private String getFirstResource(final Object responseBody) {
158 final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
159 final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
160 final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
161 final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
162 return jsonObjectMapper.asJsonString(ImmutableMap.of(firstElement.getKey(), firstElement.getValue()));