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