25467da047f47f25b703ac2473d6fa5fa4520c18
[appc.git] / appc-oam / appc-oam-bundle / src / main / java / org / openecomp / appc / oam / util / AsyncTaskHelper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.oam.util;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import org.openecomp.appc.oam.AppcOam;
29 import org.openecomp.appc.oam.processor.BaseActionRunnable;
30 import org.osgi.framework.Bundle;
31 import org.osgi.framework.FrameworkUtil;
32
33 import java.util.concurrent.Callable;
34 import java.util.concurrent.Executors;
35 import java.util.concurrent.Future;
36 import java.util.concurrent.LinkedBlockingQueue;
37 import java.util.concurrent.ScheduledExecutorService;
38 import java.util.concurrent.ThreadPoolExecutor;
39 import java.util.concurrent.TimeUnit;
40
41 /**
42  * Utility class provides general async task related help.
43  */
44 @SuppressWarnings("unchecked")
45 public class AsyncTaskHelper {
46     final int MMODE_TASK_DELAY = 10000;
47     final int COMMON_INITIAL_DELAY = 0;
48     final int COMMON_INTERVAL = 1000;
49
50     private final EELFLogger logger;
51     private final ScheduledExecutorService scheduledExecutorService;
52     private final ThreadPoolExecutor bundleOperationService;
53
54     /** Reference to the Async task */
55     private volatile Future<?> backgroundOamTask;
56     /** Reference to the runnable of Async task */
57     private volatile BaseActionRunnable taskRunnable;
58
59     /**
60      * Constructor
61      * @param eelfLogger of the logger
62      */
63     public AsyncTaskHelper(EELFLogger eelfLogger) {
64         logger = eelfLogger;
65
66         scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
67                 (runnable) -> {
68                     Bundle bundle = FrameworkUtil.getBundle(AppcOam.class);
69                     return new Thread(runnable, bundle.getSymbolicName() + " scheduledExecutor");
70                 }
71         );
72
73         bundleOperationService = new ThreadPoolExecutor(
74                 0,
75                 10,
76                 10,
77                 TimeUnit.SECONDS,
78                 new LinkedBlockingQueue(),// BlockingQueue<Runnable> workQueue
79                 (runnable) -> new Thread(runnable, "OAM bundler operation executor")//ThreadFactory
80         );
81     }
82
83     void addThreadsToPool() {
84         bundleOperationService.setCorePoolSize(bundleOperationService.getMaximumPoolSize());
85     }
86
87     void removeThreadsFromPoolWhenDone() {
88         bundleOperationService.setCorePoolSize(0);
89     }
90
91     /**
92      * Terminate the class <bS>ScheduledExecutorService</b>
93      */
94     public void close() {
95         logDebug("Start shutdown scheduleExcutorService.");
96         scheduledExecutorService.shutdown();
97         bundleOperationService.shutdown();
98         logDebug("Completed shutdown scheduleExcutorService.");
99     }
100
101     /**
102      * Get current async task refernce
103      * @return the class <b>backgroundOamTask</b>
104      */
105     public Future<?> getCurrentAsyncTask() {
106         return backgroundOamTask;
107     }
108
109     /**
110      * Schedule a service for async task with the passed in parameters
111      * @param rpc of the REST API call, decides how to schedule the service
112      * @param runnable of the to be scheduled service.
113      * @return the reference of the scheduled task
114      */
115     public Future<?> scheduleAsyncTask(final AppcOam.RPC rpc, final BaseActionRunnable runnable) {
116         int initialDelay, interval;
117         switch (rpc) {
118             case maintenance_mode:
119                 initialDelay = interval =MMODE_TASK_DELAY;
120                 break;
121             case start:
122             case stop:
123             case restart:
124                 initialDelay = COMMON_INITIAL_DELAY;
125                 interval = COMMON_INTERVAL;
126                 break;
127             default:
128                 // should not get here. Log it and return null
129                 logDebug(String.format("Cannot scheudle task for unsupported RPC(%s).", rpc.name()));
130                 return null;
131         }
132
133         // Always cancel existing  async task
134         if (backgroundOamTask != null) {
135             logDebug("Cancelling background task in schedule task.");
136             backgroundOamTask.cancel(true);
137             if (taskRunnable != null) {
138                 taskRunnable.abortRunnable(rpc);
139             }
140         }
141
142         taskRunnable = runnable;
143         backgroundOamTask = scheduledExecutorService.scheduleWithFixedDelay(
144                 runnable, initialDelay, interval, TimeUnit.MILLISECONDS);
145
146         return backgroundOamTask;
147     }
148
149     Future<?> submitBundleLcOperation(final Callable callable) {
150         return bundleOperationService.submit(callable);
151     }
152
153     /**
154      * Cancle a previously schedule task. If the task is the same as backgroundOamTask, set it to null.
155      * @param task to be canceled
156      */
157     public void cancelAsyncTask(Future<?> task) {
158         task.cancel(false);
159         if (task == backgroundOamTask) {
160             backgroundOamTask = null;
161             logDebug("Cancelling background task in cancel task.");
162         }
163     }
164
165     /**
166      * Genral debug log when debug logging level is enabled.
167      * @param message of the log message format
168      * @param args of the objects listed in the message format
169      */
170     private void logDebug(String message, Object... args) {
171         if (logger.isDebugEnabled()) {
172             logger.debug(String.format(message, args));
173         }
174     }
175 }