c7a298039bebe14f65222d31383a840d5655ba39
[appc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.listener;
24
25 import java.security.SecureRandom;
26 import java.util.concurrent.ArrayBlockingQueue;
27 import java.util.concurrent.BlockingQueue;
28 import java.util.concurrent.RejectedExecutionHandler;
29 import java.util.concurrent.ThreadPoolExecutor;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicBoolean;
32
33 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
34 import org.openecomp.appc.listener.impl.EventHandlerImpl;
35
36 import com.att.eelf.configuration.EELFLogger;
37 import com.att.eelf.configuration.EELFManager;
38
39 public abstract class AbstractListener implements Listener {
40
41     private final EELFLogger LOG = EELFManager.getInstance().getLogger(AbstractListener.class);
42
43     protected AtomicBoolean run = new AtomicBoolean(false);
44
45     protected int QUEUED_MIN = 1;
46     protected int QUEUED_MAX = 10;
47
48     protected int THREAD_MIN = 4;
49     protected int THREAD_MAX = THREAD_MIN; // Fixed thread pool
50     protected int THREAD_SCALE_DOWN_SEC = 10; // Number of seconds to wait until we remove idle threads
51
52     protected ThreadPoolExecutor executor;
53
54     protected EventHandler dmaap;
55
56     protected ListenerProperties props;
57
58     private String listenerId;
59
60     public AbstractListener(ListenerProperties props) {
61         updateProperties(props);
62
63         dmaap = new EventHandlerImpl(props);
64         if (dmaap.getClientId().equals("0")) {
65                 dmaap.setClientId(String.valueOf(new SecureRandom().nextInt(1000)));
66         }
67
68         BlockingQueue<Runnable> threadQueue = new ArrayBlockingQueue<Runnable>(QUEUED_MAX + QUEUED_MIN + 1);
69         executor = new ThreadPoolExecutor(THREAD_MIN, THREAD_MAX, THREAD_SCALE_DOWN_SEC, TimeUnit.SECONDS, threadQueue,
70             new JobRejectionHandler());
71
72         // Custom Named thread factory
73         BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("DMaaP-Worker-%d").build();
74         executor.setThreadFactory(threadFactory);
75
76         run.set(true);
77     }
78
79     /**
80      * Starts a loop that will only end after stop() or stopNow() are called. The loop will read messages off the DMaaP
81      * topic and perform some action on them while writing messages back to DMaaP at critical points in the execution.
82      * Inherited from Runnable.
83      * 
84      * @see java.lang.Runnable#run()
85      */
86     @Override
87     public void run() {
88         LOG.error("Listener.run() has not been implemented");
89     }
90
91     @Override
92     public void stop() {
93         run.set(false);
94         LOG.info(String.format("Stopping with %d messages in queue", executor.getQueue().size()));
95         executor.shutdown();
96         try {
97             executor.awaitTermination(10, TimeUnit.SECONDS);
98         } catch (InterruptedException e) {
99             LOG.error("Listener graceful stop() failed", e);
100         }
101         
102         // close DMaaP clients
103         if (dmaap != null) {
104                 dmaap.closeClients();
105         }
106         LOG.info("Listener Thread Pool Finished");
107     }
108
109     @Override
110     public void stopNow() {
111         run.set(false);
112         LOG.info(String.format("StopNow called. Orphaning %d messages in the queue", executor.getQueue().size()));
113         executor.getQueue().clear();
114         stop();
115     }
116
117     @Override
118     public String getBenchmark() {
119         return String.format("%s - No benchmarking implemented.", getListenerId());
120     }
121
122     @Override
123     public String getListenerId() {
124         return listenerId;
125     }
126
127     // Sets the id of the listener in
128     @Override
129     public void setListenerId(String id) {
130         listenerId = id;
131     }
132
133     private void updateProperties(ListenerProperties properties) {
134         this.props = properties;
135         QUEUED_MIN =
136             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_QUEUE, String.valueOf(QUEUED_MIN)));
137         QUEUED_MAX =
138             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_QUEUE, String.valueOf(QUEUED_MAX)));
139         THREAD_MIN =
140             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MIN_POOL, String.valueOf(THREAD_MIN)));
141         THREAD_MAX =
142             Integer.valueOf(props.getProperty(ListenerProperties.KEYS.THREADS_MAX_POOL, String.valueOf(THREAD_MAX)));
143
144         listenerId = props.getPrefix();
145     }
146
147     /**
148      * This class will be used to handle what happens when we cannot add a job because of a ThreadPool issue. It does
149      * not get invoked if there is any fault with the job. NOTE: So far, this has only been seen when doing a
150      * {@link Listener#stopNow}
151      *
152      */
153     class JobRejectionHandler implements RejectedExecutionHandler {
154         @Override
155         public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
156             LOG.error(String.format("A job was rejected. [%s]", r));
157         }
158
159     }
160 }