View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.procedure2;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.OutputStream;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.Collections;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.HashSet;
31  import java.util.TreeSet;
32  import java.util.concurrent.atomic.AtomicBoolean;
33  import java.util.concurrent.atomic.AtomicInteger;
34  import java.util.concurrent.atomic.AtomicLong;
35  import java.util.concurrent.locks.ReentrantLock;
36  import java.util.concurrent.ConcurrentHashMap;
37  import java.util.concurrent.CopyOnWriteArrayList;
38  import java.util.concurrent.TimeUnit;
39  
40  import org.apache.commons.logging.Log;
41  import org.apache.commons.logging.LogFactory;
42  import org.apache.hadoop.conf.Configuration;
43  import org.apache.hadoop.hbase.classification.InterfaceAudience;
44  import org.apache.hadoop.hbase.classification.InterfaceStability;
45  import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
46  import org.apache.hadoop.hbase.procedure2.util.StringUtils;
47  import org.apache.hadoop.hbase.procedure2.util.TimeoutBlockingQueue;
48  import org.apache.hadoop.hbase.procedure2.util.TimeoutBlockingQueue.TimeoutRetriever;
49  import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos.ProcedureState;
50  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
51  import org.apache.hadoop.hbase.util.Pair;
52  
53  import com.google.common.base.Preconditions;
54  
55  /**
56   * Thread Pool that executes the submitted procedures.
57   * The executor has a ProcedureStore associated.
58   * Each operation is logged and on restart the pending procedures are resumed.
59   *
60   * Unless the Procedure code throws an error (e.g. invalid user input)
61   * the procedure will complete (at some point in time), On restart the pending
62   * procedures are resumed and the once failed will be rolledback.
63   *
64   * The user can add procedures to the executor via submitProcedure(proc)
65   * check for the finished state via isFinished(procId)
66   * and get the result via getResult(procId)
67   */
68  @InterfaceAudience.Private
69  @InterfaceStability.Evolving
70  public class ProcedureExecutor<TEnvironment> {
71    private static final Log LOG = LogFactory.getLog(ProcedureExecutor.class);
72  
73    Testing testing = null;
74    public static class Testing {
75      protected boolean killBeforeStoreUpdate = false;
76      protected boolean toggleKillBeforeStoreUpdate = false;
77  
78      protected boolean shouldKillBeforeStoreUpdate() {
79        final boolean kill = this.killBeforeStoreUpdate;
80        if (this.toggleKillBeforeStoreUpdate) {
81          this.killBeforeStoreUpdate = !kill;
82          LOG.warn("Toggle Kill before store update to: " + this.killBeforeStoreUpdate);
83        }
84        return kill;
85      }
86    }
87  
88    public interface ProcedureExecutorListener {
89      void procedureLoaded(long procId);
90      void procedureAdded(long procId);
91      void procedureFinished(long procId);
92    }
93  
94    /**
95     * Used by the TimeoutBlockingQueue to get the timeout interval of the procedure
96     */
97    private static class ProcedureTimeoutRetriever implements TimeoutRetriever<Procedure> {
98      @Override
99      public long getTimeout(Procedure proc) {
100       return proc.getTimeRemaining();
101     }
102 
103     @Override
104     public TimeUnit getTimeUnit(Procedure proc) {
105       return TimeUnit.MILLISECONDS;
106     }
107   }
108 
109   /**
110    * Internal cleaner that removes the completed procedure results after a TTL.
111    * NOTE: This is a special case handled in timeoutLoop().
112    *
113    * Since the client code looks more or less like:
114    *   procId = master.doOperation()
115    *   while (master.getProcResult(procId) == ProcInProgress);
116    * The master should not throw away the proc result as soon as the procedure is done
117    * but should wait a result request from the client (see executor.removeResult(procId))
118    * The client will call something like master.isProcDone() or master.getProcResult()
119    * which will return the result/state to the client, and it will mark the completed
120    * proc as ready to delete. note that the client may not receive the response from
121    * the master (e.g. master failover) so, if we delay a bit the real deletion of
122    * the proc result the client will be able to get the result the next try.
123    */
124   private static class CompletedProcedureCleaner<TEnvironment> extends Procedure<TEnvironment> {
125     private static final Log LOG = LogFactory.getLog(CompletedProcedureCleaner.class);
126 
127     private static final String CLEANER_INTERVAL_CONF_KEY = "hbase.procedure.cleaner.interval";
128     private static final int DEFAULT_CLEANER_INTERVAL = 30 * 1000; // 30sec
129 
130     private static final String EVICT_TTL_CONF_KEY = "hbase.procedure.cleaner.evict.ttl";
131     private static final int DEFAULT_EVICT_TTL = 15 * 60000; // 15min
132 
133     private static final String EVICT_ACKED_TTL_CONF_KEY ="hbase.procedure.cleaner.acked.evict.ttl";
134     private static final int DEFAULT_ACKED_EVICT_TTL = 5 * 60000; // 5min
135 
136     private final Map<Long, ProcedureResult> completed;
137     private final ProcedureStore store;
138     private final Configuration conf;
139 
140     public CompletedProcedureCleaner(final Configuration conf, final ProcedureStore store,
141         final Map<Long, ProcedureResult> completedMap) {
142       // set the timeout interval that triggers the periodic-procedure
143       setTimeout(conf.getInt(CLEANER_INTERVAL_CONF_KEY, DEFAULT_CLEANER_INTERVAL));
144       this.completed = completedMap;
145       this.store = store;
146       this.conf = conf;
147     }
148 
149     public void periodicExecute(final TEnvironment env) {
150       if (completed.isEmpty()) {
151         LOG.debug("no completed procedures to cleanup");
152         return;
153       }
154 
155       final long evictTtl = conf.getInt(EVICT_TTL_CONF_KEY, DEFAULT_EVICT_TTL);
156       final long evictAckTtl = conf.getInt(EVICT_ACKED_TTL_CONF_KEY, DEFAULT_ACKED_EVICT_TTL);
157 
158       long now = EnvironmentEdgeManager.currentTime();
159       Iterator<Map.Entry<Long, ProcedureResult>> it = completed.entrySet().iterator();
160       while (it.hasNext() && store.isRunning()) {
161         Map.Entry<Long, ProcedureResult> entry = it.next();
162         ProcedureResult result = entry.getValue();
163 
164         // TODO: Select TTL based on Procedure type
165         if ((result.hasClientAckTime() && (now - result.getClientAckTime()) >= evictAckTtl) ||
166             (now - result.getLastUpdate()) >= evictTtl) {
167           LOG.debug("Evict completed procedure " + entry.getKey());
168           store.delete(entry.getKey());
169           it.remove();
170         }
171       }
172     }
173 
174     @Override
175     protected Procedure[] execute(final TEnvironment env) {
176       throw new UnsupportedOperationException();
177     }
178 
179     @Override
180     protected void rollback(final TEnvironment env) {
181       throw new UnsupportedOperationException();
182     }
183 
184     @Override
185     protected boolean abort(final TEnvironment env) {
186       throw new UnsupportedOperationException();
187     }
188 
189     @Override
190     public void serializeStateData(final OutputStream stream) {
191       throw new UnsupportedOperationException();
192     }
193 
194     @Override
195     public void deserializeStateData(final InputStream stream) {
196       throw new UnsupportedOperationException();
197     }
198   }
199 
200   /**
201    * Map the the procId returned by submitProcedure(), the Root-ProcID, to the ProcedureResult.
202    * Once a Root-Procedure completes (success or failure), the result will be added to this map.
203    * The user of ProcedureExecutor should call getResult(procId) to get the result.
204    */
205   private final ConcurrentHashMap<Long, ProcedureResult> completed =
206     new ConcurrentHashMap<Long, ProcedureResult>();
207 
208   /**
209    * Map the the procId returned by submitProcedure(), the Root-ProcID, to the RootProcedureState.
210    * The RootProcedureState contains the execution stack of the Root-Procedure,
211    * It is added to the map by submitProcedure() and removed on procedure completion.
212    */
213   private final ConcurrentHashMap<Long, RootProcedureState> rollbackStack =
214     new ConcurrentHashMap<Long, RootProcedureState>();
215 
216   /**
217    * Helper map to lookup the live procedures by ID.
218    * This map contains every procedure. root-procedures and subprocedures.
219    */
220   private final ConcurrentHashMap<Long, Procedure> procedures =
221     new ConcurrentHashMap<Long, Procedure>();
222 
223   /**
224    * Timeout Queue that contains Procedures in a WAITING_TIMEOUT state
225    * or periodic procedures.
226    */
227   private final TimeoutBlockingQueue<Procedure> waitingTimeout =
228     new TimeoutBlockingQueue<Procedure>(new ProcedureTimeoutRetriever());
229 
230   /**
231    * Queue that contains runnable procedures.
232    */
233   private final ProcedureRunnableSet runnables;
234 
235   // TODO
236   private final ReentrantLock submitLock = new ReentrantLock();
237   private final AtomicLong lastProcId = new AtomicLong(-1);
238 
239   private final CopyOnWriteArrayList<ProcedureExecutorListener> listeners =
240     new CopyOnWriteArrayList<ProcedureExecutorListener>();
241 
242   private final AtomicInteger activeExecutorCount = new AtomicInteger(0);
243   private final AtomicBoolean running = new AtomicBoolean(false);
244   private final TEnvironment environment;
245   private final ProcedureStore store;
246   private final Configuration conf;
247 
248   private Thread[] threads;
249 
250   public ProcedureExecutor(final Configuration conf, final TEnvironment environment,
251       final ProcedureStore store) {
252     this(conf, environment, store, new ProcedureSimpleRunQueue());
253   }
254 
255   public ProcedureExecutor(final Configuration conf, final TEnvironment environment,
256       final ProcedureStore store, final ProcedureRunnableSet runqueue) {
257     this.environment = environment;
258     this.runnables = runqueue;
259     this.store = store;
260     this.conf = conf;
261   }
262 
263   private List<Map.Entry<Long, RootProcedureState>> load() throws IOException {
264     Preconditions.checkArgument(completed.isEmpty());
265     Preconditions.checkArgument(rollbackStack.isEmpty());
266     Preconditions.checkArgument(procedures.isEmpty());
267     Preconditions.checkArgument(waitingTimeout.isEmpty());
268     Preconditions.checkArgument(runnables.size() == 0);
269 
270     // 1. Load the procedures
271     Iterator<Procedure> loader = store.load();
272     if (loader == null) {
273       lastProcId.set(0);
274       return null;
275     }
276 
277     long logMaxProcId = 0;
278     int runnablesCount = 0;
279     while (loader.hasNext()) {
280       Procedure proc = loader.next();
281       proc.beforeReplay(getEnvironment());
282       procedures.put(proc.getProcId(), proc);
283       logMaxProcId = Math.max(logMaxProcId, proc.getProcId());
284       LOG.debug("Loading procedure state=" + proc.getState() +
285                 " isFailed=" + proc.hasException() + ": " + proc);
286       if (!proc.hasParent() && !proc.isFinished()) {
287         rollbackStack.put(proc.getProcId(), new RootProcedureState());
288       }
289       if (proc.getState() == ProcedureState.RUNNABLE) {
290         runnablesCount++;
291       }
292     }
293     assert lastProcId.get() < 0;
294     lastProcId.set(logMaxProcId);
295 
296     // 2. Initialize the stacks
297     TreeSet<Procedure> runnableSet = null;
298     HashSet<Procedure> waitingSet = null;
299     for (final Procedure proc: procedures.values()) {
300       Long rootProcId = getRootProcedureId(proc);
301       if (rootProcId == null) {
302         // The 'proc' was ready to run but the root procedure was rolledback?
303         runnables.addBack(proc);
304         continue;
305       }
306 
307       if (!proc.hasParent() && proc.isFinished()) {
308         LOG.debug("The procedure is completed state=" + proc.getState() +
309                   " isFailed=" + proc.hasException() + ": " + proc);
310         assert !rollbackStack.containsKey(proc.getProcId());
311         completed.put(proc.getProcId(), newResultFromProcedure(proc));
312         continue;
313       }
314 
315       if (proc.hasParent() && !proc.isFinished()) {
316         Procedure parent = procedures.get(proc.getParentProcId());
317         // corrupted procedures are handled later at step 3
318         if (parent != null) {
319           parent.incChildrenLatch();
320         }
321       }
322 
323       RootProcedureState procStack = rollbackStack.get(rootProcId);
324       procStack.loadStack(proc);
325 
326       switch (proc.getState()) {
327         case RUNNABLE:
328           if (runnableSet == null) {
329             runnableSet = new TreeSet<Procedure>();
330           }
331           runnableSet.add(proc);
332           break;
333         case WAITING_TIMEOUT:
334           if (waitingSet == null) {
335             waitingSet = new HashSet<Procedure>();
336           }
337           waitingSet.add(proc);
338           break;
339         case FINISHED:
340           if (proc.hasException()) {
341             // add the proc to the runnables to perform the rollback
342             runnables.addBack(proc);
343             break;
344           }
345         case ROLLEDBACK:
346         case INITIALIZING:
347           String msg = "Unexpected " + proc.getState() + " state for " + proc;
348           LOG.error(msg);
349           throw new UnsupportedOperationException(msg);
350         default:
351           break;
352       }
353     }
354 
355     // 3. Validate the stacks
356     List<Map.Entry<Long, RootProcedureState>> corrupted = null;
357     Iterator<Map.Entry<Long, RootProcedureState>> itStack = rollbackStack.entrySet().iterator();
358     while (itStack.hasNext()) {
359       Map.Entry<Long, RootProcedureState> entry = itStack.next();
360       RootProcedureState procStack = entry.getValue();
361       if (procStack.isValid()) continue;
362 
363       for (Procedure proc: procStack.getSubprocedures()) {
364         procedures.remove(proc.getProcId());
365         if (runnableSet != null) runnableSet.remove(proc);
366         if (waitingSet != null) waitingSet.remove(proc);
367       }
368       itStack.remove();
369       if (corrupted == null) {
370         corrupted = new ArrayList<Map.Entry<Long, RootProcedureState>>();
371       }
372       corrupted.add(entry);
373     }
374 
375     // 4. Push the runnables
376     if (runnableSet != null) {
377       // TODO: See ProcedureWALFormatReader.readInitEntry() some procedure
378       // may be started way before this stuff.
379       for (Procedure proc: runnableSet) {
380         if (!proc.hasParent()) {
381           sendProcedureLoadedNotification(proc.getProcId());
382         }
383         runnables.addBack(proc);
384       }
385     }
386     return corrupted;
387   }
388 
389   public void start(int numThreads) throws IOException {
390     if (running.getAndSet(true)) {
391       LOG.warn("Already running");
392       return;
393     }
394 
395     // We have numThreads executor + one timer thread used for timing out
396     // procedures and triggering periodic procedures.
397     threads = new Thread[numThreads + 1];
398     LOG.info("Starting procedure executor threads=" + threads.length);
399 
400     // Initialize procedures executor
401     for (int i = 0; i < numThreads; ++i) {
402       threads[i] = new Thread("ProcedureExecutorThread-" + i) {
403         @Override
404         public void run() {
405           execLoop();
406         }
407       };
408     }
409 
410     // Initialize procedures timeout handler (this is the +1 thread)
411     threads[numThreads] = new Thread("ProcedureExecutorTimeoutThread") {
412       @Override
413       public void run() {
414         timeoutLoop();
415       }
416     };
417 
418     // Acquire the store lease.
419     store.recoverLease();
420 
421     // TODO: Split in two steps.
422     // TODO: Handle corrupted procedure returned (probably just a WARN)
423     // The first one will make sure that we have the latest id,
424     // so we can start the threads and accept new procedures.
425     // The second step will do the actual load of old procedures.
426     load();
427 
428     // Start the executors. Here we must have the lastProcId set.
429     for (int i = 0; i < threads.length; ++i) {
430       threads[i].start();
431     }
432 
433     // Add completed cleaner
434     waitingTimeout.add(new CompletedProcedureCleaner(conf, store, completed));
435   }
436 
437   public void stop() {
438     if (!running.getAndSet(false)) {
439       return;
440     }
441 
442     LOG.info("Stopping the procedure executor");
443     runnables.signalAll();
444     waitingTimeout.signalAll();
445   }
446 
447   public void join() {
448     boolean interrupted = false;
449 
450     for (int i = 0; i < threads.length; ++i) {
451       try {
452         threads[i].join();
453       } catch (InterruptedException ex) {
454         interrupted = true;
455       }
456     }
457 
458     if (interrupted) {
459       Thread.currentThread().interrupt();
460     }
461 
462     completed.clear();
463     rollbackStack.clear();
464     procedures.clear();
465     waitingTimeout.clear();
466     runnables.clear();
467     lastProcId.set(-1);
468   }
469 
470   public boolean isRunning() {
471     return running.get();
472   }
473 
474   /**
475    * @return the number of execution threads.
476    */
477   public int getNumThreads() {
478     return threads == null ? 0 : (threads.length - 1);
479   }
480 
481   public int getActiveExecutorCount() {
482     return activeExecutorCount.get();
483   }
484 
485   public TEnvironment getEnvironment() {
486     return this.environment;
487   }
488 
489   public ProcedureStore getStore() {
490     return this.store;
491   }
492 
493   public void registerListener(ProcedureExecutorListener listener) {
494     this.listeners.add(listener);
495   }
496 
497   public boolean unregisterListener(ProcedureExecutorListener listener) {
498     return this.listeners.remove(listener);
499   }
500 
501   /**
502    * Add a new root-procedure to the executor.
503    * @param proc the new procedure to execute.
504    * @return the procedure id, that can be used to monitor the operation
505    */
506   public long submitProcedure(final Procedure proc) {
507     Preconditions.checkArgument(proc.getState() == ProcedureState.INITIALIZING);
508     Preconditions.checkArgument(isRunning());
509     Preconditions.checkArgument(lastProcId.get() >= 0);
510     Preconditions.checkArgument(!proc.hasParent());
511 
512     // Initialize the Procedure ID
513     proc.setProcId(nextProcId());
514 
515     // Commit the transaction
516     store.insert(proc, null);
517     LOG.debug("procedure " + proc + " added to the store");
518 
519     // Create the rollback stack for the procedure
520     RootProcedureState stack = new RootProcedureState();
521     rollbackStack.put(proc.getProcId(), stack);
522 
523     // Submit the new subprocedures
524     assert !procedures.containsKey(proc.getProcId());
525     procedures.put(proc.getProcId(), proc);
526     sendProcedureAddedNotification(proc.getProcId());
527     runnables.addBack(proc);
528     return proc.getProcId();
529   }
530 
531   public ProcedureResult getResult(final long procId) {
532     return completed.get(procId);
533   }
534 
535   /**
536    * Return true if the procedure is finished.
537    * The state may be "completed successfully" or "failed and rolledback".
538    * Use getResult() to check the state or get the result data.
539    * @param procId the ID of the procedure to check
540    * @return true if the procedure execution is finished, otherwise false.
541    */
542   public boolean isFinished(final long procId) {
543     return completed.containsKey(procId);
544   }
545 
546   /**
547    * Return true if the procedure is started.
548    * @param procId the ID of the procedure to check
549    * @return true if the procedure execution is started, otherwise false.
550    */
551   public boolean isStarted(final long procId) {
552     Procedure proc = procedures.get(procId);
553     if (proc == null) {
554       return completed.get(procId) != null;
555     }
556     return proc.wasExecuted();
557   }
558 
559   /**
560    * Mark the specified completed procedure, as ready to remove.
561    * @param procId the ID of the procedure to remove
562    */
563   public void removeResult(final long procId) {
564     ProcedureResult result = completed.get(procId);
565     if (result == null) {
566       assert !procedures.containsKey(procId) : "procId=" + procId + " is still running";
567       LOG.debug("Procedure procId=" + procId + " already removed by the cleaner");
568       return;
569     }
570 
571     // The CompletedProcedureCleaner will take care of deletion, once the TTL is expired.
572     result.setClientAckTime(EnvironmentEdgeManager.currentTime());
573   }
574 
575   /**
576    * Send an abort notification the specified procedure.
577    * Depending on the procedure implementation the abort can be considered or ignored.
578    * @param procId the procedure to abort
579    * @return true if the procedure exist and has received the abort, otherwise false.
580    */
581   public boolean abort(final long procId) {
582     Procedure proc = procedures.get(procId);
583     if (proc != null) {
584       return proc.abort(getEnvironment());
585     }
586     return false;
587   }
588 
589   public Map<Long, ProcedureResult> getResults() {
590     return Collections.unmodifiableMap(completed);
591   }
592 
593   public Procedure getProcedure(final long procId) {
594     return procedures.get(procId);
595   }
596 
597   protected ProcedureRunnableSet getRunnableSet() {
598     return runnables;
599   }
600 
601   /**
602    * Execution loop (N threads)
603    * while the executor is in a running state,
604    * fetch a procedure from the runnables queue and start the execution.
605    */
606   private void execLoop() {
607     while (isRunning()) {
608       Long procId = runnables.poll();
609       Procedure proc = procId != null ? procedures.get(procId) : null;
610       if (proc == null) continue;
611 
612       try {
613         activeExecutorCount.incrementAndGet();
614         execLoop(proc);
615       } finally {
616         activeExecutorCount.decrementAndGet();
617       }
618     }
619   }
620 
621   private void execLoop(Procedure proc) {
622     if (LOG.isTraceEnabled()) {
623       LOG.trace("trying to start the execution of " + proc);
624     }
625 
626     Long rootProcId = getRootProcedureId(proc);
627     if (rootProcId == null) {
628       // The 'proc' was ready to run but the root procedure was rolledback
629       executeRollback(proc);
630       return;
631     }
632 
633     RootProcedureState procStack = rollbackStack.get(rootProcId);
634     if (procStack == null) return;
635 
636     do {
637       // Try to acquire the execution
638       if (!procStack.acquire(proc)) {
639         if (procStack.setRollback()) {
640           // we have the 'rollback-lock' we can start rollingback
641           if (!executeRollback(rootProcId, procStack)) {
642             procStack.unsetRollback();
643             runnables.yield(proc);
644           }
645         } else {
646           // if we can't rollback means that some child is still running.
647           // the rollback will be executed after all the children are done.
648           // If the procedure was never executed, remove and mark it as rolledback.
649           if (!proc.wasExecuted()) {
650             if (!executeRollback(proc)) {
651               runnables.yield(proc);
652             }
653           }
654         }
655         break;
656       }
657 
658       // Execute the procedure
659       assert proc.getState() == ProcedureState.RUNNABLE;
660       if (proc.acquireLock(getEnvironment())) {
661         execProcedure(procStack, proc);
662         proc.releaseLock(getEnvironment());
663       } else {
664         runnables.yield(proc);
665       }
666       procStack.release(proc);
667 
668       // allows to kill the executor before something is stored to the wal.
669       // useful to test the procedure recovery.
670       if (testing != null && !isRunning()) {
671         break;
672       }
673 
674       if (proc.getProcId() == rootProcId && proc.isSuccess()) {
675         // Finalize the procedure state
676         LOG.info("Procedure completed in " +
677             StringUtils.humanTimeDiff(proc.elapsedTime()) + ": " + proc);
678         procedureFinished(proc);
679         break;
680       }
681     } while (procStack.isFailed());
682   }
683 
684   private void timeoutLoop() {
685     while (isRunning()) {
686       Procedure proc = waitingTimeout.poll();
687       if (proc == null) continue;
688 
689       if (proc.getTimeRemaining() > 100) {
690         // got an early wake, maybe a stop?
691         // re-enqueue the task in case was not a stop or just a signal
692         waitingTimeout.add(proc);
693         continue;
694       }
695 
696       // ----------------------------------------------------------------------------
697       // TODO-MAYBE: Should we provide a notification to the store with the
698       // full set of procedures pending and completed to write a compacted
699       // version of the log (in case is a log)?
700       // In theory no, procedures are have a short life, so at some point the store
701       // will have the tracker saying everything is in the last log.
702       // ----------------------------------------------------------------------------
703 
704       // The CompletedProcedureCleaner is a special case, and it acts as a chore.
705       // instead of bringing the Chore class in, we reuse this timeout thread for
706       // this special case.
707       if (proc instanceof CompletedProcedureCleaner) {
708         try {
709           ((CompletedProcedureCleaner)proc).periodicExecute(getEnvironment());
710         } catch (Throwable e) {
711           LOG.error("ignoring CompletedProcedureCleaner exception: " + e.getMessage(), e);
712         }
713         proc.setStartTime(EnvironmentEdgeManager.currentTime());
714         waitingTimeout.add(proc);
715         continue;
716       }
717 
718       // The procedure received an "abort-timeout", call abort() and
719       // add the procedure back in the queue for rollback.
720       if (proc.setTimeoutFailure()) {
721         long rootProcId = Procedure.getRootProcedureId(procedures, proc);
722         RootProcedureState procStack = rollbackStack.get(rootProcId);
723         procStack.abort();
724         store.update(proc);
725         runnables.addFront(proc);
726         continue;
727       }
728     }
729   }
730 
731   /**
732    * Execute the rollback of the full procedure stack.
733    * Once the procedure is rolledback, the root-procedure will be visible as
734    * finished to user, and the result will be the fatal exception.
735    */
736   private boolean executeRollback(final long rootProcId, final RootProcedureState procStack) {
737     Procedure rootProc = procedures.get(rootProcId);
738     RemoteProcedureException exception = rootProc.getException();
739     if (exception == null) {
740       exception = procStack.getException();
741       rootProc.setFailure(exception);
742       store.update(rootProc);
743     }
744 
745     List<Procedure> subprocStack = procStack.getSubprocedures();
746     assert subprocStack != null : "called rollback with no steps executed rootProc=" + rootProc;
747 
748     int stackTail = subprocStack.size();
749     boolean reuseLock = false;
750     while (stackTail --> 0) {
751       final Procedure proc = subprocStack.get(stackTail);
752 
753       if (!reuseLock && !proc.acquireLock(getEnvironment())) {
754         // can't take a lock on the procedure, add the root-proc back on the
755         // queue waiting for the lock availability
756         return false;
757       }
758 
759       boolean abortRollback = !executeRollback(proc);
760       abortRollback |= !isRunning() || !store.isRunning();
761 
762       // If the next procedure is the same to this one
763       // (e.g. StateMachineProcedure reuse the same instance)
764       // we can avoid to lock/unlock each step
765       reuseLock = stackTail > 0 && (subprocStack.get(stackTail - 1) == proc) && !abortRollback;
766       if (!reuseLock) {
767         proc.releaseLock(getEnvironment());
768       }
769 
770       // allows to kill the executor before something is stored to the wal.
771       // useful to test the procedure recovery.
772       if (abortRollback) {
773         return false;
774       }
775 
776       subprocStack.remove(stackTail);
777     }
778 
779     // Finalize the procedure state
780     LOG.info("Rolledback procedure " + rootProc +
781              " exec-time=" + StringUtils.humanTimeDiff(rootProc.elapsedTime()) +
782              " exception=" + exception.getMessage());
783     procedureFinished(rootProc);
784     return true;
785   }
786 
787   /**
788    * Execute the rollback of the procedure step.
789    * It updates the store with the new state (stack index)
790    * or will remove completly the procedure in case it is a child.
791    */
792   private boolean executeRollback(final Procedure proc) {
793     try {
794       proc.doRollback(getEnvironment());
795     } catch (IOException e) {
796       LOG.debug("rollback attempt failed for " + proc, e);
797       return false;
798     } catch (Throwable e) {
799       // Catch NullPointerExceptions or similar errors...
800       LOG.fatal("CODE-BUG: uncatched runtime exception for procedure: " + proc, e);
801     }
802 
803     // allows to kill the executor before something is stored to the wal.
804     // useful to test the procedure recovery.
805     if (testing != null && testing.shouldKillBeforeStoreUpdate()) {
806       LOG.debug("TESTING: Kill before store update");
807       stop();
808       return false;
809     }
810 
811     if (proc.removeStackIndex()) {
812       proc.setState(ProcedureState.ROLLEDBACK);
813       if (proc.hasParent()) {
814         store.delete(proc.getProcId());
815         procedures.remove(proc.getProcId());
816       } else {
817         store.update(proc);
818       }
819     } else {
820       store.update(proc);
821     }
822     return true;
823   }
824 
825   /**
826    * Executes the specified procedure
827    *  - calls the doExecute() of the procedure
828    *  - if the procedure execution didn't fail (e.g. invalid user input)
829    *     - ...and returned subprocedures
830    *        - the subprocedures are initialized.
831    *        - the subprocedures are added to the store
832    *        - the subprocedures are added to the runnable queue
833    *        - the procedure is now in a WAITING state, waiting for the subprocedures to complete
834    *     - ...if there are no subprocedure
835    *        - the procedure completed successfully
836    *        - if there is a parent (WAITING)
837    *            - the parent state will be set to RUNNABLE
838    *  - in case of failure
839    *    - the store is updated with the new state
840    *    - the executor (caller of this method) will start the rollback of the procedure
841    */
842   private void execProcedure(final RootProcedureState procStack, final Procedure procedure) {
843     Preconditions.checkArgument(procedure.getState() == ProcedureState.RUNNABLE);
844 
845     // Execute the procedure
846     boolean reExecute = false;
847     Procedure[] subprocs = null;
848     do {
849       reExecute = false;
850       try {
851         subprocs = procedure.doExecute(getEnvironment());
852         if (subprocs != null && subprocs.length == 0) {
853           subprocs = null;
854         }
855       } catch (ProcedureYieldException e) {
856         if (LOG.isTraceEnabled()) {
857           LOG.trace("yield procedure: " + procedure);
858         }
859         runnables.yield(procedure);
860         return;
861       } catch (Throwable e) {
862         // Catch NullPointerExceptions or similar errors...
863         String msg = "CODE-BUG: uncatched runtime exception for procedure: " + procedure;
864         LOG.error(msg, e);
865         procedure.setFailure(new RemoteProcedureException(msg, e));
866       }
867 
868       if (!procedure.isFailed()) {
869         if (subprocs != null) {
870           if (subprocs.length == 1 && subprocs[0] == procedure) {
871             // quick-shortcut for a state machine like procedure
872             subprocs = null;
873             reExecute = true;
874           } else {
875             // yield the current procedure, and make the subprocedure runnable
876             for (int i = 0; i < subprocs.length; ++i) {
877               Procedure subproc = subprocs[i];
878               if (subproc == null) {
879                 String msg = "subproc[" + i + "] is null, aborting the procedure";
880                 procedure.setFailure(new RemoteProcedureException(msg,
881                   new IllegalArgumentException(msg)));
882                 subprocs = null;
883                 break;
884               }
885 
886               assert subproc.getState() == ProcedureState.INITIALIZING;
887               subproc.setParentProcId(procedure.getProcId());
888               subproc.setProcId(nextProcId());
889             }
890 
891             if (!procedure.isFailed()) {
892               procedure.setChildrenLatch(subprocs.length);
893               switch (procedure.getState()) {
894                 case RUNNABLE:
895                   procedure.setState(ProcedureState.WAITING);
896                   break;
897                 case WAITING_TIMEOUT:
898                   waitingTimeout.add(procedure);
899                   break;
900                 default:
901                   break;
902               }
903             }
904           }
905         } else if (procedure.getState() == ProcedureState.WAITING_TIMEOUT) {
906           waitingTimeout.add(procedure);
907         } else {
908           // No subtask, so we are done
909           procedure.setState(ProcedureState.FINISHED);
910         }
911       }
912 
913       // Add the procedure to the stack
914       procStack.addRollbackStep(procedure);
915 
916       // allows to kill the executor before something is stored to the wal.
917       // useful to test the procedure recovery.
918       if (testing != null && testing.shouldKillBeforeStoreUpdate()) {
919         LOG.debug("TESTING: Kill before store update");
920         stop();
921         return;
922       }
923 
924       // Commit the transaction
925       if (subprocs != null && !procedure.isFailed()) {
926         if (LOG.isTraceEnabled()) {
927           LOG.trace("store add " + procedure + " children " + Arrays.toString(subprocs));
928         }
929         store.insert(procedure, subprocs);
930       } else {
931         if (LOG.isTraceEnabled()) {
932           LOG.trace("store update " + procedure);
933         }
934         store.update(procedure);
935       }
936 
937       // if the store is not running we are aborting
938       if (!store.isRunning()) {
939         return;
940       }
941 
942       assert (reExecute && subprocs == null) || !reExecute;
943     } while (reExecute);
944 
945     // Submit the new subprocedures
946     if (subprocs != null && !procedure.isFailed()) {
947       for (int i = 0; i < subprocs.length; ++i) {
948         Procedure subproc = subprocs[i];
949         assert !procedures.containsKey(subproc.getProcId());
950         procedures.put(subproc.getProcId(), subproc);
951         runnables.addFront(subproc);
952       }
953     }
954 
955     if (procedure.isFinished() && procedure.hasParent()) {
956       Procedure parent = procedures.get(procedure.getParentProcId());
957       if (parent == null) {
958         assert procStack.isRollingback();
959         return;
960       }
961 
962       // If this procedure is the last child awake the parent procedure
963       if (LOG.isTraceEnabled()) {
964         LOG.trace(parent + " child is done: " + procedure);
965       }
966       if (parent.childrenCountDown() && parent.getState() == ProcedureState.WAITING) {
967         parent.setState(ProcedureState.RUNNABLE);
968         store.update(parent);
969         runnables.addFront(parent);
970         if (LOG.isTraceEnabled()) {
971           LOG.trace(parent + " all the children finished their work, resume.");
972         }
973         return;
974       }
975     }
976   }
977 
978   private void sendProcedureLoadedNotification(final long procId) {
979     if (!this.listeners.isEmpty()) {
980       for (ProcedureExecutorListener listener: this.listeners) {
981         try {
982           listener.procedureLoaded(procId);
983         } catch (Throwable e) {
984           LOG.error("the listener " + listener + " had an error: " + e.getMessage(), e);
985         }
986       }
987     }
988   }
989 
990   private void sendProcedureAddedNotification(final long procId) {
991     if (!this.listeners.isEmpty()) {
992       for (ProcedureExecutorListener listener: this.listeners) {
993         try {
994           listener.procedureAdded(procId);
995         } catch (Throwable e) {
996           LOG.error("the listener " + listener + " had an error: " + e.getMessage(), e);
997         }
998       }
999     }
1000   }
1001 
1002   private void sendProcedureFinishedNotification(final long procId) {
1003     if (!this.listeners.isEmpty()) {
1004       for (ProcedureExecutorListener listener: this.listeners) {
1005         try {
1006           listener.procedureFinished(procId);
1007         } catch (Throwable e) {
1008           LOG.error("the listener " + listener + " had an error: " + e.getMessage(), e);
1009         }
1010       }
1011     }
1012   }
1013 
1014   private long nextProcId() {
1015     long procId = lastProcId.incrementAndGet();
1016     if (procId < 0) {
1017       while (!lastProcId.compareAndSet(procId, 0)) {
1018         procId = lastProcId.get();
1019         if (procId >= 0)
1020           break;
1021       }
1022       while (procedures.containsKey(procId)) {
1023         procId = lastProcId.incrementAndGet();
1024       }
1025     }
1026     return procId;
1027   }
1028 
1029   private Long getRootProcedureId(Procedure proc) {
1030     return Procedure.getRootProcedureId(procedures, proc);
1031   }
1032 
1033   private void procedureFinished(final Procedure proc) {
1034     // call the procedure completion cleanup handler
1035     try {
1036       proc.completionCleanup(getEnvironment());
1037     } catch (Throwable e) {
1038       // Catch NullPointerExceptions or similar errors...
1039       LOG.error("CODE-BUG: uncatched runtime exception for procedure: " + proc, e);
1040     }
1041 
1042     // update the executor internal state maps
1043     completed.put(proc.getProcId(), newResultFromProcedure(proc));
1044     rollbackStack.remove(proc.getProcId());
1045     procedures.remove(proc.getProcId());
1046 
1047     // call the runnableSet completion cleanup handler
1048     try {
1049       runnables.completionCleanup(proc);
1050     } catch (Throwable e) {
1051       // Catch NullPointerExceptions or similar errors...
1052       LOG.error("CODE-BUG: uncatched runtime exception for runnableSet: " + runnables, e);
1053     }
1054 
1055     // Notify the listeners
1056     sendProcedureFinishedNotification(proc.getProcId());
1057   }
1058 
1059   public Pair<ProcedureResult, Procedure> getResultOrProcedure(final long procId) {
1060     ProcedureResult result = completed.get(procId);
1061     Procedure proc = null;
1062     if (result == null) {
1063       proc = procedures.get(procId);
1064       if (proc == null) {
1065         result = completed.get(procId);
1066       }
1067     }
1068     return new Pair(result, proc);
1069   }
1070 
1071   private static ProcedureResult newResultFromProcedure(final Procedure proc) {
1072     if (proc.isFailed()) {
1073       return new ProcedureResult(proc.getStartTime(), proc.getLastUpdate(), proc.getException());
1074     }
1075     return new ProcedureResult(proc.getStartTime(), proc.getLastUpdate(), proc.getResult());
1076   }
1077 }