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