CmHandle creation performance degradation
[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 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;
32 import java.util.Map;
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.CmHandleState;
44 import org.onap.cps.ncmp.api.inventory.CompositeState;
45 import org.onap.cps.ncmp.api.inventory.DataStoreSyncState;
46 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
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;
53
54 @Slf4j
55 @Service
56 @RequiredArgsConstructor
57 public class SyncUtils {
58     private final InventoryPersistence inventoryPersistence;
59
60     private final DmiDataOperations dmiDataOperations;
61
62     private final JsonObjectMapper jsonObjectMapper;
63
64     private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
65
66     /**
67      * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
68      *
69      * @return a randomized yang model cm handle list with ADVISED state, return empty list if not found
70      */
71     public List<YangModelCmHandle> getAdvisedCmHandles() {
72         final List<DataNode> advisedCmHandlesAsDataNodeList = new ArrayList<>(
73                 inventoryPersistence.getCmHandlesByState(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();
77         }
78         Collections.shuffle(advisedCmHandlesAsDataNodeList);
79         return convertCmHandlesDataNodesToYangModelCmHandles(advisedCmHandlesAsDataNodeList);
80     }
81
82     /**
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".
85      *
86      * @return a random yang model cm handle with State in READY and Operation Sync State in "UNSYNCHRONIZED",
87      *         return null if not found
88      */
89     public YangModelCmHandle getAnUnSynchronizedReadyCmHandle() {
90         final List<DataNode> unSynchronizedCmHandles = inventoryPersistence
91                 .getCmHandlesByOperationalSyncState(DataStoreSyncState.UNSYNCHRONIZED);
92         if (unSynchronizedCmHandles.isEmpty()) {
93             return null;
94         }
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);
102             }
103         }
104         return null;
105     }
106
107     /**
108      * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MODULE_SYNC_FAILED".
109      *
110      * @return a random LOCKED yang model cm handle, return null if not found
111      */
112     public List<YangModelCmHandle> getModuleSyncFailedCmHandles() {
113         final List<DataNode> lockedCmHandlesAsDataNodeList = inventoryPersistence.getCmHandleDataNodesByCpsPath(
114             "//lock-reason[@reason=\"LOCKED_MODULE_SYNC_FAILED\"]/ancestor::cm-handles",
115             FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS);
116         return convertCmHandlesDataNodesToYangModelCmHandles(lockedCmHandlesAsDataNodeList);
117     }
118
119     /**
120      * Update Composite State attempts counter and set new lock reason and details.
121      *
122      * @param lockReasonCategory lock reason category
123      * @param errorMessage       error message
124      */
125     public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
126                                                    final LockReasonCategory lockReasonCategory,
127                                                    final String errorMessage) {
128         int attempt = 1;
129         if (compositeState.getLockReason() != null) {
130             final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
131             if (matcher.find()) {
132                 attempt = 1 + Integer.parseInt(matcher.group(1));
133             }
134         }
135         compositeState.setLockReason(CompositeState.LockReason.builder()
136             .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
137             .lockReasonCategory(lockReasonCategory).build());
138     }
139
140
141     /**
142      * Check if the retry mechanism should attempt to unlock the cm handle based on the last update time.
143      *
144      * @param compositeState the composite state currently in the locked state
145      * @return if the retry mechanism should be attempted
146      */
147     public boolean isReadyForRetry(final CompositeState compositeState) {
148         int timeInMinutesUntilNextAttempt = 1;
149         final OffsetDateTime time =
150             OffsetDateTime.parse(compositeState.getLastUpdateTime(),
151                 DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
152         final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
153         if (matcher.find()) {
154             timeInMinutesUntilNextAttempt = (int) Math.pow(2, Integer.parseInt(matcher.group(1)));
155         } else {
156             log.debug("First Attempt: no current attempts found.");
157         }
158         final int timeSinceLastAttempt = (int) Duration.between(time, OffsetDateTime.now()).toMinutes();
159         if (timeInMinutesUntilNextAttempt >= timeSinceLastAttempt) {
160             log.info("Time until next attempt is {} minutes: ",
161                 timeInMinutesUntilNextAttempt - timeSinceLastAttempt);
162         }
163         return timeSinceLastAttempt > timeInMinutesUntilNextAttempt;
164     }
165
166     /**
167      * Get the Resourece Data from Node through DMI Passthrough service.
168      *
169      * @param cmHandleId cm handle id
170      * @return optional string containing the resource data
171      */
172     public String getResourceData(final String cmHandleId) {
173         final ResponseEntity<Object> resourceDataResponseEntity = dmiDataOperations.getResourceDataFromDmi(
174                 cmHandleId, DmiOperations.DataStoreEnum.PASSTHROUGH_OPERATIONAL,
175                 UUID.randomUUID().toString());
176         if (resourceDataResponseEntity.getStatusCode().is2xxSuccessful()) {
177             return getFirstResource(resourceDataResponseEntity.getBody());
178         }
179         return null;
180     }
181
182     private String getFirstResource(final Object responseBody) {
183         final String jsonObjectAsString = jsonObjectMapper.asJsonString(responseBody);
184         final JsonNode overallJsonNode = jsonObjectMapper.convertToJsonNode(jsonObjectAsString);
185         final Iterator<Map.Entry<String, JsonNode>> overallJsonTreeMap = overallJsonNode.fields();
186         final Map.Entry<String, JsonNode> firstElement = overallJsonTreeMap.next();
187         return jsonObjectMapper.asJsonString(Map.of(firstElement.getKey(), firstElement.getValue()));
188     }
189
190     private List<YangModelCmHandle> convertCmHandlesDataNodesToYangModelCmHandles(
191             final List<DataNode> cmHandlesAsDataNodeList) {
192         return cmHandlesAsDataNodeList.stream().map(dataNode -> YangDataConverter.convertCmHandleToYangModel(dataNode,
193                 dataNode.getLeaves().get("id").toString())).collect(Collectors.toList());
194     }
195 }