2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.service.engine.event;
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.HashMap;
25 import java.util.HashSet;
27 import java.util.Map.Entry;
30 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
31 import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
36 * This class holds a cache of the synchronous events sent into Apex and that have not yet been replied to. It runs a thread to time out events that have not
37 * been replied to in the specified timeout.
39 * @author Liam Fallon (liam.fallon@ericsson.com)
41 public class SynchronousEventCache extends PeeredReference implements Runnable {
42 // Get a reference to the logger
43 private static final XLogger LOGGER = XLoggerFactory.getXLogger(SynchronousEventCache.class);
45 // The default amount of time to wait for a synchronous event to be replied to is 1 second
46 private static final long DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT = 1000;
48 // The timeout to wait between event polls in milliseconds and the time to wait for the thread to stop
49 private static final long OUTSTANDING_EVENT_POLL_TIMEOUT = 50;
50 private static final long CACHE_STOP_WAIT_INTERVAL = 10;
52 // The time in milliseconds to wait for the reply to a sent synchronous event
53 private long synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT;
55 // Map holding outstanding synchronous events
56 private final Map<Long, SimpleEntry<Long, Object>> toApexEventMap = new HashMap<Long, SimpleEntry<Long, Object>>();
58 // Map holding reply events
59 private final Map<Long, SimpleEntry<Long, Object>> fromApexEventMap = new HashMap<Long, SimpleEntry<Long, Object>>();
61 // The message listener thread and stopping flag
62 private final Thread synchronousEventCacheThread;
63 private boolean stopOrderedFlag = false;
66 * Create a synchronous event cache that caches outstanding synchronous Apex events.
68 * @param peeredMode the peered mode for which to return the reference
69 * @param consumer the consumer that is populating the cache
70 * @param producer the producer that is emptying the cache
71 * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent synchronous event
73 public SynchronousEventCache(final EventHandlerPeeredMode peeredMode, final ApexEventConsumer consumer, final ApexEventProducer producer, final long synchronousEventTimeout) {
74 super(peeredMode, consumer, producer);
76 if (synchronousEventTimeout != 0) {
77 this.synchronousEventTimeout = synchronousEventTimeout;
80 this.synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT;
83 // Start scanning the outstanding events
84 synchronousEventCacheThread = new Thread(this);
85 synchronousEventCacheThread.setDaemon(true);
86 synchronousEventCacheThread.start();
90 * Gets the timeout value for synchronous events.
92 * @return the synchronous event timeout
94 public long getSynchronousEventTimeout() {
95 return synchronousEventTimeout;
99 * Cache a synchronized event sent into Apex in the event cache.
101 * @param executionId the execution ID that was assigned to the event
102 * @param event the apex event
104 public void cacheSynchronizedEventToApex(final long executionId, final Object event) {
105 // Add the event to the map
106 synchronized (toApexEventMap) {
107 cacheSynchronizedEvent(toApexEventMap, executionId, event);
112 * Remove the record of an event sent to Apex if it exists in the cache.
114 * @param executionId the execution ID of the event
115 * @return The removed event
117 public Object removeCachedEventToApexIfExists(final long executionId) {
118 synchronized (toApexEventMap) {
119 return removeCachedEventIfExists(toApexEventMap, executionId);
124 * Check if an event exists in the to apex cache.
126 * @param executionId the execution ID of the event
127 * @return true if the event exists, false otherwise
129 public boolean existsEventToApex(final long executionId) {
130 synchronized (toApexEventMap) {
131 return toApexEventMap.containsKey(executionId);
136 * Cache synchronized event received from Apex in the event cache.
138 * @param executionId the execution ID of the event
139 * @param event the apex event
141 public void cacheSynchronizedEventFromApex(final long executionId, final Object event) {
142 // Add the event to the map
143 synchronized (fromApexEventMap) {
144 cacheSynchronizedEvent(fromApexEventMap, executionId, event);
149 * Remove the record of an event received from Apex if it exists in the cache.
151 * @param executionId the execution ID of the event
152 * @return The removed event
154 public Object removeCachedEventFromApexIfExists(final long executionId) {
155 synchronized (fromApexEventMap) {
156 return removeCachedEventIfExists(fromApexEventMap, executionId);
161 * Check if an event exists in the from apex cache.
163 * @param executionId the execution ID of the event
164 * @return true if the event exists, false otherwise
166 public boolean existsEventFromApex(final long executionId) {
167 synchronized (fromApexEventMap) {
168 return fromApexEventMap.containsKey(executionId);
175 * @see java.lang.Runnable#run()
181 // Periodic scan of outstanding events
182 while (synchronousEventCacheThread.isAlive() && !stopOrderedFlag) {
183 ThreadUtilities.sleep(OUTSTANDING_EVENT_POLL_TIMEOUT);
185 // Check for timeouts on events
186 synchronized (toApexEventMap) {
187 timeoutEventsOnCache(toApexEventMap);
189 synchronized (fromApexEventMap) {
190 timeoutEventsOnCache(fromApexEventMap);
198 * Stops the scanning thread and clears the cache.
200 public synchronized void stop() {
202 stopOrderedFlag = true;
204 while (synchronousEventCacheThread.isAlive()) {
205 ThreadUtilities.sleep(CACHE_STOP_WAIT_INTERVAL);
208 // Check if there are any unprocessed events
209 if (!toApexEventMap.isEmpty()) {
210 LOGGER.warn(toApexEventMap.size() + " synchronous events dropped due to system shutdown");
213 toApexEventMap.clear();
218 * Cache a synchronized event sent in an event cache.
219 * @param eventCacheMap the map to cache the event on
220 * @param executionId the execution ID of the event
221 * @param event the event to cache
223 private void cacheSynchronizedEvent(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap, final long executionId, final Object event) {
224 LOGGER.entry("Adding event with execution ID: " + executionId);
226 // Check if the event is already in the cache
227 if (eventCacheMap.containsKey(executionId)) {
228 // If there was no sent event then the event timed out or some unexpected event was received
229 final String errorMessage = "an event with ID " + executionId
230 + " already exists in the synchronous event cache, execution IDs must be unique in the system";
231 LOGGER.warn(errorMessage);
232 throw new ApexEventRuntimeException(errorMessage);
235 // Add the event to the map
236 eventCacheMap.put(executionId, new SimpleEntry<Long, Object>(System.currentTimeMillis(), event));
238 if (LOGGER.isDebugEnabled()) {
239 LOGGER.debug("event has been cached:" + event);
242 LOGGER.exit("Added: " + executionId);
246 * Remove the record of an event if it exists in the cache.
248 * @param eventCacheMap the map to remove the event from
249 * @param executionId the execution ID of the event
250 * @return The removed event
252 private Object removeCachedEventIfExists(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap, final long executionId) {
253 LOGGER.entry("Removing: " + executionId);
255 final SimpleEntry<Long, Object> removedEventEntry = eventCacheMap.remove(executionId);
257 if (removedEventEntry != null) {
258 LOGGER.exit("Removed: " + executionId);
259 return removedEventEntry.getValue();
262 // The event may not be one of the events in our cache, so we just ignore removal failures
268 * Time out events on an event cache map. Events that have a timeout longer than the configured timeout are timed out.
269 * @param eventCacheMap the event cache to operate on
271 private void timeoutEventsOnCache(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap) {
272 // Use a set to keep track of the events that have timed out
273 final Set<Long> timedOutEventSet = new HashSet<>();
275 for (final Entry<Long, SimpleEntry<Long, Object>> cachedEventEntry : eventCacheMap.entrySet()) {
276 // The amount of time we are waiting for the event reply
277 final long eventWaitTime = System.currentTimeMillis() - cachedEventEntry.getValue().getKey();
279 // Have we a timeout?
280 if (eventWaitTime > synchronousEventTimeout) {
281 timedOutEventSet.add(cachedEventEntry.getKey());
285 // Remove timed out events from the map
286 for (final long timedoutEventExecutionID : timedOutEventSet) {
287 // Remove the map entry and issue a warning
288 final SimpleEntry<Long, Object> timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionID);
290 LOGGER.warn("synchronous event timed out, reply not received in " + synchronousEventTimeout + " milliseconds on event "
291 + timedOutEventEntry.getValue());