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>();
104 * @param servers Bus servers
105 * @param topic Bus Topic to be monitored
106 * @param apiKey Bus API Key (optional)
107 * @param apiSecret Bus API Secret (optional)
108 * @param consumerGroup Bus Reader Consumer Group
109 * @param consumerInstance Bus Reader Instance
110 * @param fetchTimeout Bus fetch timeout
111 * @param fetchLimit Bus fetch limit
112 * @param useHttps does the bus use https
113 * @param allowSelfSignedCerts are self-signed certificates allowed
114 * @throws IllegalArgumentException An invalid parameter passed in
116 public SingleThreadedBusTopicSource(List<String> servers,
120 String consumerGroup,
121 String consumerInstance,
125 boolean allowSelfSignedCerts)
126 throws IllegalArgumentException {
128 super(servers, topic, apiKey, apiSecret, useHttps, allowSelfSignedCerts);
130 if (consumerGroup == null || consumerGroup.isEmpty()) {
131 this.consumerGroup = UUID.randomUUID ().toString();
133 this.consumerGroup = consumerGroup;
136 if (consumerInstance == null || consumerInstance.isEmpty()) {
137 this.consumerInstance = DEFAULT_CONSUMER_INSTANCE;
139 this.consumerInstance = consumerInstance;
142 if (fetchTimeout <= 0) {
143 this.fetchTimeout = NO_TIMEOUT_MS_FETCH;
145 this.fetchTimeout = fetchTimeout;
148 if (fetchLimit <= 0) {
149 this.fetchLimit = NO_LIMIT_FETCH;
151 this.fetchLimit = fetchLimit;
157 * Initialize the Bus client
159 public abstract void init() throws Exception;
165 public void register(TopicListener topicListener)
166 throws IllegalArgumentException {
168 PolicyLogger.info(className,"REGISTER: " + topicListener + " INTO " + this);
171 if (topicListener == null)
172 throw new IllegalArgumentException("TopicListener must be provided");
174 /* check that this listener is not registered already */
175 for (TopicListener listener: this.topicListeners) {
176 if (listener == topicListener) {
177 // already registered
182 this.topicListeners.add(topicListener);
187 } catch (Exception e) {
188 PolicyLogger.info(className, "new registration of " + topicListener +
189 ",but can't start source because of " + e.getMessage());
197 public void unregister(TopicListener topicListener) {
199 PolicyLogger.info(className, "UNREGISTER: " + topicListener + " FROM " + this);
201 boolean stop = false;
202 synchronized (this) {
203 if (topicListener == null)
204 throw new IllegalArgumentException("TopicListener must be provided");
206 this.topicListeners.remove(topicListener);
207 stop = (this.topicListeners.isEmpty());
219 public boolean lock() {
220 PolicyLogger.info(className, "LOCK: " + this);
222 synchronized (this) {
236 public boolean unlock() {
237 PolicyLogger.info(className, "UNLOCK: " + this);
248 } catch (Exception e) {
249 PolicyLogger.warn("can't start after unlocking " + this +
250 " because of " + e.getMessage());
259 public boolean start() throws IllegalStateException {
261 PolicyLogger.info(className, "START: " + this);
270 throw new IllegalStateException(this + " is locked.");
273 if (this.busPollerThread == null ||
274 !this.busPollerThread.isAlive() ||
275 this.consumer == null) {
280 this.busPollerThread = new Thread(this);
281 this.busPollerThread.setName(this.getTopicCommInfrastructure() + "-source-" + this.getTopic());
282 busPollerThread.start();
283 } catch (Exception e) {
285 throw new IllegalStateException(e);
297 public boolean stop() {
298 PolicyLogger.info(className, "STOP: " + this);
301 BusConsumer consumerCopy = this.consumer;
304 this.consumer = null;
306 if (consumerCopy != null) {
308 consumerCopy.close();
309 } catch (Exception e) {
310 PolicyLogger.warn(MessageCodes.EXCEPTION_ERROR, e, "CONSUMER.CLOSE", this.toString());
324 public boolean isLocked() {
329 * broadcast event to all listeners
331 * @param message the event
332 * @return true if all notifications are performed with no error, false otherwise
334 protected boolean broadcast(String message) {
336 /* take a snapshot of listeners */
337 List<TopicListener> snapshotListeners = this.snapshotTopicListeners();
339 boolean success = true;
340 for (TopicListener topicListener: snapshotListeners) {
342 topicListener.onTopicEvent(this.getTopicCommInfrastructure(), this.topic, message);
343 } catch (Exception e) {
344 PolicyLogger.warn(this.className, "ERROR notifying " + topicListener.toString() +
345 " because of " + e.getMessage() + " @ " + this.toString());
353 * take a snapshot of current topic listeners
355 * @return the topic listeners
357 protected synchronized List<TopicListener> snapshotTopicListeners() {
358 @SuppressWarnings("unchecked")
359 List<TopicListener> listeners = (List<TopicListener>) topicListeners.clone();
364 * Run thread method for the Bus Reader
370 for (String event: this.consumer.fetch()) {
371 synchronized (this) {
372 this.recentEvents.add(event);
375 if (networkLogger.isInfoEnabled()) {
376 networkLogger.info("IN[" + this.getTopicCommInfrastructure() + "|" +
381 PolicyLogger.info(className, this.topic + " <-- " + event);
387 } catch (Exception e) {
388 PolicyLogger.error( MessageCodes.EXCEPTION_ERROR, className, e, "CONSUMER.FETCH", this.toString());
392 PolicyLogger.warn(this.className, "Exiting: " + this);
399 public boolean offer(String event) {
400 PolicyLogger.info(className, "OFFER: " + event + " TO " + this);
403 throw new IllegalStateException(this + " is not alive.");
406 synchronized (this) {
407 this.recentEvents.add(event);
410 if (networkLogger.isInfoEnabled()) {
411 networkLogger.info("IN[" + this.getTopicCommInfrastructure() + "|" +
417 return broadcast(event);
422 public String toString() {
423 StringBuilder builder = new StringBuilder();
424 builder.append("SingleThreadedBusTopicSource [consumerGroup=").append(consumerGroup)
425 .append(", consumerInstance=").append(consumerInstance).append(", fetchTimeout=").append(fetchTimeout)
426 .append(", fetchLimit=").append(fetchLimit)
427 .append(", consumer=").append(this.consumer).append(", alive=")
428 .append(alive).append(", locked=").append(locked).append(", uebThread=").append(busPollerThread)
429 .append(", topicListeners=").append(topicListeners.size()).append(", toString()=").append(super.toString())
431 return builder.toString();
438 public boolean isAlive() {
446 public String getConsumerGroup() {
447 return consumerGroup;
454 public String getConsumerInstance() {
455 return consumerInstance;
462 public void shutdown() throws IllegalStateException {
464 this.topicListeners.clear();
471 public int getFetchTimeout() {
479 public int getFetchLimit() {