aboutsummaryrefslogtreecommitdiffstats
path: root/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/event/SynchronousEventCache.java
blob: 5f1dcc9cf42645ebd58df51efa00b50ea34036b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2020 Nordix Foundation.
 *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.service.engine.event;

import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import lombok.Getter;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * 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 been replied to in the specified timeout.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class SynchronousEventCache extends PeeredReference implements Runnable {
    // Get a reference to the logger
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(SynchronousEventCache.class);

    // The default amount of time to wait for a synchronous event to be replied to is 1 second
    private static final long DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT = 1000;

    // The timeout to wait between event polls in milliseconds and the time to wait for the thread
    // to stop
    private static final long OUTSTANDING_EVENT_POLL_TIMEOUT = 50;
    private static final long CACHE_STOP_WAIT_INTERVAL = 10;

    // The time in milliseconds to wait for the reply to a sent synchronous event
    @Getter
    private long synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT;

    // Map holding outstanding synchronous events
    private final Map<Long, SimpleEntry<Long, Object>> toApexEventMap = new HashMap<>();

    // Map holding reply events
    private final Map<Long, SimpleEntry<Long, Object>> fromApexEventMap = new HashMap<>();

    // The message listener thread and stopping flag
    private final Thread synchronousEventCacheThread;
    private boolean stopOrderedFlag = false;

    /**
     * Create a synchronous event cache that caches outstanding synchronous Apex events.
     *
     * @param peeredMode the peered mode for which to return the reference
     * @param consumer the consumer that is populating the cache
     * @param producer the producer that is emptying the cache
     * @param synchronousEventTimeout the time in milliseconds to wait for the reply to a sent synchronous event
     */
    public SynchronousEventCache(final EventHandlerPeeredMode peeredMode, final ApexEventConsumer consumer,
                    final ApexEventProducer producer, final long synchronousEventTimeout) {
        super(peeredMode, consumer, producer);

        if (synchronousEventTimeout != 0) {
            this.synchronousEventTimeout = synchronousEventTimeout;
        } else {
            this.synchronousEventTimeout = DEFAULT_SYNCHRONOUS_EVENT_TIMEOUT;
        }

        // Start scanning the outstanding events
        synchronousEventCacheThread = new Thread(this);
        synchronousEventCacheThread.setDaemon(true);
        synchronousEventCacheThread.start();
    }

    /**
     * Cache a synchronized event sent into Apex in the event cache.
     *
     * @param executionId the execution ID that was assigned to the event
     * @param event the apex event
     */
    public void cacheSynchronizedEventToApex(final long executionId, final Object event) {
        // Add the event to the map
        synchronized (toApexEventMap) {
            cacheSynchronizedEvent(toApexEventMap, executionId, event);
        }
    }

    /**
     * Remove the record of an event sent to Apex if it exists in the cache.
     *
     * @param executionId the execution ID of the event
     * @return The removed event
     */
    public Object removeCachedEventToApexIfExists(final long executionId) {
        synchronized (toApexEventMap) {
            return removeCachedEventIfExists(toApexEventMap, executionId);
        }
    }

    /**
     * Check if an event exists in the to apex cache.
     *
     * @param executionId the execution ID of the event
     * @return true if the event exists, false otherwise
     */
    public boolean existsEventToApex(final long executionId) {
        synchronized (toApexEventMap) {
            return toApexEventMap.containsKey(executionId);
        }
    }

    /**
     * Cache synchronized event received from Apex in the event cache.
     *
     * @param executionId the execution ID of the event
     * @param event the apex event
     */
    public void cacheSynchronizedEventFromApex(final long executionId, final Object event) {
        // Add the event to the map
        synchronized (fromApexEventMap) {
            cacheSynchronizedEvent(fromApexEventMap, executionId, event);
        }
    }

    /**
     * Remove the record of an event received from Apex if it exists in the cache.
     *
     * @param executionId the execution ID of the event
     * @return The removed event
     */
    public Object removeCachedEventFromApexIfExists(final long executionId) {
        synchronized (fromApexEventMap) {
            return removeCachedEventIfExists(fromApexEventMap, executionId);
        }
    }

    /**
     * Check if an event exists in the from apex cache.
     *
     * @param executionId the execution ID of the event
     * @return true if the event exists, false otherwise
     */
    public boolean existsEventFromApex(final long executionId) {
        synchronized (fromApexEventMap) {
            return fromApexEventMap.containsKey(executionId);
        }
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void run() {
        LOGGER.entry();

        // Periodic scan of outstanding events
        while (synchronousEventCacheThread.isAlive() && !stopOrderedFlag) {
            ThreadUtilities.sleep(OUTSTANDING_EVENT_POLL_TIMEOUT);

            // Check for timeouts on events
            synchronized (toApexEventMap) {
                timeoutEventsOnCache(toApexEventMap);
            }
            synchronized (fromApexEventMap) {
                timeoutEventsOnCache(fromApexEventMap);
            }
        }

        LOGGER.exit();
    }

    /**
     * Stops the scanning thread and clears the cache.
     */
    public synchronized void stop() {
        LOGGER.entry();
        stopOrderedFlag = true;

        while (synchronousEventCacheThread.isAlive()) {
            ThreadUtilities.sleep(CACHE_STOP_WAIT_INTERVAL);
        }

        // Check if there are any unprocessed events
        if (!toApexEventMap.isEmpty()) {
            String message = toApexEventMap.size() + " synchronous events dropped due to system shutdown";
            LOGGER.warn(message);
        }

        toApexEventMap.clear();
        LOGGER.exit();
    }

    /**
     * Cache a synchronized event sent in an event cache.
     *
     * @param eventCacheMap the map to cache the event on
     * @param executionId the execution ID of the event
     * @param event the event to cache
     */
    private void cacheSynchronizedEvent(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap,
                    final long executionId, final Object event) {
        LOGGER.entry("Adding event with execution ID: " + executionId);

        // Check if the event is already in the cache
        if (eventCacheMap.containsKey(executionId)) {
            // If there was no sent event then the event timed out or some unexpected event was
            // received
            final String errorMessage = "an event with ID " + executionId
                            + " already exists in the synchronous event cache, "
                            + "execution IDs must be unique in the system";
            LOGGER.warn(errorMessage);
            throw new ApexEventRuntimeException(errorMessage);
        }

        // Add the event to the map
        eventCacheMap.put(executionId, new SimpleEntry<>(System.currentTimeMillis(), event));

        if (LOGGER.isDebugEnabled()) {
            String message = "event has been cached:" + event;
            LOGGER.debug(message);
        }

        LOGGER.exit("Added: " + executionId);
    }

    /**
     * Remove the record of an event if it exists in the cache.
     *
     * @param eventCacheMap the map to remove the event from
     * @param executionId the execution ID of the event
     * @return The removed event
     */
    private Object removeCachedEventIfExists(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap,
                    final long executionId) {
        LOGGER.entry("Removing: " + executionId);

        final SimpleEntry<Long, Object> removedEventEntry = eventCacheMap.remove(executionId);

        if (removedEventEntry != null) {
            LOGGER.exit("Removed: " + executionId);
            return removedEventEntry.getValue();
        } else {
            // The event may not be one of the events in our cache, so we just ignore removal
            // failures
            return null;
        }
    }

    /**
     * Time out events on an event cache map. Events that have a timeout longer than the configured timeout are timed
     * out.
     *
     * @param eventCacheMap the event cache to operate on
     */
    private void timeoutEventsOnCache(final Map<Long, SimpleEntry<Long, Object>> eventCacheMap) {
        // Use a set to keep track of the events that have timed out
        final Set<Long> timedOutEventSet = new HashSet<>();

        for (final Entry<Long, SimpleEntry<Long, Object>> cachedEventEntry : eventCacheMap.entrySet()) {
            // The amount of time we are waiting for the event reply
            final long eventWaitTime = System.currentTimeMillis() - cachedEventEntry.getValue().getKey();

            // Have we a timeout?
            if (eventWaitTime > synchronousEventTimeout) {
                timedOutEventSet.add(cachedEventEntry.getKey());
            }
        }

        // Remove timed out events from the map
        for (final long timedoutEventExecutionId : timedOutEventSet) {
            // Remove the map entry and issue a warning
            final SimpleEntry<Long, Object> timedOutEventEntry = eventCacheMap.remove(timedoutEventExecutionId);

            String message = "synchronous event timed out, reply not received in " + synchronousEventTimeout
                            + " milliseconds on event " + timedOutEventEntry.getValue();
            LOGGER.warn(message);
        }
    }
}