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