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