Son-handler microservice seed code
[dcaegen2/services/son-handler.git] / src / main / java / com / wipro / www / sonhms / SdnrNotificationHandlingState.java
1 /*******************************************************************************
2  * ============LICENSE_START=======================================================
3  * pcims
4  *  ================================================================================
5  *  Copyright (C) 2018 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 package com.wipro.www.sonhms;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.wipro.www.sonhms.child.ChildThread;
26 import com.wipro.www.sonhms.child.Graph;
27 import com.wipro.www.sonhms.dao.CellInfoRepository;
28 import com.wipro.www.sonhms.dao.ClusterDetailsRepository;
29 import com.wipro.www.sonhms.entity.CellInfo;
30 import com.wipro.www.sonhms.entity.ClusterDetails;
31 import com.wipro.www.sonhms.exceptions.ConfigDbNotFoundException;
32 import com.wipro.www.sonhms.model.CellPciPair;
33 import com.wipro.www.sonhms.model.FapServiceList;
34 import com.wipro.www.sonhms.model.LteNeighborListInUseLteCell;
35 import com.wipro.www.sonhms.model.Notification;
36 import com.wipro.www.sonhms.model.ThreadId;
37 import com.wipro.www.sonhms.restclient.SdnrRestClient;
38 import com.wipro.www.sonhms.utils.BeanUtil;
39
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46 import java.util.UUID;
47 import java.util.concurrent.BlockingQueue;
48 import java.util.concurrent.LinkedBlockingQueue;
49
50 import org.slf4j.Logger;
51
52 public class SdnrNotificationHandlingState implements SonState {
53     private static Map<Long, ChildThread> childThreadMap = new HashMap<>();
54     private static final Logger log = org.slf4j.LoggerFactory.getLogger(SdnrNotificationHandlingState.class);
55
56     @Override
57     public void stateChange(SonContext sonContext) {
58         // logic to determine if notif to be processed
59         log.debug("inside statechange of sdnr notif state");
60         String notification = sonContext.getSdnrNotification();
61         Notification notificationObject;
62         try {
63
64             ObjectMapper mapper = new ObjectMapper();
65             notificationObject = mapper.readValue(notification, Notification.class);
66             log.debug("notificationObject{}", notificationObject);
67
68             List<FapServiceList> serviceList = notificationObject.getPayload().getRadioAccess().getFapServiceList();
69             for (FapServiceList fapService : serviceList) {
70                 String cellId = fapService.getCellConfig().getLte().getRan().getCellIdentity();
71                 log.debug("cellId:{}", cellId);
72                 log.debug("inside for loop");
73
74                 List<ClusterDetails> clusterDetails = getAllClusters();
75
76                 ClusterDetails clusterDetail = getClusterForNotification(fapService, clusterDetails);
77
78                 if (clusterDetail == null) {
79                     // form the cluster
80                     Graph cluster = createCluster(fapService);
81                     // save to db
82                     UUID clusterId = UUID.randomUUID();
83                     cluster.setGraphId(clusterId);
84                     // create the child thread
85                     log.debug("creating new child");
86                     BlockingQueue<FapServiceList> queue = new LinkedBlockingQueue<>();
87                     ThreadId threadId = new ThreadId();
88                     threadId.setChildThreadId(0);
89                     ChildThread child = new ChildThread(sonContext.getChildStatusUpdate(), cluster, queue, threadId);
90                     queue.put(fapService);
91                     MainThreadComponent mainThreadComponent = BeanUtil.getBean(MainThreadComponent.class);
92                     mainThreadComponent.getPool().execute(child);
93
94                     waitForThreadId(threadId);
95
96                     saveCluster(cluster, clusterId, threadId.getChildThreadId());
97                     addChildThreadMap(threadId.getChildThreadId(), child);
98                     sonContext.addChildStatus(threadId.getChildThreadId(), "processingNotifications");
99
100                 }
101
102                 else {
103                     if (isOofTriggeredForCluster(sonContext, clusterDetail)) {
104                         sonContext.setNotifToBeProcessed(false);
105                         bufferNotification(fapService, clusterDetail.getClusterId());
106                     } else {
107                         sonContext.setNotifToBeProcessed(true);
108                         log.debug("childThreadId:{}", clusterDetail.getChildThreadId());
109                         childThreadMap.get(clusterDetail.getChildThreadId()).putInQueue(fapService);
110                     }
111                 }
112             }
113         } catch (Exception e) {
114             log.error("caught in sdnr notif handling state{}", e);
115         }
116
117         WaitState waitState = WaitState.getInstance();
118         sonContext.setPciState(waitState);
119         sonContext.stateChange(sonContext);
120     }
121
122     private void waitForThreadId(ThreadId threadId) {
123         try {
124             synchronized (threadId) {
125                 while (threadId.getChildThreadId() == 0) {
126                     threadId.wait();
127                 }
128             }
129         } catch (InterruptedException e) {
130
131             log.error("ChildThread queue error {}", e);
132             Thread.currentThread().interrupt();
133         }
134     }
135
136     private String saveCluster(Graph cluster, UUID clusterId, Long threadId) {
137
138         String cellPciNeighbourString = cluster.getPciNeighbourJson();
139
140         log.debug("cluster hahsmap to string : {}", cellPciNeighbourString);
141         cluster.setGraphId(clusterId);
142
143         ClusterDetails details = new ClusterDetails();
144         details.setClusterId(clusterId.toString());
145         details.setClusterInfo(cellPciNeighbourString);
146         details.setChildThreadId(threadId);
147
148         ClusterDetailsRepository clusterDetailsRepository = BeanUtil.getBean(ClusterDetailsRepository.class);
149         clusterDetailsRepository.save(details);
150
151         return clusterId.toString();
152     }
153
154     private Graph createCluster(FapServiceList fapService) throws ConfigDbNotFoundException {
155
156         Graph cluster = new Graph();
157         log.debug("cluster formation started");
158         int phycellId = fapService.getX0005b9Lte().getPhyCellIdInUse();
159         String cellId = fapService.getCellConfig().getLte().getRan().getCellIdentity();
160
161         CellInfoRepository cellInfoRepository = BeanUtil.getBean(CellInfoRepository.class);
162         cellInfoRepository.save(new CellInfo(cellId, fapService.getX0005b9Lte().getPnfName()));
163
164         CellPciPair val = new CellPciPair();
165         val.setCellId(cellId);
166         val.setPhysicalCellId(phycellId);
167         List<LteNeighborListInUseLteCell> neighbourlist;
168         neighbourlist = fapService.getCellConfig().getLte().getRan().getNeighborListInUse()
169                 .getLteNeighborListInUseLteCell();
170         log.debug("Neighbor list size: {}", neighbourlist.size());
171
172         for (int i = 0; i < neighbourlist.size(); i++) {
173             String cell = neighbourlist.get(i).getAlias();
174             int phy = neighbourlist.get(i).getPhyCellId();
175
176             cellInfoRepository.save(new CellInfo(cell, neighbourlist.get(i).getPnfName()));
177
178             log.debug("cellID: {}", cell);
179             log.debug("PCI: {}", phy);
180             CellPciPair val1 = new CellPciPair();
181             val1.setCellId(cell);
182             val1.setPhysicalCellId(phy);
183             cluster.addEdge(val, val1);
184             log.debug("cluster: {}", cluster);
185
186             List<CellPciPair> nbrList = SdnrRestClient.getNbrList(neighbourlist.get(i).getAlias());
187
188             for (CellPciPair nbr : nbrList) {
189                 String cid = nbr.getCellId();
190                 int pci = nbr.getPhysicalCellId();
191                 CellPciPair val3 = new CellPciPair();
192                 val3.setCellId(cid);
193                 val3.setPhysicalCellId(pci);
194
195                 cluster.addEdge(val1, val3);
196             }
197         }
198
199         log.debug("final cluster: {}", cluster);
200         return cluster;
201     }
202
203     private void bufferNotification(FapServiceList fapService, String clusterId) {
204
205         ObjectMapper mapper = new ObjectMapper();
206         BufferNotificationComponent bufferNotifComponent = new BufferNotificationComponent();
207         String serviceListString = "";
208         try {
209             serviceListString = mapper.writeValueAsString(fapService);
210         } catch (JsonProcessingException e) {
211             log.debug("JSON processing exception: {}", e);
212         }
213         bufferNotifComponent.bufferNotification(serviceListString, clusterId);
214
215     }
216
217     private boolean isOofTriggeredForCluster(SonContext pciContext, ClusterDetails clusterDetail) {
218         Long childThreadId = clusterDetail.getChildThreadId();
219         String childStatus = pciContext.getChildStatus(childThreadId);
220         return childStatus.equals("triggeredOof");
221
222     }
223
224     private ClusterDetails getClusterForNotification(FapServiceList fapService, List<ClusterDetails> clusterDetails) {
225
226         String cellId = fapService.getCellConfig().getLte().getRan().getCellIdentity();
227         Map<CellPciPair, ArrayList<CellPciPair>> cellPciNeighbourMap;
228
229         for (ClusterDetails clusterDetail : clusterDetails) {
230             Graph cluster = new Graph(clusterDetail.getClusterInfo());
231             cellPciNeighbourMap = cluster.getCellPciNeighbourMap();
232             Set<CellPciPair> keys = cellPciNeighbourMap.keySet();
233             Iterator<CellPciPair> traverse = keys.iterator();
234             while (traverse.hasNext()) {
235                 CellPciPair key = traverse.next();
236                 String currentCellId = key.getCellId();
237                 if (cellId.equals(currentCellId)) {
238                     return clusterDetail;
239                 }
240             }
241         }
242
243         return null;
244     }
245
246     private List<ClusterDetails> getAllClusters() {
247         ClusterDetailsComponent clusterDetailsComponent = new ClusterDetailsComponent();
248         return clusterDetailsComponent.getClusterDetails();
249     }
250
251     public static void addChildThreadMap(Long childThreadId, ChildThread child) {
252         childThreadMap.put(childThreadId, child);
253     }
254
255     public static Map<Long, ChildThread> getChildThreadMap() {
256         return childThreadMap;
257     }
258
259 }