blob: 6f90256fd81b5e637299f6b82ce59452d275de82 [file] [log] [blame]
Carmelo Cascone3977ea42019-02-28 13:43:42 -08001/*
2 * Copyright 2019-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.provider.general.device.impl;
18
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.CacheLoader;
21import com.google.common.cache.LoadingCache;
22import com.google.common.cache.RemovalListener;
23import com.google.common.collect.Sets;
24import com.google.common.util.concurrent.Striped;
25import org.onosproject.net.DeviceId;
26import org.slf4j.Logger;
27
28import java.util.Set;
29import java.util.concurrent.ConcurrentLinkedQueue;
30import java.util.concurrent.ExecutionException;
31import java.util.concurrent.ExecutorService;
32import java.util.concurrent.TimeUnit;
33import java.util.concurrent.atomic.AtomicBoolean;
34import java.util.concurrent.locks.Lock;
35
36import static com.google.common.base.Preconditions.checkNotNull;
37import static java.lang.String.format;
38import static java.lang.System.currentTimeMillis;
39import static org.slf4j.LoggerFactory.getLogger;
40
41/**
42 * Allows submitting tasks related to a specific device. Takes care of executing
43 * pending tasks sequentially for each device in a FIFO order, while using a
44 * delegate executor. It also avoids executing duplicate tasks when arriving
45 * back-to-back.
46 *
47 * @param <T> enum describing the type of task
48 */
49
50class DeviceTaskExecutor<T extends Enum> {
51 /**
52 * Minimum interval between duplicate back-to-back tasks.
53 */
54 private static final int DUPLICATE_MIN_INTERVAL_MILLIS = 1000;
55
56 private final Logger log = getLogger(getClass());
57
58 private final ExecutorService delegate;
59 private final AtomicBoolean canceled = new AtomicBoolean(false);
60 private final Set<DeviceId> busyDevices = Sets.newConcurrentHashSet();
61 private final Set<DeviceId> pendingDevices = Sets.newConcurrentHashSet();
62 private final Striped<Lock> deviceLocks = Striped.lock(30);
63 private final LoadingCache<DeviceId, TaskQueue> taskQueues = CacheBuilder.newBuilder()
64 .expireAfterAccess(1, TimeUnit.MINUTES)
65 .removalListener((RemovalListener<DeviceId, TaskQueue>) notification -> {
66 if (!notification.getValue().isEmpty()) {
67 log.warn("Cache evicted non-empty task queue for {} ({} pending tasks)",
68 notification.getKey(), notification.getValue().size());
69 }
70 })
71 .build(new CacheLoader<DeviceId, TaskQueue>() {
72 @SuppressWarnings("NullableProblems")
73 @Override
74 public TaskQueue load(DeviceId deviceId) {
75 return new TaskQueue();
76 }
77 });
78
79 /**
80 * Creates a new executor with the given delegate executor service.
81 *
82 * @param delegate executor service
83 */
84 DeviceTaskExecutor(ExecutorService delegate) {
85 checkNotNull(delegate);
86 this.delegate = delegate;
87 }
88
89 /**
90 * Submit a tasks.
91 *
92 * @param deviceId device associated with the task
93 * @param type type of task (used to remove eventual back-to-back
94 * duplicates)
95 * @param runnable runnable to execute
96 */
97 void submit(DeviceId deviceId, T type, Runnable runnable) {
98 checkNotNull(deviceId);
99 checkNotNull(type);
100 checkNotNull(runnable);
101
102 if (canceled.get()) {
103 log.warn("Executor was cancelled, cannot submit task {} for {}",
104 type, deviceId);
105 return;
106 }
107
108 final DeviceTask task = new DeviceTask(deviceId, type, runnable);
109 deviceLocks.get(deviceId).lock();
110 try {
111 if (taskQueues.get(deviceId).isBackToBackDuplicate(type)) {
112 if (log.isDebugEnabled()) {
113 log.debug("Dropping back-to-back duplicate task {} for {}",
114 type, deviceId);
115 }
116 return;
117 }
118 if (taskQueues.get(deviceId).offer(task)) {
119 pendingDevices.add(deviceId);
120 if (!busyDevices.contains(deviceId)) {
121 // The task was submitted to the queue and we are not
122 // performing any other task for this device. There is at
123 // least one task that is ready to be executed.
124 delegate.execute(this::performTaskIfAny);
125 }
126 } else {
127 log.warn("Unable to submit task {} for {}",
128 task.type, task.deviceId);
129 }
130 } catch (ExecutionException e) {
131 log.warn("Exception while accessing task queue cache", e);
132 } finally {
133 deviceLocks.get(task.deviceId).unlock();
134 }
135 }
136
137 /**
138 * Prevents the executor from executing any more tasks.
139 */
140 void cancel() {
141 canceled.set(true);
142 }
143
144 private void performTaskIfAny() {
145 final DeviceTask task = pollTask();
146 if (task == null) {
147 // No tasks.
148 return;
149 }
150 if (canceled.get()) {
151 log.warn("Executor was cancelled, dropping task {} for {}",
152 task.type, task.deviceId);
153 return;
154 }
155 if (log.isTraceEnabled()) {
156 log.trace("STARTING task {} for {}...", task.type.name(), task.deviceId);
157 }
158 try {
159 task.runnable.run();
160 } catch (DeviceTaskException e) {
161 log.error("Unable to complete task {} for {}: {}",
162 task.type, task.deviceId, e.getMessage());
163 } catch (Throwable t) {
164 log.error(format(
165 "Uncaught exception when executing task %s for %s",
166 task.type, task.deviceId), t);
167 }
168 if (log.isTraceEnabled()) {
169 log.trace("COMPLETED task {} for {}", task.type.name(), task.deviceId);
170 }
171 busyDevices.remove(task.deviceId);
172 delegate.execute(this::performTaskIfAny);
173 }
174
175 private DeviceTask pollTask() {
176 for (DeviceId deviceId : pendingDevices) {
177 final DeviceTask task;
178 deviceLocks.get(deviceId).lock();
179 try {
180 if (busyDevices.contains(deviceId)) {
181 // Next device.
182 continue;
183 }
184 task = taskQueues.get(deviceId).poll();
185 if (task == null) {
186 // Next device.
187 continue;
188 }
189 if (taskQueues.get(deviceId).isEmpty()) {
190 pendingDevices.remove(deviceId);
191 }
192 busyDevices.add(deviceId);
193 return task;
194 } catch (ExecutionException e) {
195 log.warn("Exception while accessing task queue cache", e);
196 } finally {
197 deviceLocks.get(deviceId).unlock();
198 }
199 }
200 return null;
201 }
202
203 /**
204 * Device task as stored in the task queue.
205 */
206 private class DeviceTask {
207
208 private final DeviceId deviceId;
209 private final T type;
210 private final Runnable runnable;
211
212 DeviceTask(DeviceId deviceId, T type, Runnable runnable) {
213 this.deviceId = deviceId;
214 this.type = type;
215 this.runnable = runnable;
216 }
217 }
218
219 /**
220 * A queue that keeps track of the last task added to detects back-to-back
221 * duplicates.
222 */
223 private class TaskQueue extends ConcurrentLinkedQueue<DeviceTask> {
224
225 private T lastTaskAdded;
226 private long lastAddedMillis;
227
228 @Override
229 public boolean offer(DeviceTask deviceTask) {
230 lastTaskAdded = deviceTask.type;
231 lastAddedMillis = currentTimeMillis();
232 return super.offer(deviceTask);
233 }
234
235 boolean isBackToBackDuplicate(T taskType) {
236 return lastTaskAdded != null
237 && lastTaskAdded.equals(taskType)
238 && (currentTimeMillis() - lastAddedMillis) <= DUPLICATE_MIN_INTERVAL_MILLIS;
239 }
240 }
241
242 /**
243 * Signals an error that prevented normal execution of the task.
244 */
245 static class DeviceTaskException extends RuntimeException {
246
247 /**
248 * Creates a new exception.
249 *
250 * @param message explanation
251 */
252 DeviceTaskException(String message) {
253 super(message);
254 }
255 }
256}