Modify ANR Payload aligned to A1 schema in SDNR
[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-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;
23
24 import com.fasterxml.jackson.annotation.JsonInclude.Include;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26
27 import fj.data.Either;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.UUID;
34
35 import org.onap.dcaegen2.services.sonhms.Configuration;
36 import org.onap.dcaegen2.services.sonhms.child.ChildThreadUtils;
37 import org.onap.dcaegen2.services.sonhms.child.PnfUtils;
38 import org.onap.dcaegen2.services.sonhms.dao.HandOverMetricsRepository;
39 import org.onap.dcaegen2.services.sonhms.dmaap.PolicyDmaapClient;
40 import org.onap.dcaegen2.services.sonhms.entity.HandOverMetrics;
41 import org.onap.dcaegen2.services.sonhms.model.AdditionalMeasurements;
42 import org.onap.dcaegen2.services.sonhms.model.A1Payload;
43 import org.onap.dcaegen2.services.sonhms.model.ANRPayload;
44 import org.onap.dcaegen2.services.sonhms.model.CellConfig;
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.Flag;
50 import org.onap.dcaegen2.services.sonhms.model.HoDetails;
51 import org.onap.dcaegen2.services.sonhms.model.Input;
52 import org.onap.dcaegen2.services.sonhms.model.Lte;
53 import org.onap.dcaegen2.services.sonhms.model.LteCell;
54 import org.onap.dcaegen2.services.sonhms.model.NeighborListInUse;
55 import org.onap.dcaegen2.services.sonhms.model.Neighbours;
56 import org.onap.dcaegen2.services.sonhms.model.Payload;
57 import org.onap.dcaegen2.services.sonhms.model.PmNotification;
58 import org.onap.dcaegen2.services.sonhms.model.PolicyData;
59 import org.onap.dcaegen2.services.sonhms.model.Ran;
60 import org.onap.dcaegen2.services.sonhms.utils.BeanUtil;
61 import org.onap.dcaegen2.services.sonhms.utils.DmaapUtils;
62 import org.onap.dcaegen2.services.sonhms.restclient.ConfigurationClient;
63 import org.onap.dcaegen2.services.sonhms.restclient.CpsClient;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 public class PmNotificationHandler {
68
69     private static Logger log = LoggerFactory.getLogger(PmNotificationHandler.class);
70     PolicyDmaapClient policyDmaapClient;
71     Configuration configuration = Configuration.getInstance();
72
73     public PmNotificationHandler() {
74
75     }
76
77     public PmNotificationHandler(PolicyDmaapClient policyDmaapClient) {
78         this.policyDmaapClient = policyDmaapClient;
79     }
80
81     /**
82      * handle PM notifications.
83      */
84     public Boolean handlePmNotifications(PmNotification pmNotification, int badThreshold, int poorThreshold,
85             int badCountThreshold) {
86         Boolean result;
87         Boolean newEntryFlag = false;
88         try {
89             List<HoDetails> hoDetailsList = new ArrayList<>();
90             List<Neighbours> neighbourList = new ArrayList<>();
91             String srcCellId = pmNotification.getEvent().getCommonEventHeader().getSourceName();
92             /*
93              * check whether entry already exists if yes : read the hometrics and update it
94              * with latest info else store the current data
95              */
96             HoMetricsComponent hoMetricsComponent = new HoMetricsComponent();
97             Either<List<HoDetails>, Integer> hoMetrics = hoMetricsComponent.getHoMetrics(srcCellId);
98             Map<String, Integer> dstCellIdPcPair = new HashMap<>();
99             Map<String, Integer> dstCellIdBcPair = new HashMap<>();
100             if (hoMetrics.isLeft()) {
101                 List<HoDetails> oldHoDetailsList = hoMetrics.left().value();
102                 for (HoDetails hodetail : oldHoDetailsList) {
103                     dstCellIdBcPair.put(hodetail.getDstCellId(), hodetail.getBadCount());
104                     dstCellIdPcPair.put(hodetail.getDstCellId(), hodetail.getPoorCount());
105                 }
106
107             } else if (hoMetrics.right().value() == 404) {
108                 newEntryFlag = true;
109                 log.info("no history of srcCell found");
110             }
111             for (AdditionalMeasurements additionalMeasurements : pmNotification.getEvent().getMeasurementFields()
112                     .getAdditionalMeasurements()) {
113                 int attemptsCount = Integer.parseInt(additionalMeasurements.getHashMap().get("InterEnbOutAtt_X2HO"));
114                 int successCount = Integer.parseInt(additionalMeasurements.getHashMap().get("InterEnbOutSucc_X2HO"));
115                 int successRate = (int)(((float) successCount / attemptsCount) * 100);
116
117                 Neighbours neighbourCell = new Neighbours();
118                 neighbourCell.setHoKpi(successRate);
119                 neighbourCell.setCellId(additionalMeasurements.getName());
120                 neighbourCell.setPlmnId(additionalMeasurements.getHashMap().get("networkId"));
121                 neighbourCell.setPnfName(pmNotification.getEvent().getCommonEventHeader().getReportingEntityName());
122                 neighbourList.add(neighbourCell);
123             }
124             if (!neighbourList.isEmpty()) {
125                 log.info("triggering policy to remove bad neighbors");
126                 Flag policyTriggerFlag = BeanUtil.getBean(Flag.class);
127
128                 while (policyTriggerFlag.getHolder().equals("CHILD")) {
129                     Thread.sleep(100);
130                 }
131
132                 policyTriggerFlag.setHolder("PM");
133                 result = sendAnrUpdateToPolicy(pmNotification, neighbourList);
134                 log.info("Sent ANR update to policy {}", result);
135                 policyTriggerFlag.setHolder("NONE");
136             }
137             if (!hoDetailsList.isEmpty() && newEntryFlag) {
138                 result = saveToHandOverMetrics(hoDetailsList, srcCellId);
139                 log.debug("save HO metrics result {} ", result);
140
141             } else if (!hoDetailsList.isEmpty()) {
142                 String hoDetailsString = null;
143                 ObjectMapper mapper = new ObjectMapper();
144                 try {
145                     hoDetailsString = mapper.writeValueAsString(hoDetailsList);
146                 } catch (Exception e) {
147                     log.error("Error in writing handover metrics json ", e);
148                     return false;
149                 }
150                 hoMetricsComponent.update(hoDetailsString, srcCellId);
151             }
152
153         } catch (Exception e) {
154             log.error("Error in handlePmNotifications ", e);
155             return false;
156         }
157         return true;
158
159     }
160
161     private Boolean sendAnrUpdateToPolicy(PmNotification pmNotification, List<Neighbours> neighbourList) {
162         ObjectMapper mapper = new ObjectMapper();
163         try {
164             mapper.setSerializationInclusion(Include.NON_NULL);
165             String nearRtricUrl = configuration.getNearRtricUrl();
166             String cellId = pmNotification.getEvent().getCommonEventHeader().getSourceName();
167             String pnfName = pmNotification.getEvent().getCommonEventHeader().getReportingEntityName();
168             String plmnId =  pmNotification.getEvent().getMeasurementFields()
169                .getAdditionalMeasurements().get(0).getHashMap().get("networkId");
170             UUID uuid = UUID.randomUUID();
171
172             A1Payload payload = new A1Payload(new Input(nearRtricUrl,
173                                        new ANRPayload(uuid.toString(),"ANR","a1-terminator",
174                                        new PolicyData(pnfName,plmnId,cellId,neighbourList),"",false,"")));
175
176             String anrUpdateString = mapper.writeValueAsString(payload);
177             log.info("After converting A1Paylod to String: " + anrUpdateString);
178             ChildThreadUtils childUtils = new ChildThreadUtils(ConfigPolicy.getInstance(), new PnfUtils(),
179                     new PolicyDmaapClient(new DmaapUtils(), Configuration.getInstance()), new HoMetricsComponent());
180             String requestId = UUID.randomUUID().toString();
181             String notification = childUtils.getNotificationString(
182                     pmNotification.getEvent().getCommonEventHeader().getReportingEntityName(), requestId,
183                     anrUpdateString, System.currentTimeMillis(), "putA1Policy");
184             log.info("Policy Notification: {}", notification);
185             Boolean result = policyDmaapClient.sendNotificationToPolicy(notification);
186             log.info("send notification to policy result {} ", result);
187
188         } catch (Exception e) {
189             log.error("Exception in sending Anr update to policy ", e);
190             return false;
191         }
192         return true;
193     }
194
195     private Boolean saveToHandOverMetrics(List<HoDetails> hoDetailsList, String srcCellId) {
196         ObjectMapper mapper = new ObjectMapper();
197         String hoDetailsString = null;
198         try {
199             hoDetailsString = mapper.writeValueAsString(hoDetailsList);
200         } catch (Exception e) {
201             log.error("Error in writing handover metrics json ", e);
202             return false;
203         }
204         HandOverMetrics handOverMetrics = new HandOverMetrics();
205         handOverMetrics.setHoDetails(hoDetailsString);
206         handOverMetrics.setSrcCellId(srcCellId);
207         HandOverMetricsRepository handOverMetricsRepository = BeanUtil.getBean(HandOverMetricsRepository.class);
208         handOverMetricsRepository.save(handOverMetrics);
209         return true;
210     }
211 }
212