a3c5aba9191d8adcf0b2890371d4e679b8ab3278
[appc.git] / appc-event-listener / appc-event-listener-bundle / src / main / java / org / onap / appc / listener / LCM / impl / ListenerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.listener.LCM.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.eelf.i18n.EELFResourceManager;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import java.text.DateFormat;
32 import java.text.SimpleDateFormat;
33 import java.util.Date;
34 import java.util.List;
35 import java.util.TimeZone;
36 import java.util.concurrent.RejectedExecutionException;
37 import org.apache.commons.lang3.StringUtils;
38 import org.onap.appc.listener.AbstractListener;
39 import org.onap.appc.listener.LCM.conv.Converter;
40 import org.onap.appc.listener.LCM.model.DmaapIncomingMessage;
41 import org.onap.appc.listener.LCM.operation.ProviderOperations;
42 import org.onap.appc.listener.ListenerProperties;
43
44 public class ListenerImpl extends AbstractListener {
45
46     private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class);
47
48     private long startTime = 0;
49
50     private final ProviderOperations providerOperations;
51
52     public ListenerImpl(ListenerProperties props) {
53         super(props);
54
55         String url = props.getProperty("provider.url");
56         String user = props.getProperty("provider.user");
57         String pass = props.getProperty("provider.pass");
58         providerOperations = new ProviderOperations(url, user, pass);
59         LOG.info("DMaaP Provider Endpoint: " + url);
60     }
61
62     @Override
63     public void run() {
64         // Some vars for benchmarking
65         startTime = System.currentTimeMillis();
66
67         LOG.info("Running DMaaP Listener");
68
69         while (run.get()) {
70             // Only update if the queue is low. otherwise we read in more
71             // messages than we need
72             try {
73                 if (executor.getQueue().size() <= QUEUED_MIN) {
74                     LOG.debug("DMaaP queue running low. Querying for more jobs");
75
76                     List<DmaapIncomingMessage> messages = dmaap
77                         .getIncomingEvents(DmaapIncomingMessage.class, QUEUED_MAX);
78                     LOG.debug(String.format("Read %d messages from dmaap", messages.size()));
79                     for (DmaapIncomingMessage incoming : messages) {
80                         // Acknowledge that we read the event
81                         if (isValid(incoming)) {
82                             String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody());
83                             LOG.info("Acknowledging Message: " + requestIdWithSubId);
84                         }
85                     }
86                     for (DmaapIncomingMessage incoming : messages) {
87                         String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody());
88                         // Add to pool if still running
89                         if (run.get()) {
90                             if (isValid(incoming)) {
91                                 LOG.info(String.format("Adding DMaaP message to pool queue [%s]", requestIdWithSubId));
92                                 try {
93                                     executor.execute(new WorkerImpl(incoming, dmaap, providerOperations));
94                                 } catch (RejectedExecutionException rejectEx) {
95                                     LOG.error("Task Rejected: ", rejectEx);
96                                 }
97                             } else {
98                                 // Badly formed message
99                                 LOG.error("Message was not valid. Rejecting message: " + incoming);
100                             }
101                         } else {
102                             if (isValid(incoming)) {
103                                 LOG.info("Run stopped. Orphaning Message: " + requestIdWithSubId);
104                             } else {
105                                 // Badly formed message
106                                 LOG.error("Message was not valid. Rejecting message: " + incoming);
107                             }
108                         }
109                     }
110                 }
111             } catch (Exception e) {
112                 LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener");
113                 LOG.error(EELFResourceManager.format(e));
114                 LOG.error("DMaaP Listener logging and ignoring the exception, continue...");
115             }
116         }
117
118         LOG.info("Stopping DMaaP Listener thread");
119
120         // We've told the listener to stop
121         // TODO - Should we:
122         // 1) Put a message back on the queue indicating that APP-C never got to
123         // the message
124         // or
125         // 2) Let downstream figure it out after timeout between PENDING and
126         // ACTIVE messages
127     }
128
129     private boolean isValid(DmaapIncomingMessage incoming) {
130         return ((incoming != null) &&
131             incoming.getBody() != null
132             && !StringUtils.isEmpty(incoming.getRpcName()));
133     }
134
135     @Override
136     public String getBenchmark() {
137         long time = System.currentTimeMillis();
138         DateFormat df = new SimpleDateFormat("HH:mm:ss");
139         df.setTimeZone(TimeZone.getTimeZone("UTC"));
140         String runningTime = df.format(new Date(time - startTime));
141
142         String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime,
143             executor.getCompletedTaskCount(), executor.getPoolSize());
144         LOG.info("***BENCHMARK*** " + out);
145         return out;
146     }
147
148     private String getRequestIdWithSubId(JsonNode event) {
149         String requestId = "";
150         try {
151             requestId = Converter.extractRequestIdWithSubId(event);
152         } catch (Exception e) {
153             LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e);
154         }
155         return requestId;
156     }
157 }