aboutsummaryrefslogtreecommitdiffstats
path: root/appc-oam/appc-oam-bundle/src/main/java/org/openecomp/appc/oam/util/AsyncTaskHelper.java
blob: 0a4b868a820908bc1a83029ba3e247a324f4c909 (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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*-
 * ============LICENSE_START=======================================================
 * ONAP : APPC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Copyright (C) 2017 Amdocs
 * =============================================================================
 * 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.
 * 
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.appc.oam.util;

import com.att.eelf.configuration.EELFLogger;
import org.openecomp.appc.oam.AppcOam;
import org.openecomp.appc.oam.processor.BaseActionRunnable;
import org.openecomp.appc.statemachine.impl.readers.AppcOamStates;
import org.osgi.framework.Bundle;
import org.osgi.framework.FrameworkUtil;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

/**
 * The AsyncTaskHelper class manages an internal parent child data structure.   The parent is a transient singleton,
 * meaning only one can exist at any given time.     The parent is scheduled with the
 * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and is executed at configured interval.   It can be
 * terminated by using the {@link Future#cancel(boolean)} or the {@link Future#cancel(boolean)} returned from \
 * {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)}.
 * <p>
 * The children are scheduled using {@link #submitBaseSubCallable(Callable)}} and can only be scheduled if a parent
 * is scheduled.   Children only execute once, but can be terminated preemptively by the {@link Future#cancel(boolean)}
 * returned from {@link #submitBaseSubCallable(Callable)} or indirectly by terminating the parent via the method
 * described above.
 * <p>
 * This class augments the meaning of {@link Future#isDone()} in that it guarantees that this method only returns true
 * if the scheduled {@link Runnable} or {@link Callable}  is not currently executing and is not going to execute in the
 * future.   This is different than the Java core implementation of {@link Future#isDone()} in which it will return
 * true immediately after the {@link Future#cancel(boolean)} is called. Even if a Thread is actively executing the
 * {@link Runnable} or {@link Callable} and has not return yet. See Java BUG JDK-8073704
 * <p>
 * The parent {@link Future#isDone()} has an additional augmentation in that it will not return true until all of its
 * children's {@link Future#isDone()} also return true.
 *
 */
@SuppressWarnings("unchecked")
public class AsyncTaskHelper {

    private final EELFLogger logger;
    private final ScheduledExecutorService scheduledExecutorService;
    private final ThreadPoolExecutor bundleOperationService;

    /** Reference to {@link MyFuture} return from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} */
    private MyFuture backgroundBaseRunnableFuture;

    /** The cancel Callback from {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)}   */
    private Consumer<AppcOam.RPC> cancelCallBackForBaseRunnable;

    /** All Futures created by thus calls which have not completed -- {@link Future#isDone()} equals false  */
    private Set<MyFuture> myFutureSet = new HashSet<>();

    /**
     * Constructor
     * @param eelfLogger of the logger
     */
    public AsyncTaskHelper(EELFLogger eelfLogger) {
        logger = eelfLogger;

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
            (runnable) -> {
                Bundle bundle = FrameworkUtil.getBundle(AppcOam.class);
                return new Thread(runnable, bundle.getSymbolicName() + " scheduledExecutor");
            }
        );

        bundleOperationService = new ThreadPoolExecutor(
            0,
            10,
            10,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue(), //BlockingQueue<Runnable> workQueue
            (runnable) -> {
                Bundle bundle = FrameworkUtil.getBundle(AppcOam.class);
                return new Thread(runnable, bundle.getSymbolicName() + " bundle operation executor");
            }
        );
    }

    /**
     * Terminate the class <bS>ScheduledExecutorService</b>
     */
    public void close() {
        logDebug("Start shutdown scheduleExcutorService.");
        bundleOperationService.shutdownNow();
        scheduledExecutorService.shutdownNow();
        logDebug("Completed shutdown scheduleExcutorService.");
    }


    /**
     * Cancel currently executing {@link BaseActionRunnable} if any.
     * This method returns immediately if there is currently no {@link BaseActionRunnable} actively executing.
     * @param rpcCausingAbort - The RPC causing the abort
     * @param stateBeingAbborted - The current state being canceled
     * @param timeout - The amount of time to wait for a cancel to complete
     * @param timeUnit - The unit of time of timeout
     * @throws TimeoutException - If {@link BaseActionRunnable} has not completely cancelled within the timeout period
     * @throws InterruptedException - If the Thread waiting for the abort
     */
    public synchronized void cancelBaseActionRunnable(final AppcOam.RPC rpcCausingAbort,
                                                      AppcOamStates stateBeingAbborted,
                                                      long timeout, TimeUnit timeUnit)
        throws TimeoutException,InterruptedException {

        final MyFuture localBackgroundBaseRunnableFuture = backgroundBaseRunnableFuture;
        final Consumer<AppcOam.RPC> localCancelCallBackForBaseRunnable = cancelCallBackForBaseRunnable;

        if (localBackgroundBaseRunnableFuture == null || localBackgroundBaseRunnableFuture.isDone()) {
          return;
        }

        if (localCancelCallBackForBaseRunnable != null) {
            localCancelCallBackForBaseRunnable.accept(rpcCausingAbort);
        }
        localBackgroundBaseRunnableFuture.cancel(true);

        long timeoutMillis = timeUnit.toMillis(timeout);
        long expiryTime = System.currentTimeMillis() + timeoutMillis;
        while (!(localBackgroundBaseRunnableFuture.isDone())) {
            long sleepTime = expiryTime - System.currentTimeMillis();
            if (sleepTime < 1) {
                break;
            }
            this.wait(sleepTime);
        }

        if (!localBackgroundBaseRunnableFuture.isDone()) {
            throw new TimeoutException(String.format("Unable to abort %s in timely manner.",stateBeingAbborted));
        }
    }

    /**
     * Schedule a {@link BaseActionRunnable} to begin async execution.   This is the Parent  {@link Runnable} for the
     * children that are submitted by {@link #submitBaseSubCallable(Callable)}
     *
     * The currently executing {@link BaseActionRunnable} must fully be terminated before the next can be scheduled.
     * This means all Tasks' {@link MyFuture#isDone()} must equal true and all threads must return to their respective
     * thread pools.
     *
     * @param runnable of the to be scheduled service.
     * @param cancelCallBack to be invoked when
     *        {@link #cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)} is invoked.
     * @param initialDelayMillis the time to delay first execution
     * @param delayMillis the delay between the termination of one
     * execution and the commencement of the next
     * @return The {@link BaseActionRunnable}'s {@link Future}
     * @throws IllegalStateException if there is currently executing Task
     */
    public synchronized Future<?> scheduleBaseRunnable(final Runnable runnable,
                                                       final Consumer<AppcOam.RPC> cancelCallBack,
                                                       long initialDelayMillis,
                                                       long delayMillis)
        throws IllegalStateException {

        if (backgroundBaseRunnableFuture != null && !backgroundBaseRunnableFuture.isDone()) {
            throw new IllegalStateException("Unable to schedule background task when one is already running.  All task must fully terminated before another can be scheduled. ");
        }

        this.cancelCallBackForBaseRunnable = cancelCallBack;

        backgroundBaseRunnableFuture = new MyFuture(runnable) {
            /**
             * augments the cancel operation to cancel all subTack too,
             */
            @Override
            public boolean cancel(final boolean mayInterruptIfRunning) {
                boolean cancel;
                synchronized (AsyncTaskHelper.this) {
                    cancel = super.cancel(mayInterruptIfRunning);
                    myFutureSet.stream().filter(f->!this.equals(f)).forEach(f->f.cancel(mayInterruptIfRunning));
                }
                return cancel;
            }

            /**
             * augments the isDone operation to return false until all subTask have completed too.
             */
            @Override
            public boolean isDone() {
                synchronized (AsyncTaskHelper.this) {
                    return myFutureSet.isEmpty();
                }
            }
        };
        backgroundBaseRunnableFuture.setFuture(
            scheduledExecutorService.scheduleWithFixedDelay(
                backgroundBaseRunnableFuture, initialDelayMillis, delayMillis, TimeUnit.MILLISECONDS)
        );
        return backgroundBaseRunnableFuture;
    }

    /**
     * Submits children {@link Callable} to be executed as soon as possible,  A parent must have been scheduled
     * previously via {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)}
     * @param callable the Callable to be submitted
     * @return The {@link Callable}'s {@link Future}
     */
    synchronized Future<?> submitBaseSubCallable(final Callable callable) {

        if (backgroundBaseRunnableFuture == null
            || backgroundBaseRunnableFuture.isCancelled()
            || backgroundBaseRunnableFuture.isDone()){
            throw new IllegalStateException("Unable to schedule subCallable when a base Runnable is not running.");
        }

        //Make sure the pool is ready to go
        if(bundleOperationService.getPoolSize() != bundleOperationService.getMaximumPoolSize()){
            bundleOperationService.setCorePoolSize(bundleOperationService.getMaximumPoolSize());
            bundleOperationService.prestartAllCoreThreads();
            bundleOperationService.setCorePoolSize(0);
        }

        MyFuture<?> myFuture = new MyFuture(callable);
        myFuture.setFuture(bundleOperationService.submit((Callable)myFuture));
        return myFuture;
    }

    /**
     * Genral debug log when debug logging level is enabled.
     * @param message of the log message format
     * @param args of the objects listed in the message format
     */
    private void logDebug(String message, Object... args) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format(message, args));
        }
    }

    /**
     * This class has two purposes.  First it insures  {@link #isDone()} only returns true if the deligate is not
     * currently running and will not be running in the future: See Java BUG JDK-8073704 Second this class maintains
     * the {@link #myFutureSet } by insurring that itself is removed when  {@link #isDone()} returns true.
     *
     * See {@link #scheduleBaseRunnable(Runnable, Consumer, long, long)} and {@link #submitBaseSubCallable(Callable)}
     * for usage of this class
     */
    private class MyFuture<T> implements Future<T>, Runnable, Callable<T> {

        private Future<T> future;
        private final Runnable runnable;
        private final Callable<T> callable;
        private boolean isRunning;

        MyFuture(Runnable runnable) {
            this.runnable = runnable;
            this.callable = null;
            myFutureSet.add(this);
        }

        MyFuture(Callable<T> callable) {
            this.runnable = null;
            this.callable = callable;
            myFutureSet.add(this);
        }

        void setFuture(Future<T> future) {
            this.future = future;
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            synchronized (AsyncTaskHelper.this) {
                if (!isRunning) {
                    myFutureSetRemove();
                }

                return future.cancel(mayInterruptIfRunning);
            }
        }

        @Override
        public boolean isCancelled() {
            synchronized (AsyncTaskHelper.this) {
                return future.isCancelled();
            }
        }

        @Override
        public boolean isDone() {
            synchronized (AsyncTaskHelper.this) {
                return future.isDone() && !isRunning;
            }
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
                return future.get();
        }

        @Override
        public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
            return future.get(timeout, unit);
        }

        @Override
        public void run() {
            synchronized (AsyncTaskHelper.this) {
                if(future.isCancelled()){
                    return;
                }
                isRunning = true;
            }
            try {
                runnable.run();
            } finally {
                synchronized (AsyncTaskHelper.this) {
                    isRunning = false;

                    //The Base Runnable is expected to run again.
                    //unless it has been canceled.
                    //so only removed if it is canceled.
                    if (future.isCancelled()) {
                        myFutureSetRemove();
                    }
                }
            }
        }

        @Override
        public T call() throws Exception {
            synchronized (AsyncTaskHelper.this) {
                if(future.isCancelled()){
                    throw new CancellationException();
                }
                isRunning = true;
            }
            try {
                return callable.call();
            } finally {
                synchronized (AsyncTaskHelper.this){
                    isRunning = false;
                    myFutureSetRemove();
                }
            }
        }


        /**
         * Removes this from the the myFutureSet.
         * When all the BaseActionRunnable is Done notify any thread waiting in
         * {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}
         */
        void myFutureSetRemove(){
            synchronized (AsyncTaskHelper.this) {
                myFutureSet.remove(this);
                if(myFutureSet.isEmpty()){
                    backgroundBaseRunnableFuture = null;
                    cancelCallBackForBaseRunnable = null;
                    AsyncTaskHelper.this.notifyAll();

                }
            }
        }

    }
}