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