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