22eeabb0dfc1f14c508ca19a8fa6dfa7d71318c3
[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 java.security.SecureRandom;
25 import java.util.List;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import java.util.stream.Collectors;
29 import lombok.RequiredArgsConstructor;
30 import lombok.extern.slf4j.Slf4j;
31 import org.onap.cps.ncmp.api.impl.utils.YangDataConverter;
32 import org.onap.cps.ncmp.api.impl.yangmodels.YangModelCmHandle;
33 import org.onap.cps.ncmp.api.inventory.CmHandleState;
34 import org.onap.cps.ncmp.api.inventory.CompositeState;
35 import org.onap.cps.ncmp.api.inventory.InventoryPersistence;
36 import org.onap.cps.ncmp.api.inventory.LockReasonCategory;
37 import org.onap.cps.spi.model.DataNode;
38 import org.springframework.stereotype.Component;
39
40 @Slf4j
41 @Component
42 @RequiredArgsConstructor
43 public class SyncUtils {
44
45     private static final SecureRandom secureRandom = new SecureRandom();
46
47     private final InventoryPersistence inventoryPersistence;
48
49     private static final Pattern retryAttemptPattern = Pattern.compile("^Attempt #(\\d+) failed:");
50
51     /**
52      * Query data nodes for cm handles with an "ADVISED" cm handle state, and select a random entry for processing.
53      *
54      * @return a random yang model cm handle with an ADVISED state, return null if not found
55      */
56     public YangModelCmHandle getAnAdvisedCmHandle() {
57         final List<DataNode> advisedCmHandles = inventoryPersistence.getCmHandlesByState(CmHandleState.ADVISED);
58         if (advisedCmHandles.isEmpty()) {
59             return null;
60         }
61         final int randomElementIndex = secureRandom.nextInt(advisedCmHandles.size());
62         final String cmHandleId = advisedCmHandles.get(randomElementIndex).getLeaves()
63             .get("id").toString();
64         return inventoryPersistence.getYangModelCmHandle(cmHandleId);
65     }
66
67
68     /**
69      * Query data nodes for cm handles with an "LOCKED" cm handle state with reason LOCKED_MISBEHAVING".
70      *
71      * @return a random yang model cm handle with an ADVISED state, return null if not found
72      */
73     public List<YangModelCmHandle> getLockedMisbehavingCmHandles() {
74         final List<DataNode> lockedCmHandleAsDataNodeList = inventoryPersistence.getCmHandlesByCpsPath(
75             "//lock-reason[@reason=\"LOCKED_MISBEHAVING\"]/ancestor::cm-handles");
76         return lockedCmHandleAsDataNodeList.stream()
77             .map(cmHandle -> YangDataConverter.convertCmHandleToYangModel(cmHandle,
78                 cmHandle.getLeaves().get("id").toString())).collect(Collectors.toList());
79     }
80
81     /**
82      * Update Composite State attempts counter and set new lock reason and details.
83      *
84      * @param lockReasonCategory lock reason category
85      * @param errorMessage       error message
86      */
87     public void updateLockReasonDetailsAndAttempts(final CompositeState compositeState,
88                                                    final LockReasonCategory lockReasonCategory,
89                                                    final String errorMessage) {
90         int attempt = 1;
91         if (compositeState.getLockReason() != null) {
92             final Matcher matcher = retryAttemptPattern.matcher(compositeState.getLockReason().getDetails());
93             if (matcher.find()) {
94                 attempt = 1 + Integer.parseInt(matcher.group(1));
95             }
96         }
97         compositeState.setLockReason(CompositeState.LockReason.builder()
98             .details(String.format("Attempt #%d failed: %s", attempt, errorMessage))
99             .lockReasonCategory(lockReasonCategory).build());
100     }
101
102 }