d567c8aa90948792c460ea8c71ed28042c5a48a9
[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 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.HoMetricsComponent;
38 import org.onap.dcaegen2.services.sonhms.dao.SonRequestsRepository;
39 import org.onap.dcaegen2.services.sonhms.dmaap.PolicyDmaapClient;
40 import org.onap.dcaegen2.services.sonhms.entity.SonRequests;
41 import org.onap.dcaegen2.services.sonhms.exceptions.ConfigDbNotFoundException;
42 import org.onap.dcaegen2.services.sonhms.model.CellConfig;
43 import org.onap.dcaegen2.services.sonhms.model.CellPciPair;
44 import org.onap.dcaegen2.services.sonhms.model.Common;
45 import org.onap.dcaegen2.services.sonhms.model.Configurations;
46 import org.onap.dcaegen2.services.sonhms.model.Data;
47 import org.onap.dcaegen2.services.sonhms.model.FapService;
48 import org.onap.dcaegen2.services.sonhms.model.HoDetails;
49 import org.onap.dcaegen2.services.sonhms.model.Lte;
50 import org.onap.dcaegen2.services.sonhms.model.LteCell;
51 import org.onap.dcaegen2.services.sonhms.model.NeighborListInUse;
52 import org.onap.dcaegen2.services.sonhms.model.Payload;
53 import org.onap.dcaegen2.services.sonhms.model.PolicyNotification;
54 import org.onap.dcaegen2.services.sonhms.model.Ran;
55 import org.onap.dcaegen2.services.sonhms.model.X0005b9Lte;
56 import org.onap.dcaegen2.services.sonhms.restclient.AsyncResponseBody;
57 import org.onap.dcaegen2.services.sonhms.restclient.SdnrRestClient;
58 import org.onap.dcaegen2.services.sonhms.restclient.Solutions;
59 import org.onap.dcaegen2.services.sonhms.utils.BeanUtil;
60 import org.slf4j.Logger;
61
62 public class ChildThreadUtils {
63
64     private static final Logger log = org.slf4j.LoggerFactory.getLogger(ChildThreadUtils.class);
65     private ConfigPolicy configPolicy;
66     private PnfUtils pnfUtils;
67     private PolicyDmaapClient policyDmaapClient;
68     private HoMetricsComponent hoMetricsComponent;
69
70     /**
71      * Parameterized constructor.
72      */
73     public ChildThreadUtils(ConfigPolicy configPolicy, PnfUtils pnfUtils, PolicyDmaapClient policyDmaapClient, HoMetricsComponent hoMetricsComponent) {
74         this.configPolicy = configPolicy;
75         this.pnfUtils = pnfUtils;
76         this.policyDmaapClient = policyDmaapClient;
77         this.hoMetricsComponent = hoMetricsComponent;
78     }
79
80     /**
81      * Save request.
82      */
83     public void saveRequest(String transactionId, long childThreadId) {
84         SonRequestsRepository sonRequestsRepository = BeanUtil.getBean(SonRequestsRepository.class);
85
86         SonRequests sonRequest = new SonRequests();
87         sonRequest.setTransactionId(transactionId);
88         sonRequest.setChildThreadId(childThreadId);
89         sonRequestsRepository.save(sonRequest);
90     }
91
92     /**
93      * Determines whether to trigger Oof or wait for notifications.
94      */
95     public Boolean triggerOrWait(Map<String, ArrayList<Integer>> collisionConfusionResult) {
96         // determine collision or confusion
97
98         Configuration configuration = Configuration.getInstance();
99         int collisionSum = 0;
100         int confusionSum = 0;
101
102         for (Map.Entry<String, ArrayList<Integer>> entry : collisionConfusionResult.entrySet()) {
103
104             ArrayList<Integer> arr;
105             arr = entry.getValue();
106             // check for 0 collision and confusion
107             if (!arr.isEmpty()) {
108                 collisionSum = collisionSum + arr.get(0);
109                 confusionSum = confusionSum + arr.get(1);
110             }
111         }
112         return ((collisionSum >= configuration.getMinCollision()) && (confusionSum >= configuration.getMinConfusion()));
113
114     }
115
116     /**
117      * get policy notification string from oof result.
118      *
119      */
120     public String getNotificationString(String pnfName, String requestId, String payloadString, Long alarmStartTime,
121             String action) {
122
123         String closedLoopControlName = "ControlLoop-vPCI-fb41f388-a5f2-11e8-98d0-529269fb1459";
124         try {
125             closedLoopControlName = (String) configPolicy.getConfig().get("PCI_MODCONFIG_POLICY_NAME");
126         } catch (NullPointerException e) {
127             log.error("Config policy not found, Using default");
128         }
129
130         PolicyNotification policyNotification = new PolicyNotification(closedLoopControlName, requestId, alarmStartTime,
131                 pnfName, action);
132
133         policyNotification.setClosedLoopControlName(closedLoopControlName);
134         policyNotification.setPayload(payloadString);
135         ObjectMapper mapper = new ObjectMapper();
136         mapper.setSerializationInclusion(Include.NON_NULL);
137
138         String notification = "";
139         try {
140             notification = mapper.writeValueAsString(policyNotification);
141         } catch (JsonProcessingException e1) {
142             log.debug("JSON processing exception: {}", e1);
143         }
144         return notification;
145     }
146
147     /**
148      * Sends Dmaap notification to Policy.
149      *
150      * @throws ConfigDbNotFoundException
151      *             when config db is unreachable
152      */
153     public Boolean sendToPolicy(AsyncResponseBody async) throws ConfigDbNotFoundException {
154
155         if (log.isDebugEnabled()) {
156             log.debug(async.toString());
157         }
158
159         Solutions solutions;
160         solutions = async.getSolutions();
161         if (!solutions.getPciSolutions().isEmpty()) {
162             Map<String, List<CellPciPair>> pnfs = pnfUtils.getPnfs(solutions);
163             for (Map.Entry<String, List<CellPciPair>> entry : pnfs.entrySet()) {
164                 String pnfName = entry.getKey();
165                 List<CellPciPair> cellPciPairs = entry.getValue();
166                 ArrayList<Configurations> configurations = new ArrayList<>();
167                 for (CellPciPair cellPciPair : cellPciPairs) {
168                     String cellId = cellPciPair.getCellId();
169                     int pci = cellPciPair.getPhysicalCellId();
170                     Configurations configuration = new Configurations(new Data(new FapService(cellId,
171                             new X0005b9Lte(pci, pnfName), new CellConfig(new Lte(new Ran(new Common(cellId), null))))),
172                             null);
173                     configurations.add(configuration);
174                 }
175
176                 Payload payload = new Payload(configurations);
177                 ObjectMapper mapper = new ObjectMapper();
178                 mapper.setSerializationInclusion(Include.NON_NULL);
179                 String payloadString = "";
180                 try {
181                     payloadString = mapper.writeValueAsString(payload);
182                 } catch (JsonProcessingException e) {
183                     log.debug("JSON processing exception: {}", e);
184                 }
185
186                 String requestId = UUID.randomUUID().toString();
187
188                 String notification = getNotificationString(pnfName, requestId, payloadString,
189                         System.currentTimeMillis(), "ModifyConfig");
190                 log.info("Policy Notification: {}", notification);
191                 boolean status = policyDmaapClient.sendNotificationToPolicy(notification);
192                 log.debug("sent Message: {}", status);
193                 if (status) {
194                     log.debug("Message sent to policy");
195                 } else {
196                     log.debug("Sending notification to policy failed");
197                 }
198                 policyDmaapClient.handlePolicyResponse(requestId);
199                 log.info("handled policy response in ModifyConfig");
200
201             }
202         }
203         if (!solutions.getAnrSolutions().isEmpty()) {
204             Map<String, List<Map<String, List<String>>>> anrPnfs;
205             List<Configurations> configurations = new ArrayList<>();
206             anrPnfs = pnfUtils.getPnfsForAnrSolutions(solutions.getAnrSolutions());
207             for (Map.Entry<String, List<Map<String, List<String>>>> entry : anrPnfs.entrySet()) {
208                 String pnfName = entry.getKey();
209                 for (Map<String, List<String>> cellRemNeighborsPair : anrPnfs.get(pnfName)) {
210                     for (Map.Entry<String, List<String>> entry1 : cellRemNeighborsPair.entrySet()) {
211                         String cellId = entry1.getKey();
212                         List<LteCell> lteCellList = new ArrayList<>();
213                         for (String removeableNeighbor : entry1.getValue()) {
214                             LteCell lteCell = new LteCell();
215                             lteCell.setBlacklisted("true");
216                             lteCell.setPlmnId(solutions.getNetworkId());
217                             lteCell.setCid(removeableNeighbor);
218                             int pci = SdnrRestClient.getPci(cellId);
219                             lteCell.setPhyCellId(pci);
220                             lteCell.setPnfName(pnfName);
221                             lteCellList.add(lteCell);
222                         }
223                         Configurations configuration = new Configurations(new Data(new FapService(cellId, null,
224                                 new CellConfig(new Lte(new Ran(new Common(cellId), new NeighborListInUse(null,
225                                         lteCellList, String.valueOf(lteCellList.size()))))))),
226                                 null);
227                         configurations.add(configuration);
228                         Either<List<HoDetails>, Integer> hoMetrics = hoMetricsComponent.getHoMetrics(cellId);
229                         if(hoMetrics.isLeft()) {
230                             List<HoDetails> hoDetailsList = hoMetrics.left().value();
231                             for(LteCell lteCell:lteCellList) {
232                                 String removedNbr = lteCell.getCid();
233                                 for(HoDetails hoDetail:hoDetailsList) {
234                                     if(removedNbr.equals(hoDetail.getDstCellId())) {
235                                         hoDetailsList.remove(hoDetail);
236                                         break;
237                                     }
238                                 }
239                             }
240                             String hoDetailsString = null;
241                             ObjectMapper mapper = new ObjectMapper();
242                             try {
243                                 hoDetailsString = mapper.writeValueAsString(hoDetailsList);
244                             } catch (Exception e) {
245                                 log.error("Error in writing handover metrics json ", e);
246                                 return false;
247                             }
248                             hoMetricsComponent.update(hoDetailsString, cellId);
249                     }
250                     
251                 }
252                 Payload payload = new Payload(configurations);
253                 ObjectMapper mapper = new ObjectMapper();
254                 mapper.setSerializationInclusion(Include.NON_NULL);
255                 String payloadString = null;
256                 try {
257                     payloadString = mapper.writeValueAsString(payload);
258                 } catch (JsonProcessingException e) {
259                     log.error("Exception in writing anrupdate string", e);
260                 }
261                 String requestId = UUID.randomUUID().toString();
262                 String notification = getNotificationString(pnfName, requestId, payloadString,
263                         System.currentTimeMillis(), "ModifyConfigANR");
264                 log.info("Policy Notification: {}", notification);
265                 Boolean result = policyDmaapClient.sendNotificationToPolicy(notification);
266                 log.info("send notification to policy result {} ", result);
267                 policyDmaapClient.handlePolicyResponse(requestId);
268                 log.info("handled policy response in ModifyConfigANR");
269                 
270                 }
271
272             }
273
274         }
275         return true;
276     }
277
278 }