aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/dcaegen2/services/sonhms/EventHandler.java
blob: 312ca60e809d23fb15f7c6579890bb08b4870e7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/*******************************************************************************
 * ============LICENSE_START=======================================================
 * pcims
 *  ================================================================================
 *  Copyright (C) 2018 Wipro Limited.
 *  ==============================================================================
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *   ============LICENSE_END=========================================================
 ******************************************************************************/

package org.onap.dcaegen2.services.sonhms;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.onap.dcaegen2.services.sonhms.child.ChildThread;
import org.onap.dcaegen2.services.sonhms.child.Graph;
import org.onap.dcaegen2.services.sonhms.entity.ClusterDetails;
import org.onap.dcaegen2.services.sonhms.exceptions.ConfigDbNotFoundException;
import org.onap.dcaegen2.services.sonhms.model.FapServiceList;
import org.onap.dcaegen2.services.sonhms.model.Notification;
import org.onap.dcaegen2.services.sonhms.utils.ClusterUtils;
import org.onap.dcaegen2.services.sonhms.utils.ThreadUtils;

import fj.data.Either;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventHandler {

    private static Logger log = LoggerFactory.getLogger(EventHandler.class);

    private static Map<Long, ChildThread> childThreadMap = new HashMap<>();

    private BlockingQueue<List<String>> childStatusQueue;

    private Map<Long, String> childStatus;

    private ExecutorService pool;

    private ClusterUtils clusterUtils;
    
    private ThreadUtils threadUtils;

    /**
     * Constructor.
     */
    public EventHandler(BlockingQueue<List<String>> childStatusQueue, ExecutorService pool,
            Map<Long, String> childStatus, ClusterUtils clusterUtils, ThreadUtils threadUtils) {

        this.childStatusQueue = childStatusQueue;
        this.childStatus = childStatus;
        this.pool = pool;
        this.clusterUtils = clusterUtils;
        this.threadUtils = threadUtils;
    }

    /**
     * handle sdnr notification.
     */
    public Boolean handleSdnrNotification(Notification notification) {
        // Check if notification matches with a cluster

        try {
            List<ClusterDetails> clusterDetails = clusterUtils.getAllClusters();

            NotificationToClusterMapping mapping = new NotificationToClusterMapping();
            mapping = clusterUtils.getClustersForNotification(notification, clusterDetails);

            // Matching cells
            System.out.println(mapping);
            if (mapping.getCellsinCluster() != null) {
                handleMatchingCells(mapping.getCellsinCluster(), clusterDetails);
            }

            // unmatched cells
            if (mapping.getNewCells() != null) {
                handleUnMatchingCells(mapping.getNewCells());
            }
        } catch (Exception e) {
            log.error("Exception in sdnr notification handling {}", e);
            return false;
        }

        return true;

    }

    private void handleUnMatchingCells(List<FapServiceList> newCells) {
        List<Graph> newClusters = new ArrayList<>();

        for (FapServiceList fapService : newCells) {

            Either<Graph, Integer> existingCluster = clusterUtils.getClusterForCell(fapService, newClusters);
            if (existingCluster.isRight()) {
                try {
                    Graph cluster = clusterUtils.createCluster(fapService);
                    newClusters.add(cluster);
                } catch (ConfigDbNotFoundException e) {
                    log.error("Error connecting with configDB {}", e);
                }
            }

            else {
                Graph cluster = existingCluster.left().value();

                Graph modifiedCluster = clusterUtils.modifyCluster(cluster, fapService);
                newClusters.remove(cluster);
                newClusters.add(modifiedCluster);
            }

        }

        // create new child thread
        
        threadUtils.createNewThread(newClusters, childStatusQueue, pool, this);

    }

    private void handleMatchingCells(Map<FapServiceList, String> cellsInCluster, List<ClusterDetails> clusterDetails) {
        for (Entry<FapServiceList, String> entry : cellsInCluster.entrySet()) {

            FapServiceList fapService = entry.getKey();
            String clusterId = entry.getValue();
            Either<ClusterDetails, Integer> clusterDetail = clusterUtils.getClusterDetailsFromClusterId(clusterId,
                    clusterDetails);

            if (clusterDetail.isRight()) {
                log.error("Cannot find the cluster for Cluster ID");
                return;
            } else {
                long threadId = clusterDetail.left().value().getChildThreadId();

                if (childStatus.get(threadId).equals("triggeredOof")) {
                    log.info("OOF triggered for the cluster, buffering notification");
                    bufferNotification(fapService, clusterId);
                } else {
                    childThreadMap.get(threadId).putInQueue(fapService);
                }
            }
        }
    }

    private void bufferNotification(FapServiceList fapService, String clusterId) {
        ObjectMapper mapper = new ObjectMapper();
        BufferNotificationComponent bufferNotifComponent = new BufferNotificationComponent();
        String serviceListString = "";
        try {
            serviceListString = mapper.writeValueAsString(fapService);
        } catch (JsonProcessingException e) {
            log.debug("JSON processing exception: {}", e);
        }
        bufferNotifComponent.bufferNotification(serviceListString, clusterId);

    }

    /**
     * handle child status update.
     */
    public void handleChildStatusUpdate(List<String> childStatus) {

        // update Child status in data structure
        Long childThreadId = Long.parseLong(childStatus.get(0));
        addChildStatus(childThreadId, childStatus.get(1));

        // if child status is OOF result success, handle buffered notifications
        if (childStatus.get(1).equals("success")) {
            BufferNotificationComponent bufferNotificationComponent = new BufferNotificationComponent();
            ClusterDetailsComponent clusterDetailsComponent = new ClusterDetailsComponent();
            String clusterId = clusterDetailsComponent.getClusterId(childThreadId);
            List<String> bufferedNotifications = bufferNotificationComponent.getBufferedNotification(clusterId);

            if (bufferedNotifications == null || bufferedNotifications.isEmpty()) {
                log.info("No buffered notification for this thread");

                Set<Thread> setOfThread = Thread.getAllStackTraces().keySet();
                for (Thread thread : setOfThread) {
                    if (thread.getId() == childThreadId) {
                        deleteChildStatus(childThreadId);
                        thread.interrupt();
                    }
                }
            } else {
                handleBufferedNotifications(childThreadId, bufferedNotifications);
            }
        }
        // else kill the child thread

    }

    private void handleBufferedNotifications(Long childThreadId, List<String> bufferedNotifications) {

        ObjectMapper mapper = new ObjectMapper();
        for (String notification : bufferedNotifications) {
            FapServiceList fapServiceList;
            try {
                fapServiceList = mapper.readValue(notification, FapServiceList.class);
                log.debug("fapServiceList{}", fapServiceList);

                childThreadMap.get(childThreadId).putInQueueWithNotify(fapServiceList);

            } catch (IOException e) {
                log.error("Error parsing the buffered notification, skipping {}", e);
            }
        }
    }

    public static void addChildThreadMap(Long childThreadId, ChildThread child) {
        childThreadMap.put(childThreadId, child);
    }

    public static Map<Long, ChildThread> getChildThreadMap() {
        return childThreadMap;
    }

    public void addChildStatus(Long threadId, String status) {
        this.childStatus.put(threadId, status);
    }

    public String getChildStatus(Long threadId) {
        return childStatus.get(threadId);

    }

    public void deleteChildStatus(Long childThreadId) {
        this.childStatus.remove(childThreadId);

    }

    public ExecutorService getPool() {
        return pool;
    }

}