d0ba7fbf5ca2c97b1d22df33eb7abbf9df46f7cf
[appc.git] / appc-event-listener / appc-event-listener-bundle / src / main / java / org / openecomp / 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.openecomp.appc.listener.LCM.impl;
26
27 import com.fasterxml.jackson.databind.JsonNode;
28 import org.apache.commons.lang3.StringUtils;
29 import org.openecomp.appc.listener.AbstractListener;
30 import org.openecomp.appc.listener.ListenerProperties;
31 import org.openecomp.appc.listener.LCM.conv.Converter;
32 import org.openecomp.appc.listener.LCM.model.DmaapIncomingMessage;
33 import org.openecomp.appc.listener.LCM.operation.ProviderOperations;
34
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import com.att.eelf.i18n.EELFResourceManager;
38
39 import java.text.DateFormat;
40 import java.text.SimpleDateFormat;
41 import java.util.Date;
42 import java.util.List;
43 import java.util.TimeZone;
44 import java.util.concurrent.RejectedExecutionException;
45
46 public class ListenerImpl extends AbstractListener {
47
48     private final EELFLogger LOG = EELFManager.getInstance().getLogger(ListenerImpl.class);
49
50     private long startTime = 0;
51
52     private final ProviderOperations providerOperations;
53
54     public ListenerImpl(ListenerProperties props) {
55         super(props);
56
57         String url = props.getProperty("provider.url");
58         LOG.info("DMaaP Provider Endpoint: " + url);
59         providerOperations = new ProviderOperations();
60         providerOperations.setUrl(url);
61
62         // Set Basic Auth
63         String user = props.getProperty("provider.user");
64         String pass = props.getProperty("provider.pass");
65         providerOperations.setAuthentication(user, pass);
66     }
67
68     @Override
69     public void run() {
70         // Some vars for benchmarking
71         startTime = System.currentTimeMillis();
72
73         LOG.info("Running DMaaP Listener");
74
75         while (run.get()) {
76             // Only update if the queue is low. otherwise we read in more
77             // messages than we need
78             try {
79                 if (executor.getQueue().size() <= QUEUED_MIN) {
80                     LOG.debug("DMaaP queue running low. Querying for more jobs");
81
82
83                     List<DmaapIncomingMessage> messages = dmaap.getIncomingEvents(DmaapIncomingMessage.class, QUEUED_MAX);
84                     LOG.debug(String.format("Read %d messages from dmaap", messages.size()));
85                     for (DmaapIncomingMessage incoming : messages) {
86                         // Acknowledge that we read the event
87                         if (isValid(incoming)) {
88                             String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody());
89                             LOG.info("Acknowledging Message: " + requestIdWithSubId);
90 //                            dmaap.postStatus(incoming.toOutgoing(OperationStatus.PENDING));
91                         }
92                     }
93                     for (DmaapIncomingMessage incoming : messages) {
94                         String requestIdWithSubId = getRequestIdWithSubId(incoming.getBody());
95                         // Add to pool if still running
96                         if (run.get()) {
97                             if (isValid(incoming)) {
98                                 LOG.info(String.format("Adding DMaaP message to pool queue [%s]", requestIdWithSubId));
99                                 try {
100                                     executor.execute(new WorkerImpl(incoming, dmaap, providerOperations));
101                                 } catch (RejectedExecutionException rejectEx) {
102                                     LOG.error("Task Rejected: ", rejectEx);
103                                 }
104                             } else {
105                                 // Badly formed message
106                                 LOG.error("Message was not valid. Rejecting message: "+incoming);
107                             }
108                         } else {
109                             if (isValid(incoming)) {
110                                 LOG.info("Run stopped. Orphaning Message: " + requestIdWithSubId);
111                             }
112                             else {
113                                 // Badly formed message
114                                 LOG.error("Message was not valid. Rejecting message: "+incoming);
115                             }
116                         }
117                     }
118                 }
119             } catch (Exception e) {
120                 LOG.error("Exception " + e.getClass().getSimpleName() + " caught in DMaaP listener");
121                 LOG.error(EELFResourceManager.format(e));
122                 LOG.error("DMaaP Listener logging and ignoring the exception, continue...");
123             }
124         }
125
126         LOG.info("Stopping DMaaP Listener thread");
127
128         // We've told the listener to stop
129         // TODO - Should we:
130         // 1) Put a message back on the queue indicating that APP-C never got to
131         // the message
132         // or
133         // 2) Let downstream figure it out after timeout between PENDING and
134         // ACTIVE messages
135     }
136
137     private boolean isValid(DmaapIncomingMessage incoming) {
138         return ((incoming != null) &&
139                 incoming.getBody() != null
140                 && !StringUtils.isEmpty(incoming.getRpcName()));
141     }
142
143     @Override
144     public String getBenchmark() {
145         long time = System.currentTimeMillis();
146         DateFormat df = new SimpleDateFormat("HH:mm:ss");
147         df.setTimeZone(TimeZone.getTimeZone("UTC"));
148         String runningTime = df.format(new Date(time - startTime));
149
150         String out = String.format("Running for %s and completed %d jobs using %d threads.", runningTime,
151                 executor.getCompletedTaskCount(), executor.getPoolSize());
152         LOG.info("***BENCHMARK*** " + out);
153         return out;
154     }
155
156     private String getRequestIdWithSubId(JsonNode event){
157         String requestId = "";
158         try {
159             requestId = Converter.extractRequestIdWithSubId(event);
160         } catch (Exception e) {
161             LOG.error("failed to parse request-id and sub-request-id. Json not in expected format", e);
162         }
163         return requestId;
164     }
165 }