001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.procedure2;
019
020import edu.umd.cs.findbugs.annotations.Nullable;
021import java.io.IOException;
022import java.io.UncheckedIOException;
023import java.util.ArrayDeque;
024import java.util.ArrayList;
025import java.util.Arrays;
026import java.util.Collection;
027import java.util.Comparator;
028import java.util.Deque;
029import java.util.HashSet;
030import java.util.List;
031import java.util.PriorityQueue;
032import java.util.Set;
033import java.util.concurrent.ConcurrentHashMap;
034import java.util.concurrent.CopyOnWriteArrayList;
035import java.util.concurrent.ExecutorService;
036import java.util.concurrent.Executors;
037import java.util.concurrent.LinkedBlockingQueue;
038import java.util.concurrent.ThreadFactory;
039import java.util.concurrent.ThreadPoolExecutor;
040import java.util.concurrent.TimeUnit;
041import java.util.concurrent.atomic.AtomicBoolean;
042import java.util.concurrent.atomic.AtomicInteger;
043import java.util.concurrent.atomic.AtomicLong;
044import java.util.stream.Collectors;
045import java.util.stream.Stream;
046import org.apache.hadoop.conf.Configuration;
047import org.apache.hadoop.hbase.HConstants;
048import org.apache.hadoop.hbase.exceptions.IllegalArgumentIOException;
049import org.apache.hadoop.hbase.log.HBaseMarkers;
050import org.apache.hadoop.hbase.procedure2.Procedure.LockState;
051import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
052import org.apache.hadoop.hbase.procedure2.store.ProcedureStore.ProcedureIterator;
053import org.apache.hadoop.hbase.procedure2.store.ProcedureStore.ProcedureStoreListener;
054import org.apache.hadoop.hbase.procedure2.trace.ProcedureSpanBuilder;
055import org.apache.hadoop.hbase.procedure2.util.StringUtils;
056import org.apache.hadoop.hbase.security.User;
057import org.apache.hadoop.hbase.trace.TraceUtil;
058import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
059import org.apache.hadoop.hbase.util.IdLock;
060import org.apache.hadoop.hbase.util.NonceKey;
061import org.apache.hadoop.hbase.util.Threads;
062import org.apache.yetus.audience.InterfaceAudience;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
067import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
068
069import org.apache.hadoop.hbase.shaded.protobuf.generated.ProcedureProtos.ProcedureState;
070
071/**
072 * Thread Pool that executes the submitted procedures. The executor has a ProcedureStore associated.
073 * Each operation is logged and on restart the pending procedures are resumed. Unless the Procedure
074 * code throws an error (e.g. invalid user input) the procedure will complete (at some point in
075 * time), On restart the pending procedures are resumed and the once failed will be rolledback. The
076 * user can add procedures to the executor via submitProcedure(proc) check for the finished state
077 * via isFinished(procId) and get the result via getResult(procId)
078 */
079@InterfaceAudience.Private
080public class ProcedureExecutor<TEnvironment> {
081  private static final Logger LOG = LoggerFactory.getLogger(ProcedureExecutor.class);
082
083  public static final String CHECK_OWNER_SET_CONF_KEY = "hbase.procedure.check.owner.set";
084  private static final boolean DEFAULT_CHECK_OWNER_SET = false;
085
086  public static final String WORKER_KEEP_ALIVE_TIME_CONF_KEY =
087    "hbase.procedure.worker.keep.alive.time.msec";
088  private static final long DEFAULT_WORKER_KEEP_ALIVE_TIME = TimeUnit.MINUTES.toMillis(1);
089
090  public static final String EVICT_TTL_CONF_KEY = "hbase.procedure.cleaner.evict.ttl";
091  static final int DEFAULT_EVICT_TTL = 15 * 60000; // 15min
092
093  public static final String EVICT_ACKED_TTL_CONF_KEY = "hbase.procedure.cleaner.acked.evict.ttl";
094  static final int DEFAULT_ACKED_EVICT_TTL = 5 * 60000; // 5min
095
096  /**
097   * {@link #testing} is non-null when ProcedureExecutor is being tested. Tests will try to break PE
098   * having it fail at various junctures. When non-null, testing is set to an instance of the below
099   * internal {@link Testing} class with flags set for the particular test.
100   */
101  volatile Testing testing = null;
102
103  /**
104   * Class with parameters describing how to fail/die when in testing-context.
105   */
106  public static class Testing {
107    protected volatile boolean killIfHasParent = true;
108    protected volatile boolean killIfSuspended = false;
109
110    /**
111     * Kill the PE BEFORE we store state to the WAL. Good for figuring out if a Procedure is
112     * persisting all the state it needs to recover after a crash.
113     */
114    protected volatile boolean killBeforeStoreUpdate = false;
115    protected volatile boolean toggleKillBeforeStoreUpdate = false;
116
117    /**
118     * Set when we want to fail AFTER state has been stored into the WAL. Rarely used. HBASE-20978
119     * is about a case where memory-state was being set after store to WAL where a crash could cause
120     * us to get stuck. This flag allows killing at what was a vulnerable time.
121     */
122    protected volatile boolean killAfterStoreUpdate = false;
123    protected volatile boolean toggleKillAfterStoreUpdate = false;
124
125    protected volatile boolean killBeforeStoreUpdateInRollback = false;
126    protected volatile boolean toggleKillBeforeStoreUpdateInRollback = false;
127
128    protected boolean shouldKillBeforeStoreUpdate() {
129      final boolean kill = this.killBeforeStoreUpdate;
130      if (this.toggleKillBeforeStoreUpdate) {
131        this.killBeforeStoreUpdate = !kill;
132        LOG.warn("Toggle KILL before store update to: " + this.killBeforeStoreUpdate);
133      }
134      return kill;
135    }
136
137    protected boolean shouldKillBeforeStoreUpdate(boolean isSuspended, boolean hasParent) {
138      if (isSuspended && !killIfSuspended) {
139        return false;
140      }
141      if (hasParent && !killIfHasParent) {
142        return false;
143      }
144      return shouldKillBeforeStoreUpdate();
145    }
146
147    protected boolean shouldKillAfterStoreUpdate() {
148      final boolean kill = this.killAfterStoreUpdate;
149      if (this.toggleKillAfterStoreUpdate) {
150        this.killAfterStoreUpdate = !kill;
151        LOG.warn("Toggle KILL after store update to: " + this.killAfterStoreUpdate);
152      }
153      return kill;
154    }
155
156    protected boolean shouldKillAfterStoreUpdate(final boolean isSuspended) {
157      return (isSuspended && !killIfSuspended) ? false : shouldKillAfterStoreUpdate();
158    }
159
160    protected boolean shouldKillBeforeStoreUpdateInRollback() {
161      final boolean kill = this.killBeforeStoreUpdateInRollback;
162      if (this.toggleKillBeforeStoreUpdateInRollback) {
163        this.killBeforeStoreUpdateInRollback = !kill;
164        LOG.warn("Toggle KILL before store update in rollback to: "
165          + this.killBeforeStoreUpdateInRollback);
166      }
167      return kill;
168    }
169  }
170
171  public interface ProcedureExecutorListener {
172    void procedureLoaded(long procId);
173
174    void procedureAdded(long procId);
175
176    void procedureFinished(long procId);
177  }
178
179  /**
180   * Map the the procId returned by submitProcedure(), the Root-ProcID, to the Procedure. Once a
181   * Root-Procedure completes (success or failure), the result will be added to this map. The user
182   * of ProcedureExecutor should call getResult(procId) to get the result.
183   */
184  private final ConcurrentHashMap<Long, CompletedProcedureRetainer<TEnvironment>> completed =
185    new ConcurrentHashMap<>();
186
187  /**
188   * Map the the procId returned by submitProcedure(), the Root-ProcID, to the RootProcedureState.
189   * The RootProcedureState contains the execution stack of the Root-Procedure, It is added to the
190   * map by submitProcedure() and removed on procedure completion.
191   */
192  private final ConcurrentHashMap<Long, RootProcedureState<TEnvironment>> rollbackStack =
193    new ConcurrentHashMap<>();
194
195  /**
196   * Helper map to lookup the live procedures by ID. This map contains every procedure.
197   * root-procedures and subprocedures.
198   */
199  private final ConcurrentHashMap<Long, Procedure<TEnvironment>> procedures =
200    new ConcurrentHashMap<>();
201
202  /**
203   * Helper map to lookup whether the procedure already issued from the same client. This map
204   * contains every root procedure.
205   */
206  private final ConcurrentHashMap<NonceKey, Long> nonceKeysToProcIdsMap = new ConcurrentHashMap<>();
207
208  private final CopyOnWriteArrayList<ProcedureExecutorListener> listeners =
209    new CopyOnWriteArrayList<>();
210
211  private Configuration conf;
212
213  /**
214   * Created in the {@link #init(int, boolean)} method. Destroyed in {@link #join()} (FIX! Doing
215   * resource handling rather than observing in a #join is unexpected). Overridden when we do the
216   * ProcedureTestingUtility.testRecoveryAndDoubleExecution trickery (Should be ok).
217   */
218  private ThreadGroup threadGroup;
219
220  /**
221   * Created in the {@link #init(int, boolean)} method. Terminated in {@link #join()} (FIX! Doing
222   * resource handling rather than observing in a #join is unexpected). Overridden when we do the
223   * ProcedureTestingUtility.testRecoveryAndDoubleExecution trickery (Should be ok).
224   */
225  private CopyOnWriteArrayList<WorkerThread> workerThreads;
226
227  /**
228   * Created in the {@link #init(int, boolean)} method. Terminated in {@link #join()} (FIX! Doing
229   * resource handling rather than observing in a #join is unexpected). Overridden when we do the
230   * ProcedureTestingUtility.testRecoveryAndDoubleExecution trickery (Should be ok).
231   */
232  private TimeoutExecutorThread<TEnvironment> timeoutExecutor;
233
234  /**
235   * WorkerMonitor check for stuck workers and new worker thread when necessary, for example if
236   * there is no worker to assign meta, it will new worker thread for it, so it is very important.
237   * TimeoutExecutor execute many tasks like DeadServerMetricRegionChore RegionInTransitionChore and
238   * so on, some tasks may execute for a long time so will block other tasks like WorkerMonitor, so
239   * use a dedicated thread for executing WorkerMonitor.
240   */
241  private TimeoutExecutorThread<TEnvironment> workerMonitorExecutor;
242
243  private ExecutorService forceUpdateExecutor;
244
245  // A thread pool for executing some asynchronous tasks for procedures, you can find references to
246  // getAsyncTaskExecutor to see the usage
247  private ExecutorService asyncTaskExecutor;
248
249  private int corePoolSize;
250  private int maxPoolSize;
251
252  private volatile long keepAliveTime;
253
254  /**
255   * Scheduler/Queue that contains runnable procedures.
256   */
257  private final ProcedureScheduler scheduler;
258
259  private final AtomicLong lastProcId = new AtomicLong(-1);
260  private final AtomicLong workerId = new AtomicLong(0);
261  private final AtomicInteger activeExecutorCount = new AtomicInteger(0);
262  private final AtomicBoolean running = new AtomicBoolean(false);
263  private final TEnvironment environment;
264  private final ProcedureStore store;
265
266  private final boolean checkOwnerSet;
267
268  // To prevent concurrent execution of the same procedure.
269  // For some rare cases, especially if the procedure uses ProcedureEvent, it is possible that the
270  // procedure is woken up before we finish the suspend which causes the same procedures to be
271  // executed in parallel. This does lead to some problems, see HBASE-20939&HBASE-20949, and is also
272  // a bit confusing to the developers. So here we introduce this lock to prevent the concurrent
273  // execution of the same procedure.
274  private final IdLock procExecutionLock = new IdLock();
275
276  public ProcedureExecutor(final Configuration conf, final TEnvironment environment,
277    final ProcedureStore store) {
278    this(conf, environment, store, new SimpleProcedureScheduler());
279  }
280
281  private boolean isRootFinished(Procedure<?> proc) {
282    Procedure<?> rootProc = procedures.get(proc.getRootProcId());
283    return rootProc == null || rootProc.isFinished();
284  }
285
286  private void forceUpdateProcedure(long procId) throws IOException {
287    IdLock.Entry lockEntry = procExecutionLock.getLockEntry(procId);
288    try {
289      Procedure<TEnvironment> proc = procedures.get(procId);
290      if (proc != null) {
291        if (proc.isFinished() && proc.hasParent() && isRootFinished(proc)) {
292          LOG.debug("Procedure {} has already been finished and parent is succeeded,"
293            + " skip force updating", proc);
294          return;
295        }
296      } else {
297        CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
298        if (retainer == null || retainer.getProcedure() instanceof FailedProcedure) {
299          LOG.debug("No pending procedure with id = {}, skip force updating.", procId);
300          return;
301        }
302        long evictTtl = conf.getInt(EVICT_TTL_CONF_KEY, DEFAULT_EVICT_TTL);
303        long evictAckTtl = conf.getInt(EVICT_ACKED_TTL_CONF_KEY, DEFAULT_ACKED_EVICT_TTL);
304        if (retainer.isExpired(EnvironmentEdgeManager.currentTime(), evictTtl, evictAckTtl)) {
305          LOG.debug("Procedure {} has already been finished and expired, skip force updating",
306            procId);
307          return;
308        }
309        proc = retainer.getProcedure();
310      }
311      LOG.debug("Force update procedure {}", proc);
312      store.update(proc);
313    } finally {
314      procExecutionLock.releaseLockEntry(lockEntry);
315    }
316  }
317
318  public ProcedureExecutor(final Configuration conf, final TEnvironment environment,
319    final ProcedureStore store, final ProcedureScheduler scheduler) {
320    this.environment = environment;
321    this.scheduler = scheduler;
322    this.store = store;
323    this.conf = conf;
324    this.checkOwnerSet = conf.getBoolean(CHECK_OWNER_SET_CONF_KEY, DEFAULT_CHECK_OWNER_SET);
325    refreshConfiguration(conf);
326  }
327
328  private void load(final boolean abortOnCorruption) throws IOException {
329    Preconditions.checkArgument(completed.isEmpty(), "completed not empty: %s", completed);
330    Preconditions.checkArgument(rollbackStack.isEmpty(), "rollback state not empty: %s",
331      rollbackStack);
332    Preconditions.checkArgument(procedures.isEmpty(), "procedure map not empty: %s", procedures);
333    Preconditions.checkArgument(scheduler.size() == 0, "scheduler queue not empty: %s", scheduler);
334
335    store.load(new ProcedureStore.ProcedureLoader() {
336      @Override
337      public void setMaxProcId(long maxProcId) {
338        assert lastProcId.get() < 0 : "expected only one call to setMaxProcId()";
339        lastProcId.set(maxProcId);
340      }
341
342      @Override
343      public void load(ProcedureIterator procIter) throws IOException {
344        loadProcedures(procIter);
345      }
346
347      @Override
348      public void handleCorrupted(ProcedureIterator procIter) throws IOException {
349        int corruptedCount = 0;
350        while (procIter.hasNext()) {
351          Procedure<?> proc = procIter.next();
352          LOG.error("Corrupt " + proc);
353          corruptedCount++;
354        }
355        if (abortOnCorruption && corruptedCount > 0) {
356          throw new IOException("found " + corruptedCount + " corrupted procedure(s) on replay");
357        }
358      }
359    });
360  }
361
362  private void restoreLock(Procedure<TEnvironment> proc, Set<Long> restored) {
363    proc.restoreLock(getEnvironment());
364    restored.add(proc.getProcId());
365  }
366
367  private void restoreLocks(Deque<Procedure<TEnvironment>> stack, Set<Long> restored) {
368    while (!stack.isEmpty()) {
369      restoreLock(stack.pop(), restored);
370    }
371  }
372
373  // Restore the locks for all the procedures.
374  // Notice that we need to restore the locks starting from the root proc, otherwise there will be
375  // problem that a sub procedure may hold the exclusive lock first and then we are stuck when
376  // calling the acquireLock method for the parent procedure.
377  // The algorithm is straight-forward:
378  // 1. Use a set to record the procedures which locks have already been restored.
379  // 2. Use a stack to store the hierarchy of the procedures
380  // 3. For all the procedure, we will first try to find its parent and push it into the stack,
381  // unless
382  // a. We have no parent, i.e, we are the root procedure
383  // b. The lock has already been restored(by checking the set introduced in #1)
384  // then we start to pop the stack and call acquireLock for each procedure.
385  // Notice that this should be done for all procedures, not only the ones in runnableList.
386  private void restoreLocks() {
387    Set<Long> restored = new HashSet<>();
388    Deque<Procedure<TEnvironment>> stack = new ArrayDeque<>();
389    procedures.values().forEach(proc -> {
390      for (;;) {
391        if (restored.contains(proc.getProcId())) {
392          restoreLocks(stack, restored);
393          return;
394        }
395        if (!proc.hasParent()) {
396          restoreLock(proc, restored);
397          restoreLocks(stack, restored);
398          return;
399        }
400        stack.push(proc);
401        proc = procedures.get(proc.getParentProcId());
402      }
403    });
404  }
405
406  private void initializeStacks(ProcedureIterator procIter,
407    List<Procedure<TEnvironment>> runnableList, List<Procedure<TEnvironment>> failedList,
408    List<Procedure<TEnvironment>> waitingList, List<Procedure<TEnvironment>> waitingTimeoutList)
409    throws IOException {
410    procIter.reset();
411    while (procIter.hasNext()) {
412      if (procIter.isNextFinished()) {
413        procIter.skipNext();
414        continue;
415      }
416
417      @SuppressWarnings("unchecked")
418      Procedure<TEnvironment> proc = procIter.next();
419      assert !(proc.isFinished() && !proc.hasParent()) : "unexpected completed proc=" + proc;
420      LOG.debug("Loading {}", proc);
421      Long rootProcId = getRootProcedureId(proc);
422      // The orphan procedures will be passed to handleCorrupted, so add an assert here
423      assert rootProcId != null;
424
425      if (proc.hasParent()) {
426        Procedure<TEnvironment> parent = procedures.get(proc.getParentProcId());
427        if (parent != null && !proc.isFinished()) {
428          parent.incChildrenLatch();
429        }
430      }
431
432      RootProcedureState<TEnvironment> procStack = rollbackStack.get(rootProcId);
433      procStack.loadStack(proc);
434
435      proc.setRootProcId(rootProcId);
436      switch (proc.getState()) {
437        case RUNNABLE:
438          runnableList.add(proc);
439          break;
440        case WAITING:
441          waitingList.add(proc);
442          break;
443        case WAITING_TIMEOUT:
444          waitingTimeoutList.add(proc);
445          break;
446        case FAILED:
447          failedList.add(proc);
448          break;
449        case ROLLEDBACK:
450        case INITIALIZING:
451          String msg = "Unexpected " + proc.getState() + " state for " + proc;
452          LOG.error(msg);
453          throw new UnsupportedOperationException(msg);
454        default:
455          break;
456      }
457    }
458    rollbackStack.forEach((rootProcId, procStack) -> {
459      if (procStack.getSubproceduresStack() != null) {
460        // if we have already record some stack ids, it means we support rollback
461        procStack.setRollbackSupported(true);
462      } else {
463        // otherwise, test the root procedure to see if we support rollback
464        procStack.setRollbackSupported(procedures.get(rootProcId).isRollbackSupported());
465      }
466    });
467  }
468
469  private void processWaitingProcedures(List<Procedure<TEnvironment>> waitingList,
470    List<Procedure<TEnvironment>> runnableList) {
471    waitingList.forEach(proc -> {
472      if (!proc.hasChildren()) {
473        // Normally, WAITING procedures should be waken by its children. But, there is a case that,
474        // all the children are successful and before they can wake up their parent procedure, the
475        // master was killed. So, during recovering the procedures from ProcedureWal, its children
476        // are not loaded because of their SUCCESS state. So we need to continue to run this WAITING
477        // procedure. But before executing, we need to set its state to RUNNABLE, otherwise, a
478        // exception will throw:
479        // Preconditions.checkArgument(procedure.getState() == ProcedureState.RUNNABLE,
480        // "NOT RUNNABLE! " + procedure.toString());
481        proc.setState(ProcedureState.RUNNABLE);
482        runnableList.add(proc);
483      } else {
484        proc.afterReplay(getEnvironment());
485      }
486    });
487  }
488
489  private void processWaitingTimeoutProcedures(List<Procedure<TEnvironment>> waitingTimeoutList) {
490    waitingTimeoutList.forEach(proc -> {
491      proc.afterReplay(getEnvironment());
492      timeoutExecutor.add(proc);
493    });
494  }
495
496  private void pushProceduresAfterLoad(List<Procedure<TEnvironment>> runnableList,
497    List<Procedure<TEnvironment>> failedList) {
498    failedList.forEach(scheduler::addBack);
499    runnableList.forEach(p -> {
500      p.afterReplay(getEnvironment());
501      if (!p.hasParent()) {
502        sendProcedureLoadedNotification(p.getProcId());
503      }
504      scheduler.addBack(p);
505    });
506  }
507
508  private void loadProcedures(ProcedureIterator procIter) throws IOException {
509    // 1. Build the rollback stack
510    int runnableCount = 0;
511    int failedCount = 0;
512    int waitingCount = 0;
513    int waitingTimeoutCount = 0;
514    while (procIter.hasNext()) {
515      boolean finished = procIter.isNextFinished();
516      @SuppressWarnings("unchecked")
517      Procedure<TEnvironment> proc = procIter.next();
518      NonceKey nonceKey = proc.getNonceKey();
519      long procId = proc.getProcId();
520
521      if (finished) {
522        completed.put(proc.getProcId(), new CompletedProcedureRetainer<>(proc));
523        LOG.debug("Completed {}", proc);
524      } else {
525        if (!proc.hasParent()) {
526          assert !proc.isFinished() : "unexpected finished procedure";
527          rollbackStack.put(proc.getProcId(), new RootProcedureState<>());
528        }
529
530        // add the procedure to the map
531        proc.beforeReplay(getEnvironment());
532        procedures.put(proc.getProcId(), proc);
533        switch (proc.getState()) {
534          case RUNNABLE:
535            runnableCount++;
536            break;
537          case FAILED:
538            failedCount++;
539            break;
540          case WAITING:
541            waitingCount++;
542            break;
543          case WAITING_TIMEOUT:
544            waitingTimeoutCount++;
545            break;
546          default:
547            break;
548        }
549      }
550
551      if (nonceKey != null) {
552        nonceKeysToProcIdsMap.put(nonceKey, procId); // add the nonce to the map
553      }
554    }
555
556    // 2. Initialize the stacks: In the old implementation, for procedures in FAILED state, we will
557    // push it into the ProcedureScheduler directly to execute the rollback. But this does not work
558    // after we introduce the restore lock stage. For now, when we acquire a xlock, we will remove
559    // the queue from runQueue in scheduler, and then when a procedure which has lock access, for
560    // example, a sub procedure of the procedure which has the xlock, is pushed into the scheduler,
561    // we will add the queue back to let the workers poll from it. The assumption here is that, the
562    // procedure which has the xlock should have been polled out already, so when loading we can not
563    // add the procedure to scheduler first and then call acquireLock, since the procedure is still
564    // in the queue, and since we will remove the queue from runQueue, then no one can poll it out,
565    // then there is a dead lock
566    List<Procedure<TEnvironment>> runnableList = new ArrayList<>(runnableCount);
567    List<Procedure<TEnvironment>> failedList = new ArrayList<>(failedCount);
568    List<Procedure<TEnvironment>> waitingList = new ArrayList<>(waitingCount);
569    List<Procedure<TEnvironment>> waitingTimeoutList = new ArrayList<>(waitingTimeoutCount);
570
571    initializeStacks(procIter, runnableList, failedList, waitingList, waitingTimeoutList);
572
573    // 3. Check the waiting procedures to see if some of them can be added to runnable.
574    processWaitingProcedures(waitingList, runnableList);
575
576    // 4. restore locks
577    restoreLocks();
578
579    // 5. Push the procedures to the timeout executor
580    processWaitingTimeoutProcedures(waitingTimeoutList);
581
582    // 6. Push the procedure to the scheduler
583    pushProceduresAfterLoad(runnableList, failedList);
584    // After all procedures put into the queue, signal the worker threads.
585    // Otherwise, there is a race condition. See HBASE-21364.
586    scheduler.signalAll();
587  }
588
589  /**
590   * Initialize the procedure executor, but do not start workers. We will start them later.
591   * <p/>
592   * It calls ProcedureStore.recoverLease() and ProcedureStore.load() to recover the lease, and
593   * ensure a single executor, and start the procedure replay to resume and recover the previous
594   * pending and in-progress procedures.
595   * @param numThreads        number of threads available for procedure execution.
596   * @param abortOnCorruption true if you want to abort your service in case a corrupted procedure
597   *                          is found on replay. otherwise false.
598   */
599  public void init(int numThreads, boolean abortOnCorruption) throws IOException {
600    // We have numThreads executor + one timer thread used for timing out
601    // procedures and triggering periodic procedures.
602    this.corePoolSize = numThreads;
603    this.maxPoolSize = 10 * numThreads;
604    LOG.info("Starting {} core workers (bigger of cpus/4 or 16) with max (burst) worker count={}",
605      corePoolSize, maxPoolSize);
606
607    this.threadGroup = new ThreadGroup("PEWorkerGroup");
608    this.timeoutExecutor = new TimeoutExecutorThread<>(this, threadGroup, "ProcExecTimeout");
609    this.workerMonitorExecutor = new TimeoutExecutorThread<>(this, threadGroup, "WorkerMonitor");
610    ThreadFactory backingThreadFactory = new ThreadFactory() {
611
612      @Override
613      public Thread newThread(Runnable r) {
614        return new Thread(threadGroup, r);
615      }
616    };
617    int size = Math.max(2, Runtime.getRuntime().availableProcessors());
618    ThreadPoolExecutor executor =
619      new ThreadPoolExecutor(size, size, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(),
620        new ThreadFactoryBuilder().setDaemon(true)
621          .setNameFormat(getClass().getSimpleName() + "-Async-Task-Executor-%d")
622          .setThreadFactory(backingThreadFactory).build());
623    executor.allowCoreThreadTimeOut(true);
624    this.asyncTaskExecutor = executor;
625    forceUpdateExecutor = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().setDaemon(true)
626      .setNameFormat("Force-Update-PEWorker-%d").setThreadFactory(backingThreadFactory).build());
627    store.registerListener(new ProcedureStoreListener() {
628
629      @Override
630      public void forceUpdate(long[] procIds) {
631        Arrays.stream(procIds).forEach(procId -> forceUpdateExecutor.execute(() -> {
632          try {
633            forceUpdateProcedure(procId);
634          } catch (IOException e) {
635            LOG.warn("Failed to force update procedure with pid={}", procId);
636          }
637        }));
638      }
639    });
640
641    // Create the workers
642    workerId.set(0);
643    workerThreads = new CopyOnWriteArrayList<>();
644    for (int i = 0; i < corePoolSize; ++i) {
645      workerThreads.add(new WorkerThread(threadGroup));
646    }
647
648    long st, et;
649
650    // Acquire the store lease.
651    st = System.nanoTime();
652    store.recoverLease();
653    et = System.nanoTime();
654    LOG.info("Recovered {} lease in {}", store.getClass().getSimpleName(),
655      StringUtils.humanTimeDiff(TimeUnit.NANOSECONDS.toMillis(et - st)));
656
657    // start the procedure scheduler
658    scheduler.start();
659
660    // TODO: Split in two steps.
661    // TODO: Handle corrupted procedures (currently just a warn)
662    // The first one will make sure that we have the latest id,
663    // so we can start the threads and accept new procedures.
664    // The second step will do the actual load of old procedures.
665    st = System.nanoTime();
666    load(abortOnCorruption);
667    et = System.nanoTime();
668    LOG.info("Loaded {} in {}", store.getClass().getSimpleName(),
669      StringUtils.humanTimeDiff(TimeUnit.NANOSECONDS.toMillis(et - st)));
670  }
671
672  /**
673   * Start the workers.
674   */
675  public void startWorkers() throws IOException {
676    if (!running.compareAndSet(false, true)) {
677      LOG.warn("Already running");
678      return;
679    }
680    // Start the executors. Here we must have the lastProcId set.
681    LOG.trace("Start workers {}", workerThreads.size());
682    timeoutExecutor.start();
683    workerMonitorExecutor.start();
684    for (WorkerThread worker : workerThreads) {
685      worker.start();
686    }
687
688    // Internal chores
689    workerMonitorExecutor.add(new WorkerMonitor());
690
691    // Add completed cleaner chore
692    addChore(new CompletedProcedureCleaner<>(conf, store, procExecutionLock, completed,
693      nonceKeysToProcIdsMap));
694  }
695
696  public void stop() {
697    // it is possible that we fail in init, while loading procedures, so we will not set running to
698    // true but we should have already started the ProcedureScheduler, and also the two
699    // ExecutorServices, so here we do not check running state, just stop them
700    running.set(false);
701    LOG.info("Stopping");
702    scheduler.stop();
703    timeoutExecutor.sendStopSignal();
704    workerMonitorExecutor.sendStopSignal();
705    forceUpdateExecutor.shutdown();
706    asyncTaskExecutor.shutdown();
707  }
708
709  public void join() {
710    assert !isRunning() : "expected not running";
711
712    // stop the timeout executor
713    timeoutExecutor.awaitTermination();
714    // stop the work monitor executor
715    workerMonitorExecutor.awaitTermination();
716
717    // stop the worker threads
718    for (WorkerThread worker : workerThreads) {
719      worker.awaitTermination();
720    }
721    try {
722      if (!forceUpdateExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
723        LOG.warn("There are still pending tasks in forceUpdateExecutor");
724      }
725    } catch (InterruptedException e) {
726      LOG.warn("interrupted while waiting for forceUpdateExecutor termination", e);
727      Thread.currentThread().interrupt();
728    }
729    try {
730      if (!asyncTaskExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
731        LOG.warn("There are still pending tasks in asyncTaskExecutor");
732      }
733    } catch (InterruptedException e) {
734      LOG.warn("interrupted while waiting for asyncTaskExecutor termination", e);
735      Thread.currentThread().interrupt();
736    }
737
738    // log the still active threads, ThreadGroup.destroy is deprecated in JDK17 and it is not
739    // necessary for us to must destroy it here, so we just do a check and log
740    if (threadGroup.activeCount() > 0) {
741      LOG.error("There are still active thread in group {}, see STDOUT", threadGroup);
742      threadGroup.list();
743    }
744
745    // reset the in-memory state for testing
746    completed.clear();
747    rollbackStack.clear();
748    procedures.clear();
749    nonceKeysToProcIdsMap.clear();
750    scheduler.clear();
751    lastProcId.set(-1);
752  }
753
754  public void refreshConfiguration(final Configuration conf) {
755    this.conf = conf;
756    setKeepAliveTime(conf.getLong(WORKER_KEEP_ALIVE_TIME_CONF_KEY, DEFAULT_WORKER_KEEP_ALIVE_TIME),
757      TimeUnit.MILLISECONDS);
758  }
759
760  // ==========================================================================
761  // Accessors
762  // ==========================================================================
763  public boolean isRunning() {
764    return running.get();
765  }
766
767  /** Returns the current number of worker threads. */
768  public int getWorkerThreadCount() {
769    return workerThreads.size();
770  }
771
772  /** Returns the core pool size settings. */
773  public int getCorePoolSize() {
774    return corePoolSize;
775  }
776
777  public int getActiveExecutorCount() {
778    return activeExecutorCount.get();
779  }
780
781  public TEnvironment getEnvironment() {
782    return this.environment;
783  }
784
785  public ProcedureStore getStore() {
786    return this.store;
787  }
788
789  ProcedureScheduler getScheduler() {
790    return scheduler;
791  }
792
793  public void setKeepAliveTime(final long keepAliveTime, final TimeUnit timeUnit) {
794    this.keepAliveTime = timeUnit.toMillis(keepAliveTime);
795    this.scheduler.signalAll();
796  }
797
798  public long getKeepAliveTime(final TimeUnit timeUnit) {
799    return timeUnit.convert(keepAliveTime, TimeUnit.MILLISECONDS);
800  }
801
802  // ==========================================================================
803  // Submit/Remove Chores
804  // ==========================================================================
805
806  /**
807   * Add a chore procedure to the executor
808   * @param chore the chore to add
809   */
810  public void addChore(@Nullable ProcedureInMemoryChore<TEnvironment> chore) {
811    if (chore == null) {
812      return;
813    }
814    chore.setState(ProcedureState.WAITING_TIMEOUT);
815    timeoutExecutor.add(chore);
816  }
817
818  /**
819   * Remove a chore procedure from the executor
820   * @param chore the chore to remove
821   * @return whether the chore is removed, or it will be removed later
822   */
823  public boolean removeChore(@Nullable ProcedureInMemoryChore<TEnvironment> chore) {
824    if (chore == null) {
825      return true;
826    }
827    chore.setState(ProcedureState.SUCCESS);
828    return timeoutExecutor.remove(chore);
829  }
830
831  // ==========================================================================
832  // Nonce Procedure helpers
833  // ==========================================================================
834  /**
835   * Create a NonceKey from the specified nonceGroup and nonce.
836   * @param nonceGroup the group to use for the {@link NonceKey}
837   * @param nonce      the nonce to use in the {@link NonceKey}
838   * @return the generated NonceKey
839   */
840  public NonceKey createNonceKey(final long nonceGroup, final long nonce) {
841    return (nonce == HConstants.NO_NONCE) ? null : new NonceKey(nonceGroup, nonce);
842  }
843
844  /**
845   * Register a nonce for a procedure that is going to be submitted. A procId will be reserved and
846   * on submitProcedure(), the procedure with the specified nonce will take the reserved ProcId. If
847   * someone already reserved the nonce, this method will return the procId reserved, otherwise an
848   * invalid procId will be returned. and the caller should procede and submit the procedure.
849   * @param nonceKey A unique identifier for this operation from the client or process.
850   * @return the procId associated with the nonce, if any otherwise an invalid procId.
851   */
852  public long registerNonce(final NonceKey nonceKey) {
853    if (nonceKey == null) {
854      return -1;
855    }
856
857    // check if we have already a Reserved ID for the nonce
858    Long oldProcId = nonceKeysToProcIdsMap.get(nonceKey);
859    if (oldProcId == null) {
860      // reserve a new Procedure ID, this will be associated with the nonce
861      // and the procedure submitted with the specified nonce will use this ID.
862      final long newProcId = nextProcId();
863      oldProcId = nonceKeysToProcIdsMap.putIfAbsent(nonceKey, newProcId);
864      if (oldProcId == null) {
865        return -1;
866      }
867    }
868
869    // we found a registered nonce, but the procedure may not have been submitted yet.
870    // since the client expect the procedure to be submitted, spin here until it is.
871    final boolean traceEnabled = LOG.isTraceEnabled();
872    while (
873      isRunning() && !(procedures.containsKey(oldProcId) || completed.containsKey(oldProcId))
874        && nonceKeysToProcIdsMap.containsKey(nonceKey)
875    ) {
876      if (traceEnabled) {
877        LOG.trace("Waiting for pid=" + oldProcId.longValue() + " to be submitted");
878      }
879      Threads.sleep(100);
880    }
881    return oldProcId.longValue();
882  }
883
884  /**
885   * Remove the NonceKey if the procedure was not submitted to the executor.
886   * @param nonceKey A unique identifier for this operation from the client or process.
887   */
888  public void unregisterNonceIfProcedureWasNotSubmitted(final NonceKey nonceKey) {
889    if (nonceKey == null) {
890      return;
891    }
892
893    final Long procId = nonceKeysToProcIdsMap.get(nonceKey);
894    if (procId == null) {
895      return;
896    }
897
898    // if the procedure was not submitted, remove the nonce
899    if (!(procedures.containsKey(procId) || completed.containsKey(procId))) {
900      nonceKeysToProcIdsMap.remove(nonceKey);
901    }
902  }
903
904  /**
905   * If the failure failed before submitting it, we may want to give back the same error to the
906   * requests with the same nonceKey.
907   * @param nonceKey  A unique identifier for this operation from the client or process
908   * @param procName  name of the procedure, used to inform the user
909   * @param procOwner name of the owner of the procedure, used to inform the user
910   * @param exception the failure to report to the user
911   */
912  public void setFailureResultForNonce(NonceKey nonceKey, String procName, User procOwner,
913    IOException exception) {
914    if (nonceKey == null) {
915      return;
916    }
917
918    Long procId = nonceKeysToProcIdsMap.get(nonceKey);
919    if (procId == null || completed.containsKey(procId)) {
920      return;
921    }
922
923    completed.computeIfAbsent(procId, (key) -> {
924      Procedure<TEnvironment> proc =
925        new FailedProcedure<>(procId.longValue(), procName, procOwner, nonceKey, exception);
926
927      return new CompletedProcedureRetainer<>(proc);
928    });
929  }
930
931  // ==========================================================================
932  // Submit/Abort Procedure
933  // ==========================================================================
934  /**
935   * Add a new root-procedure to the executor.
936   * @param proc the new procedure to execute.
937   * @return the procedure id, that can be used to monitor the operation
938   */
939  public long submitProcedure(Procedure<TEnvironment> proc) {
940    return submitProcedure(proc, null);
941  }
942
943  /**
944   * Bypass a procedure. If the procedure is set to bypass, all the logic in execute/rollback will
945   * be ignored and it will return success, whatever. It is used to recover buggy stuck procedures,
946   * releasing the lock resources and letting other procedures run. Bypassing one procedure (and its
947   * ancestors will be bypassed automatically) may leave the cluster in a middle state, e.g. region
948   * not assigned, or some hdfs files left behind. After getting rid of those stuck procedures, the
949   * operators may have to do some clean up on hdfs or schedule some assign procedures to let region
950   * online. DO AT YOUR OWN RISK.
951   * <p>
952   * A procedure can be bypassed only if 1. The procedure is in state of RUNNABLE, WAITING,
953   * WAITING_TIMEOUT or it is a root procedure without any child. 2. No other worker thread is
954   * executing it 3. No child procedure has been submitted
955   * <p>
956   * If all the requirements are meet, the procedure and its ancestors will be bypassed and
957   * persisted to WAL.
958   * <p>
959   * If the procedure is in WAITING state, will set it to RUNNABLE add it to run queue. TODO: What
960   * about WAITING_TIMEOUT?
961   * @param pids      the procedure id
962   * @param lockWait  time to wait lock
963   * @param force     if force set to true, we will bypass the procedure even if it is executing.
964   *                  This is for procedures which can't break out during executing(due to bug,
965   *                  mostly) In this case, bypassing the procedure is not enough, since it is
966   *                  already stuck there. We need to restart the master after bypassing, and
967   *                  letting the problematic procedure to execute wth bypass=true, so in that
968   *                  condition, the procedure can be successfully bypassed.
969   * @param recursive We will do an expensive search for children of each pid. EXPENSIVE!
970   * @return true if bypass success
971   * @throws IOException IOException
972   */
973  public List<Boolean> bypassProcedure(List<Long> pids, long lockWait, boolean force,
974    boolean recursive) throws IOException {
975    List<Boolean> result = new ArrayList<Boolean>(pids.size());
976    for (long pid : pids) {
977      result.add(bypassProcedure(pid, lockWait, force, recursive));
978    }
979    return result;
980  }
981
982  boolean bypassProcedure(long pid, long lockWait, boolean override, boolean recursive)
983    throws IOException {
984    Preconditions.checkArgument(lockWait > 0, "lockWait should be positive");
985    final Procedure<TEnvironment> procedure = getProcedure(pid);
986    if (procedure == null) {
987      LOG.debug("Procedure pid={} does not exist, skipping bypass", pid);
988      return false;
989    }
990
991    LOG.debug("Begin bypass {} with lockWait={}, override={}, recursive={}", procedure, lockWait,
992      override, recursive);
993    IdLock.Entry lockEntry = procExecutionLock.tryLockEntry(procedure.getProcId(), lockWait);
994    if (lockEntry == null && !override) {
995      LOG.debug("Waited {} ms, but {} is still running, skipping bypass with force={}", lockWait,
996        procedure, override);
997      return false;
998    } else if (lockEntry == null) {
999      LOG.debug("Waited {} ms, but {} is still running, begin bypass with force={}", lockWait,
1000        procedure, override);
1001    }
1002    try {
1003      // check whether the procedure is already finished
1004      if (procedure.isFinished()) {
1005        LOG.debug("{} is already finished, skipping bypass", procedure);
1006        return false;
1007      }
1008
1009      if (procedure.hasChildren()) {
1010        if (recursive) {
1011          // EXPENSIVE. Checks each live procedure of which there could be many!!!
1012          // Is there another way to get children of a procedure?
1013          LOG.info("Recursive bypass on children of pid={}", procedure.getProcId());
1014          this.procedures.forEachValue(1 /* Single-threaded */,
1015            // Transformer
1016            v -> v.getParentProcId() == procedure.getProcId() ? v : null,
1017            // Consumer
1018            v -> {
1019              try {
1020                bypassProcedure(v.getProcId(), lockWait, override, recursive);
1021              } catch (IOException e) {
1022                LOG.warn("Recursive bypass of pid={}", v.getProcId(), e);
1023              }
1024            });
1025        } else {
1026          LOG.debug("{} has children, skipping bypass", procedure);
1027          return false;
1028        }
1029      }
1030
1031      // If the procedure has no parent or no child, we are safe to bypass it in whatever state
1032      if (
1033        procedure.hasParent() && procedure.getState() != ProcedureState.RUNNABLE
1034          && procedure.getState() != ProcedureState.WAITING
1035          && procedure.getState() != ProcedureState.WAITING_TIMEOUT
1036      ) {
1037        LOG.debug("Bypassing procedures in RUNNABLE, WAITING and WAITING_TIMEOUT states "
1038          + "(with no parent), {}", procedure);
1039        // Question: how is the bypass done here?
1040        return false;
1041      }
1042
1043      // Now, the procedure is not finished, and no one can execute it since we take the lock now
1044      // And we can be sure that its ancestor is not running too, since their child has not
1045      // finished yet
1046      Procedure<TEnvironment> current = procedure;
1047      while (current != null) {
1048        LOG.debug("Bypassing {}", current);
1049        current.bypass(getEnvironment());
1050        store.update(current);
1051        long parentID = current.getParentProcId();
1052        current = getProcedure(parentID);
1053      }
1054
1055      // wake up waiting procedure, already checked there is no child
1056      if (procedure.getState() == ProcedureState.WAITING) {
1057        procedure.setState(ProcedureState.RUNNABLE);
1058        store.update(procedure);
1059      }
1060
1061      // If state of procedure is WAITING_TIMEOUT, we can directly submit it to the scheduler.
1062      // Instead we should remove it from timeout Executor queue and tranfer its state to RUNNABLE
1063      if (procedure.getState() == ProcedureState.WAITING_TIMEOUT) {
1064        LOG.debug("transform procedure {} from WAITING_TIMEOUT to RUNNABLE", procedure);
1065        if (timeoutExecutor.remove(procedure)) {
1066          LOG.debug("removed procedure {} from timeoutExecutor", procedure);
1067          timeoutExecutor.executeTimedoutProcedure(procedure);
1068        }
1069      } else if (lockEntry != null) {
1070        scheduler.addFront(procedure);
1071        LOG.debug("Bypassing {} and its ancestors successfully, adding to queue", procedure);
1072      } else {
1073        // If we don't have the lock, we can't re-submit the queue,
1074        // since it is already executing. To get rid of the stuck situation, we
1075        // need to restart the master. With the procedure set to bypass, the procedureExecutor
1076        // will bypass it and won't get stuck again.
1077        LOG.debug("Bypassing {} and its ancestors successfully, but since it is already running, "
1078          + "skipping add to queue", procedure);
1079      }
1080      return true;
1081
1082    } finally {
1083      if (lockEntry != null) {
1084        procExecutionLock.releaseLockEntry(lockEntry);
1085      }
1086    }
1087  }
1088
1089  /**
1090   * Add a new root-procedure to the executor.
1091   * @param proc     the new procedure to execute.
1092   * @param nonceKey the registered unique identifier for this operation from the client or process.
1093   * @return the procedure id, that can be used to monitor the operation
1094   */
1095  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NULL_ON_SOME_PATH",
1096      justification = "FindBugs is blind to the check-for-null")
1097  public long submitProcedure(Procedure<TEnvironment> proc, NonceKey nonceKey) {
1098    Preconditions.checkArgument(lastProcId.get() >= 0);
1099
1100    prepareProcedure(proc);
1101
1102    final Long currentProcId;
1103    if (nonceKey != null) {
1104      currentProcId = nonceKeysToProcIdsMap.get(nonceKey);
1105      Preconditions.checkArgument(currentProcId != null,
1106        "Expected nonceKey=" + nonceKey + " to be reserved, use registerNonce(); proc=" + proc);
1107    } else {
1108      currentProcId = nextProcId();
1109    }
1110
1111    // Initialize the procedure
1112    proc.setNonceKey(nonceKey);
1113    proc.setProcId(currentProcId.longValue());
1114
1115    // Commit the transaction
1116    store.insert(proc, null);
1117    LOG.debug("Stored {}", proc);
1118
1119    // Add the procedure to the executor
1120    return pushProcedure(proc);
1121  }
1122
1123  /**
1124   * Add a set of new root-procedure to the executor.
1125   * @param procs the new procedures to execute.
1126   */
1127  // TODO: Do we need to take nonces here?
1128  public void submitProcedures(Procedure<TEnvironment>[] procs) {
1129    Preconditions.checkArgument(lastProcId.get() >= 0);
1130    if (procs == null || procs.length <= 0) {
1131      return;
1132    }
1133
1134    // Prepare procedure
1135    for (int i = 0; i < procs.length; ++i) {
1136      prepareProcedure(procs[i]).setProcId(nextProcId());
1137    }
1138
1139    // Commit the transaction
1140    store.insert(procs);
1141    if (LOG.isDebugEnabled()) {
1142      LOG.debug("Stored " + Arrays.toString(procs));
1143    }
1144
1145    // Add the procedure to the executor
1146    for (int i = 0; i < procs.length; ++i) {
1147      pushProcedure(procs[i]);
1148    }
1149  }
1150
1151  private Procedure<TEnvironment> prepareProcedure(Procedure<TEnvironment> proc) {
1152    Preconditions.checkArgument(proc.getState() == ProcedureState.INITIALIZING);
1153    Preconditions.checkArgument(!proc.hasParent(), "unexpected parent", proc);
1154    if (this.checkOwnerSet) {
1155      Preconditions.checkArgument(proc.hasOwner(), "missing owner");
1156    }
1157    return proc;
1158  }
1159
1160  private long pushProcedure(Procedure<TEnvironment> proc) {
1161    final long currentProcId = proc.getProcId();
1162
1163    // Update metrics on start of a procedure
1164    proc.updateMetricsOnSubmit(getEnvironment());
1165
1166    // Create the rollback stack for the procedure
1167    RootProcedureState<TEnvironment> stack = new RootProcedureState<>();
1168    stack.setRollbackSupported(proc.isRollbackSupported());
1169    rollbackStack.put(currentProcId, stack);
1170
1171    // Submit the new subprocedures
1172    assert !procedures.containsKey(currentProcId);
1173    procedures.put(currentProcId, proc);
1174    sendProcedureAddedNotification(currentProcId);
1175    scheduler.addBack(proc);
1176    return proc.getProcId();
1177  }
1178
1179  /**
1180   * Send an abort notification the specified procedure. Depending on the procedure implementation
1181   * the abort can be considered or ignored.
1182   * @param procId the procedure to abort
1183   * @return true if the procedure exists and has received the abort, otherwise false.
1184   */
1185  public boolean abort(long procId) {
1186    return abort(procId, true);
1187  }
1188
1189  /**
1190   * Send an abort notification to the specified procedure. Depending on the procedure
1191   * implementation, the abort can be considered or ignored.
1192   * @param procId                the procedure to abort
1193   * @param mayInterruptIfRunning if the proc completed at least one step, should it be aborted?
1194   * @return true if the procedure exists and has received the abort, otherwise false.
1195   */
1196  public boolean abort(long procId, boolean mayInterruptIfRunning) {
1197    Procedure<TEnvironment> proc = procedures.get(procId);
1198    if (proc != null) {
1199      if (!mayInterruptIfRunning && proc.wasExecuted()) {
1200        return false;
1201      }
1202      return proc.abort(getEnvironment());
1203    }
1204    return false;
1205  }
1206
1207  // ==========================================================================
1208  // Executor query helpers
1209  // ==========================================================================
1210  public Procedure<TEnvironment> getProcedure(final long procId) {
1211    return procedures.get(procId);
1212  }
1213
1214  public <T extends Procedure<TEnvironment>> T getProcedure(Class<T> clazz, long procId) {
1215    Procedure<TEnvironment> proc = getProcedure(procId);
1216    if (clazz.isInstance(proc)) {
1217      return clazz.cast(proc);
1218    }
1219    return null;
1220  }
1221
1222  public Procedure<TEnvironment> getResult(long procId) {
1223    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1224    if (retainer == null) {
1225      return null;
1226    } else {
1227      return retainer.getProcedure();
1228    }
1229  }
1230
1231  /**
1232   * Return true if the procedure is finished. The state may be "completed successfully" or "failed
1233   * and rolledback". Use getResult() to check the state or get the result data.
1234   * @param procId the ID of the procedure to check
1235   * @return true if the procedure execution is finished, otherwise false.
1236   */
1237  public boolean isFinished(final long procId) {
1238    return !procedures.containsKey(procId);
1239  }
1240
1241  /**
1242   * Return true if the procedure is started.
1243   * @param procId the ID of the procedure to check
1244   * @return true if the procedure execution is started, otherwise false.
1245   */
1246  public boolean isStarted(long procId) {
1247    Procedure<?> proc = procedures.get(procId);
1248    if (proc == null) {
1249      return completed.get(procId) != null;
1250    }
1251    return proc.wasExecuted();
1252  }
1253
1254  /**
1255   * Mark the specified completed procedure, as ready to remove.
1256   * @param procId the ID of the procedure to remove
1257   */
1258  public void removeResult(long procId) {
1259    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1260    if (retainer == null) {
1261      assert !procedures.containsKey(procId) : "pid=" + procId + " is still running";
1262      LOG.debug("pid={} already removed by the cleaner.", procId);
1263      return;
1264    }
1265
1266    // The CompletedProcedureCleaner will take care of deletion, once the TTL is expired.
1267    retainer.setClientAckTime(EnvironmentEdgeManager.currentTime());
1268  }
1269
1270  public Procedure<TEnvironment> getResultOrProcedure(long procId) {
1271    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1272    if (retainer == null) {
1273      return procedures.get(procId);
1274    } else {
1275      return retainer.getProcedure();
1276    }
1277  }
1278
1279  /**
1280   * Check if the user is this procedure's owner
1281   * @param procId the target procedure
1282   * @param user   the user
1283   * @return true if the user is the owner of the procedure, false otherwise or the owner is
1284   *         unknown.
1285   */
1286  public boolean isProcedureOwner(long procId, User user) {
1287    if (user == null) {
1288      return false;
1289    }
1290    final Procedure<TEnvironment> runningProc = procedures.get(procId);
1291    if (runningProc != null) {
1292      return runningProc.getOwner().equals(user.getShortName());
1293    }
1294
1295    final CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1296    if (retainer != null) {
1297      return retainer.getProcedure().getOwner().equals(user.getShortName());
1298    }
1299
1300    // Procedure either does not exist or has already completed and got cleaned up.
1301    // At this time, we cannot check the owner of the procedure
1302    return false;
1303  }
1304
1305  /**
1306   * Should only be used when starting up, where the procedure workers have not been started.
1307   * <p/>
1308   * If the procedure works has been started, the return values maybe changed when you are
1309   * processing it so usually this is not safe. Use {@link #getProcedures()} below for most cases as
1310   * it will do a copy, and also include the finished procedures.
1311   */
1312  public Collection<Procedure<TEnvironment>> getActiveProceduresNoCopy() {
1313    return procedures.values();
1314  }
1315
1316  /**
1317   * Get procedures.
1318   * @return the procedures in a list
1319   */
1320  public List<Procedure<TEnvironment>> getProcedures() {
1321    List<Procedure<TEnvironment>> procedureList =
1322      new ArrayList<>(procedures.size() + completed.size());
1323    procedureList.addAll(procedures.values());
1324    // Note: The procedure could show up twice in the list with different state, as
1325    // it could complete after we walk through procedures list and insert into
1326    // procedureList - it is ok, as we will use the information in the Procedure
1327    // to figure it out; to prevent this would increase the complexity of the logic.
1328    completed.values().stream().map(CompletedProcedureRetainer::getProcedure)
1329      .forEach(procedureList::add);
1330    return procedureList;
1331  }
1332
1333  // ==========================================================================
1334  // Listeners helpers
1335  // ==========================================================================
1336  public void registerListener(ProcedureExecutorListener listener) {
1337    this.listeners.add(listener);
1338  }
1339
1340  public boolean unregisterListener(ProcedureExecutorListener listener) {
1341    return this.listeners.remove(listener);
1342  }
1343
1344  private void sendProcedureLoadedNotification(final long procId) {
1345    if (!this.listeners.isEmpty()) {
1346      for (ProcedureExecutorListener listener : this.listeners) {
1347        try {
1348          listener.procedureLoaded(procId);
1349        } catch (Throwable e) {
1350          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1351        }
1352      }
1353    }
1354  }
1355
1356  private void sendProcedureAddedNotification(final long procId) {
1357    if (!this.listeners.isEmpty()) {
1358      for (ProcedureExecutorListener listener : this.listeners) {
1359        try {
1360          listener.procedureAdded(procId);
1361        } catch (Throwable e) {
1362          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1363        }
1364      }
1365    }
1366  }
1367
1368  private void sendProcedureFinishedNotification(final long procId) {
1369    if (!this.listeners.isEmpty()) {
1370      for (ProcedureExecutorListener listener : this.listeners) {
1371        try {
1372          listener.procedureFinished(procId);
1373        } catch (Throwable e) {
1374          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1375        }
1376      }
1377    }
1378  }
1379
1380  // ==========================================================================
1381  // Procedure IDs helpers
1382  // ==========================================================================
1383  private long nextProcId() {
1384    long procId = lastProcId.incrementAndGet();
1385    if (procId < 0) {
1386      while (!lastProcId.compareAndSet(procId, 0)) {
1387        procId = lastProcId.get();
1388        if (procId >= 0) {
1389          break;
1390        }
1391      }
1392      while (procedures.containsKey(procId)) {
1393        procId = lastProcId.incrementAndGet();
1394      }
1395    }
1396    assert procId >= 0 : "Invalid procId " + procId;
1397    return procId;
1398  }
1399
1400  protected long getLastProcId() {
1401    return lastProcId.get();
1402  }
1403
1404  public Set<Long> getActiveProcIds() {
1405    return procedures.keySet();
1406  }
1407
1408  Long getRootProcedureId(Procedure<TEnvironment> proc) {
1409    return Procedure.getRootProcedureId(procedures, proc);
1410  }
1411
1412  // ==========================================================================
1413  // Executions
1414  // ==========================================================================
1415  private void executeProcedure(Procedure<TEnvironment> proc) {
1416    if (proc.isFinished()) {
1417      LOG.debug("{} is already finished, skipping execution", proc);
1418      return;
1419    }
1420    final Long rootProcId = getRootProcedureId(proc);
1421    if (rootProcId == null) {
1422      // The 'proc' was ready to run but the root procedure was rolledback
1423      LOG.warn("Rollback because parent is done/rolledback proc=" + proc);
1424      executeRollback(proc);
1425      return;
1426    }
1427
1428    RootProcedureState<TEnvironment> procStack = rollbackStack.get(rootProcId);
1429    if (procStack == null) {
1430      LOG.warn("RootProcedureState is null for " + proc.getProcId());
1431      return;
1432    }
1433    do {
1434      // Try to acquire the execution
1435      if (!procStack.acquire(proc)) {
1436        if (procStack.setRollback()) {
1437          // we have the 'rollback-lock' we can start rollingback
1438          switch (executeRollback(rootProcId, procStack)) {
1439            case LOCK_ACQUIRED:
1440              break;
1441            case LOCK_YIELD_WAIT:
1442              procStack.unsetRollback();
1443              scheduler.yield(proc);
1444              break;
1445            case LOCK_EVENT_WAIT:
1446              LOG.info("LOCK_EVENT_WAIT rollback..." + proc);
1447              procStack.unsetRollback();
1448              break;
1449            default:
1450              throw new UnsupportedOperationException();
1451          }
1452        } else {
1453          // if we can't rollback means that some child is still running.
1454          // the rollback will be executed after all the children are done.
1455          // If the procedure was never executed, remove and mark it as rolledback.
1456          if (!proc.wasExecuted()) {
1457            switch (executeRollback(proc)) {
1458              case LOCK_ACQUIRED:
1459                break;
1460              case LOCK_YIELD_WAIT:
1461                scheduler.yield(proc);
1462                break;
1463              case LOCK_EVENT_WAIT:
1464                LOG.info("LOCK_EVENT_WAIT can't rollback child running?..." + proc);
1465                break;
1466              default:
1467                throw new UnsupportedOperationException();
1468            }
1469          }
1470        }
1471        break;
1472      }
1473
1474      // Execute the procedure
1475      assert proc.getState() == ProcedureState.RUNNABLE : proc;
1476      // Note that lock is NOT about concurrency but rather about ensuring
1477      // ownership of a procedure of an entity such as a region or table
1478      LockState lockState = acquireLock(proc);
1479      switch (lockState) {
1480        case LOCK_ACQUIRED:
1481          execProcedure(procStack, proc);
1482          break;
1483        case LOCK_YIELD_WAIT:
1484          LOG.info(lockState + " " + proc);
1485          scheduler.yield(proc);
1486          break;
1487        case LOCK_EVENT_WAIT:
1488          // Someone will wake us up when the lock is available
1489          LOG.debug(lockState + " " + proc);
1490          break;
1491        default:
1492          throw new UnsupportedOperationException();
1493      }
1494      procStack.release(proc);
1495
1496      if (proc.isSuccess()) {
1497        // update metrics on finishing the procedure
1498        proc.updateMetricsOnFinish(getEnvironment(), proc.elapsedTime(), true);
1499        LOG.info("Finished " + proc + " in " + StringUtils.humanTimeDiff(proc.elapsedTime()));
1500        // Finalize the procedure state
1501        if (proc.getProcId() == rootProcId) {
1502          procedureFinished(proc);
1503        } else {
1504          execCompletionCleanup(proc);
1505        }
1506        break;
1507      }
1508    } while (procStack.isFailed());
1509  }
1510
1511  private LockState acquireLock(Procedure<TEnvironment> proc) {
1512    TEnvironment env = getEnvironment();
1513    // if holdLock is true, then maybe we already have the lock, so just return LOCK_ACQUIRED if
1514    // hasLock is true.
1515    if (proc.hasLock()) {
1516      return LockState.LOCK_ACQUIRED;
1517    }
1518    return proc.doAcquireLock(env, store);
1519  }
1520
1521  private void releaseLock(Procedure<TEnvironment> proc, boolean force) {
1522    TEnvironment env = getEnvironment();
1523    // For how the framework works, we know that we will always have the lock
1524    // when we call releaseLock(), so we can avoid calling proc.hasLock()
1525    if (force || !proc.holdLock(env) || proc.isFinished()) {
1526      proc.doReleaseLock(env, store);
1527    }
1528  }
1529
1530  // Returning null means we have already held the execution lock, so you do not need to get the
1531  // lock entry for releasing
1532  private IdLock.Entry getLockEntryForRollback(long procId) {
1533    // Hold the execution lock if it is not held by us. The IdLock is not reentrant so we need
1534    // this check, as the worker will hold the lock before executing a procedure. This is the only
1535    // place where we may hold two procedure execution locks, and there is a fence in the
1536    // RootProcedureState where we can make sure that only one worker can execute the rollback of
1537    // a RootProcedureState, so there is no dead lock problem. And the lock here is necessary to
1538    // prevent race between us and the force update thread.
1539    if (!procExecutionLock.isHeldByCurrentThread(procId)) {
1540      try {
1541        return procExecutionLock.getLockEntry(procId);
1542      } catch (IOException e) {
1543        // can only happen if interrupted, so not a big deal to propagate it
1544        throw new UncheckedIOException(e);
1545      }
1546    }
1547    return null;
1548  }
1549
1550  private void executeUnexpectedRollback(Procedure<TEnvironment> rootProc,
1551    RootProcedureState<TEnvironment> procStack) {
1552    if (procStack.getSubprocs() != null) {
1553      // comparing proc id in reverse order, so we will delete later procedures first, otherwise we
1554      // may delete parent procedure first and if we fail in the middle of this operation, when
1555      // loading we will find some orphan procedures
1556      PriorityQueue<Procedure<TEnvironment>> pq =
1557        new PriorityQueue<>(procStack.getSubprocs().size(),
1558          Comparator.<Procedure<TEnvironment>> comparingLong(Procedure::getProcId).reversed());
1559      pq.addAll(procStack.getSubprocs());
1560      for (;;) {
1561        Procedure<TEnvironment> subproc = pq.poll();
1562        if (subproc == null) {
1563          break;
1564        }
1565        if (!procedures.containsKey(subproc.getProcId())) {
1566          // this means it has already been rolledback
1567          continue;
1568        }
1569        IdLock.Entry lockEntry = getLockEntryForRollback(subproc.getProcId());
1570        try {
1571          cleanupAfterRollbackOneStep(subproc);
1572          execCompletionCleanup(subproc);
1573        } finally {
1574          if (lockEntry != null) {
1575            procExecutionLock.releaseLockEntry(lockEntry);
1576          }
1577        }
1578      }
1579    }
1580    IdLock.Entry lockEntry = getLockEntryForRollback(rootProc.getProcId());
1581    try {
1582      cleanupAfterRollbackOneStep(rootProc);
1583    } finally {
1584      if (lockEntry != null) {
1585        procExecutionLock.releaseLockEntry(lockEntry);
1586      }
1587    }
1588  }
1589
1590  private LockState executeNormalRollback(Procedure<TEnvironment> rootProc,
1591    RootProcedureState<TEnvironment> procStack) {
1592    List<Procedure<TEnvironment>> subprocStack = procStack.getSubproceduresStack();
1593    assert subprocStack != null : "Called rollback with no steps executed rootProc=" + rootProc;
1594
1595    int stackTail = subprocStack.size();
1596    while (stackTail-- > 0) {
1597      Procedure<TEnvironment> proc = subprocStack.get(stackTail);
1598      IdLock.Entry lockEntry = getLockEntryForRollback(proc.getProcId());
1599      try {
1600        // For the sub procedures which are successfully finished, we do not rollback them.
1601        // Typically, if we want to rollback a procedure, we first need to rollback it, and then
1602        // recursively rollback its ancestors. The state changes which are done by sub procedures
1603        // should be handled by parent procedures when rolling back. For example, when rolling back
1604        // a MergeTableProcedure, we will schedule new procedures to bring the offline regions
1605        // online, instead of rolling back the original procedures which offlined the regions(in
1606        // fact these procedures can not be rolled back...).
1607        if (proc.isSuccess()) {
1608          // Just do the cleanup work, without actually executing the rollback
1609          subprocStack.remove(stackTail);
1610          cleanupAfterRollbackOneStep(proc);
1611          continue;
1612        }
1613        LockState lockState = acquireLock(proc);
1614        if (lockState != LockState.LOCK_ACQUIRED) {
1615          // can't take a lock on the procedure, add the root-proc back on the
1616          // queue waiting for the lock availability
1617          return lockState;
1618        }
1619
1620        lockState = executeRollback(proc);
1621        releaseLock(proc, false);
1622        boolean abortRollback = lockState != LockState.LOCK_ACQUIRED;
1623        abortRollback |= !isRunning() || !store.isRunning();
1624
1625        // allows to kill the executor before something is stored to the wal.
1626        // useful to test the procedure recovery.
1627        if (abortRollback) {
1628          return lockState;
1629        }
1630
1631        subprocStack.remove(stackTail);
1632
1633        // if the procedure is kind enough to pass the slot to someone else, yield
1634        // if the proc is already finished, do not yield
1635        if (!proc.isFinished() && proc.isYieldAfterExecutionStep(getEnvironment())) {
1636          return LockState.LOCK_YIELD_WAIT;
1637        }
1638
1639        if (proc != rootProc) {
1640          execCompletionCleanup(proc);
1641        }
1642      } finally {
1643        if (lockEntry != null) {
1644          procExecutionLock.releaseLockEntry(lockEntry);
1645        }
1646      }
1647    }
1648    return LockState.LOCK_ACQUIRED;
1649  }
1650
1651  /**
1652   * Execute the rollback of the full procedure stack. Once the procedure is rolledback, the
1653   * root-procedure will be visible as finished to user, and the result will be the fatal exception.
1654   */
1655  private LockState executeRollback(long rootProcId, RootProcedureState<TEnvironment> procStack) {
1656    Procedure<TEnvironment> rootProc = procedures.get(rootProcId);
1657    RemoteProcedureException exception = rootProc.getException();
1658    // TODO: This needs doc. The root proc doesn't have an exception. Maybe we are
1659    // rolling back because the subprocedure does. Clarify.
1660    if (exception == null) {
1661      exception = procStack.getException();
1662      rootProc.setFailure(exception);
1663      store.update(rootProc);
1664    }
1665
1666    if (procStack.isRollbackSupported()) {
1667      LockState lockState = executeNormalRollback(rootProc, procStack);
1668      if (lockState != LockState.LOCK_ACQUIRED) {
1669        return lockState;
1670      }
1671    } else {
1672      // the procedure does not support rollback, so typically we should not reach here, this
1673      // usually means there are code bugs, let's just wait all the subprocedures to finish and then
1674      // mark the root procedure as failure.
1675      LOG.error(HBaseMarkers.FATAL,
1676        "Root Procedure {} does not support rollback but the execution failed"
1677          + " and try to rollback, code bug?",
1678        rootProc, exception);
1679      executeUnexpectedRollback(rootProc, procStack);
1680    }
1681
1682    IdLock.Entry lockEntry = getLockEntryForRollback(rootProc.getProcId());
1683    try {
1684      // Finalize the procedure state
1685      LOG.info("Rolled back {} exec-time={}", rootProc,
1686        StringUtils.humanTimeDiff(rootProc.elapsedTime()));
1687      procedureFinished(rootProc);
1688    } finally {
1689      if (lockEntry != null) {
1690        procExecutionLock.releaseLockEntry(lockEntry);
1691      }
1692    }
1693
1694    return LockState.LOCK_ACQUIRED;
1695  }
1696
1697  private void cleanupAfterRollbackOneStep(Procedure<TEnvironment> proc) {
1698    if (testing != null && testing.shouldKillBeforeStoreUpdateInRollback()) {
1699      kill("TESTING: Kill BEFORE store update in rollback: " + proc);
1700    }
1701    if (proc.removeStackIndex()) {
1702      if (!proc.isSuccess()) {
1703        proc.setState(ProcedureState.ROLLEDBACK);
1704      }
1705
1706      // update metrics on finishing the procedure (fail)
1707      proc.updateMetricsOnFinish(getEnvironment(), proc.elapsedTime(), false);
1708
1709      if (proc.hasParent()) {
1710        store.delete(proc.getProcId());
1711        procedures.remove(proc.getProcId());
1712      } else {
1713        final long[] childProcIds = rollbackStack.get(proc.getProcId()).getSubprocedureIds();
1714        if (childProcIds != null) {
1715          store.delete(proc, childProcIds);
1716        } else {
1717          store.update(proc);
1718        }
1719      }
1720    } else {
1721      store.update(proc);
1722    }
1723  }
1724
1725  /**
1726   * Execute the rollback of the procedure step. It updates the store with the new state (stack
1727   * index) or will remove completly the procedure in case it is a child.
1728   */
1729  private LockState executeRollback(Procedure<TEnvironment> proc) {
1730    try {
1731      proc.doRollback(getEnvironment());
1732    } catch (IOException e) {
1733      LOG.debug("Roll back attempt failed for {}", proc, e);
1734      return LockState.LOCK_YIELD_WAIT;
1735    } catch (InterruptedException e) {
1736      handleInterruptedException(proc, e);
1737      return LockState.LOCK_YIELD_WAIT;
1738    } catch (Throwable e) {
1739      // Catch NullPointerExceptions or similar errors...
1740      LOG.error(HBaseMarkers.FATAL, "CODE-BUG: Uncaught runtime exception for " + proc, e);
1741    }
1742
1743    cleanupAfterRollbackOneStep(proc);
1744
1745    return LockState.LOCK_ACQUIRED;
1746  }
1747
1748  private void yieldProcedure(Procedure<TEnvironment> proc) {
1749    releaseLock(proc, false);
1750    scheduler.yield(proc);
1751  }
1752
1753  /**
1754   * Executes <code>procedure</code>
1755   * <ul>
1756   * <li>Calls the doExecute() of the procedure
1757   * <li>If the procedure execution didn't fail (i.e. valid user input)
1758   * <ul>
1759   * <li>...and returned subprocedures
1760   * <ul>
1761   * <li>The subprocedures are initialized.
1762   * <li>The subprocedures are added to the store
1763   * <li>The subprocedures are added to the runnable queue
1764   * <li>The procedure is now in a WAITING state, waiting for the subprocedures to complete
1765   * </ul>
1766   * </li>
1767   * <li>...if there are no subprocedure
1768   * <ul>
1769   * <li>the procedure completed successfully
1770   * <li>if there is a parent (WAITING)
1771   * <li>the parent state will be set to RUNNABLE
1772   * </ul>
1773   * </li>
1774   * </ul>
1775   * </li>
1776   * <li>In case of failure
1777   * <ul>
1778   * <li>The store is updated with the new state</li>
1779   * <li>The executor (caller of this method) will start the rollback of the procedure</li>
1780   * </ul>
1781   * </li>
1782   * </ul>
1783   */
1784  private void execProcedure(RootProcedureState<TEnvironment> procStack,
1785    Procedure<TEnvironment> procedure) {
1786    Preconditions.checkArgument(procedure.getState() == ProcedureState.RUNNABLE,
1787      "NOT RUNNABLE! " + procedure.toString());
1788
1789    // Procedures can suspend themselves. They skip out by throwing a ProcedureSuspendedException.
1790    // The exception is caught below and then we hurry to the exit without disturbing state. The
1791    // idea is that the processing of this procedure will be unsuspended later by an external event
1792    // such the report of a region open.
1793    boolean suspended = false;
1794
1795    // Whether to 're-' -execute; run through the loop again.
1796    boolean reExecute = false;
1797
1798    Procedure<TEnvironment>[] subprocs = null;
1799    do {
1800      reExecute = false;
1801      procedure.resetPersistence();
1802      try {
1803        subprocs = procedure.doExecute(getEnvironment());
1804        if (subprocs != null && subprocs.length == 0) {
1805          subprocs = null;
1806        }
1807      } catch (ProcedureSuspendedException e) {
1808        LOG.trace("Suspend {}", procedure);
1809        suspended = true;
1810      } catch (ProcedureYieldException e) {
1811        LOG.trace("Yield {}", procedure, e);
1812        yieldProcedure(procedure);
1813        return;
1814      } catch (InterruptedException e) {
1815        LOG.trace("Yield interrupt {}", procedure, e);
1816        handleInterruptedException(procedure, e);
1817        yieldProcedure(procedure);
1818        return;
1819      } catch (Throwable e) {
1820        // Catch NullPointerExceptions or similar errors...
1821        String msg = "CODE-BUG: Uncaught runtime exception: " + procedure;
1822        LOG.error(msg, e);
1823        procedure.setFailure(new RemoteProcedureException(msg, e));
1824      }
1825
1826      if (!procedure.isFailed()) {
1827        if (subprocs != null) {
1828          if (subprocs.length == 1 && subprocs[0] == procedure) {
1829            // Procedure returned itself. Quick-shortcut for a state machine-like procedure;
1830            // i.e. we go around this loop again rather than go back out on the scheduler queue.
1831            subprocs = null;
1832            reExecute = true;
1833            LOG.trace("Short-circuit to next step on pid={}", procedure.getProcId());
1834          } else {
1835            // Yield the current procedure, and make the subprocedure runnable
1836            // subprocs may come back 'null'.
1837            subprocs = initializeChildren(procStack, procedure, subprocs);
1838            LOG.info("Initialized subprocedures=" + (subprocs == null
1839              ? null
1840              : Stream.of(subprocs).map(e -> "{" + e.toString() + "}").collect(Collectors.toList())
1841                .toString()));
1842          }
1843        } else if (procedure.getState() == ProcedureState.WAITING_TIMEOUT) {
1844          LOG.trace("Added to timeoutExecutor {}", procedure);
1845          timeoutExecutor.add(procedure);
1846        } else if (!suspended) {
1847          // No subtask, so we are done
1848          procedure.setState(ProcedureState.SUCCESS);
1849        }
1850      }
1851
1852      // allows to kill the executor before something is stored to the wal.
1853      // useful to test the procedure recovery.
1854      if (
1855        testing != null && testing.shouldKillBeforeStoreUpdate(suspended, procedure.hasParent())
1856      ) {
1857        kill("TESTING: Kill BEFORE store update: " + procedure);
1858      }
1859
1860      // TODO: The code here doesn't check if store is running before persisting to the store as
1861      // it relies on the method call below to throw RuntimeException to wind up the stack and
1862      // executor thread to stop. The statement following the method call below seems to check if
1863      // store is not running, to prevent scheduling children procedures, re-execution or yield
1864      // of this procedure. This may need more scrutiny and subsequent cleanup in future
1865      //
1866      // Commit the transaction even if a suspend (state may have changed). Note this append
1867      // can take a bunch of time to complete.
1868      if (procedure.needPersistence()) {
1869        // Add the procedure to the stack
1870        // See HBASE-28210 on why we need synchronized here
1871        boolean needUpdateStoreOutsideLock = false;
1872        synchronized (procStack) {
1873          if (procStack.addRollbackStep(procedure)) {
1874            updateStoreOnExec(procStack, procedure, subprocs);
1875          } else {
1876            needUpdateStoreOutsideLock = true;
1877          }
1878        }
1879        // this is an optimization if we do not need to maintain rollback step, as all subprocedures
1880        // of the same root procedure share the same root procedure state, if we can only update
1881        // store under the above lock, the sub procedures of the same root procedure can only be
1882        // persistent sequentially, which will have a bad performance. See HBASE-28212 for more
1883        // details.
1884        if (needUpdateStoreOutsideLock) {
1885          updateStoreOnExec(procStack, procedure, subprocs);
1886        }
1887      }
1888
1889      // if the store is not running we are aborting
1890      if (!store.isRunning()) {
1891        return;
1892      }
1893      // if the procedure is kind enough to pass the slot to someone else, yield
1894      if (
1895        procedure.isRunnable() && !suspended
1896          && procedure.isYieldAfterExecutionStep(getEnvironment())
1897      ) {
1898        yieldProcedure(procedure);
1899        return;
1900      }
1901
1902      assert (reExecute && subprocs == null) || !reExecute;
1903    } while (reExecute);
1904
1905    // Allows to kill the executor after something is stored to the WAL but before the below
1906    // state settings are done -- in particular the one on the end where we make parent
1907    // RUNNABLE again when its children are done; see countDownChildren.
1908    if (testing != null && testing.shouldKillAfterStoreUpdate(suspended)) {
1909      kill("TESTING: Kill AFTER store update: " + procedure);
1910    }
1911
1912    // Submit the new subprocedures
1913    if (subprocs != null && !procedure.isFailed()) {
1914      submitChildrenProcedures(subprocs);
1915    }
1916
1917    // we need to log the release lock operation before waking up the parent procedure, as there
1918    // could be race that the parent procedure may call updateStoreOnExec ahead of us and remove all
1919    // the sub procedures from store and cause problems...
1920    releaseLock(procedure, false);
1921
1922    // if the procedure is complete and has a parent, count down the children latch.
1923    // If 'suspended', do nothing to change state -- let other threads handle unsuspend event.
1924    if (!suspended && procedure.isFinished() && procedure.hasParent()) {
1925      countDownChildren(procStack, procedure);
1926    }
1927  }
1928
1929  private void kill(String msg) {
1930    LOG.debug(msg);
1931    stop();
1932    throw new RuntimeException(msg);
1933  }
1934
1935  private Procedure<TEnvironment>[] initializeChildren(RootProcedureState<TEnvironment> procStack,
1936    Procedure<TEnvironment> procedure, Procedure<TEnvironment>[] subprocs) {
1937    assert subprocs != null : "expected subprocedures";
1938    final long rootProcId = getRootProcedureId(procedure);
1939    for (int i = 0; i < subprocs.length; ++i) {
1940      Procedure<TEnvironment> subproc = subprocs[i];
1941      if (subproc == null) {
1942        String msg = "subproc[" + i + "] is null, aborting the procedure";
1943        procedure
1944          .setFailure(new RemoteProcedureException(msg, new IllegalArgumentIOException(msg)));
1945        return null;
1946      }
1947
1948      assert subproc.getState() == ProcedureState.INITIALIZING : subproc;
1949      subproc.setParentProcId(procedure.getProcId());
1950      subproc.setRootProcId(rootProcId);
1951      subproc.setProcId(nextProcId());
1952      procStack.addSubProcedure(subproc);
1953    }
1954
1955    if (!procedure.isFailed()) {
1956      procedure.setChildrenLatch(subprocs.length);
1957      switch (procedure.getState()) {
1958        case RUNNABLE:
1959          procedure.setState(ProcedureState.WAITING);
1960          break;
1961        case WAITING_TIMEOUT:
1962          timeoutExecutor.add(procedure);
1963          break;
1964        default:
1965          break;
1966      }
1967    }
1968    return subprocs;
1969  }
1970
1971  private void submitChildrenProcedures(Procedure<TEnvironment>[] subprocs) {
1972    for (int i = 0; i < subprocs.length; ++i) {
1973      Procedure<TEnvironment> subproc = subprocs[i];
1974      subproc.updateMetricsOnSubmit(getEnvironment());
1975      assert !procedures.containsKey(subproc.getProcId());
1976      procedures.put(subproc.getProcId(), subproc);
1977      scheduler.addFront(subproc);
1978    }
1979  }
1980
1981  private void countDownChildren(RootProcedureState<TEnvironment> procStack,
1982    Procedure<TEnvironment> procedure) {
1983    Procedure<TEnvironment> parent = procedures.get(procedure.getParentProcId());
1984    if (parent == null) {
1985      assert procStack.isRollingback();
1986      return;
1987    }
1988
1989    // If this procedure is the last child awake the parent procedure
1990    if (parent.tryRunnable()) {
1991      // If we succeeded in making the parent runnable -- i.e. all of its
1992      // children have completed, move parent to front of the queue.
1993      store.update(parent);
1994      scheduler.addFront(parent);
1995      LOG.info("Finished subprocedure pid={}, resume processing ppid={}", procedure.getProcId(),
1996        parent.getProcId());
1997      return;
1998    }
1999  }
2000
2001  private void updateStoreOnExec(RootProcedureState<TEnvironment> procStack,
2002    Procedure<TEnvironment> procedure, Procedure<TEnvironment>[] subprocs) {
2003    if (subprocs != null && !procedure.isFailed()) {
2004      if (LOG.isTraceEnabled()) {
2005        LOG.trace("Stored " + procedure + ", children " + Arrays.toString(subprocs));
2006      }
2007      store.insert(procedure, subprocs);
2008    } else {
2009      LOG.trace("Store update {}", procedure);
2010      if (procedure.isFinished() && !procedure.hasParent()) {
2011        // remove child procedures
2012        final long[] childProcIds = procStack.getSubprocedureIds();
2013        if (childProcIds != null) {
2014          store.delete(procedure, childProcIds);
2015          for (int i = 0; i < childProcIds.length; ++i) {
2016            procedures.remove(childProcIds[i]);
2017          }
2018        } else {
2019          store.update(procedure);
2020        }
2021      } else {
2022        store.update(procedure);
2023      }
2024    }
2025  }
2026
2027  private void handleInterruptedException(Procedure<TEnvironment> proc, InterruptedException e) {
2028    LOG.trace("Interrupt during {}. suspend and retry it later.", proc, e);
2029    // NOTE: We don't call Thread.currentThread().interrupt()
2030    // because otherwise all the subsequent calls e.g. Thread.sleep() will throw
2031    // the InterruptedException. If the master is going down, we will be notified
2032    // and the executor/store will be stopped.
2033    // (The interrupted procedure will be retried on the next run)
2034  }
2035
2036  private void execCompletionCleanup(Procedure<TEnvironment> proc) {
2037    final TEnvironment env = getEnvironment();
2038    if (proc.hasLock()) {
2039      LOG.warn("Usually this should not happen, we will release the lock before if the procedure"
2040        + " is finished, even if the holdLock is true, arrive here means we have some holes where"
2041        + " we do not release the lock. And the releaseLock below may fail since the procedure may"
2042        + " have already been deleted from the procedure store.");
2043      releaseLock(proc, true);
2044    }
2045    try {
2046      proc.completionCleanup(env);
2047    } catch (Throwable e) {
2048      // Catch NullPointerExceptions or similar errors...
2049      LOG.error("CODE-BUG: uncatched runtime exception for procedure: " + proc, e);
2050    }
2051  }
2052
2053  private void procedureFinished(Procedure<TEnvironment> proc) {
2054    // call the procedure completion cleanup handler
2055    execCompletionCleanup(proc);
2056
2057    CompletedProcedureRetainer<TEnvironment> retainer = new CompletedProcedureRetainer<>(proc);
2058
2059    // update the executor internal state maps
2060    if (!proc.shouldWaitClientAck(getEnvironment())) {
2061      retainer.setClientAckTime(0);
2062    }
2063
2064    completed.put(proc.getProcId(), retainer);
2065    rollbackStack.remove(proc.getProcId());
2066    procedures.remove(proc.getProcId());
2067
2068    // call the runnableSet completion cleanup handler
2069    try {
2070      scheduler.completionCleanup(proc);
2071    } catch (Throwable e) {
2072      // Catch NullPointerExceptions or similar errors...
2073      LOG.error("CODE-BUG: uncatched runtime exception for completion cleanup: {}", proc, e);
2074    }
2075
2076    // Notify the listeners
2077    sendProcedureFinishedNotification(proc.getProcId());
2078  }
2079
2080  RootProcedureState<TEnvironment> getProcStack(long rootProcId) {
2081    return rollbackStack.get(rootProcId);
2082  }
2083
2084  ProcedureScheduler getProcedureScheduler() {
2085    return scheduler;
2086  }
2087
2088  int getCompletedSize() {
2089    return completed.size();
2090  }
2091
2092  public IdLock getProcExecutionLock() {
2093    return procExecutionLock;
2094  }
2095
2096  /**
2097   * Get a thread pool for executing some asynchronous tasks
2098   */
2099  public ExecutorService getAsyncTaskExecutor() {
2100    return asyncTaskExecutor;
2101  }
2102
2103  // ==========================================================================
2104  // Worker Thread
2105  // ==========================================================================
2106  private class WorkerThread extends StoppableThread {
2107    private final AtomicLong executionStartTime = new AtomicLong(Long.MAX_VALUE);
2108    private volatile Procedure<TEnvironment> activeProcedure;
2109
2110    public WorkerThread(ThreadGroup group) {
2111      this(group, "PEWorker-");
2112    }
2113
2114    protected WorkerThread(ThreadGroup group, String prefix) {
2115      super(group, prefix + workerId.incrementAndGet());
2116      setDaemon(true);
2117    }
2118
2119    @Override
2120    public void sendStopSignal() {
2121      scheduler.signalAll();
2122    }
2123
2124    /**
2125     * Encapsulates execution of the current {@link #activeProcedure} for easy tracing.
2126     */
2127    private long runProcedure() throws IOException {
2128      final Procedure<TEnvironment> proc = this.activeProcedure;
2129      int activeCount = activeExecutorCount.incrementAndGet();
2130      int runningCount = store.setRunningProcedureCount(activeCount);
2131      LOG.trace("Execute pid={} runningCount={}, activeCount={}", proc.getProcId(), runningCount,
2132        activeCount);
2133      executionStartTime.set(EnvironmentEdgeManager.currentTime());
2134      IdLock.Entry lockEntry = procExecutionLock.getLockEntry(proc.getProcId());
2135      try {
2136        executeProcedure(proc);
2137      } catch (AssertionError e) {
2138        LOG.info("ASSERT pid=" + proc.getProcId(), e);
2139        throw e;
2140      } finally {
2141        procExecutionLock.releaseLockEntry(lockEntry);
2142        activeCount = activeExecutorCount.decrementAndGet();
2143        runningCount = store.setRunningProcedureCount(activeCount);
2144        LOG.trace("Halt pid={} runningCount={}, activeCount={}", proc.getProcId(), runningCount,
2145          activeCount);
2146        this.activeProcedure = null;
2147        executionStartTime.set(Long.MAX_VALUE);
2148      }
2149      return EnvironmentEdgeManager.currentTime();
2150    }
2151
2152    @Override
2153    public void run() {
2154      long lastUpdate = EnvironmentEdgeManager.currentTime();
2155      try {
2156        while (isRunning() && keepAlive(lastUpdate)) {
2157          @SuppressWarnings("unchecked")
2158          Procedure<TEnvironment> proc = scheduler.poll(keepAliveTime, TimeUnit.MILLISECONDS);
2159          if (proc == null) {
2160            continue;
2161          }
2162          this.activeProcedure = proc;
2163          lastUpdate = TraceUtil.trace(this::runProcedure, new ProcedureSpanBuilder(proc));
2164        }
2165      } catch (Throwable t) {
2166        LOG.warn("Worker terminating UNNATURALLY {}", this.activeProcedure, t);
2167      } finally {
2168        LOG.trace("Worker terminated.");
2169      }
2170      workerThreads.remove(this);
2171    }
2172
2173    @Override
2174    public String toString() {
2175      Procedure<?> p = this.activeProcedure;
2176      return getName() + "(pid=" + (p == null ? Procedure.NO_PROC_ID : p.getProcId() + ")");
2177    }
2178
2179    /** Returns the time since the current procedure is running */
2180    public long getCurrentRunTime() {
2181      return EnvironmentEdgeManager.currentTime() - executionStartTime.get();
2182    }
2183
2184    // core worker never timeout
2185    protected boolean keepAlive(long lastUpdate) {
2186      return true;
2187    }
2188  }
2189
2190  // A worker thread which can be added when core workers are stuck. Will timeout after
2191  // keepAliveTime if there is no procedure to run.
2192  private final class KeepAliveWorkerThread extends WorkerThread {
2193    public KeepAliveWorkerThread(ThreadGroup group) {
2194      super(group, "KeepAlivePEWorker-");
2195    }
2196
2197    @Override
2198    protected boolean keepAlive(long lastUpdate) {
2199      return EnvironmentEdgeManager.currentTime() - lastUpdate < keepAliveTime;
2200    }
2201  }
2202
2203  // ----------------------------------------------------------------------------
2204  // TODO-MAYBE: Should we provide a InlineChore to notify the store with the
2205  // full set of procedures pending and completed to write a compacted
2206  // version of the log (in case is a log)?
2207  // In theory no, procedures are have a short life, so at some point the store
2208  // will have the tracker saying everything is in the last log.
2209  // ----------------------------------------------------------------------------
2210
2211  private final class WorkerMonitor extends InlineChore {
2212    public static final String WORKER_MONITOR_INTERVAL_CONF_KEY =
2213      "hbase.procedure.worker.monitor.interval.msec";
2214    private static final int DEFAULT_WORKER_MONITOR_INTERVAL = 5000; // 5sec
2215
2216    public static final String WORKER_STUCK_THRESHOLD_CONF_KEY =
2217      "hbase.procedure.worker.stuck.threshold.msec";
2218    private static final int DEFAULT_WORKER_STUCK_THRESHOLD = 10000; // 10sec
2219
2220    public static final String WORKER_ADD_STUCK_PERCENTAGE_CONF_KEY =
2221      "hbase.procedure.worker.add.stuck.percentage";
2222    private static final float DEFAULT_WORKER_ADD_STUCK_PERCENTAGE = 0.5f; // 50% stuck
2223
2224    private float addWorkerStuckPercentage = DEFAULT_WORKER_ADD_STUCK_PERCENTAGE;
2225    private int timeoutInterval = DEFAULT_WORKER_MONITOR_INTERVAL;
2226    private int stuckThreshold = DEFAULT_WORKER_STUCK_THRESHOLD;
2227
2228    public WorkerMonitor() {
2229      refreshConfig();
2230    }
2231
2232    @Override
2233    public void run() {
2234      final int stuckCount = checkForStuckWorkers();
2235      checkThreadCount(stuckCount);
2236
2237      // refresh interval (poor man dynamic conf update)
2238      refreshConfig();
2239    }
2240
2241    private int checkForStuckWorkers() {
2242      // check if any of the worker is stuck
2243      int stuckCount = 0;
2244      for (WorkerThread worker : workerThreads) {
2245        if (worker.getCurrentRunTime() < stuckThreshold) {
2246          continue;
2247        }
2248
2249        // WARN the worker is stuck
2250        stuckCount++;
2251        LOG.warn("Worker stuck {}, run time {}", worker,
2252          StringUtils.humanTimeDiff(worker.getCurrentRunTime()));
2253      }
2254      return stuckCount;
2255    }
2256
2257    private void checkThreadCount(final int stuckCount) {
2258      // nothing to do if there are no runnable tasks
2259      if (stuckCount < 1 || !scheduler.hasRunnables()) {
2260        return;
2261      }
2262
2263      // add a new thread if the worker stuck percentage exceed the threshold limit
2264      // and every handler is active.
2265      final float stuckPerc = ((float) stuckCount) / workerThreads.size();
2266      // let's add new worker thread more aggressively, as they will timeout finally if there is no
2267      // work to do.
2268      if (stuckPerc >= addWorkerStuckPercentage && workerThreads.size() < maxPoolSize) {
2269        final KeepAliveWorkerThread worker = new KeepAliveWorkerThread(threadGroup);
2270        workerThreads.add(worker);
2271        worker.start();
2272        LOG.debug("Added new worker thread {}", worker);
2273      }
2274    }
2275
2276    private void refreshConfig() {
2277      addWorkerStuckPercentage =
2278        conf.getFloat(WORKER_ADD_STUCK_PERCENTAGE_CONF_KEY, DEFAULT_WORKER_ADD_STUCK_PERCENTAGE);
2279      timeoutInterval =
2280        conf.getInt(WORKER_MONITOR_INTERVAL_CONF_KEY, DEFAULT_WORKER_MONITOR_INTERVAL);
2281      stuckThreshold = conf.getInt(WORKER_STUCK_THRESHOLD_CONF_KEY, DEFAULT_WORKER_STUCK_THRESHOLD);
2282    }
2283
2284    @Override
2285    public int getTimeoutInterval() {
2286      return timeoutInterval;
2287    }
2288  }
2289}