2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.policy.drools.event.comm.bus.internal;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.UUID;
27 import org.apache.log4j.Logger;
29 import org.openecomp.policy.drools.event.comm.TopicListener;
30 import org.openecomp.policy.drools.event.comm.bus.BusTopicSource;
31 import org.openecomp.policy.common.logging.eelf.MessageCodes;
32 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
35 * This topic source implementation specializes in reading messages
36 * over a bus topic source and notifying its listeners
38 public abstract class SingleThreadedBusTopicSource
40 implements Runnable, BusTopicSource {
42 private String className = SingleThreadedBusTopicSource.class.getName();
44 * Not to be converted to PolicyLogger.
45 * This will contain all instract /out traffic and only that in a single file in a concise format.
47 protected static final Logger networkLogger = Logger.getLogger(NETWORK_LOGGER);
52 protected final String consumerGroup;
55 * Bus consumer instance
57 protected final String consumerInstance;
62 protected final int fetchTimeout;
67 protected final int fetchLimit;
70 * Message Bus Consumer
72 protected BusConsumer consumer;
76 * reflects invocation of start()/stop()
77 * !locked & start() => alive
80 protected volatile boolean alive = false;
84 * reflects invocation of lock()/unlock() operations
85 * locked => !alive (but not in the other direction necessarily)
86 * locked => !offer, !run, !start, !stop (but this last one is obvious
87 * since locked => !alive)
89 protected volatile boolean locked = false;
92 * Independent thread reading message over my topic
94 protected Thread busPollerThread;
97 * All my subscribers for new message notifications
99 protected final ArrayList<TopicListener> topicListeners = new ArrayList<TopicListener>();
103 * @param servers Bus servers
104 * @param topic Bus Topic to be monitored
105 * @param apiKey Bus API Key (optional)
106 * @param apiSecret Bus API Secret (optional)
107 * @param consumerGroup Bus Reader Consumer Group
108 * @param consumerInstance Bus Reader Instance
109 * @param fetchTimeout Bus fetch timeout
110 * @param fetchLimit Bus fetch limit
111 * @throws IllegalArgumentException An invalid parameter passed in
113 public SingleThreadedBusTopicSource(List<String> servers,
117 String consumerGroup,
118 String consumerInstance,
121 throws IllegalArgumentException {
123 super(servers, topic, apiKey, apiSecret);
125 if (consumerGroup == null || consumerGroup.isEmpty()) {
126 this.consumerGroup = UUID.randomUUID ().toString();
128 this.consumerGroup = consumerGroup;
131 if (consumerInstance == null || consumerInstance.isEmpty()) {
132 this.consumerInstance = DEFAULT_CONSUMER_INSTANCE;
134 this.consumerInstance = consumerInstance;
137 if (fetchTimeout <= 0) {
138 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
140 this.fetchTimeout = fetchTimeout;
143 if (fetchLimit <= 0) {
144 this.fetchLimit = NO_LIMIT_FETCH;
146 this.fetchLimit = fetchLimit;
151 * Initialize the Bus client
153 public abstract void init() throws Exception;
159 public void register(TopicListener topicListener)
160 throws IllegalArgumentException {
162 PolicyLogger.info(className,"REGISTER: " + topicListener + " INTO " + this);
165 if (topicListener == null)
166 throw new IllegalArgumentException("TopicListener must be provided");
168 /* check that this listener is not registered already */
169 for (TopicListener listener: this.topicListeners) {
170 if (listener == topicListener) {
171 // already registered
176 this.topicListeners.add(topicListener);
181 } catch (Exception e) {
182 PolicyLogger.info(className, "new registration of " + topicListener +
183 ",but can't start source because of " + e.getMessage());
191 public void unregister(TopicListener topicListener) {
193 PolicyLogger.info(className, "UNREGISTER: " + topicListener + " FROM " + this);
195 boolean stop = false;
196 synchronized (this) {
197 if (topicListener == null)
198 throw new IllegalArgumentException("TopicListener must be provided");
200 this.topicListeners.remove(topicListener);
201 stop = (this.topicListeners.isEmpty());
213 public boolean lock() {
214 PolicyLogger.info(className, "LOCK: " + this);
216 synchronized (this) {
230 public boolean unlock() {
231 PolicyLogger.info(className, "UNLOCK: " + this);
242 } catch (Exception e) {
243 PolicyLogger.warn("can't start after unlocking " + this +
244 " because of " + e.getMessage());
253 public boolean start() throws IllegalStateException {
255 PolicyLogger.info(className, "START: " + this);
264 throw new IllegalStateException(this + " is locked.");
267 if (this.busPollerThread == null ||
268 !this.busPollerThread.isAlive() ||
269 this.consumer == null) {
274 this.busPollerThread = new Thread(this);
275 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
276 busPollerThread.start();
277 } catch (Exception e) {
279 throw new IllegalStateException(e);
291 public boolean stop() {
292 PolicyLogger.info(className, "STOP: " + this);
295 BusConsumer consumerCopy = this.consumer;
298 this.consumer = null;
300 if (consumerCopy != null) {
302 consumerCopy.close();
303 } catch (Exception e) {
304 PolicyLogger.warn(MessageCodes.EXCEPTION_ERROR, e, "CONSUMER.CLOSE", this.toString());
318 public boolean isLocked() {
323 * broadcast event to all listeners
325 * @param message the event
326 * @return true if all notifications are performed with no error, false otherwise
328 protected boolean broadcast(String message) {
330 /* take a snapshot of listeners */
331 List<TopicListener> snapshotListeners = this.snapshotTopicListeners();
333 boolean success = true;
334 for (TopicListener topicListener: snapshotListeners) {
336 topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message);
337 } catch (Exception e) {
338 PolicyLogger.warn(this.className, "ERROR notifying " + topicListener.toString() +
339 " because of " + e.getMessage() + " @ " + this.toString());
347 * take a snapshot of current topic listeners
349 * @return the topic listeners
351 protected synchronized List<TopicListener> snapshotTopicListeners() {
352 @SuppressWarnings("unchecked")
353 List<TopicListener> listeners = (List<TopicListener>) topicListeners.clone();
358 * Run thread method for the Bus Reader
364 for (String event: this.consumer.fetch()) {
365 synchronized (this) {
366 this.recentEvents.add(event);
369 if (networkLogger.isInfoEnabled()) {
370 networkLogger.info("IN[" + this.getTopicCommInfrastructure() + "|" +
375 PolicyLogger.info(className, this.topic + " <-- " + event);
381 } catch (Exception e) {
382 PolicyLogger.error( MessageCodes.EXCEPTION_ERROR, className, e, "CONSUMER.FETCH", this.toString());
386 PolicyLogger.warn(this.className, "Exiting: " + this);
393 public boolean offer(String event) {
394 PolicyLogger.info(className, "OFFER: " + event + " TO " + this);
397 throw new IllegalStateException(this + " is not alive.");
400 synchronized (this) {
401 this.recentEvents.add(event);
404 if (networkLogger.isInfoEnabled()) {
405 networkLogger.info("IN[" + this.getTopicCommInfrastructure() + "|" +
411 return broadcast(event);
416 public String toString() {
417 StringBuilder builder = new StringBuilder();
418 builder.append("SingleThreadedBusTopicSource [consumerGroup=").append(consumerGroup)
419 .append(", consumerInstance=").append(consumerInstance).append(", fetchTimeout=").append(fetchTimeout)
420 .append(", fetchLimit=").append(fetchLimit)
421 .append(", consumer=").append(this.consumer).append(", alive=")
422 .append(alive).append(", locked=").append(locked).append(", uebThread=").append(busPollerThread)
423 .append(", topicListeners=").append(topicListeners.size()).append(", toString()=").append(super.toString())
425 return builder.toString();
432 public boolean isAlive() {
440 public String getConsumerGroup() {
441 return consumerGroup;
448 public String getConsumerInstance() {
449 return consumerInstance;
456 public void shutdown() throws IllegalStateException {
458 this.topicListeners.clear();
465 public int getFetchTimeout() {
473 public int getFetchLimit() {