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.lang.reflect.Constructor;
25  import java.lang.reflect.Modifier;
26  import java.util.Arrays;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.concurrent.TimeoutException;
30  
31  import org.apache.hadoop.hbase.classification.InterfaceAudience;
32  import org.apache.hadoop.hbase.classification.InterfaceStability;
33  import org.apache.hadoop.hbase.procedure2.util.StringUtils;
34  import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos;
35  import org.apache.hadoop.hbase.protobuf.generated.ProcedureProtos.ProcedureState;
36  import org.apache.hadoop.hbase.util.ByteStringer;
37  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
38  
39  import com.google.common.annotations.VisibleForTesting;
40  import com.google.common.base.Preconditions;
41  import com.google.protobuf.ByteString;
42  
43  /**
44   * Base Procedure class responsible to handle the Procedure Metadata
45   * e.g. state, startTime, lastUpdate, stack-indexes, ...
46   *
47   * execute() is called each time the procedure is executed.
48   * it may be called multiple times in case of failure and restart, so the
49   * code must be idempotent.
50   * the return is a set of sub-procedures or null in case the procedure doesn't
51   * have sub-procedures. Once the sub-procedures are successfully completed
52   * the execute() method is called again, you should think at it as a stack:
53   *  -> step 1
54   *  ---> step 2
55   *  -> step 1
56   *
57   * rollback() is called when the procedure or one of the sub-procedures is failed.
58   * the rollback step is supposed to cleanup the resources created during the
59   * execute() step. in case of failure and restart rollback() may be called
60   * multiple times, so the code must be idempotent.
61   */
62  @InterfaceAudience.Private
63  @InterfaceStability.Evolving
64  public abstract class Procedure<TEnvironment> implements Comparable<Procedure> {
65    // unchanged after initialization
66    private String owner = null;
67    private Long parentProcId = null;
68    private Long procId = null;
69    private long startTime;
70  
71    // runtime state, updated every operation
72    private ProcedureState state = ProcedureState.INITIALIZING;
73    private Integer timeout = null;
74    private int[] stackIndexes = null;
75    private int childrenLatch = 0;
76    private long lastUpdate;
77  
78    private RemoteProcedureException exception = null;
79    private byte[] result = null;
80  
81    /**
82     * The main code of the procedure. It must be idempotent since execute()
83     * may be called multiple time in case of machine failure in the middle
84     * of the execution.
85     * @return a set of sub-procedures or null if there is nothing else to execute.
86     */
87    protected abstract Procedure[] execute(TEnvironment env)
88      throws ProcedureYieldException;
89  
90    /**
91     * The code to undo what done by the execute() code.
92     * It is called when the procedure or one of the sub-procedure failed or an
93     * abort was requested. It should cleanup all the resources created by
94     * the execute() call. The implementation must be idempotent since rollback()
95     * may be called multiple time in case of machine failure in the middle
96     * of the execution.
97     * @throws IOException temporary failure, the rollback will retry later
98     */
99    protected abstract void rollback(TEnvironment env)
100     throws IOException;
101 
102   /**
103    * The abort() call is asynchronous and each procedure must decide how to deal
104    * with that, if they want to be abortable. The simplest implementation
105    * is to have an AtomicBoolean set in the abort() method and then the execute()
106    * will check if the abort flag is set or not.
107    * abort() may be called multiple times from the client, so the implementation
108    * must be idempotent.
109    *
110    * NOTE: abort() is not like Thread.interrupt() it is just a notification
111    * that allows the procedure implementor where to abort to avoid leak and
112    * have a better control on what was executed and what not.
113    */
114   protected abstract boolean abort(TEnvironment env);
115 
116   /**
117    * The user-level code of the procedure may have some state to
118    * persist (e.g. input arguments) to be able to resume on failure.
119    * @param stream the stream that will contain the user serialized data
120    */
121   protected abstract void serializeStateData(final OutputStream stream)
122     throws IOException;
123 
124   /**
125    * Called on store load to allow the user to decode the previously serialized
126    * state.
127    * @param stream the stream that contains the user serialized data
128    */
129   protected abstract void deserializeStateData(final InputStream stream)
130     throws IOException;
131 
132   /**
133    * The user should override this method, and try to take a lock if necessary.
134    * A lock can be anything, and it is up to the implementor.
135    * Example: in our Master we can execute request in parallel for different tables
136    *          create t1 and create t2 can be executed at the same time.
137    *          anything else on t1/t2 is queued waiting that specific table create to happen.
138    *
139    * @return true if the lock was acquired and false otherwise
140    */
141   protected boolean acquireLock(final TEnvironment env) {
142     return true;
143   }
144 
145   /**
146    * The user should override this method, and release lock if necessary.
147    */
148   protected void releaseLock(final TEnvironment env) {
149     // no-op
150   }
151 
152   /**
153    * Called when the procedure is loaded for replay.
154    * The procedure implementor may use this method to perform some quick
155    * operation before replay.
156    * e.g. failing the procedure if the state on replay may be unknown.
157    */
158   protected void beforeReplay(final TEnvironment env) {
159     // no-op
160   }
161 
162   /**
163    * Called when the procedure is marked as completed (success or rollback).
164    * The procedure implementor may use this method to cleanup in-memory states.
165    * This operation will not be retried on failure.
166    */
167   protected void completionCleanup(final TEnvironment env) {
168     // no-op
169   }
170 
171   @Override
172   public String toString() {
173     StringBuilder sb = new StringBuilder();
174     toStringClassDetails(sb);
175 
176     if (procId != null) {
177       sb.append(" id=");
178       sb.append(getProcId());
179     }
180 
181     if (hasParent()) {
182       sb.append(" parent=");
183       sb.append(getParentProcId());
184     }
185 
186     if (hasOwner()) {
187       sb.append(" owner=");
188       sb.append(getOwner());
189     }
190 
191     sb.append(" state=");
192     sb.append(getState());
193     return sb.toString();
194   }
195 
196   /**
197    * Extend the toString() information with the procedure details
198    * e.g. className and parameters
199    * @param builder the string builder to use to append the proc specific information
200    */
201   protected void toStringClassDetails(StringBuilder builder) {
202     builder.append(getClass().getName());
203   }
204 
205   /**
206    * @return the serialized result if any, otherwise null
207    */
208   public byte[] getResult() {
209     return result;
210   }
211 
212   /**
213    * The procedure may leave a "result" on completion.
214    * @param result the serialized result that will be passed to the client
215    */
216   protected void setResult(final byte[] result) {
217     this.result = result;
218   }
219 
220   public long getProcId() {
221     return procId;
222   }
223 
224   public boolean hasParent() {
225     return parentProcId != null;
226   }
227 
228   public boolean hasException() {
229     return exception != null;
230   }
231 
232   public boolean hasTimeout() {
233     return timeout != null;
234   }
235 
236   public long getParentProcId() {
237     return parentProcId;
238   }
239 
240   /**
241    * @return true if the procedure has failed.
242    *         true may mean failed but not yet rolledback or failed and rolledback.
243    */
244   public synchronized boolean isFailed() {
245     return exception != null || state == ProcedureState.ROLLEDBACK;
246   }
247 
248   /**
249    * @return true if the procedure is finished successfully.
250    */
251   public synchronized boolean isSuccess() {
252     return state == ProcedureState.FINISHED && exception == null;
253   }
254 
255   /**
256    * @return true if the procedure is finished. The Procedure may be completed
257    *         successfuly or failed and rolledback.
258    */
259   public synchronized boolean isFinished() {
260     switch (state) {
261       case ROLLEDBACK:
262         return true;
263       case FINISHED:
264         return exception == null;
265       default:
266         break;
267     }
268     return false;
269   }
270 
271   /**
272    * @return true if the procedure is waiting for a child to finish or for an external event.
273    */
274   public synchronized boolean isWaiting() {
275     switch (state) {
276       case WAITING:
277       case WAITING_TIMEOUT:
278         return true;
279       default:
280         break;
281     }
282     return false;
283   }
284 
285   public synchronized RemoteProcedureException getException() {
286     return exception;
287   }
288 
289   public long getStartTime() {
290     return startTime;
291   }
292 
293   public synchronized long getLastUpdate() {
294     return lastUpdate;
295   }
296 
297   public synchronized long elapsedTime() {
298     return lastUpdate - startTime;
299   }
300 
301   /**
302    * @param timeout timeout in msec
303    */
304   protected void setTimeout(final int timeout) {
305     this.timeout = timeout;
306   }
307 
308   /**
309    * @return the timeout in msec
310    */
311   public int getTimeout() {
312     return timeout;
313   }
314 
315   /**
316    * @return the remaining time before the timeout
317    */
318   public long getTimeRemaining() {
319     return Math.max(0, timeout - (EnvironmentEdgeManager.currentTime() - startTime));
320   }
321 
322   protected void setOwner(final String owner) {
323     this.owner = StringUtils.isEmpty(owner) ? null : owner;
324   }
325 
326   public String getOwner() {
327     return owner;
328   }
329 
330   public boolean hasOwner() {
331     return owner != null;
332   }
333 
334   @VisibleForTesting
335   @InterfaceAudience.Private
336   protected synchronized void setState(final ProcedureState state) {
337     this.state = state;
338     updateTimestamp();
339   }
340 
341   @InterfaceAudience.Private
342   protected synchronized ProcedureState getState() {
343     return state;
344   }
345 
346   protected void setFailure(final String source, final Throwable cause) {
347     setFailure(new RemoteProcedureException(source, cause));
348   }
349 
350   protected synchronized void setFailure(final RemoteProcedureException exception) {
351     this.exception = exception;
352     if (!isFinished()) {
353       setState(ProcedureState.FINISHED);
354     }
355   }
356 
357   protected void setAbortFailure(final String source, final String msg) {
358     setFailure(source, new ProcedureAbortedException(msg));
359   }
360 
361   @InterfaceAudience.Private
362   protected synchronized boolean setTimeoutFailure() {
363     if (state == ProcedureState.WAITING_TIMEOUT) {
364       long timeDiff = EnvironmentEdgeManager.currentTime() - lastUpdate;
365       setFailure("ProcedureExecutor", new TimeoutException(
366         "Operation timed out after " + StringUtils.humanTimeDiff(timeDiff)));
367       return true;
368     }
369     return false;
370   }
371 
372   /**
373    * Called by the ProcedureExecutor to assign the ID to the newly created procedure.
374    */
375   @VisibleForTesting
376   @InterfaceAudience.Private
377   protected void setProcId(final long procId) {
378     this.procId = procId;
379     this.startTime = EnvironmentEdgeManager.currentTime();
380     setState(ProcedureState.RUNNABLE);
381   }
382 
383   /**
384    * Called by the ProcedureExecutor to assign the parent to the newly created procedure.
385    */
386   @InterfaceAudience.Private
387   protected void setParentProcId(final long parentProcId) {
388     this.parentProcId = parentProcId;
389   }
390 
391   /**
392    * Internal method called by the ProcedureExecutor that starts the
393    * user-level code execute().
394    */
395   @InterfaceAudience.Private
396   protected Procedure[] doExecute(final TEnvironment env)
397       throws ProcedureYieldException {
398     try {
399       updateTimestamp();
400       return execute(env);
401     } finally {
402       updateTimestamp();
403     }
404   }
405 
406   /**
407    * Internal method called by the ProcedureExecutor that starts the
408    * user-level code rollback().
409    */
410   @InterfaceAudience.Private
411   protected void doRollback(final TEnvironment env) throws IOException {
412     try {
413       updateTimestamp();
414       rollback(env);
415     } finally {
416       updateTimestamp();
417     }
418   }
419 
420   /**
421    * Called on store load to initialize the Procedure internals after
422    * the creation/deserialization.
423    */
424   @InterfaceAudience.Private
425   protected void setStartTime(final long startTime) {
426     this.startTime = startTime;
427   }
428 
429   /**
430    * Called on store load to initialize the Procedure internals after
431    * the creation/deserialization.
432    */
433   private synchronized void setLastUpdate(final long lastUpdate) {
434     this.lastUpdate = lastUpdate;
435   }
436 
437   protected synchronized void updateTimestamp() {
438     this.lastUpdate = EnvironmentEdgeManager.currentTime();
439   }
440 
441   /**
442    * Called by the ProcedureExecutor on procedure-load to restore the latch state
443    */
444   @InterfaceAudience.Private
445   protected synchronized void setChildrenLatch(final int numChildren) {
446     this.childrenLatch = numChildren;
447   }
448 
449   /**
450    * Called by the ProcedureExecutor on procedure-load to restore the latch state
451    */
452   @InterfaceAudience.Private
453   protected synchronized void incChildrenLatch() {
454     // TODO: can this be inferred from the stack? I think so...
455     this.childrenLatch++;
456   }
457 
458   /**
459    * Called by the ProcedureExecutor to notify that one of the sub-procedures
460    * has completed.
461    */
462   @InterfaceAudience.Private
463   protected synchronized boolean childrenCountDown() {
464     assert childrenLatch > 0;
465     return --childrenLatch == 0;
466   }
467 
468   /**
469    * Called by the RootProcedureState on procedure execution.
470    * Each procedure store its stack-index positions.
471    */
472   @InterfaceAudience.Private
473   protected synchronized void addStackIndex(final int index) {
474     if (stackIndexes == null) {
475       stackIndexes = new int[] { index };
476     } else {
477       int count = stackIndexes.length;
478       stackIndexes = Arrays.copyOf(stackIndexes, count + 1);
479       stackIndexes[count] = index;
480     }
481   }
482 
483   @InterfaceAudience.Private
484   protected synchronized boolean removeStackIndex() {
485     if (stackIndexes.length > 1) {
486       stackIndexes = Arrays.copyOf(stackIndexes, stackIndexes.length - 1);
487       return false;
488     } else {
489       stackIndexes = null;
490       return true;
491     }
492   }
493 
494   /**
495    * Called on store load to initialize the Procedure internals after
496    * the creation/deserialization.
497    */
498   @InterfaceAudience.Private
499   protected synchronized void setStackIndexes(final List<Integer> stackIndexes) {
500     this.stackIndexes = new int[stackIndexes.size()];
501     for (int i = 0; i < this.stackIndexes.length; ++i) {
502       this.stackIndexes[i] = stackIndexes.get(i);
503     }
504   }
505 
506   @InterfaceAudience.Private
507   protected synchronized boolean wasExecuted() {
508     return stackIndexes != null;
509   }
510 
511   @InterfaceAudience.Private
512   protected synchronized int[] getStackIndexes() {
513     return stackIndexes;
514   }
515 
516   @Override
517   public int compareTo(final Procedure other) {
518     long diff = getProcId() - other.getProcId();
519     return (diff < 0) ? -1 : (diff > 0) ? 1 : 0;
520   }
521 
522   /*
523    * Helper to lookup the root Procedure ID given a specified procedure.
524    */
525   @InterfaceAudience.Private
526   protected static Long getRootProcedureId(final Map<Long, Procedure> procedures, Procedure proc) {
527     while (proc.hasParent()) {
528       proc = procedures.get(proc.getParentProcId());
529       if (proc == null) return null;
530     }
531     return proc.getProcId();
532   }
533 
534   protected static Procedure newInstance(final String className) throws IOException {
535     try {
536       Class<?> clazz = Class.forName(className);
537       if (!Modifier.isPublic(clazz.getModifiers())) {
538         throw new Exception("the " + clazz + " class is not public");
539       }
540 
541       Constructor<?> ctor = clazz.getConstructor();
542       assert ctor != null : "no constructor found";
543       if (!Modifier.isPublic(ctor.getModifiers())) {
544         throw new Exception("the " + clazz + " constructor is not public");
545       }
546       return (Procedure)ctor.newInstance();
547     } catch (Exception e) {
548       throw new IOException("The procedure class " + className +
549           " must be accessible and have an empty constructor", e);
550     }
551   }
552 
553   protected static void validateClass(final Procedure proc) throws IOException {
554     try {
555       Class<?> clazz = proc.getClass();
556       if (!Modifier.isPublic(clazz.getModifiers())) {
557         throw new Exception("the " + clazz + " class is not public");
558       }
559 
560       Constructor<?> ctor = clazz.getConstructor();
561       assert ctor != null;
562       if (!Modifier.isPublic(ctor.getModifiers())) {
563         throw new Exception("the " + clazz + " constructor is not public");
564       }
565     } catch (Exception e) {
566       throw new IOException("The procedure class " + proc.getClass().getName() +
567           " must be accessible and have an empty constructor", e);
568     }
569   }
570 
571   /**
572    * Helper to convert the procedure to protobuf.
573    * Used by ProcedureStore implementations.
574    */
575   @InterfaceAudience.Private
576   public static ProcedureProtos.Procedure convert(final Procedure proc)
577       throws IOException {
578     Preconditions.checkArgument(proc != null);
579     validateClass(proc);
580 
581     ProcedureProtos.Procedure.Builder builder = ProcedureProtos.Procedure.newBuilder()
582       .setClassName(proc.getClass().getName())
583       .setProcId(proc.getProcId())
584       .setState(proc.getState())
585       .setStartTime(proc.getStartTime())
586       .setLastUpdate(proc.getLastUpdate());
587 
588     if (proc.hasParent()) {
589       builder.setParentId(proc.getParentProcId());
590     }
591 
592     if (proc.hasTimeout()) {
593       builder.setTimeout(proc.getTimeout());
594     }
595 
596     if (proc.hasOwner()) {
597       builder.setOwner(proc.getOwner());
598     }
599 
600     int[] stackIds = proc.getStackIndexes();
601     if (stackIds != null) {
602       for (int i = 0; i < stackIds.length; ++i) {
603         builder.addStackId(stackIds[i]);
604       }
605     }
606 
607     if (proc.hasException()) {
608       RemoteProcedureException exception = proc.getException();
609       builder.setException(
610         RemoteProcedureException.toProto(exception.getSource(), exception.getCause()));
611     }
612 
613     byte[] result = proc.getResult();
614     if (result != null) {
615       builder.setResult(ByteStringer.wrap(result));
616     }
617 
618     ByteString.Output stateStream = ByteString.newOutput();
619     proc.serializeStateData(stateStream);
620     if (stateStream.size() > 0) {
621       builder.setStateData(stateStream.toByteString());
622     }
623 
624     return builder.build();
625   }
626 
627   /**
628    * Helper to convert the protobuf procedure.
629    * Used by ProcedureStore implementations.
630    *
631    * TODO: OPTIMIZATION: some of the field never change during the execution
632    *                     (e.g. className, procId, parentId, ...).
633    *                     We can split in 'data' and 'state', and the store
634    *                     may take advantage of it by storing the data only on insert().
635    */
636   @InterfaceAudience.Private
637   public static Procedure convert(final ProcedureProtos.Procedure proto)
638       throws IOException {
639     // Procedure from class name
640     Procedure proc = Procedure.newInstance(proto.getClassName());
641 
642     // set fields
643     proc.setProcId(proto.getProcId());
644     proc.setState(proto.getState());
645     proc.setStartTime(proto.getStartTime());
646     proc.setLastUpdate(proto.getLastUpdate());
647 
648     if (proto.hasParentId()) {
649       proc.setParentProcId(proto.getParentId());
650     }
651 
652     if (proto.hasOwner()) {
653       proc.setOwner(proto.getOwner());
654     }
655 
656     if (proto.hasTimeout()) {
657       proc.setTimeout(proto.getTimeout());
658     }
659 
660     if (proto.getStackIdCount() > 0) {
661       proc.setStackIndexes(proto.getStackIdList());
662     }
663 
664     if (proto.hasException()) {
665       assert proc.getState() == ProcedureState.FINISHED ||
666              proc.getState() == ProcedureState.ROLLEDBACK :
667              "The procedure must be failed (waiting to rollback) or rolledback";
668       proc.setFailure(RemoteProcedureException.fromProto(proto.getException()));
669     }
670 
671     if (proto.hasResult()) {
672       proc.setResult(proto.getResult().toByteArray());
673     }
674 
675     // we want to call deserialize even when the stream is empty, mainly for testing.
676     proc.deserializeStateData(proto.getStateData().newInput());
677 
678     return proc;
679   }
680 }