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    // Destroy the Thread Group for the executors
739    // TODO: Fix. #join is not place to destroy resources.
740    try {
741      threadGroup.destroy();
742    } catch (IllegalThreadStateException e) {
743      LOG.error("ThreadGroup {} contains running threads; {}: See STDOUT", this.threadGroup, e);
744      // This dumps list of threads on STDOUT.
745      this.threadGroup.list();
746    }
747
748    // reset the in-memory state for testing
749    completed.clear();
750    rollbackStack.clear();
751    procedures.clear();
752    nonceKeysToProcIdsMap.clear();
753    scheduler.clear();
754    lastProcId.set(-1);
755  }
756
757  public void refreshConfiguration(final Configuration conf) {
758    this.conf = conf;
759    setKeepAliveTime(conf.getLong(WORKER_KEEP_ALIVE_TIME_CONF_KEY, DEFAULT_WORKER_KEEP_ALIVE_TIME),
760      TimeUnit.MILLISECONDS);
761  }
762
763  // ==========================================================================
764  // Accessors
765  // ==========================================================================
766  public boolean isRunning() {
767    return running.get();
768  }
769
770  /** Returns the current number of worker threads. */
771  public int getWorkerThreadCount() {
772    return workerThreads.size();
773  }
774
775  /** Returns the core pool size settings. */
776  public int getCorePoolSize() {
777    return corePoolSize;
778  }
779
780  public int getActiveExecutorCount() {
781    return activeExecutorCount.get();
782  }
783
784  public TEnvironment getEnvironment() {
785    return this.environment;
786  }
787
788  public ProcedureStore getStore() {
789    return this.store;
790  }
791
792  ProcedureScheduler getScheduler() {
793    return scheduler;
794  }
795
796  public void setKeepAliveTime(final long keepAliveTime, final TimeUnit timeUnit) {
797    this.keepAliveTime = timeUnit.toMillis(keepAliveTime);
798    this.scheduler.signalAll();
799  }
800
801  public long getKeepAliveTime(final TimeUnit timeUnit) {
802    return timeUnit.convert(keepAliveTime, TimeUnit.MILLISECONDS);
803  }
804
805  // ==========================================================================
806  // Submit/Remove Chores
807  // ==========================================================================
808
809  /**
810   * Add a chore procedure to the executor
811   * @param chore the chore to add
812   */
813  public void addChore(@Nullable ProcedureInMemoryChore<TEnvironment> chore) {
814    if (chore == null) {
815      return;
816    }
817    chore.setState(ProcedureState.WAITING_TIMEOUT);
818    timeoutExecutor.add(chore);
819  }
820
821  /**
822   * Remove a chore procedure from the executor
823   * @param chore the chore to remove
824   * @return whether the chore is removed, or it will be removed later
825   */
826  public boolean removeChore(@Nullable ProcedureInMemoryChore<TEnvironment> chore) {
827    if (chore == null) {
828      return true;
829    }
830    chore.setState(ProcedureState.SUCCESS);
831    return timeoutExecutor.remove(chore);
832  }
833
834  // ==========================================================================
835  // Nonce Procedure helpers
836  // ==========================================================================
837  /**
838   * Create a NonceKey from the specified nonceGroup and nonce.
839   * @param nonceGroup the group to use for the {@link NonceKey}
840   * @param nonce      the nonce to use in the {@link NonceKey}
841   * @return the generated NonceKey
842   */
843  public NonceKey createNonceKey(final long nonceGroup, final long nonce) {
844    return (nonce == HConstants.NO_NONCE) ? null : new NonceKey(nonceGroup, nonce);
845  }
846
847  /**
848   * Register a nonce for a procedure that is going to be submitted. A procId will be reserved and
849   * on submitProcedure(), the procedure with the specified nonce will take the reserved ProcId. If
850   * someone already reserved the nonce, this method will return the procId reserved, otherwise an
851   * invalid procId will be returned. and the caller should procede and submit the procedure.
852   * @param nonceKey A unique identifier for this operation from the client or process.
853   * @return the procId associated with the nonce, if any otherwise an invalid procId.
854   */
855  public long registerNonce(final NonceKey nonceKey) {
856    if (nonceKey == null) {
857      return -1;
858    }
859
860    // check if we have already a Reserved ID for the nonce
861    Long oldProcId = nonceKeysToProcIdsMap.get(nonceKey);
862    if (oldProcId == null) {
863      // reserve a new Procedure ID, this will be associated with the nonce
864      // and the procedure submitted with the specified nonce will use this ID.
865      final long newProcId = nextProcId();
866      oldProcId = nonceKeysToProcIdsMap.putIfAbsent(nonceKey, newProcId);
867      if (oldProcId == null) {
868        return -1;
869      }
870    }
871
872    // we found a registered nonce, but the procedure may not have been submitted yet.
873    // since the client expect the procedure to be submitted, spin here until it is.
874    final boolean traceEnabled = LOG.isTraceEnabled();
875    while (
876      isRunning() && !(procedures.containsKey(oldProcId) || completed.containsKey(oldProcId))
877        && nonceKeysToProcIdsMap.containsKey(nonceKey)
878    ) {
879      if (traceEnabled) {
880        LOG.trace("Waiting for pid=" + oldProcId.longValue() + " to be submitted");
881      }
882      Threads.sleep(100);
883    }
884    return oldProcId.longValue();
885  }
886
887  /**
888   * Remove the NonceKey if the procedure was not submitted to the executor.
889   * @param nonceKey A unique identifier for this operation from the client or process.
890   */
891  public void unregisterNonceIfProcedureWasNotSubmitted(final NonceKey nonceKey) {
892    if (nonceKey == null) {
893      return;
894    }
895
896    final Long procId = nonceKeysToProcIdsMap.get(nonceKey);
897    if (procId == null) {
898      return;
899    }
900
901    // if the procedure was not submitted, remove the nonce
902    if (!(procedures.containsKey(procId) || completed.containsKey(procId))) {
903      nonceKeysToProcIdsMap.remove(nonceKey);
904    }
905  }
906
907  /**
908   * If the failure failed before submitting it, we may want to give back the same error to the
909   * requests with the same nonceKey.
910   * @param nonceKey  A unique identifier for this operation from the client or process
911   * @param procName  name of the procedure, used to inform the user
912   * @param procOwner name of the owner of the procedure, used to inform the user
913   * @param exception the failure to report to the user
914   */
915  public void setFailureResultForNonce(NonceKey nonceKey, String procName, User procOwner,
916    IOException exception) {
917    if (nonceKey == null) {
918      return;
919    }
920
921    Long procId = nonceKeysToProcIdsMap.get(nonceKey);
922    if (procId == null || completed.containsKey(procId)) {
923      return;
924    }
925
926    completed.computeIfAbsent(procId, (key) -> {
927      Procedure<TEnvironment> proc =
928        new FailedProcedure<>(procId.longValue(), procName, procOwner, nonceKey, exception);
929
930      return new CompletedProcedureRetainer<>(proc);
931    });
932  }
933
934  // ==========================================================================
935  // Submit/Abort Procedure
936  // ==========================================================================
937  /**
938   * Add a new root-procedure to the executor.
939   * @param proc the new procedure to execute.
940   * @return the procedure id, that can be used to monitor the operation
941   */
942  public long submitProcedure(Procedure<TEnvironment> proc) {
943    return submitProcedure(proc, null);
944  }
945
946  /**
947   * Bypass a procedure. If the procedure is set to bypass, all the logic in execute/rollback will
948   * be ignored and it will return success, whatever. It is used to recover buggy stuck procedures,
949   * releasing the lock resources and letting other procedures run. Bypassing one procedure (and its
950   * ancestors will be bypassed automatically) may leave the cluster in a middle state, e.g. region
951   * not assigned, or some hdfs files left behind. After getting rid of those stuck procedures, the
952   * operators may have to do some clean up on hdfs or schedule some assign procedures to let region
953   * online. DO AT YOUR OWN RISK.
954   * <p>
955   * A procedure can be bypassed only if 1. The procedure is in state of RUNNABLE, WAITING,
956   * WAITING_TIMEOUT or it is a root procedure without any child. 2. No other worker thread is
957   * executing it 3. No child procedure has been submitted
958   * <p>
959   * If all the requirements are meet, the procedure and its ancestors will be bypassed and
960   * persisted to WAL.
961   * <p>
962   * If the procedure is in WAITING state, will set it to RUNNABLE add it to run queue. TODO: What
963   * about WAITING_TIMEOUT?
964   * @param pids      the procedure id
965   * @param lockWait  time to wait lock
966   * @param force     if force set to true, we will bypass the procedure even if it is executing.
967   *                  This is for procedures which can't break out during executing(due to bug,
968   *                  mostly) In this case, bypassing the procedure is not enough, since it is
969   *                  already stuck there. We need to restart the master after bypassing, and
970   *                  letting the problematic procedure to execute wth bypass=true, so in that
971   *                  condition, the procedure can be successfully bypassed.
972   * @param recursive We will do an expensive search for children of each pid. EXPENSIVE!
973   * @return true if bypass success
974   * @throws IOException IOException
975   */
976  public List<Boolean> bypassProcedure(List<Long> pids, long lockWait, boolean force,
977    boolean recursive) throws IOException {
978    List<Boolean> result = new ArrayList<Boolean>(pids.size());
979    for (long pid : pids) {
980      result.add(bypassProcedure(pid, lockWait, force, recursive));
981    }
982    return result;
983  }
984
985  boolean bypassProcedure(long pid, long lockWait, boolean override, boolean recursive)
986    throws IOException {
987    Preconditions.checkArgument(lockWait > 0, "lockWait should be positive");
988    final Procedure<TEnvironment> procedure = getProcedure(pid);
989    if (procedure == null) {
990      LOG.debug("Procedure pid={} does not exist, skipping bypass", pid);
991      return false;
992    }
993
994    LOG.debug("Begin bypass {} with lockWait={}, override={}, recursive={}", procedure, lockWait,
995      override, recursive);
996    IdLock.Entry lockEntry = procExecutionLock.tryLockEntry(procedure.getProcId(), lockWait);
997    if (lockEntry == null && !override) {
998      LOG.debug("Waited {} ms, but {} is still running, skipping bypass with force={}", lockWait,
999        procedure, override);
1000      return false;
1001    } else if (lockEntry == null) {
1002      LOG.debug("Waited {} ms, but {} is still running, begin bypass with force={}", lockWait,
1003        procedure, override);
1004    }
1005    try {
1006      // check whether the procedure is already finished
1007      if (procedure.isFinished()) {
1008        LOG.debug("{} is already finished, skipping bypass", procedure);
1009        return false;
1010      }
1011
1012      if (procedure.hasChildren()) {
1013        if (recursive) {
1014          // EXPENSIVE. Checks each live procedure of which there could be many!!!
1015          // Is there another way to get children of a procedure?
1016          LOG.info("Recursive bypass on children of pid={}", procedure.getProcId());
1017          this.procedures.forEachValue(1 /* Single-threaded */,
1018            // Transformer
1019            v -> v.getParentProcId() == procedure.getProcId() ? v : null,
1020            // Consumer
1021            v -> {
1022              try {
1023                bypassProcedure(v.getProcId(), lockWait, override, recursive);
1024              } catch (IOException e) {
1025                LOG.warn("Recursive bypass of pid={}", v.getProcId(), e);
1026              }
1027            });
1028        } else {
1029          LOG.debug("{} has children, skipping bypass", procedure);
1030          return false;
1031        }
1032      }
1033
1034      // If the procedure has no parent or no child, we are safe to bypass it in whatever state
1035      if (
1036        procedure.hasParent() && procedure.getState() != ProcedureState.RUNNABLE
1037          && procedure.getState() != ProcedureState.WAITING
1038          && procedure.getState() != ProcedureState.WAITING_TIMEOUT
1039      ) {
1040        LOG.debug("Bypassing procedures in RUNNABLE, WAITING and WAITING_TIMEOUT states "
1041          + "(with no parent), {}", procedure);
1042        // Question: how is the bypass done here?
1043        return false;
1044      }
1045
1046      // Now, the procedure is not finished, and no one can execute it since we take the lock now
1047      // And we can be sure that its ancestor is not running too, since their child has not
1048      // finished yet
1049      Procedure<TEnvironment> current = procedure;
1050      while (current != null) {
1051        LOG.debug("Bypassing {}", current);
1052        current.bypass(getEnvironment());
1053        store.update(current);
1054        long parentID = current.getParentProcId();
1055        current = getProcedure(parentID);
1056      }
1057
1058      // wake up waiting procedure, already checked there is no child
1059      if (procedure.getState() == ProcedureState.WAITING) {
1060        procedure.setState(ProcedureState.RUNNABLE);
1061        store.update(procedure);
1062      }
1063
1064      // If state of procedure is WAITING_TIMEOUT, we can directly submit it to the scheduler.
1065      // Instead we should remove it from timeout Executor queue and tranfer its state to RUNNABLE
1066      if (procedure.getState() == ProcedureState.WAITING_TIMEOUT) {
1067        LOG.debug("transform procedure {} from WAITING_TIMEOUT to RUNNABLE", procedure);
1068        if (timeoutExecutor.remove(procedure)) {
1069          LOG.debug("removed procedure {} from timeoutExecutor", procedure);
1070          timeoutExecutor.executeTimedoutProcedure(procedure);
1071        }
1072      } else if (lockEntry != null) {
1073        scheduler.addFront(procedure);
1074        LOG.debug("Bypassing {} and its ancestors successfully, adding to queue", procedure);
1075      } else {
1076        // If we don't have the lock, we can't re-submit the queue,
1077        // since it is already executing. To get rid of the stuck situation, we
1078        // need to restart the master. With the procedure set to bypass, the procedureExecutor
1079        // will bypass it and won't get stuck again.
1080        LOG.debug("Bypassing {} and its ancestors successfully, but since it is already running, "
1081          + "skipping add to queue", procedure);
1082      }
1083      return true;
1084
1085    } finally {
1086      if (lockEntry != null) {
1087        procExecutionLock.releaseLockEntry(lockEntry);
1088      }
1089    }
1090  }
1091
1092  /**
1093   * Add a new root-procedure to the executor.
1094   * @param proc     the new procedure to execute.
1095   * @param nonceKey the registered unique identifier for this operation from the client or process.
1096   * @return the procedure id, that can be used to monitor the operation
1097   */
1098  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "NP_NULL_ON_SOME_PATH",
1099      justification = "FindBugs is blind to the check-for-null")
1100  public long submitProcedure(Procedure<TEnvironment> proc, NonceKey nonceKey) {
1101    Preconditions.checkArgument(lastProcId.get() >= 0);
1102
1103    prepareProcedure(proc);
1104
1105    final Long currentProcId;
1106    if (nonceKey != null) {
1107      currentProcId = nonceKeysToProcIdsMap.get(nonceKey);
1108      Preconditions.checkArgument(currentProcId != null,
1109        "Expected nonceKey=" + nonceKey + " to be reserved, use registerNonce(); proc=" + proc);
1110    } else {
1111      currentProcId = nextProcId();
1112    }
1113
1114    // Initialize the procedure
1115    proc.setNonceKey(nonceKey);
1116    proc.setProcId(currentProcId.longValue());
1117
1118    // Commit the transaction
1119    store.insert(proc, null);
1120    LOG.debug("Stored {}", proc);
1121
1122    // Add the procedure to the executor
1123    return pushProcedure(proc);
1124  }
1125
1126  /**
1127   * Add a set of new root-procedure to the executor.
1128   * @param procs the new procedures to execute.
1129   */
1130  // TODO: Do we need to take nonces here?
1131  public void submitProcedures(Procedure<TEnvironment>[] procs) {
1132    Preconditions.checkArgument(lastProcId.get() >= 0);
1133    if (procs == null || procs.length <= 0) {
1134      return;
1135    }
1136
1137    // Prepare procedure
1138    for (int i = 0; i < procs.length; ++i) {
1139      prepareProcedure(procs[i]).setProcId(nextProcId());
1140    }
1141
1142    // Commit the transaction
1143    store.insert(procs);
1144    if (LOG.isDebugEnabled()) {
1145      LOG.debug("Stored " + Arrays.toString(procs));
1146    }
1147
1148    // Add the procedure to the executor
1149    for (int i = 0; i < procs.length; ++i) {
1150      pushProcedure(procs[i]);
1151    }
1152  }
1153
1154  private Procedure<TEnvironment> prepareProcedure(Procedure<TEnvironment> proc) {
1155    Preconditions.checkArgument(proc.getState() == ProcedureState.INITIALIZING);
1156    Preconditions.checkArgument(!proc.hasParent(), "unexpected parent", proc);
1157    if (this.checkOwnerSet) {
1158      Preconditions.checkArgument(proc.hasOwner(), "missing owner");
1159    }
1160    return proc;
1161  }
1162
1163  private long pushProcedure(Procedure<TEnvironment> proc) {
1164    final long currentProcId = proc.getProcId();
1165
1166    // Update metrics on start of a procedure
1167    proc.updateMetricsOnSubmit(getEnvironment());
1168
1169    // Create the rollback stack for the procedure
1170    RootProcedureState<TEnvironment> stack = new RootProcedureState<>();
1171    stack.setRollbackSupported(proc.isRollbackSupported());
1172    rollbackStack.put(currentProcId, stack);
1173
1174    // Submit the new subprocedures
1175    assert !procedures.containsKey(currentProcId);
1176    procedures.put(currentProcId, proc);
1177    sendProcedureAddedNotification(currentProcId);
1178    scheduler.addBack(proc);
1179    return proc.getProcId();
1180  }
1181
1182  /**
1183   * Send an abort notification the specified procedure. Depending on the procedure implementation
1184   * the abort can be considered or ignored.
1185   * @param procId the procedure to abort
1186   * @return true if the procedure exists and has received the abort, otherwise false.
1187   */
1188  public boolean abort(long procId) {
1189    return abort(procId, true);
1190  }
1191
1192  /**
1193   * Send an abort notification to the specified procedure. Depending on the procedure
1194   * implementation, the abort can be considered or ignored.
1195   * @param procId                the procedure to abort
1196   * @param mayInterruptIfRunning if the proc completed at least one step, should it be aborted?
1197   * @return true if the procedure exists and has received the abort, otherwise false.
1198   */
1199  public boolean abort(long procId, boolean mayInterruptIfRunning) {
1200    Procedure<TEnvironment> proc = procedures.get(procId);
1201    if (proc != null) {
1202      if (!mayInterruptIfRunning && proc.wasExecuted()) {
1203        return false;
1204      }
1205      return proc.abort(getEnvironment());
1206    }
1207    return false;
1208  }
1209
1210  // ==========================================================================
1211  // Executor query helpers
1212  // ==========================================================================
1213  public Procedure<TEnvironment> getProcedure(final long procId) {
1214    return procedures.get(procId);
1215  }
1216
1217  public <T extends Procedure<TEnvironment>> T getProcedure(Class<T> clazz, long procId) {
1218    Procedure<TEnvironment> proc = getProcedure(procId);
1219    if (clazz.isInstance(proc)) {
1220      return clazz.cast(proc);
1221    }
1222    return null;
1223  }
1224
1225  public Procedure<TEnvironment> getResult(long procId) {
1226    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1227    if (retainer == null) {
1228      return null;
1229    } else {
1230      return retainer.getProcedure();
1231    }
1232  }
1233
1234  /**
1235   * Return true if the procedure is finished. The state may be "completed successfully" or "failed
1236   * and rolledback". Use getResult() to check the state or get the result data.
1237   * @param procId the ID of the procedure to check
1238   * @return true if the procedure execution is finished, otherwise false.
1239   */
1240  public boolean isFinished(final long procId) {
1241    return !procedures.containsKey(procId);
1242  }
1243
1244  /**
1245   * Return true if the procedure is started.
1246   * @param procId the ID of the procedure to check
1247   * @return true if the procedure execution is started, otherwise false.
1248   */
1249  public boolean isStarted(long procId) {
1250    Procedure<?> proc = procedures.get(procId);
1251    if (proc == null) {
1252      return completed.get(procId) != null;
1253    }
1254    return proc.wasExecuted();
1255  }
1256
1257  /**
1258   * Mark the specified completed procedure, as ready to remove.
1259   * @param procId the ID of the procedure to remove
1260   */
1261  public void removeResult(long procId) {
1262    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1263    if (retainer == null) {
1264      assert !procedures.containsKey(procId) : "pid=" + procId + " is still running";
1265      LOG.debug("pid={} already removed by the cleaner.", procId);
1266      return;
1267    }
1268
1269    // The CompletedProcedureCleaner will take care of deletion, once the TTL is expired.
1270    retainer.setClientAckTime(EnvironmentEdgeManager.currentTime());
1271  }
1272
1273  public Procedure<TEnvironment> getResultOrProcedure(long procId) {
1274    CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1275    if (retainer == null) {
1276      return procedures.get(procId);
1277    } else {
1278      return retainer.getProcedure();
1279    }
1280  }
1281
1282  /**
1283   * Check if the user is this procedure's owner
1284   * @param procId the target procedure
1285   * @param user   the user
1286   * @return true if the user is the owner of the procedure, false otherwise or the owner is
1287   *         unknown.
1288   */
1289  public boolean isProcedureOwner(long procId, User user) {
1290    if (user == null) {
1291      return false;
1292    }
1293    final Procedure<TEnvironment> runningProc = procedures.get(procId);
1294    if (runningProc != null) {
1295      return runningProc.getOwner().equals(user.getShortName());
1296    }
1297
1298    final CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
1299    if (retainer != null) {
1300      return retainer.getProcedure().getOwner().equals(user.getShortName());
1301    }
1302
1303    // Procedure either does not exist or has already completed and got cleaned up.
1304    // At this time, we cannot check the owner of the procedure
1305    return false;
1306  }
1307
1308  /**
1309   * Should only be used when starting up, where the procedure workers have not been started.
1310   * <p/>
1311   * If the procedure works has been started, the return values maybe changed when you are
1312   * processing it so usually this is not safe. Use {@link #getProcedures()} below for most cases as
1313   * it will do a copy, and also include the finished procedures.
1314   */
1315  public Collection<Procedure<TEnvironment>> getActiveProceduresNoCopy() {
1316    return procedures.values();
1317  }
1318
1319  /**
1320   * Get procedures.
1321   * @return the procedures in a list
1322   */
1323  public List<Procedure<TEnvironment>> getProcedures() {
1324    List<Procedure<TEnvironment>> procedureList =
1325      new ArrayList<>(procedures.size() + completed.size());
1326    procedureList.addAll(procedures.values());
1327    // Note: The procedure could show up twice in the list with different state, as
1328    // it could complete after we walk through procedures list and insert into
1329    // procedureList - it is ok, as we will use the information in the Procedure
1330    // to figure it out; to prevent this would increase the complexity of the logic.
1331    completed.values().stream().map(CompletedProcedureRetainer::getProcedure)
1332      .forEach(procedureList::add);
1333    return procedureList;
1334  }
1335
1336  // ==========================================================================
1337  // Listeners helpers
1338  // ==========================================================================
1339  public void registerListener(ProcedureExecutorListener listener) {
1340    this.listeners.add(listener);
1341  }
1342
1343  public boolean unregisterListener(ProcedureExecutorListener listener) {
1344    return this.listeners.remove(listener);
1345  }
1346
1347  private void sendProcedureLoadedNotification(final long procId) {
1348    if (!this.listeners.isEmpty()) {
1349      for (ProcedureExecutorListener listener : this.listeners) {
1350        try {
1351          listener.procedureLoaded(procId);
1352        } catch (Throwable e) {
1353          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1354        }
1355      }
1356    }
1357  }
1358
1359  private void sendProcedureAddedNotification(final long procId) {
1360    if (!this.listeners.isEmpty()) {
1361      for (ProcedureExecutorListener listener : this.listeners) {
1362        try {
1363          listener.procedureAdded(procId);
1364        } catch (Throwable e) {
1365          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1366        }
1367      }
1368    }
1369  }
1370
1371  private void sendProcedureFinishedNotification(final long procId) {
1372    if (!this.listeners.isEmpty()) {
1373      for (ProcedureExecutorListener listener : this.listeners) {
1374        try {
1375          listener.procedureFinished(procId);
1376        } catch (Throwable e) {
1377          LOG.error("Listener " + listener + " had an error: " + e.getMessage(), e);
1378        }
1379      }
1380    }
1381  }
1382
1383  // ==========================================================================
1384  // Procedure IDs helpers
1385  // ==========================================================================
1386  private long nextProcId() {
1387    long procId = lastProcId.incrementAndGet();
1388    if (procId < 0) {
1389      while (!lastProcId.compareAndSet(procId, 0)) {
1390        procId = lastProcId.get();
1391        if (procId >= 0) {
1392          break;
1393        }
1394      }
1395      while (procedures.containsKey(procId)) {
1396        procId = lastProcId.incrementAndGet();
1397      }
1398    }
1399    assert procId >= 0 : "Invalid procId " + procId;
1400    return procId;
1401  }
1402
1403  protected long getLastProcId() {
1404    return lastProcId.get();
1405  }
1406
1407  public Set<Long> getActiveProcIds() {
1408    return procedures.keySet();
1409  }
1410
1411  Long getRootProcedureId(Procedure<TEnvironment> proc) {
1412    return Procedure.getRootProcedureId(procedures, proc);
1413  }
1414
1415  // ==========================================================================
1416  // Executions
1417  // ==========================================================================
1418  private void executeProcedure(Procedure<TEnvironment> proc) {
1419    if (proc.isFinished()) {
1420      LOG.debug("{} is already finished, skipping execution", proc);
1421      return;
1422    }
1423    final Long rootProcId = getRootProcedureId(proc);
1424    if (rootProcId == null) {
1425      // The 'proc' was ready to run but the root procedure was rolledback
1426      LOG.warn("Rollback because parent is done/rolledback proc=" + proc);
1427      executeRollback(proc);
1428      return;
1429    }
1430
1431    RootProcedureState<TEnvironment> procStack = rollbackStack.get(rootProcId);
1432    if (procStack == null) {
1433      LOG.warn("RootProcedureState is null for " + proc.getProcId());
1434      return;
1435    }
1436    do {
1437      // Try to acquire the execution
1438      if (!procStack.acquire(proc)) {
1439        if (procStack.setRollback()) {
1440          // we have the 'rollback-lock' we can start rollingback
1441          switch (executeRollback(rootProcId, procStack)) {
1442            case LOCK_ACQUIRED:
1443              break;
1444            case LOCK_YIELD_WAIT:
1445              procStack.unsetRollback();
1446              scheduler.yield(proc);
1447              break;
1448            case LOCK_EVENT_WAIT:
1449              LOG.info("LOCK_EVENT_WAIT rollback..." + proc);
1450              procStack.unsetRollback();
1451              break;
1452            default:
1453              throw new UnsupportedOperationException();
1454          }
1455        } else {
1456          // if we can't rollback means that some child is still running.
1457          // the rollback will be executed after all the children are done.
1458          // If the procedure was never executed, remove and mark it as rolledback.
1459          if (!proc.wasExecuted()) {
1460            switch (executeRollback(proc)) {
1461              case LOCK_ACQUIRED:
1462                break;
1463              case LOCK_YIELD_WAIT:
1464                scheduler.yield(proc);
1465                break;
1466              case LOCK_EVENT_WAIT:
1467                LOG.info("LOCK_EVENT_WAIT can't rollback child running?..." + proc);
1468                break;
1469              default:
1470                throw new UnsupportedOperationException();
1471            }
1472          }
1473        }
1474        break;
1475      }
1476
1477      // Execute the procedure
1478      assert proc.getState() == ProcedureState.RUNNABLE : proc;
1479      // Note that lock is NOT about concurrency but rather about ensuring
1480      // ownership of a procedure of an entity such as a region or table
1481      LockState lockState = acquireLock(proc);
1482      switch (lockState) {
1483        case LOCK_ACQUIRED:
1484          execProcedure(procStack, proc);
1485          break;
1486        case LOCK_YIELD_WAIT:
1487          LOG.info(lockState + " " + proc);
1488          scheduler.yield(proc);
1489          break;
1490        case LOCK_EVENT_WAIT:
1491          // Someone will wake us up when the lock is available
1492          LOG.debug(lockState + " " + proc);
1493          break;
1494        default:
1495          throw new UnsupportedOperationException();
1496      }
1497      procStack.release(proc);
1498
1499      if (proc.isSuccess()) {
1500        // update metrics on finishing the procedure
1501        proc.updateMetricsOnFinish(getEnvironment(), proc.elapsedTime(), true);
1502        LOG.info("Finished " + proc + " in " + StringUtils.humanTimeDiff(proc.elapsedTime()));
1503        // Finalize the procedure state
1504        if (proc.getProcId() == rootProcId) {
1505          procedureFinished(proc);
1506        } else {
1507          execCompletionCleanup(proc);
1508        }
1509        break;
1510      }
1511    } while (procStack.isFailed());
1512  }
1513
1514  private LockState acquireLock(Procedure<TEnvironment> proc) {
1515    TEnvironment env = getEnvironment();
1516    // if holdLock is true, then maybe we already have the lock, so just return LOCK_ACQUIRED if
1517    // hasLock is true.
1518    if (proc.hasLock()) {
1519      return LockState.LOCK_ACQUIRED;
1520    }
1521    return proc.doAcquireLock(env, store);
1522  }
1523
1524  private void releaseLock(Procedure<TEnvironment> proc, boolean force) {
1525    TEnvironment env = getEnvironment();
1526    // For how the framework works, we know that we will always have the lock
1527    // when we call releaseLock(), so we can avoid calling proc.hasLock()
1528    if (force || !proc.holdLock(env) || proc.isFinished()) {
1529      proc.doReleaseLock(env, store);
1530    }
1531  }
1532
1533  // Returning null means we have already held the execution lock, so you do not need to get the
1534  // lock entry for releasing
1535  private IdLock.Entry getLockEntryForRollback(long procId) {
1536    // Hold the execution lock if it is not held by us. The IdLock is not reentrant so we need
1537    // this check, as the worker will hold the lock before executing a procedure. This is the only
1538    // place where we may hold two procedure execution locks, and there is a fence in the
1539    // RootProcedureState where we can make sure that only one worker can execute the rollback of
1540    // a RootProcedureState, so there is no dead lock problem. And the lock here is necessary to
1541    // prevent race between us and the force update thread.
1542    if (!procExecutionLock.isHeldByCurrentThread(procId)) {
1543      try {
1544        return procExecutionLock.getLockEntry(procId);
1545      } catch (IOException e) {
1546        // can only happen if interrupted, so not a big deal to propagate it
1547        throw new UncheckedIOException(e);
1548      }
1549    }
1550    return null;
1551  }
1552
1553  private void executeUnexpectedRollback(Procedure<TEnvironment> rootProc,
1554    RootProcedureState<TEnvironment> procStack) {
1555    if (procStack.getSubprocs() != null) {
1556      // comparing proc id in reverse order, so we will delete later procedures first, otherwise we
1557      // may delete parent procedure first and if we fail in the middle of this operation, when
1558      // loading we will find some orphan procedures
1559      PriorityQueue<Procedure<TEnvironment>> pq =
1560        new PriorityQueue<>(procStack.getSubprocs().size(),
1561          Comparator.<Procedure<TEnvironment>> comparingLong(Procedure::getProcId).reversed());
1562      pq.addAll(procStack.getSubprocs());
1563      for (;;) {
1564        Procedure<TEnvironment> subproc = pq.poll();
1565        if (subproc == null) {
1566          break;
1567        }
1568        if (!procedures.containsKey(subproc.getProcId())) {
1569          // this means it has already been rolledback
1570          continue;
1571        }
1572        IdLock.Entry lockEntry = getLockEntryForRollback(subproc.getProcId());
1573        try {
1574          cleanupAfterRollbackOneStep(subproc);
1575          execCompletionCleanup(subproc);
1576        } finally {
1577          if (lockEntry != null) {
1578            procExecutionLock.releaseLockEntry(lockEntry);
1579          }
1580        }
1581      }
1582    }
1583    IdLock.Entry lockEntry = getLockEntryForRollback(rootProc.getProcId());
1584    try {
1585      cleanupAfterRollbackOneStep(rootProc);
1586    } finally {
1587      if (lockEntry != null) {
1588        procExecutionLock.releaseLockEntry(lockEntry);
1589      }
1590    }
1591  }
1592
1593  private LockState executeNormalRollback(Procedure<TEnvironment> rootProc,
1594    RootProcedureState<TEnvironment> procStack) {
1595    List<Procedure<TEnvironment>> subprocStack = procStack.getSubproceduresStack();
1596    assert subprocStack != null : "Called rollback with no steps executed rootProc=" + rootProc;
1597
1598    int stackTail = subprocStack.size();
1599    while (stackTail-- > 0) {
1600      Procedure<TEnvironment> proc = subprocStack.get(stackTail);
1601      IdLock.Entry lockEntry = getLockEntryForRollback(proc.getProcId());
1602      try {
1603        // For the sub procedures which are successfully finished, we do not rollback them.
1604        // Typically, if we want to rollback a procedure, we first need to rollback it, and then
1605        // recursively rollback its ancestors. The state changes which are done by sub procedures
1606        // should be handled by parent procedures when rolling back. For example, when rolling back
1607        // a MergeTableProcedure, we will schedule new procedures to bring the offline regions
1608        // online, instead of rolling back the original procedures which offlined the regions(in
1609        // fact these procedures can not be rolled back...).
1610        if (proc.isSuccess()) {
1611          // Just do the cleanup work, without actually executing the rollback
1612          subprocStack.remove(stackTail);
1613          cleanupAfterRollbackOneStep(proc);
1614          continue;
1615        }
1616        LockState lockState = acquireLock(proc);
1617        if (lockState != LockState.LOCK_ACQUIRED) {
1618          // can't take a lock on the procedure, add the root-proc back on the
1619          // queue waiting for the lock availability
1620          return lockState;
1621        }
1622
1623        lockState = executeRollback(proc);
1624        releaseLock(proc, false);
1625        boolean abortRollback = lockState != LockState.LOCK_ACQUIRED;
1626        abortRollback |= !isRunning() || !store.isRunning();
1627
1628        // allows to kill the executor before something is stored to the wal.
1629        // useful to test the procedure recovery.
1630        if (abortRollback) {
1631          return lockState;
1632        }
1633
1634        subprocStack.remove(stackTail);
1635
1636        // if the procedure is kind enough to pass the slot to someone else, yield
1637        // if the proc is already finished, do not yield
1638        if (!proc.isFinished() && proc.isYieldAfterExecutionStep(getEnvironment())) {
1639          return LockState.LOCK_YIELD_WAIT;
1640        }
1641
1642        if (proc != rootProc) {
1643          execCompletionCleanup(proc);
1644        }
1645      } finally {
1646        if (lockEntry != null) {
1647          procExecutionLock.releaseLockEntry(lockEntry);
1648        }
1649      }
1650    }
1651    return LockState.LOCK_ACQUIRED;
1652  }
1653
1654  /**
1655   * Execute the rollback of the full procedure stack. Once the procedure is rolledback, the
1656   * root-procedure will be visible as finished to user, and the result will be the fatal exception.
1657   */
1658  private LockState executeRollback(long rootProcId, RootProcedureState<TEnvironment> procStack) {
1659    Procedure<TEnvironment> rootProc = procedures.get(rootProcId);
1660    RemoteProcedureException exception = rootProc.getException();
1661    // TODO: This needs doc. The root proc doesn't have an exception. Maybe we are
1662    // rolling back because the subprocedure does. Clarify.
1663    if (exception == null) {
1664      exception = procStack.getException();
1665      rootProc.setFailure(exception);
1666      store.update(rootProc);
1667    }
1668
1669    if (procStack.isRollbackSupported()) {
1670      LockState lockState = executeNormalRollback(rootProc, procStack);
1671      if (lockState != LockState.LOCK_ACQUIRED) {
1672        return lockState;
1673      }
1674    } else {
1675      // the procedure does not support rollback, so typically we should not reach here, this
1676      // usually means there are code bugs, let's just wait all the subprocedures to finish and then
1677      // mark the root procedure as failure.
1678      LOG.error(HBaseMarkers.FATAL,
1679        "Root Procedure {} does not support rollback but the execution failed"
1680          + " and try to rollback, code bug?",
1681        rootProc, exception);
1682      executeUnexpectedRollback(rootProc, procStack);
1683    }
1684
1685    IdLock.Entry lockEntry = getLockEntryForRollback(rootProc.getProcId());
1686    try {
1687      // Finalize the procedure state
1688      LOG.info("Rolled back {} exec-time={}", rootProc,
1689        StringUtils.humanTimeDiff(rootProc.elapsedTime()));
1690      procedureFinished(rootProc);
1691    } finally {
1692      if (lockEntry != null) {
1693        procExecutionLock.releaseLockEntry(lockEntry);
1694      }
1695    }
1696
1697    return LockState.LOCK_ACQUIRED;
1698  }
1699
1700  private void cleanupAfterRollbackOneStep(Procedure<TEnvironment> proc) {
1701    if (testing != null && testing.shouldKillBeforeStoreUpdateInRollback()) {
1702      kill("TESTING: Kill BEFORE store update in rollback: " + proc);
1703    }
1704    if (proc.removeStackIndex()) {
1705      if (!proc.isSuccess()) {
1706        proc.setState(ProcedureState.ROLLEDBACK);
1707      }
1708
1709      // update metrics on finishing the procedure (fail)
1710      proc.updateMetricsOnFinish(getEnvironment(), proc.elapsedTime(), false);
1711
1712      if (proc.hasParent()) {
1713        store.delete(proc.getProcId());
1714        procedures.remove(proc.getProcId());
1715      } else {
1716        final long[] childProcIds = rollbackStack.get(proc.getProcId()).getSubprocedureIds();
1717        if (childProcIds != null) {
1718          store.delete(proc, childProcIds);
1719        } else {
1720          store.update(proc);
1721        }
1722      }
1723    } else {
1724      store.update(proc);
1725    }
1726  }
1727
1728  /**
1729   * Execute the rollback of the procedure step. It updates the store with the new state (stack
1730   * index) or will remove completly the procedure in case it is a child.
1731   */
1732  private LockState executeRollback(Procedure<TEnvironment> proc) {
1733    try {
1734      proc.doRollback(getEnvironment());
1735    } catch (IOException e) {
1736      LOG.debug("Roll back attempt failed for {}", proc, e);
1737      return LockState.LOCK_YIELD_WAIT;
1738    } catch (InterruptedException e) {
1739      handleInterruptedException(proc, e);
1740      return LockState.LOCK_YIELD_WAIT;
1741    } catch (Throwable e) {
1742      // Catch NullPointerExceptions or similar errors...
1743      LOG.error(HBaseMarkers.FATAL, "CODE-BUG: Uncaught runtime exception for " + proc, e);
1744    }
1745
1746    cleanupAfterRollbackOneStep(proc);
1747
1748    return LockState.LOCK_ACQUIRED;
1749  }
1750
1751  private void yieldProcedure(Procedure<TEnvironment> proc) {
1752    releaseLock(proc, false);
1753    scheduler.yield(proc);
1754  }
1755
1756  /**
1757   * Executes <code>procedure</code>
1758   * <ul>
1759   * <li>Calls the doExecute() of the procedure
1760   * <li>If the procedure execution didn't fail (i.e. valid user input)
1761   * <ul>
1762   * <li>...and returned subprocedures
1763   * <ul>
1764   * <li>The subprocedures are initialized.
1765   * <li>The subprocedures are added to the store
1766   * <li>The subprocedures are added to the runnable queue
1767   * <li>The procedure is now in a WAITING state, waiting for the subprocedures to complete
1768   * </ul>
1769   * </li>
1770   * <li>...if there are no subprocedure
1771   * <ul>
1772   * <li>the procedure completed successfully
1773   * <li>if there is a parent (WAITING)
1774   * <li>the parent state will be set to RUNNABLE
1775   * </ul>
1776   * </li>
1777   * </ul>
1778   * </li>
1779   * <li>In case of failure
1780   * <ul>
1781   * <li>The store is updated with the new state</li>
1782   * <li>The executor (caller of this method) will start the rollback of the procedure</li>
1783   * </ul>
1784   * </li>
1785   * </ul>
1786   */
1787  private void execProcedure(RootProcedureState<TEnvironment> procStack,
1788    Procedure<TEnvironment> procedure) {
1789    Preconditions.checkArgument(procedure.getState() == ProcedureState.RUNNABLE,
1790      "NOT RUNNABLE! " + procedure.toString());
1791
1792    // Procedures can suspend themselves. They skip out by throwing a ProcedureSuspendedException.
1793    // The exception is caught below and then we hurry to the exit without disturbing state. The
1794    // idea is that the processing of this procedure will be unsuspended later by an external event
1795    // such the report of a region open.
1796    boolean suspended = false;
1797
1798    // Whether to 're-' -execute; run through the loop again.
1799    boolean reExecute = false;
1800
1801    Procedure<TEnvironment>[] subprocs = null;
1802    do {
1803      reExecute = false;
1804      procedure.resetPersistence();
1805      try {
1806        subprocs = procedure.doExecute(getEnvironment());
1807        if (subprocs != null && subprocs.length == 0) {
1808          subprocs = null;
1809        }
1810      } catch (ProcedureSuspendedException e) {
1811        LOG.trace("Suspend {}", procedure);
1812        suspended = true;
1813      } catch (ProcedureYieldException e) {
1814        LOG.trace("Yield {}", procedure, e);
1815        yieldProcedure(procedure);
1816        return;
1817      } catch (InterruptedException e) {
1818        LOG.trace("Yield interrupt {}", procedure, e);
1819        handleInterruptedException(procedure, e);
1820        yieldProcedure(procedure);
1821        return;
1822      } catch (Throwable e) {
1823        // Catch NullPointerExceptions or similar errors...
1824        String msg = "CODE-BUG: Uncaught runtime exception: " + procedure;
1825        LOG.error(msg, e);
1826        procedure.setFailure(new RemoteProcedureException(msg, e));
1827      }
1828
1829      if (!procedure.isFailed()) {
1830        if (subprocs != null) {
1831          if (subprocs.length == 1 && subprocs[0] == procedure) {
1832            // Procedure returned itself. Quick-shortcut for a state machine-like procedure;
1833            // i.e. we go around this loop again rather than go back out on the scheduler queue.
1834            subprocs = null;
1835            reExecute = true;
1836            LOG.trace("Short-circuit to next step on pid={}", procedure.getProcId());
1837          } else {
1838            // Yield the current procedure, and make the subprocedure runnable
1839            // subprocs may come back 'null'.
1840            subprocs = initializeChildren(procStack, procedure, subprocs);
1841            LOG.info("Initialized subprocedures=" + (subprocs == null
1842              ? null
1843              : Stream.of(subprocs).map(e -> "{" + e.toString() + "}").collect(Collectors.toList())
1844                .toString()));
1845          }
1846        } else if (procedure.getState() == ProcedureState.WAITING_TIMEOUT) {
1847          LOG.trace("Added to timeoutExecutor {}", procedure);
1848          timeoutExecutor.add(procedure);
1849        } else if (!suspended) {
1850          // No subtask, so we are done
1851          procedure.setState(ProcedureState.SUCCESS);
1852        }
1853      }
1854
1855      // allows to kill the executor before something is stored to the wal.
1856      // useful to test the procedure recovery.
1857      if (
1858        testing != null && testing.shouldKillBeforeStoreUpdate(suspended, procedure.hasParent())
1859      ) {
1860        kill("TESTING: Kill BEFORE store update: " + procedure);
1861      }
1862
1863      // TODO: The code here doesn't check if store is running before persisting to the store as
1864      // it relies on the method call below to throw RuntimeException to wind up the stack and
1865      // executor thread to stop. The statement following the method call below seems to check if
1866      // store is not running, to prevent scheduling children procedures, re-execution or yield
1867      // of this procedure. This may need more scrutiny and subsequent cleanup in future
1868      //
1869      // Commit the transaction even if a suspend (state may have changed). Note this append
1870      // can take a bunch of time to complete.
1871      if (procedure.needPersistence()) {
1872        // Add the procedure to the stack
1873        // See HBASE-28210 on why we need synchronized here
1874        boolean needUpdateStoreOutsideLock = false;
1875        synchronized (procStack) {
1876          if (procStack.addRollbackStep(procedure)) {
1877            updateStoreOnExec(procStack, procedure, subprocs);
1878          } else {
1879            needUpdateStoreOutsideLock = true;
1880          }
1881        }
1882        // this is an optimization if we do not need to maintain rollback step, as all subprocedures
1883        // of the same root procedure share the same root procedure state, if we can only update
1884        // store under the above lock, the sub procedures of the same root procedure can only be
1885        // persistent sequentially, which will have a bad performance. See HBASE-28212 for more
1886        // details.
1887        if (needUpdateStoreOutsideLock) {
1888          updateStoreOnExec(procStack, procedure, subprocs);
1889        }
1890      }
1891
1892      // if the store is not running we are aborting
1893      if (!store.isRunning()) {
1894        return;
1895      }
1896      // if the procedure is kind enough to pass the slot to someone else, yield
1897      if (
1898        procedure.isRunnable() && !suspended
1899          && procedure.isYieldAfterExecutionStep(getEnvironment())
1900      ) {
1901        yieldProcedure(procedure);
1902        return;
1903      }
1904
1905      assert (reExecute && subprocs == null) || !reExecute;
1906    } while (reExecute);
1907
1908    // Allows to kill the executor after something is stored to the WAL but before the below
1909    // state settings are done -- in particular the one on the end where we make parent
1910    // RUNNABLE again when its children are done; see countDownChildren.
1911    if (testing != null && testing.shouldKillAfterStoreUpdate(suspended)) {
1912      kill("TESTING: Kill AFTER store update: " + procedure);
1913    }
1914
1915    // Submit the new subprocedures
1916    if (subprocs != null && !procedure.isFailed()) {
1917      submitChildrenProcedures(subprocs);
1918    }
1919
1920    // we need to log the release lock operation before waking up the parent procedure, as there
1921    // could be race that the parent procedure may call updateStoreOnExec ahead of us and remove all
1922    // the sub procedures from store and cause problems...
1923    releaseLock(procedure, false);
1924
1925    // if the procedure is complete and has a parent, count down the children latch.
1926    // If 'suspended', do nothing to change state -- let other threads handle unsuspend event.
1927    if (!suspended && procedure.isFinished() && procedure.hasParent()) {
1928      countDownChildren(procStack, procedure);
1929    }
1930  }
1931
1932  private void kill(String msg) {
1933    LOG.debug(msg);
1934    stop();
1935    throw new RuntimeException(msg);
1936  }
1937
1938  private Procedure<TEnvironment>[] initializeChildren(RootProcedureState<TEnvironment> procStack,
1939    Procedure<TEnvironment> procedure, Procedure<TEnvironment>[] subprocs) {
1940    assert subprocs != null : "expected subprocedures";
1941    final long rootProcId = getRootProcedureId(procedure);
1942    for (int i = 0; i < subprocs.length; ++i) {
1943      Procedure<TEnvironment> subproc = subprocs[i];
1944      if (subproc == null) {
1945        String msg = "subproc[" + i + "] is null, aborting the procedure";
1946        procedure
1947          .setFailure(new RemoteProcedureException(msg, new IllegalArgumentIOException(msg)));
1948        return null;
1949      }
1950
1951      assert subproc.getState() == ProcedureState.INITIALIZING : subproc;
1952      subproc.setParentProcId(procedure.getProcId());
1953      subproc.setRootProcId(rootProcId);
1954      subproc.setProcId(nextProcId());
1955      procStack.addSubProcedure(subproc);
1956    }
1957
1958    if (!procedure.isFailed()) {
1959      procedure.setChildrenLatch(subprocs.length);
1960      switch (procedure.getState()) {
1961        case RUNNABLE:
1962          procedure.setState(ProcedureState.WAITING);
1963          break;
1964        case WAITING_TIMEOUT:
1965          timeoutExecutor.add(procedure);
1966          break;
1967        default:
1968          break;
1969      }
1970    }
1971    return subprocs;
1972  }
1973
1974  private void submitChildrenProcedures(Procedure<TEnvironment>[] subprocs) {
1975    for (int i = 0; i < subprocs.length; ++i) {
1976      Procedure<TEnvironment> subproc = subprocs[i];
1977      subproc.updateMetricsOnSubmit(getEnvironment());
1978      assert !procedures.containsKey(subproc.getProcId());
1979      procedures.put(subproc.getProcId(), subproc);
1980      scheduler.addFront(subproc);
1981    }
1982  }
1983
1984  private void countDownChildren(RootProcedureState<TEnvironment> procStack,
1985    Procedure<TEnvironment> procedure) {
1986    Procedure<TEnvironment> parent = procedures.get(procedure.getParentProcId());
1987    if (parent == null) {
1988      assert procStack.isRollingback();
1989      return;
1990    }
1991
1992    // If this procedure is the last child awake the parent procedure
1993    if (parent.tryRunnable()) {
1994      // If we succeeded in making the parent runnable -- i.e. all of its
1995      // children have completed, move parent to front of the queue.
1996      store.update(parent);
1997      scheduler.addFront(parent);
1998      LOG.info("Finished subprocedure pid={}, resume processing ppid={}", procedure.getProcId(),
1999        parent.getProcId());
2000      return;
2001    }
2002  }
2003
2004  private void updateStoreOnExec(RootProcedureState<TEnvironment> procStack,
2005    Procedure<TEnvironment> procedure, Procedure<TEnvironment>[] subprocs) {
2006    if (subprocs != null && !procedure.isFailed()) {
2007      if (LOG.isTraceEnabled()) {
2008        LOG.trace("Stored " + procedure + ", children " + Arrays.toString(subprocs));
2009      }
2010      store.insert(procedure, subprocs);
2011    } else {
2012      LOG.trace("Store update {}", procedure);
2013      if (procedure.isFinished() && !procedure.hasParent()) {
2014        // remove child procedures
2015        final long[] childProcIds = procStack.getSubprocedureIds();
2016        if (childProcIds != null) {
2017          store.delete(procedure, childProcIds);
2018          for (int i = 0; i < childProcIds.length; ++i) {
2019            procedures.remove(childProcIds[i]);
2020          }
2021        } else {
2022          store.update(procedure);
2023        }
2024      } else {
2025        store.update(procedure);
2026      }
2027    }
2028  }
2029
2030  private void handleInterruptedException(Procedure<TEnvironment> proc, InterruptedException e) {
2031    LOG.trace("Interrupt during {}. suspend and retry it later.", proc, e);
2032    // NOTE: We don't call Thread.currentThread().interrupt()
2033    // because otherwise all the subsequent calls e.g. Thread.sleep() will throw
2034    // the InterruptedException. If the master is going down, we will be notified
2035    // and the executor/store will be stopped.
2036    // (The interrupted procedure will be retried on the next run)
2037  }
2038
2039  private void execCompletionCleanup(Procedure<TEnvironment> proc) {
2040    final TEnvironment env = getEnvironment();
2041    if (proc.hasLock()) {
2042      LOG.warn("Usually this should not happen, we will release the lock before if the procedure"
2043        + " is finished, even if the holdLock is true, arrive here means we have some holes where"
2044        + " we do not release the lock. And the releaseLock below may fail since the procedure may"
2045        + " have already been deleted from the procedure store.");
2046      releaseLock(proc, true);
2047    }
2048    try {
2049      proc.completionCleanup(env);
2050    } catch (Throwable e) {
2051      // Catch NullPointerExceptions or similar errors...
2052      LOG.error("CODE-BUG: uncatched runtime exception for procedure: " + proc, e);
2053    }
2054  }
2055
2056  private void procedureFinished(Procedure<TEnvironment> proc) {
2057    // call the procedure completion cleanup handler
2058    execCompletionCleanup(proc);
2059
2060    CompletedProcedureRetainer<TEnvironment> retainer = new CompletedProcedureRetainer<>(proc);
2061
2062    // update the executor internal state maps
2063    if (!proc.shouldWaitClientAck(getEnvironment())) {
2064      retainer.setClientAckTime(0);
2065    }
2066
2067    completed.put(proc.getProcId(), retainer);
2068    rollbackStack.remove(proc.getProcId());
2069    procedures.remove(proc.getProcId());
2070
2071    // call the runnableSet completion cleanup handler
2072    try {
2073      scheduler.completionCleanup(proc);
2074    } catch (Throwable e) {
2075      // Catch NullPointerExceptions or similar errors...
2076      LOG.error("CODE-BUG: uncatched runtime exception for completion cleanup: {}", proc, e);
2077    }
2078
2079    // Notify the listeners
2080    sendProcedureFinishedNotification(proc.getProcId());
2081  }
2082
2083  RootProcedureState<TEnvironment> getProcStack(long rootProcId) {
2084    return rollbackStack.get(rootProcId);
2085  }
2086
2087  ProcedureScheduler getProcedureScheduler() {
2088    return scheduler;
2089  }
2090
2091  int getCompletedSize() {
2092    return completed.size();
2093  }
2094
2095  public IdLock getProcExecutionLock() {
2096    return procExecutionLock;
2097  }
2098
2099  /**
2100   * Get a thread pool for executing some asynchronous tasks
2101   */
2102  public ExecutorService getAsyncTaskExecutor() {
2103    return asyncTaskExecutor;
2104  }
2105
2106  // ==========================================================================
2107  // Worker Thread
2108  // ==========================================================================
2109  private class WorkerThread extends StoppableThread {
2110    private final AtomicLong executionStartTime = new AtomicLong(Long.MAX_VALUE);
2111    private volatile Procedure<TEnvironment> activeProcedure;
2112
2113    public WorkerThread(ThreadGroup group) {
2114      this(group, "PEWorker-");
2115    }
2116
2117    protected WorkerThread(ThreadGroup group, String prefix) {
2118      super(group, prefix + workerId.incrementAndGet());
2119      setDaemon(true);
2120    }
2121
2122    @Override
2123    public void sendStopSignal() {
2124      scheduler.signalAll();
2125    }
2126
2127    /**
2128     * Encapsulates execution of the current {@link #activeProcedure} for easy tracing.
2129     */
2130    private long runProcedure() throws IOException {
2131      final Procedure<TEnvironment> proc = this.activeProcedure;
2132      int activeCount = activeExecutorCount.incrementAndGet();
2133      int runningCount = store.setRunningProcedureCount(activeCount);
2134      LOG.trace("Execute pid={} runningCount={}, activeCount={}", proc.getProcId(), runningCount,
2135        activeCount);
2136      executionStartTime.set(EnvironmentEdgeManager.currentTime());
2137      IdLock.Entry lockEntry = procExecutionLock.getLockEntry(proc.getProcId());
2138      try {
2139        executeProcedure(proc);
2140      } catch (AssertionError e) {
2141        LOG.info("ASSERT pid=" + proc.getProcId(), e);
2142        throw e;
2143      } finally {
2144        procExecutionLock.releaseLockEntry(lockEntry);
2145        activeCount = activeExecutorCount.decrementAndGet();
2146        runningCount = store.setRunningProcedureCount(activeCount);
2147        LOG.trace("Halt pid={} runningCount={}, activeCount={}", proc.getProcId(), runningCount,
2148          activeCount);
2149        this.activeProcedure = null;
2150        executionStartTime.set(Long.MAX_VALUE);
2151      }
2152      return EnvironmentEdgeManager.currentTime();
2153    }
2154
2155    @Override
2156    public void run() {
2157      long lastUpdate = EnvironmentEdgeManager.currentTime();
2158      try {
2159        while (isRunning() && keepAlive(lastUpdate)) {
2160          @SuppressWarnings("unchecked")
2161          Procedure<TEnvironment> proc = scheduler.poll(keepAliveTime, TimeUnit.MILLISECONDS);
2162          if (proc == null) {
2163            continue;
2164          }
2165          this.activeProcedure = proc;
2166          lastUpdate = TraceUtil.trace(this::runProcedure, new ProcedureSpanBuilder(proc));
2167        }
2168      } catch (Throwable t) {
2169        LOG.warn("Worker terminating UNNATURALLY {}", this.activeProcedure, t);
2170      } finally {
2171        LOG.trace("Worker terminated.");
2172      }
2173      workerThreads.remove(this);
2174    }
2175
2176    @Override
2177    public String toString() {
2178      Procedure<?> p = this.activeProcedure;
2179      return getName() + "(pid=" + (p == null ? Procedure.NO_PROC_ID : p.getProcId() + ")");
2180    }
2181
2182    /** Returns the time since the current procedure is running */
2183    public long getCurrentRunTime() {
2184      return EnvironmentEdgeManager.currentTime() - executionStartTime.get();
2185    }
2186
2187    // core worker never timeout
2188    protected boolean keepAlive(long lastUpdate) {
2189      return true;
2190    }
2191  }
2192
2193  // A worker thread which can be added when core workers are stuck. Will timeout after
2194  // keepAliveTime if there is no procedure to run.
2195  private final class KeepAliveWorkerThread extends WorkerThread {
2196    public KeepAliveWorkerThread(ThreadGroup group) {
2197      super(group, "KeepAlivePEWorker-");
2198    }
2199
2200    @Override
2201    protected boolean keepAlive(long lastUpdate) {
2202      return EnvironmentEdgeManager.currentTime() - lastUpdate < keepAliveTime;
2203    }
2204  }
2205
2206  // ----------------------------------------------------------------------------
2207  // TODO-MAYBE: Should we provide a InlineChore to notify the store with the
2208  // full set of procedures pending and completed to write a compacted
2209  // version of the log (in case is a log)?
2210  // In theory no, procedures are have a short life, so at some point the store
2211  // will have the tracker saying everything is in the last log.
2212  // ----------------------------------------------------------------------------
2213
2214  private final class WorkerMonitor extends InlineChore {
2215    public static final String WORKER_MONITOR_INTERVAL_CONF_KEY =
2216      "hbase.procedure.worker.monitor.interval.msec";
2217    private static final int DEFAULT_WORKER_MONITOR_INTERVAL = 5000; // 5sec
2218
2219    public static final String WORKER_STUCK_THRESHOLD_CONF_KEY =
2220      "hbase.procedure.worker.stuck.threshold.msec";
2221    private static final int DEFAULT_WORKER_STUCK_THRESHOLD = 10000; // 10sec
2222
2223    public static final String WORKER_ADD_STUCK_PERCENTAGE_CONF_KEY =
2224      "hbase.procedure.worker.add.stuck.percentage";
2225    private static final float DEFAULT_WORKER_ADD_STUCK_PERCENTAGE = 0.5f; // 50% stuck
2226
2227    private float addWorkerStuckPercentage = DEFAULT_WORKER_ADD_STUCK_PERCENTAGE;
2228    private int timeoutInterval = DEFAULT_WORKER_MONITOR_INTERVAL;
2229    private int stuckThreshold = DEFAULT_WORKER_STUCK_THRESHOLD;
2230
2231    public WorkerMonitor() {
2232      refreshConfig();
2233    }
2234
2235    @Override
2236    public void run() {
2237      final int stuckCount = checkForStuckWorkers();
2238      checkThreadCount(stuckCount);
2239
2240      // refresh interval (poor man dynamic conf update)
2241      refreshConfig();
2242    }
2243
2244    private int checkForStuckWorkers() {
2245      // check if any of the worker is stuck
2246      int stuckCount = 0;
2247      for (WorkerThread worker : workerThreads) {
2248        if (worker.getCurrentRunTime() < stuckThreshold) {
2249          continue;
2250        }
2251
2252        // WARN the worker is stuck
2253        stuckCount++;
2254        LOG.warn("Worker stuck {}, run time {}", worker,
2255          StringUtils.humanTimeDiff(worker.getCurrentRunTime()));
2256      }
2257      return stuckCount;
2258    }
2259
2260    private void checkThreadCount(final int stuckCount) {
2261      // nothing to do if there are no runnable tasks
2262      if (stuckCount < 1 || !scheduler.hasRunnables()) {
2263        return;
2264      }
2265
2266      // add a new thread if the worker stuck percentage exceed the threshold limit
2267      // and every handler is active.
2268      final float stuckPerc = ((float) stuckCount) / workerThreads.size();
2269      // let's add new worker thread more aggressively, as they will timeout finally if there is no
2270      // work to do.
2271      if (stuckPerc >= addWorkerStuckPercentage && workerThreads.size() < maxPoolSize) {
2272        final KeepAliveWorkerThread worker = new KeepAliveWorkerThread(threadGroup);
2273        workerThreads.add(worker);
2274        worker.start();
2275        LOG.debug("Added new worker thread {}", worker);
2276      }
2277    }
2278
2279    private void refreshConfig() {
2280      addWorkerStuckPercentage =
2281        conf.getFloat(WORKER_ADD_STUCK_PERCENTAGE_CONF_KEY, DEFAULT_WORKER_ADD_STUCK_PERCENTAGE);
2282      timeoutInterval =
2283        conf.getInt(WORKER_MONITOR_INTERVAL_CONF_KEY, DEFAULT_WORKER_MONITOR_INTERVAL);
2284      stuckThreshold = conf.getInt(WORKER_STUCK_THRESHOLD_CONF_KEY, DEFAULT_WORKER_STUCK_THRESHOLD);
2285    }
2286
2287    @Override
2288    public int getTimeoutInterval() {
2289      return timeoutInterval;
2290    }
2291  }
2292}