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