aboutsummaryrefslogtreecommitdiffstats
path: root/utils-test/src/main/java/org/onap/policy/common/utils/time/TestTimeMulti.java
blob: f52105ed885ea2ee535447b46d52c7fe9830a4bd (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2018-2019 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.common.utils.time;

import static org.junit.Assert.fail;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import org.onap.policy.common.utils.time.TestTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * "Current" time, when running junit tests in multiple threads. This is intended to be
 * injected into classes under test, to replace their {@link CurrentTime} objects. The
 * {@link #sleep(long)} method blocks until the "time" has reached the specified sleep
 * time. A queue of work items is maintained, sorted by the time for which the items are
 * scheduled to execute. Tasks are executed by the test/controlling thread when one of the
 * waitXxx() methods is invoked. {@link PseudoTimer} and
 * {@link PseudoScheduledExecutorService} add work items to the queue.
 *
 * <p/>
 * This only handles relatively simple situations, though it does support multi-threaded
 * testing.
 */
public class TestTimeMulti extends TestTime {
    private static final Logger logger = LoggerFactory.getLogger(TestTimeMulti.class);

    public static final String NEVER_SATISFIED = "condition was never satisfied";

    /**
     * Default value, in milliseconds, to wait for an item to be added to the queue.
     */
    public static final long DEFAULT_MAX_WAIT_MS = 5000L;

    /**
     * Maximum time that the test thread should wait for something to be added to its work
     * queue.
     */
    @Getter
    private final long maxWaitMs;

    /**
     * Queue of timer tasks to be executed, sorted by {@link WorkItem#nextMs}.
     */
    private final PriorityQueue<WorkItem> queue =
                    new PriorityQueue<>((item1, item2) -> Long.compare(item1.getNextMs(), item2.getNextMs()));

    /**
     * Lock used when modifying the queue.
     */
    private final Object updateLock = new Object();

    /**
     * Constructs the object using the default maximum wait time.
     */
    public TestTimeMulti() {
        this(DEFAULT_MAX_WAIT_MS);
    }

    /**
     * Constructs the object.
     *
     * @param maxWaitMs maximum time that the test thread should wait for something to be
     *        added to its work queue
     */
    public TestTimeMulti(long maxWaitMs) {
        this.maxWaitMs = maxWaitMs;
    }

    /**
     * Determines if the task queue is empty.
     *
     * @return {@code true} if the task queue is empty, {@code false} otherwise
     */
    public boolean isEmpty() {
        synchronized (updateLock) {
            purgeItems();
            return queue.isEmpty();
        }
    }

    /**
     * Gets the number of tasks in the work queue.
     *
     * @return the number of tasks in the work queue
     */
    public int queueLength() {
        synchronized (updateLock) {
            purgeItems();
            return queue.size();
        }
    }

    /**
     * Indicates that this will no longer be used. Interrupts any threads that are waiting
     * for their "sleep()" to complete.
     */
    public void destroy() {
        synchronized (updateLock) {
            queue.forEach(WorkItem::interrupt);
            queue.clear();
        }
    }

    /**
     * Runs a single task from the queue.
     *
     * @param waitMs time, in milliseconds, for which to wait. This is "real" time rather
     *        than pseudo time
     *
     * @return {@code true} if a task was run, {@code false} if the queue was empty
     * @throws InterruptedException if the current thread is interrupted
     */
    public boolean runOneTask(long waitMs) throws InterruptedException {
        WorkItem item = pollQueue(waitMs);
        if (item == null) {
            return false;
        }

        runItem(item);
        return true;
    }

    /**
     * Waits for the pseudo time to reach a certain point. Executes work items until the
     * time is reached.
     *
     * @param waitMs pseudo time, in milliseconds, for which to wait
     * @throws InterruptedException if the current thread is interrupted
     */
    public void waitFor(long waitMs) throws InterruptedException {
        // pseudo time for which we're waiting
        long tend = getMillis() + waitMs;

        while (getMillis() < tend) {
            if (!runOneTask(maxWaitMs)) {
                /*
                 * Waited the maximum poll time and nothing has happened, so we'll just
                 * bump the time directly.
                 */
                super.sleep(tend - getMillis());
                break;
            }
        }
    }

    /**
     * Waits for a condition to become true. Executes work items until the given condition
     * is true.
     *
     * @param condition condition to be checked
     */
    public void waitUntil(Callable<Boolean> condition) {
        try {
            // real time for which we're waiting
            long realEnd = System.currentTimeMillis() + maxWaitMs;

            while (System.currentTimeMillis() < realEnd) {
                if (condition.call()) {
                    return;
                }

                runOneTask(100);
            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            logger.error("interrupted while waiting for condition", e);
            fail("interrupted while waiting for condition: " + e.getMessage());

        } catch (Exception e) {
            logger.error("condition evaluator threw an exception", e);
            fail("condition evaluator threw an exception: " + e.getMessage());
        }

        fail(NEVER_SATISFIED);
    }

    /**
     * Waits for a condition to become true. Executes work items until the given condition
     * is true or the maximum wait time is reached.
     *
     * @param twait maximum, pseudo time to wait
     * @param units time units represented by "twait"
     * @param condition condition to be checked
     */
    public void waitUntil(long twait, TimeUnit units, Callable<Boolean> condition) {
        // pseudo time for which we're waiting
        long tend = getMillis() + units.toMillis(twait);

        waitUntil(() -> {
            if (getMillis() >= tend) {
                fail(NEVER_SATISFIED);
            }

            return condition.call();
        });
    }

    /**
     * Gets one item from the work queue.
     *
     * @param waitMs time, in milliseconds, for which to wait. This is "real" time rather
     *        than pseudo time
     * @return the first item in the queue, or {@code null} if no item was added to the
     *         queue before the wait time expired
     * @throws InterruptedException if the current thread was interrupted
     */
    private WorkItem pollQueue(long waitMs) throws InterruptedException {
        long realEnd = System.currentTimeMillis() + waitMs;
        WorkItem work;

        synchronized (updateLock) {
            while ((work = queue.poll()) == null) {
                updateLock.wait(Math.max(1, realEnd - System.currentTimeMillis()));

                if (queue.isEmpty() && System.currentTimeMillis() >= realEnd) {
                    return null;
                }
            }
        }

        return work;
    }

    /**
     * Runs a work item.
     *
     * @param work work item to be run
     * @throws InterruptedException if the current thread was interrupted
     */
    private void runItem(WorkItem work) throws InterruptedException {
        if (work.wasCancelled()) {
            logger.info("work item was canceled {}", work);
            return;
        }

        // update the pseudo time
        super.sleep(work.getNextMs() - getMillis());

        /*
         * Add it back into the queue if appropriate, in case cancel() is called while
         * it's executing.
         */
        if (work.bumpNextTime()) {
            logger.info("re-enqueuing work item");
            enqueue(work);
        }

        logger.info("fire work item {}", work);
        work.fire();
    }

    @Override
    public void sleep(long sleepMs) throws InterruptedException {
        if (sleepMs <= 0) {
            return;
        }

        SleepItem item = new SleepItem(this, sleepMs, Thread.currentThread());
        enqueue(item);

        // wait for the item to fire
        logger.info("sleeping {}", item);
        item.await();
        logger.info("done sleeping {}", Thread.currentThread());
    }

    /**
     * Adds an item to the {@link #queue}.
     *
     * @param item item to be added
     */
    protected void enqueue(WorkItem item) {
        logger.info("enqueue work item {}", item);
        synchronized (updateLock) {
            queue.add(item);
            updateLock.notify();
        }
    }

    /**
     * Cancels work items by removing them from the queue if they're associated with the
     * specified object.
     *
     * @param associate object whose associated items are to be cancelled
     * @return list of items that were canceled
     */
    protected List<WorkItem> cancelItems(Object associate) {
        List<WorkItem> items = new LinkedList<>();

        synchronized (updateLock) {
            Iterator<WorkItem> iter = queue.iterator();
            while (iter.hasNext()) {
                WorkItem item = iter.next();
                if (item.isAssociatedWith(associate)) {
                    iter.remove();
                    items.add(item);
                }
            }
        }

        return items;
    }

    /**
     * Purges work items that are known to have been canceled. (Does not remove canceled
     * TimerTasks, as there is no way via the public API to determine if the task has been
     * canceled.)
     */
    public void purgeItems() {
        synchronized (updateLock) {
            Iterator<WorkItem> iter = queue.iterator();
            while (iter.hasNext()) {
                if (iter.next().wasCancelled()) {
                    iter.remove();
                }
            }
        }
    }
}