|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the "Elastic License |
| 4 | + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side |
| 5 | + * Public License v 1"; you may not use this file except in compliance with, at |
| 6 | + * your election, the "Elastic License 2.0", the "GNU Affero General Public |
| 7 | + * License v3.0 only", or the "Server Side Public License, v 1". |
| 8 | + */ |
| 9 | + |
| 10 | +package org.elasticsearch.threadpool; |
| 11 | + |
| 12 | +import org.elasticsearch.common.util.concurrent.AbstractRunnable; |
| 13 | +import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; |
| 14 | +import org.elasticsearch.common.util.concurrent.ThreadContext; |
| 15 | +import org.elasticsearch.logging.LogManager; |
| 16 | +import org.elasticsearch.logging.Logger; |
| 17 | + |
| 18 | +import java.util.Collection; |
| 19 | +import java.util.List; |
| 20 | +import java.util.concurrent.Callable; |
| 21 | +import java.util.concurrent.ExecutionException; |
| 22 | +import java.util.concurrent.ExecutorService; |
| 23 | +import java.util.concurrent.Future; |
| 24 | +import java.util.concurrent.RejectedExecutionException; |
| 25 | +import java.util.concurrent.TimeUnit; |
| 26 | +import java.util.concurrent.TimeoutException; |
| 27 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 28 | +import java.util.concurrent.atomic.AtomicInteger; |
| 29 | + |
| 30 | +import static org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor.WORKER_PROBE; |
| 31 | +import static org.elasticsearch.core.Strings.format; |
| 32 | + |
| 33 | +/** |
| 34 | + * There is a subtle interaction between a scaling {@link org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor} with |
| 35 | + * {@link org.elasticsearch.threadpool.ScalingExecutorBuilder.ScalingExecutorSettings#rejectAfterShutdown} set to false, and |
| 36 | + * the {@link org.elasticsearch.common.util.concurrent.ThrottledTaskRunner}. |
| 37 | + * <p> |
| 38 | + * When a {@link org.elasticsearch.common.util.concurrent.ThrottledTaskRunner} is feeding into a scaling executor that doesn't |
| 39 | + * reject after shutdown, it will always be fully processed in the event of a shutdown. This is because whenever a throttled |
| 40 | + * task finishes, it checks if there are more queued and forces them onto the end of the thread-pool queue even though they |
| 41 | + * are rejected by {@link java.util.concurrent.ThreadPoolExecutor#execute(Runnable)}. The executor won't terminate until all |
| 42 | + * workers are finished and the queue is empty, so the fact each worker adds a task to the end of the queue before it terminates |
| 43 | + * means the {@link org.elasticsearch.common.util.concurrent.ThrottledTaskRunner} queue will be drained before the thread pool |
| 44 | + * executor terminates. |
| 45 | + * <p> |
| 46 | + * This decorator attempts to emulate that behavior in the absence of an explicit queue, and also ensures that {@link ThreadContext} |
| 47 | + * is propagated to tasks that are dispatched. |
| 48 | + */ |
| 49 | +public class EsExecutorServiceDecorator implements ExecutorService { |
| 50 | + |
| 51 | + private static final Logger logger = LogManager.getLogger(EsExecutorServiceDecorator.class); |
| 52 | + |
| 53 | + private final String name; |
| 54 | + private final ExecutorService delegate; |
| 55 | + private final ThreadContext contextHolder; |
| 56 | + private final boolean rejectAfterShutdown; |
| 57 | + private final AtomicInteger runningTasks = new AtomicInteger(); |
| 58 | + private final AtomicBoolean shutdownRequested = new AtomicBoolean(false); |
| 59 | + |
| 60 | + public EsExecutorServiceDecorator(String name, ExecutorService delegate, ThreadContext contextHolder, boolean rejectAfterShutdown) { |
| 61 | + this.name = name; |
| 62 | + this.delegate = delegate; |
| 63 | + this.contextHolder = contextHolder; |
| 64 | + this.rejectAfterShutdown = rejectAfterShutdown; |
| 65 | + } |
| 66 | + |
| 67 | + @Override |
| 68 | + public void shutdown() { |
| 69 | + shutdownRequested.set(true); |
| 70 | + tryShutdownDelegate(); |
| 71 | + } |
| 72 | + |
| 73 | + private void tryShutdownDelegate() { |
| 74 | + if (shutdownRequested.get() && runningTasks.compareAndSet(0, -1)) { |
| 75 | + delegate.shutdown(); |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public List<Runnable> shutdownNow() { |
| 81 | + return delegate.shutdownNow(); |
| 82 | + } |
| 83 | + |
| 84 | + @Override |
| 85 | + public boolean isShutdown() { |
| 86 | + return delegate.isShutdown(); |
| 87 | + } |
| 88 | + |
| 89 | + @Override |
| 90 | + public boolean isTerminated() { |
| 91 | + return delegate.isTerminated(); |
| 92 | + } |
| 93 | + |
| 94 | + @Override |
| 95 | + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { |
| 96 | + long endTime = System.nanoTime() + unit.toNanos(timeout); |
| 97 | + shutdownRequested.set(true); |
| 98 | + while (delegate.isShutdown() == false) { |
| 99 | + if (System.nanoTime() > endTime) { |
| 100 | + return false; |
| 101 | + } |
| 102 | + Thread.sleep(1); |
| 103 | + tryShutdownDelegate(); |
| 104 | + } |
| 105 | + logger.info("Falling through"); |
| 106 | + return delegate.awaitTermination(timeout, unit); |
| 107 | + } |
| 108 | + |
| 109 | + @Override |
| 110 | + public <T> Future<T> submit(Callable<T> task) { |
| 111 | + return delegate.submit(task); |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public <T> Future<T> submit(Runnable task, T result) { |
| 116 | + return delegate.submit(task, result); |
| 117 | + } |
| 118 | + |
| 119 | + @Override |
| 120 | + public Future<?> submit(Runnable task) { |
| 121 | + return delegate.submit(task); |
| 122 | + } |
| 123 | + |
| 124 | + @Override |
| 125 | + public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { |
| 126 | + return delegate.invokeAll(tasks); |
| 127 | + } |
| 128 | + |
| 129 | + @Override |
| 130 | + public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { |
| 131 | + return delegate.invokeAll(tasks, timeout, unit); |
| 132 | + } |
| 133 | + |
| 134 | + @Override |
| 135 | + public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { |
| 136 | + return delegate.invokeAny(tasks); |
| 137 | + } |
| 138 | + |
| 139 | + @Override |
| 140 | + public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, |
| 141 | + ExecutionException, TimeoutException { |
| 142 | + return delegate.invokeAny(tasks, timeout, unit); |
| 143 | + } |
| 144 | + |
| 145 | + @Override |
| 146 | + public void execute(Runnable command) { |
| 147 | + final Runnable wrappedRunnable = command != WORKER_PROBE ? wrapRunnable(command) : WORKER_PROBE; |
| 148 | + try { |
| 149 | + if (rejectAfterShutdown && shutdownRequested.get() || delegate.isShutdown()) { |
| 150 | + throw new EsRejectedExecutionException("executor has been shutdown", delegate.isShutdown()); |
| 151 | + } |
| 152 | + // Increment outstanding task count |
| 153 | + runningTasks.getAndUpdate(currentValue -> { |
| 154 | + if (currentValue == -1) { |
| 155 | + throw new EsRejectedExecutionException("executor has been shutdown", true); |
| 156 | + } else { |
| 157 | + return currentValue + 1; |
| 158 | + } |
| 159 | + }); |
| 160 | + try { |
| 161 | + delegate.execute(() -> { |
| 162 | + try { |
| 163 | + wrappedRunnable.run(); |
| 164 | + } finally { |
| 165 | + // Decrement outstanding |
| 166 | + runningTasks.decrementAndGet(); |
| 167 | + tryShutdownDelegate(); |
| 168 | + } |
| 169 | + }); |
| 170 | + } catch (RejectedExecutionException e) { |
| 171 | + if (command == WORKER_PROBE) { |
| 172 | + return; |
| 173 | + } |
| 174 | + throw new EsRejectedExecutionException("delegate rejected execution", delegate.isShutdown()); |
| 175 | + } |
| 176 | + } catch (Exception e) { |
| 177 | + if (wrappedRunnable instanceof AbstractRunnable abstractRunnable) { |
| 178 | + try { |
| 179 | + // If we are an abstract runnable we can handle the exception |
| 180 | + // directly and don't need to rethrow it, but we log and assert |
| 181 | + // any unexpected exception first. |
| 182 | + if (e instanceof EsRejectedExecutionException == false) { |
| 183 | + logException(abstractRunnable, e); |
| 184 | + } |
| 185 | + abstractRunnable.onRejection(e); |
| 186 | + } finally { |
| 187 | + abstractRunnable.onAfter(); |
| 188 | + } |
| 189 | + } else { |
| 190 | + throw e; |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + // package-visible for testing |
| 196 | + void logException(AbstractRunnable r, Exception e) { |
| 197 | + logger.error(() -> format("[%s] unexpected exception when submitting task [%s] for execution", name, r), e); |
| 198 | + assert false : "executor throws an exception (not a rejected execution exception) before the task has been submitted " + e; |
| 199 | + } |
| 200 | + |
| 201 | + protected Runnable wrapRunnable(Runnable command) { |
| 202 | + return contextHolder.preserveContext(command); |
| 203 | + } |
| 204 | +} |
0 commit comments