Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | package org.onosproject.provider.general.device.impl; |
| 18 | |
| 19 | import com.google.common.cache.CacheBuilder; |
| 20 | import com.google.common.cache.CacheLoader; |
| 21 | import com.google.common.cache.LoadingCache; |
| 22 | import com.google.common.cache.RemovalListener; |
| 23 | import com.google.common.collect.Sets; |
| 24 | import com.google.common.util.concurrent.Striped; |
| 25 | import org.onosproject.net.DeviceId; |
| 26 | import org.slf4j.Logger; |
| 27 | |
| 28 | import java.util.Set; |
| 29 | import java.util.concurrent.ConcurrentLinkedQueue; |
| 30 | import java.util.concurrent.ExecutionException; |
| 31 | import java.util.concurrent.ExecutorService; |
| 32 | import java.util.concurrent.TimeUnit; |
| 33 | import java.util.concurrent.atomic.AtomicBoolean; |
| 34 | import java.util.concurrent.locks.Lock; |
| 35 | |
| 36 | import static com.google.common.base.Preconditions.checkNotNull; |
| 37 | import static java.lang.String.format; |
| 38 | import static java.lang.System.currentTimeMillis; |
| 39 | import 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 | |
| 50 | class 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 | }); |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 78 | /** |
| 79 | * Type of tasks allowed to be back to back. |
| 80 | */ |
| 81 | private final Set<T> allowList; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 82 | |
| 83 | /** |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 84 | * Creates a new executor with the given delegate executor service |
| 85 | * and the allowed back to back task types. |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 86 | * |
| 87 | * @param delegate executor service |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 88 | * @param allowed tasks allowed to be back to back |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 89 | */ |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 90 | DeviceTaskExecutor(ExecutorService delegate, Set<T> allowed) { |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 91 | checkNotNull(delegate); |
| 92 | this.delegate = delegate; |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 93 | this.allowList = allowed; |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 94 | } |
| 95 | |
| 96 | /** |
| 97 | * Submit a tasks. |
| 98 | * |
| 99 | * @param deviceId device associated with the task |
| 100 | * @param type type of task (used to remove eventual back-to-back |
| 101 | * duplicates) |
| 102 | * @param runnable runnable to execute |
| 103 | */ |
| 104 | void submit(DeviceId deviceId, T type, Runnable runnable) { |
| 105 | checkNotNull(deviceId); |
| 106 | checkNotNull(type); |
| 107 | checkNotNull(runnable); |
| 108 | |
| 109 | if (canceled.get()) { |
| 110 | log.warn("Executor was cancelled, cannot submit task {} for {}", |
| 111 | type, deviceId); |
| 112 | return; |
| 113 | } |
| 114 | |
| 115 | final DeviceTask task = new DeviceTask(deviceId, type, runnable); |
| 116 | deviceLocks.get(deviceId).lock(); |
| 117 | try { |
pierventre | 309d98e | 2022-02-28 13:37:08 -0800 | [diff] [blame] | 118 | if (taskQueues.get(deviceId).isBackToBackDuplicate(type) && !allowList.contains(type)) { |
Carmelo Cascone | 3977ea4 | 2019-02-28 13:43:42 -0800 | [diff] [blame] | 119 | if (log.isDebugEnabled()) { |
| 120 | log.debug("Dropping back-to-back duplicate task {} for {}", |
| 121 | type, deviceId); |
| 122 | } |
| 123 | return; |
| 124 | } |
| 125 | if (taskQueues.get(deviceId).offer(task)) { |
| 126 | pendingDevices.add(deviceId); |
| 127 | if (!busyDevices.contains(deviceId)) { |
| 128 | // The task was submitted to the queue and we are not |
| 129 | // performing any other task for this device. There is at |
| 130 | // least one task that is ready to be executed. |
| 131 | delegate.execute(this::performTaskIfAny); |
| 132 | } |
| 133 | } else { |
| 134 | log.warn("Unable to submit task {} for {}", |
| 135 | task.type, task.deviceId); |
| 136 | } |
| 137 | } catch (ExecutionException e) { |
| 138 | log.warn("Exception while accessing task queue cache", e); |
| 139 | } finally { |
| 140 | deviceLocks.get(task.deviceId).unlock(); |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Prevents the executor from executing any more tasks. |
| 146 | */ |
| 147 | void cancel() { |
| 148 | canceled.set(true); |
| 149 | } |
| 150 | |
| 151 | private void performTaskIfAny() { |
| 152 | final DeviceTask task = pollTask(); |
| 153 | if (task == null) { |
| 154 | // No tasks. |
| 155 | return; |
| 156 | } |
| 157 | if (canceled.get()) { |
| 158 | log.warn("Executor was cancelled, dropping task {} for {}", |
| 159 | task.type, task.deviceId); |
| 160 | return; |
| 161 | } |
| 162 | if (log.isTraceEnabled()) { |
| 163 | log.trace("STARTING task {} for {}...", task.type.name(), task.deviceId); |
| 164 | } |
| 165 | try { |
| 166 | task.runnable.run(); |
| 167 | } catch (DeviceTaskException e) { |
| 168 | log.error("Unable to complete task {} for {}: {}", |
| 169 | task.type, task.deviceId, e.getMessage()); |
| 170 | } catch (Throwable t) { |
| 171 | log.error(format( |
| 172 | "Uncaught exception when executing task %s for %s", |
| 173 | task.type, task.deviceId), t); |
| 174 | } |
| 175 | if (log.isTraceEnabled()) { |
| 176 | log.trace("COMPLETED task {} for {}", task.type.name(), task.deviceId); |
| 177 | } |
| 178 | busyDevices.remove(task.deviceId); |
| 179 | delegate.execute(this::performTaskIfAny); |
| 180 | } |
| 181 | |
| 182 | private DeviceTask pollTask() { |
| 183 | for (DeviceId deviceId : pendingDevices) { |
| 184 | final DeviceTask task; |
| 185 | deviceLocks.get(deviceId).lock(); |
| 186 | try { |
| 187 | if (busyDevices.contains(deviceId)) { |
| 188 | // Next device. |
| 189 | continue; |
| 190 | } |
| 191 | task = taskQueues.get(deviceId).poll(); |
| 192 | if (task == null) { |
| 193 | // Next device. |
| 194 | continue; |
| 195 | } |
| 196 | if (taskQueues.get(deviceId).isEmpty()) { |
| 197 | pendingDevices.remove(deviceId); |
| 198 | } |
| 199 | busyDevices.add(deviceId); |
| 200 | return task; |
| 201 | } catch (ExecutionException e) { |
| 202 | log.warn("Exception while accessing task queue cache", e); |
| 203 | } finally { |
| 204 | deviceLocks.get(deviceId).unlock(); |
| 205 | } |
| 206 | } |
| 207 | return null; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Device task as stored in the task queue. |
| 212 | */ |
| 213 | private class DeviceTask { |
| 214 | |
| 215 | private final DeviceId deviceId; |
| 216 | private final T type; |
| 217 | private final Runnable runnable; |
| 218 | |
| 219 | DeviceTask(DeviceId deviceId, T type, Runnable runnable) { |
| 220 | this.deviceId = deviceId; |
| 221 | this.type = type; |
| 222 | this.runnable = runnable; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | /** |
| 227 | * A queue that keeps track of the last task added to detects back-to-back |
| 228 | * duplicates. |
| 229 | */ |
| 230 | private class TaskQueue extends ConcurrentLinkedQueue<DeviceTask> { |
| 231 | |
| 232 | private T lastTaskAdded; |
| 233 | private long lastAddedMillis; |
| 234 | |
| 235 | @Override |
| 236 | public boolean offer(DeviceTask deviceTask) { |
| 237 | lastTaskAdded = deviceTask.type; |
| 238 | lastAddedMillis = currentTimeMillis(); |
| 239 | return super.offer(deviceTask); |
| 240 | } |
| 241 | |
| 242 | boolean isBackToBackDuplicate(T taskType) { |
| 243 | return lastTaskAdded != null |
| 244 | && lastTaskAdded.equals(taskType) |
| 245 | && (currentTimeMillis() - lastAddedMillis) <= DUPLICATE_MIN_INTERVAL_MILLIS; |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /** |
| 250 | * Signals an error that prevented normal execution of the task. |
| 251 | */ |
| 252 | static class DeviceTaskException extends RuntimeException { |
| 253 | |
| 254 | /** |
| 255 | * Creates a new exception. |
| 256 | * |
| 257 | * @param message explanation |
| 258 | */ |
| 259 | DeviceTaskException(String message) { |
| 260 | super(message); |
| 261 | } |
| 262 | } |
| 263 | } |