42edcb7ec89a4c6002c0d2b2fab4149457956f10
[cps.git] / cps-ncmp-service / src / main / java / org / onap / cps / ncmp / api / inventory / sync / SyncUtils.java
1 /*
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
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.ncmp.api.inventory.sync;
23
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;
30 import java.util.Map;
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;
51
52 @Slf4j
53 @Service
54 @RequiredArgsConstructor
55 public class SyncUtils {
56
57     private static final SecureRandom secureRandom = new SecureRandom();
58
59     private final InventoryPersistence inventoryPersistence;
60
61     private final DmiDataOperations dmiDataOperations;
62
63     private final JsonObjectMapper jsonObjectMapper;
64
65     private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
66
67     /**
68      * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
69      *
70      * @return a random yang model cm handle with an ADVISED state, return null if not found
71      */
72     public YangModelCmHandle getAnAdvisedCmHandle() {
73         final List<DataNode> advisedCmHandles = inventoryPersistence.getCmHandlesByState(CmHandleState.ADVISED);
74         if (advisedCmHandles.isEmpty()) {
75             return null;
76         }
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);
81     }
82
83     /**
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".
86      *
87      * @return a random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
88      *         return null if not found
89      */
90     public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
91         final List<DataNode> unSynchronizedCmHandles = inventoryPersistence
92                 .getCmHandlesByOperationalSyncState(SyncState.UNSYNCHRONIZED);
93         if (unSynchronizedCmHandles.isEmpty()) {
94             return null;
95         }
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);
103             }
104         }
105         return null;
106     }
107
108     /**
109      * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MISBEHAVING".
110      *
111      * @return a random yang model cm handle with an ADVISED state, return null if not found
112      */
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());
120     }
121
122     /**
123      * Update Composite State attempts counter and set new lock reason and details.
124      *
125      * @param lockReasonCategory lock reason category
126      * @param errorMessage       error message
127      */
128     public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
129                                                    final LockReasonCategory lockReasonCategory,
130                                                    final String errorMessage) {
131         int attempt = 1;
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));
136             }
137         }
138         compositeState.setLockReason(CompositeState.LockReason.builder()
139             .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
140             .lockReasonCategory(lockReasonCategory).build());
141     }
142
143     /**
144      * Get the Resourece Data from Node through DMI Passthrough service.
145      *
146      * @param cmHandleId cm handle id
147      * @return optional string containing the resource data
148      */
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());
155         }
156         return null;
157     }
158
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()));
165     }
166 }