Implement DMaaP message handling from policy
[dcaegen2/services/son-handler.git] / src / main / java / org / onap / dcaegen2 / services / sonhms / PmNotificationHandler.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;
23
24 import com.fasterxml.jackson.annotation.JsonInclude.Include;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.UUID;
29
30 import org.onap.dcaegen2.services.sonhms.child.ChildThreadUtils;
31 import org.onap.dcaegen2.services.sonhms.child.PnfUtils;
32 import org.onap.dcaegen2.services.sonhms.dao.HandOverMetricsRepository;
33 import org.onap.dcaegen2.services.sonhms.dmaap.PolicyDmaapClient;
34 import org.onap.dcaegen2.services.sonhms.entity.HandOverMetrics;
35 import org.onap.dcaegen2.services.sonhms.model.AdditionalMeasurements;
36 import org.onap.dcaegen2.services.sonhms.model.CellConfig;
37 import org.onap.dcaegen2.services.sonhms.model.Common;
38 import org.onap.dcaegen2.services.sonhms.model.Configurations;
39 import org.onap.dcaegen2.services.sonhms.model.Data;
40 import org.onap.dcaegen2.services.sonhms.model.FapService;
41 import org.onap.dcaegen2.services.sonhms.model.Flag;
42 import org.onap.dcaegen2.services.sonhms.model.HoDetails;
43 import org.onap.dcaegen2.services.sonhms.model.Lte;
44 import org.onap.dcaegen2.services.sonhms.model.LteCell;
45 import org.onap.dcaegen2.services.sonhms.model.NeighborListInUse;
46 import org.onap.dcaegen2.services.sonhms.model.Payload;
47 import org.onap.dcaegen2.services.sonhms.model.PmNotification;
48 import org.onap.dcaegen2.services.sonhms.model.Ran;
49 import org.onap.dcaegen2.services.sonhms.utils.BeanUtil;
50 import org.onap.dcaegen2.services.sonhms.utils.DmaapUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class PmNotificationHandler {
55
56     private static Logger log = LoggerFactory.getLogger(PmNotificationHandler.class);
57     PolicyDmaapClient policyDmaapClient;
58
59     public PmNotificationHandler() {
60
61     }
62
63     public PmNotificationHandler(PolicyDmaapClient policyDmaapClient) {
64         this.policyDmaapClient = policyDmaapClient;
65     }
66
67     /**
68      * handle PM notifications.
69      */
70     public Boolean handlePmNotifications(PmNotification pmNotification, int badThreshold) {
71         HandOverMetricsRepository handOverMetricsRepository = BeanUtil.getBean(HandOverMetricsRepository.class);
72         Boolean result;
73         try {
74             List<HoDetails> hoDetailsList = new ArrayList<>();
75             List<LteCell> lteCellList = new ArrayList<>();
76             String srcCellId = pmNotification.getEvent().getCommonEventHeader().getSourceName();
77             for (AdditionalMeasurements additionalMeasurements : pmNotification.getEvent().getMeasurementFields()
78                     .getAdditionalMeasurements()) {
79                 int attemptsCount = Integer.parseInt(additionalMeasurements.getHashMap().get("InterEnbOutAtt_X2HO"));
80                 int successCount = Integer.parseInt(additionalMeasurements.getHashMap().get("InterEnbOutSucc_X2HO"));
81                 float successRate = ((float) successCount / attemptsCount) * 100;
82                 if (successRate >= badThreshold) {
83                     HoDetails hoDetails = new HoDetails();
84                     hoDetails.setDstCellId(additionalMeasurements.getName());
85                     hoDetails.setAttemptsCount(attemptsCount);
86                     hoDetails.setSuccessCount(successCount);
87                     hoDetails.setSuccessRate(successRate);
88                     hoDetailsList.add(hoDetails);
89                     log.info("not bad  neighbor {}", additionalMeasurements.getName());
90                 } else {
91                     log.info(" bad  neighbor {}", additionalMeasurements.getName());
92                     LteCell lteCell = new LteCell();
93                     lteCell.setBlacklisted("true");
94                     lteCell.setCid(additionalMeasurements.getName());
95                     lteCell.setPlmnId(additionalMeasurements.getHashMap().get("networkId"));
96                     lteCell.setPnfName(pmNotification.getEvent().getCommonEventHeader().getReportingEntityName());
97                     lteCellList.add(lteCell);
98                 }
99             }
100             if (!lteCellList.isEmpty()) {
101                 log.info("triggering policy to remove bad neighbors");
102                 Flag policyTriggerFlag = BeanUtil.getBean(Flag.class);
103
104                 while (policyTriggerFlag.getHolder().equals("CHILD")) {
105                     Thread.sleep(100);
106                 }
107
108                 policyTriggerFlag.setHolder("PM");
109                 result = sendAnrUpdateToPolicy(pmNotification, lteCellList);
110                 log.info("Sent ANR update to policy {}", result);
111                 policyTriggerFlag.setHolder("NONE");
112
113                 String hoDetailsString = handOverMetricsRepository.getHandOverMetrics(srcCellId);
114                 if (hoDetailsString != null) {
115                     ObjectMapper mapper = new ObjectMapper();
116                     String newHoDetailsString = null;
117                     try {
118                         newHoDetailsString = mapper.writeValueAsString(hoDetailsList);
119                     } catch (Exception e) {
120                         log.error("Error in writing handover metrics json ", e);
121                         return false;
122                     }
123                     handOverMetricsRepository.updateHoMetrics(newHoDetailsString, srcCellId);
124                 }
125             }
126             if (!hoDetailsList.isEmpty()) {
127                 result = saveToHandOverMetrics(hoDetailsList, srcCellId);
128                 log.debug("save HO metrics result {} ", result);
129
130             }
131
132         } catch (Exception e) {
133             log.error("Error in handlePmNotifications ", e);
134             return false;
135         }
136         return true;
137
138     }
139
140     private Boolean sendAnrUpdateToPolicy(PmNotification pmNotification, List<LteCell> lteCellList) {
141         ObjectMapper mapper = new ObjectMapper();
142         try {
143             mapper.setSerializationInclusion(Include.NON_NULL);
144             ArrayList<Configurations> configurations = new ArrayList<>();
145             String cellId = pmNotification.getEvent().getCommonEventHeader().getSourceName();
146             Configurations configuration = new Configurations(
147                     new Data(new FapService(cellId, null,
148                             new CellConfig(new Lte(new Ran(new Common(cellId),
149                                     new NeighborListInUse(null, lteCellList, String.valueOf(lteCellList.size()))))))),
150                     null);
151             configurations.add(configuration);
152             Payload payload = new Payload(configurations);
153             log.info("payload : {}", payload);
154             String anrUpdateString = mapper.writeValueAsString(payload);
155             ChildThreadUtils childUtils = new ChildThreadUtils(ConfigPolicy.getInstance(), new PnfUtils(),
156                     new PolicyDmaapClient(new DmaapUtils(), Configuration.getInstance()));
157             String requestId = UUID.randomUUID().toString();
158             String notification = childUtils.getNotificationString(
159                     pmNotification.getEvent().getCommonEventHeader().getReportingEntityName(), requestId,
160                     anrUpdateString, System.currentTimeMillis(), "ModifyConfigANR");
161             log.info("Policy Notification: {}", notification);
162             Boolean result = policyDmaapClient.sendNotificationToPolicy(notification);
163             log.info("send notification to policy result {} ", result);
164             // getting policy response
165             policyDmaapClient.handlePolicyResponse(requestId);
166             log.info("handled policy response");
167
168         } catch (Exception e) {
169             log.error("Exception in sending Anr update to policy ", e);
170             return false;
171         }
172         return true;
173     }
174
175     private Boolean saveToHandOverMetrics(List<HoDetails> hoDetailsList, String srcCellId) {
176         HandOverMetricsRepository handOverMetricsRepository = BeanUtil.getBean(HandOverMetricsRepository.class);
177         ObjectMapper mapper = new ObjectMapper();
178         String hoDetailsString = null;
179         try {
180             hoDetailsString = mapper.writeValueAsString(hoDetailsList);
181         } catch (Exception e) {
182             log.error("Error in writing handover metrics json ", e);
183             return false;
184         }
185
186         if (handOverMetricsRepository.getHandOverMetrics(srcCellId) == null) {
187             HandOverMetrics handOverMetrics = new HandOverMetrics();
188             handOverMetrics.setHoDetails(hoDetailsString);
189             handOverMetrics.setSrcCellId(srcCellId);
190             handOverMetricsRepository.save(handOverMetrics);
191         } else {
192             handOverMetricsRepository.updateHoMetrics(hoDetailsString, srcCellId);
193         }
194         return true;
195     }
196 }