Modify ANR Payload aligned to A1 schema in SDNR
[dcaegen2/services/son-handler.git] / src / main / java / org / onap / dcaegen2 / services / sonhms / child / ChildThreadUtils.java
1 /*******************************************************************************
2  *  ============LICENSE_START=======================================================
3  *  son-handler
4  *  ================================================================================
5  *   Copyright (C) 2019-2022 Wipro Limited.
6  *   ==============================================================================
7  *     Licensed under the Apache License, Version 2.0 (the "License");
8  *     you may not use this file except in compliance with the License.
9  *     You may obtain a copy of the License at
10  *
11  *          http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *     Unless required by applicable law or agreed to in writing, software
14  *     distributed under the License is distributed on an "AS IS" BASIS,
15  *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *     See the License for the specific language governing permissions and
17  *     limitations under the License.
18  *     ============LICENSE_END=========================================================
19  *
20  *******************************************************************************/
21
22 package org.onap.dcaegen2.services.sonhms.child;
23
24 import com.fasterxml.jackson.annotation.JsonInclude.Include;
25 import com.fasterxml.jackson.core.JsonProcessingException;
26 import com.fasterxml.jackson.databind.ObjectMapper;
27
28 import fj.data.Either;
29
30 import java.util.ArrayList;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.UUID;
34
35 import org.onap.dcaegen2.services.sonhms.ConfigPolicy;
36 import org.onap.dcaegen2.services.sonhms.Configuration;
37 import org.onap.dcaegen2.services.sonhms.exceptions.CpsNotFoundException;
38 import org.onap.dcaegen2.services.sonhms.HoMetricsComponent;
39 import org.onap.dcaegen2.services.sonhms.dao.SonRequestsRepository;
40 import org.onap.dcaegen2.services.sonhms.dmaap.PolicyDmaapClient;
41 import org.onap.dcaegen2.services.sonhms.entity.SonRequests;
42 import org.onap.dcaegen2.services.sonhms.exceptions.ConfigDbNotFoundException;
43 import org.onap.dcaegen2.services.sonhms.model.CellConfig;
44 import org.onap.dcaegen2.services.sonhms.model.CellPciPair;
45 import org.onap.dcaegen2.services.sonhms.model.Common;
46 import org.onap.dcaegen2.services.sonhms.model.Configurations;
47 import org.onap.dcaegen2.services.sonhms.model.Data;
48 import org.onap.dcaegen2.services.sonhms.model.FapService;
49 import org.onap.dcaegen2.services.sonhms.model.HoDetails;
50 import org.onap.dcaegen2.services.sonhms.model.Lte;
51 import org.onap.dcaegen2.services.sonhms.model.LteCell;
52 import org.onap.dcaegen2.services.sonhms.model.NeighborListInUse;
53 import org.onap.dcaegen2.services.sonhms.model.Payload;
54 import org.onap.dcaegen2.services.sonhms.model.PolicyNotification;
55 import org.onap.dcaegen2.services.sonhms.model.Ran;
56 import org.onap.dcaegen2.services.sonhms.model.X0005b9Lte;
57 import org.onap.dcaegen2.services.sonhms.restclient.AsyncResponseBody;
58 import org.onap.dcaegen2.services.sonhms.restclient.SdnrRestClient;
59 import org.onap.dcaegen2.services.sonhms.restclient.ConfigurationClient;
60 import org.onap.dcaegen2.services.sonhms.restclient.Solutions;
61 import org.onap.dcaegen2.services.sonhms.utils.BeanUtil;
62 import org.slf4j.Logger;
63
64 public class ChildThreadUtils {
65
66     private static final Logger log = org.slf4j.LoggerFactory.getLogger(ChildThreadUtils.class);
67     private ConfigPolicy configPolicy;
68     private PnfUtils pnfUtils;
69     private PolicyDmaapClient policyDmaapClient;
70     private HoMetricsComponent hoMetricsComponent;
71     Configuration configuration = Configuration.getInstance();
72
73     /**
74      * Parameterized constructor.
75      */
76     public ChildThreadUtils(ConfigPolicy configPolicy, PnfUtils pnfUtils, PolicyDmaapClient policyDmaapClient,
77             HoMetricsComponent hoMetricsComponent) {
78         this.configPolicy = configPolicy;
79         this.pnfUtils = pnfUtils;
80         this.policyDmaapClient = policyDmaapClient;
81         this.hoMetricsComponent = hoMetricsComponent;
82     }
83
84     /**
85      * Save request.
86      */
87     public void saveRequest(String transactionId, long childThreadId) {
88         SonRequestsRepository sonRequestsRepository = BeanUtil.getBean(SonRequestsRepository.class);
89
90         SonRequests sonRequest = new SonRequests();
91         sonRequest.setTransactionId(transactionId);
92         sonRequest.setChildThreadId(childThreadId);
93         sonRequestsRepository.save(sonRequest);
94     }
95
96     /**
97      * Determines whether to trigger Oof or wait for notifications.
98      */
99     public Boolean triggerOrWait(Map<String, ArrayList<Integer>> collisionConfusionResult) {
100         // determine collision or confusion
101
102         int collisionSum = 0;
103         int confusionSum = 0;
104
105         for (Map.Entry<String, ArrayList<Integer>> entry : collisionConfusionResult.entrySet()) {
106
107             ArrayList<Integer> arr;
108             arr = entry.getValue();
109             // check for 0 collision and confusion
110             if (!arr.isEmpty()) {
111                 collisionSum = collisionSum + arr.get(0);
112                 confusionSum = confusionSum + arr.get(1);
113             }
114         }
115         return ((collisionSum >= configuration.getMinCollision()) && (confusionSum >= configuration.getMinConfusion()));
116
117     }
118
119     /**
120      * get policy notification string from oof result.
121      *
122      */
123     public String getNotificationString(String pnfName, String requestId, String payloadString, Long alarmStartTime,
124             String action) {
125
126         String closedLoopControlName = "";
127         String policyName = "";
128         if (action.equals("ModifyO1Config")) {
129             closedLoopControlName = "ControlLoop-SONO1-fb41f388-a5f2-11e8-98d0-529269fb1459";
130             policyName = "SONO1";
131             try {
132                 closedLoopControlName = (String) configPolicy.getConfig().get("PCI_MODCONFIG_POLICY_NAME");
133             } catch (NullPointerException e) {
134                 log.error("Config policy not found, Using default");
135             }
136         }
137         else {
138             closedLoopControlName = "ControlLoop-SONA1-7d4baf04-8875-4d1f-946d-06b874048b61";
139             policyName = "SONA1";
140             try {
141                 closedLoopControlName = (String) configPolicy.getConfig().get("PCI_MODCONFIGANR_POLICY_NAME");
142             } catch (NullPointerException e) {
143                 log.error("Config policy not found, Using default");
144             }
145         }
146
147         PolicyNotification policyNotification = new PolicyNotification(closedLoopControlName, requestId, alarmStartTime,
148                 pnfName, action, policyName);
149
150         policyNotification.setClosedLoopControlName(closedLoopControlName);
151         policyNotification.setPayload(payloadString);
152         policyNotification.setPolicyName(policyName);
153         ObjectMapper mapper = new ObjectMapper();
154         mapper.setSerializationInclusion(Include.NON_NULL);
155
156         String notification = "";
157         try {
158             notification = mapper.writeValueAsString(policyNotification);
159         } catch (JsonProcessingException e1) {
160             log.debug("JSON processing exception: {}", e1);
161         }
162         return notification;
163     }
164
165     /**
166      * Sends Dmaap notification to Policy.
167      *
168      * @throws ConfigDbNotFoundException
169      *             when config db is unreachable
170      */
171     public Boolean sendToPolicy(AsyncResponseBody async) throws ConfigDbNotFoundException, CpsNotFoundException {
172
173         if (log.isDebugEnabled()) {
174             log.debug(async.toString());
175         }
176
177         Solutions solutions;
178         solutions = async.getSolutions();
179         if (!solutions.getPciSolutions().isEmpty()) {
180             Map<String, List<CellPciPair>> pnfs = pnfUtils.getPnfs(solutions);
181             for (Map.Entry<String, List<CellPciPair>> entry : pnfs.entrySet()) {
182                 String pnfName = entry.getKey();
183                 List<CellPciPair> cellPciPairs = entry.getValue();
184                 ArrayList<Configurations> configurations = new ArrayList<>();
185                 for (CellPciPair cellPciPair : cellPciPairs) {
186                     String cellId = cellPciPair.getCellId();
187                     int pci = cellPciPair.getPhysicalCellId();
188                     Configurations configuration = new Configurations(new Data(new FapService(cellId,
189                             new X0005b9Lte(pci, pnfName), new CellConfig(new Lte(new Ran(new Common(cellId), null))))),
190                             null);
191                     configurations.add(configuration);
192                 }
193
194                 Payload payload = new Payload(configurations);
195                 ObjectMapper mapper = new ObjectMapper();
196                 mapper.setSerializationInclusion(Include.NON_NULL);
197                 String payloadString = "";
198                 try {
199                     payloadString = mapper.writeValueAsString(payload);
200                 } catch (JsonProcessingException e) {
201                     log.debug("JSON processing exception: {}", e);
202                 }
203
204                 String requestId = UUID.randomUUID().toString();
205
206                 String notification = getNotificationString(pnfName, requestId, payloadString,
207                         System.currentTimeMillis(), "ModifyO1Config");
208                 log.info("Policy Notification: {}", notification);
209                 boolean status = policyDmaapClient.sendNotificationToPolicy(notification);
210                 log.debug("sent Message: {}", status);
211                 if (status) {
212                     log.debug("Message sent to policy");
213                 } else {
214                     log.debug("Sending notification to policy failed");
215                 }
216             }
217         }
218         if (!solutions.getAnrSolutions().isEmpty()) {
219             Map<String, List<Map<String, List<String>>>> anrPnfs;
220             List<Configurations> configurations = new ArrayList<>();
221             anrPnfs = pnfUtils.getPnfsForAnrSolutions(solutions.getAnrSolutions());
222             for (Map.Entry<String, List<Map<String, List<String>>>> entry : anrPnfs.entrySet()) {
223                 String pnfName = entry.getKey();
224                 for (Map<String, List<String>> cellRemNeighborsPair : anrPnfs.get(pnfName)) {
225                     for (Map.Entry<String, List<String>> entry1 : cellRemNeighborsPair.entrySet()) {
226                         String cellId = entry1.getKey();
227                         List<LteCell> lteCellList = new ArrayList<>();
228                         for (String removeableNeighbor : entry1.getValue()) {
229                             LteCell lteCell = new LteCell();
230                             lteCell.setBlacklisted("true");
231                             lteCell.setPlmnId(solutions.getNetworkId());
232                             lteCell.setCid(removeableNeighbor);
233                             int pci = configuration.getConfigurationClient().getPci(cellId);
234                             lteCell.setPhyCellId(pci);
235                             lteCell.setPnfName(pnfName);
236                             lteCellList.add(lteCell);
237                         }
238                         Configurations configuration = new Configurations(new Data(new FapService(cellId, null,
239                                 new CellConfig(new Lte(new Ran(new Common(cellId), new NeighborListInUse(null,
240                                         lteCellList, String.valueOf(lteCellList.size()))))))),
241                                 null);
242                         configurations.add(configuration);
243                         Either<List<HoDetails>, Integer> hoMetrics = hoMetricsComponent.getHoMetrics(cellId);
244                         if (hoMetrics.isLeft()) {
245                             List<HoDetails> hoDetailsList = hoMetrics.left().value();
246                             for (LteCell lteCell : lteCellList) {
247                                 String removedNbr = lteCell.getCid();
248                                 for (HoDetails hoDetail : hoDetailsList) {
249                                     if (removedNbr.equals(hoDetail.getDstCellId())) {
250                                         hoDetailsList.remove(hoDetail);
251                                         break;
252                                     }
253                                 }
254                             }
255                             String hoDetailsString = null;
256                             ObjectMapper mapper = new ObjectMapper();
257                             try {
258                                 hoDetailsString = mapper.writeValueAsString(hoDetailsList);
259                             } catch (Exception e) {
260                                 log.error("Error in writing handover metrics json ", e);
261                                 return false;
262                             }
263                             hoMetricsComponent.update(hoDetailsString, cellId);
264                         }
265
266                     }
267                     Payload payload = new Payload(configurations);
268                     ObjectMapper mapper = new ObjectMapper();
269                     mapper.setSerializationInclusion(Include.NON_NULL);
270                     String payloadString = null;
271                     try {
272                         payloadString = mapper.writeValueAsString(payload);
273                     } catch (JsonProcessingException e) {
274                         log.error("Exception in writing anrupdate string", e);
275                     }
276                     String requestId = UUID.randomUUID().toString();
277                     String notification = getNotificationString(pnfName, requestId, payloadString,
278                             System.currentTimeMillis(), "putA1Policy");
279                     log.info("Policy Notification: {}", notification);
280                     Boolean result = policyDmaapClient.sendNotificationToPolicy(notification);
281                     log.info("send notification to policy result {} ", result);
282                 }
283
284             }
285
286         }
287         return true;
288     }
289
290 }