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  package org.apache.hadoop.hbase.procedure;
19  
20  import java.io.IOException;
21  import java.util.Collection;
22  import java.util.HashSet;
23  import java.util.List;
24  import java.util.Set;
25  import java.util.concurrent.ConcurrentMap;
26  import java.util.concurrent.ExecutorService;
27  import java.util.concurrent.RejectedExecutionException;
28  import java.util.concurrent.SynchronousQueue;
29  import java.util.concurrent.ThreadPoolExecutor;
30  import java.util.concurrent.TimeUnit;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  import org.apache.hadoop.hbase.DaemonThreadFactory;
36  import org.apache.hadoop.hbase.errorhandling.ForeignException;
37  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
38  
39  import com.google.common.collect.MapMaker;
40  
41  /**
42   * This is the master side of a distributed complex procedure execution.
43   * <p>
44   * The {@link Procedure} is generic and subclassing or customization shouldn't be
45   * necessary -- any customization should happen just in {@link Subprocedure}s.
46   */
47  @InterfaceAudience.Private
48  public class ProcedureCoordinator {
49    private static final Log LOG = LogFactory.getLog(ProcedureCoordinator.class);
50  
51    final static long KEEP_ALIVE_MILLIS_DEFAULT = 5000;
52    final static long TIMEOUT_MILLIS_DEFAULT = 60000;
53    final static long WAKE_MILLIS_DEFAULT = 500;
54  
55    private final ProcedureCoordinatorRpcs rpcs;
56    private final ExecutorService pool;
57    private final long wakeTimeMillis;
58    private final long timeoutMillis;
59  
60    // Running procedure table.  Maps procedure name to running procedure reference
61    private final ConcurrentMap<String, Procedure> procedures =
62        new MapMaker().concurrencyLevel(4).weakValues().makeMap();
63  
64    /**
65     * Create and start a ProcedureCoordinator.
66     *
67     * The rpc object registers the ProcedureCoordinator and starts any threads in this
68     * constructor.
69     *
70     * @param rpcs
71     * @param pool Used for executing procedures.
72     */
73    public ProcedureCoordinator(ProcedureCoordinatorRpcs rpcs, ThreadPoolExecutor pool) {
74      this(rpcs, pool, TIMEOUT_MILLIS_DEFAULT, WAKE_MILLIS_DEFAULT);
75    }
76  
77    /**
78     * Create and start a ProcedureCoordinator.
79     *
80     * The rpc object registers the ProcedureCoordinator and starts any threads in
81     * this constructor.
82     *
83     * @param rpcs
84     * @param pool Used for executing procedures.
85     * @param timeoutMillis
86     */
87    public ProcedureCoordinator(ProcedureCoordinatorRpcs rpcs, ThreadPoolExecutor pool,
88        long timeoutMillis, long wakeTimeMillis) {
89      this.timeoutMillis = timeoutMillis;
90      this.wakeTimeMillis = wakeTimeMillis;
91      this.rpcs = rpcs;
92      this.pool = pool;
93      this.rpcs.start(this);
94    }
95  
96    /**
97     * Default thread pool for the procedure
98     *
99     * @param coordName
100    * @param opThreads the maximum number of threads to allow in the pool
101    */
102   public static ThreadPoolExecutor defaultPool(String coordName, int opThreads) {
103     return defaultPool(coordName, opThreads, KEEP_ALIVE_MILLIS_DEFAULT);
104   }
105 
106   /**
107    * Default thread pool for the procedure
108    *
109    * @param coordName
110    * @param opThreads the maximum number of threads to allow in the pool
111    * @param keepAliveMillis the maximum time (ms) that excess idle threads will wait for new tasks
112    */
113   public static ThreadPoolExecutor defaultPool(String coordName, int opThreads,
114       long keepAliveMillis) {
115     return new ThreadPoolExecutor(1, opThreads, keepAliveMillis, TimeUnit.MILLISECONDS,
116         new SynchronousQueue<Runnable>(),
117         new DaemonThreadFactory("(" + coordName + ")-proc-coordinator-pool"));
118   }
119 
120   /**
121    * Shutdown the thread pools and release rpc resources
122    * @throws IOException
123    */
124   public void close() throws IOException {
125     // have to use shutdown now to break any latch waiting
126     pool.shutdownNow();
127     rpcs.close();
128   }
129 
130   /**
131    * Submit an procedure to kick off its dependent subprocedures.
132    * @param proc Procedure to execute
133    * @return <tt>true</tt> if the procedure was started correctly, <tt>false</tt> if the
134    *         procedure or any subprocedures could not be started.  Failure could be due to
135    *         submitting a procedure multiple times (or one with the same name), or some sort
136    *         of IO problem.  On errors, the procedure's monitor holds a reference to the exception
137    *         that caused the failure.
138    */
139   boolean submitProcedure(Procedure proc) {
140     // if the submitted procedure was null, then we don't want to run it
141     if (proc == null) {
142       return false;
143     }
144     String procName = proc.getName();
145 
146     // make sure we aren't already running a procedure of that name
147     Procedure oldProc = procedures.get(procName);
148     if (oldProc != null) {
149       // procedures are always eventually completed on both successful and failed execution
150       if (oldProc.completedLatch.getCount() != 0) {
151         LOG.warn("Procedure " + procName + " currently running.  Rejecting new request");
152         return false;
153       } else {
154         LOG.debug("Procedure " + procName
155           + " was in running list but was completed.  Accepting new attempt.");
156         if (!procedures.remove(procName, oldProc)) {
157           LOG.warn("Procedure " + procName
158             + " has been resubmitted by another thread. Rejecting this request.");
159           return false;
160         }
161       }
162     }
163 
164     // kick off the procedure's execution in a separate thread
165     try {
166       if (this.procedures.putIfAbsent(procName, proc) == null) {
167         this.pool.submit(proc);
168         return true;
169       } else {
170         LOG.error("Another thread has submitted procedure '" + procName + "'. Ignoring this attempt.");
171         return false;
172       }
173     } catch (RejectedExecutionException e) {
174       LOG.warn("Procedure " + procName + " rejected by execution pool.  Propagating error.", e);
175       // Remove the procedure from the list since is not started
176       this.procedures.remove(procName, proc);
177       // the thread pool is full and we can't run the procedure
178       proc.receive(new ForeignException(procName, e));
179     }
180     return false;
181   }
182 
183   /**
184    * The connection to the rest of the procedure group (members and coordinator) has been
185    * broken/lost/failed. This should fail any interested procedures, but not attempt to notify other
186    * members since we cannot reach them anymore.
187    * @param message description of the error
188    * @param cause the actual cause of the failure
189    */
190   void rpcConnectionFailure(final String message, final IOException cause) {
191     Collection<Procedure> toNotify = procedures.values();
192 
193     for (Procedure proc : toNotify) {
194       if (proc == null) {
195         continue;
196       }
197       // notify the elements, if they aren't null
198       proc.receive(new ForeignException(proc.getName(), cause));
199     }
200   }
201 
202   /**
203    * Abort the procedure with the given name
204    * @param procName name of the procedure to abort
205    * @param reason serialized information about the abort
206    */
207   public void abortProcedure(String procName, ForeignException reason) {
208     // if we know about the Procedure, notify it
209     Procedure proc = procedures.get(procName);
210     if (proc == null) {
211       return;
212     }
213     proc.receive(reason);
214   }
215 
216   /**
217    * Exposed for hooking with unit tests.
218    * @param procName
219    * @param procArgs
220    * @param expectedMembers
221    * @return the newly created procedure
222    */
223   Procedure createProcedure(ForeignExceptionDispatcher fed, String procName, byte[] procArgs,
224       List<String> expectedMembers) {
225     // build the procedure
226     return new Procedure(this, fed, wakeTimeMillis, timeoutMillis,
227         procName, procArgs, expectedMembers);
228   }
229 
230   /**
231    * Kick off the named procedure
232    * @param procName name of the procedure to start
233    * @param procArgs arguments for the procedure
234    * @param expectedMembers expected members to start
235    * @return handle to the running procedure, if it was started correctly, <tt>null</tt> otherwise
236    * @throws RejectedExecutionException if there are no more available threads to run the procedure
237    */
238   public Procedure startProcedure(ForeignExceptionDispatcher fed, String procName, byte[] procArgs,
239       List<String> expectedMembers) throws RejectedExecutionException {
240     Procedure proc = createProcedure(fed, procName, procArgs, expectedMembers);
241     if (!this.submitProcedure(proc)) {
242       LOG.error("Failed to submit procedure '" + procName + "'");
243       return null;
244     }
245     return proc;
246   }
247 
248   /**
249    * Notification that the procedure had the specified member acquired its part of the barrier
250    * via {@link Subprocedure#acquireBarrier()}.
251    * @param procName name of the procedure that acquired
252    * @param member name of the member that acquired
253    */
254   void memberAcquiredBarrier(String procName, final String member) {
255     Procedure proc = procedures.get(procName);
256     if (proc == null) {
257       LOG.warn("Member '"+ member +"' is trying to acquire an unknown procedure '"+ procName +"'");
258       return;
259     }
260 
261     proc.barrierAcquiredByMember(member);
262   }
263 
264   /**
265    * Notification that the procedure had another member finished executing its in-barrier subproc
266    * via {@link Subprocedure#insideBarrier()}.
267    * @param procName name of the subprocedure that finished
268    * @param member name of the member that executed and released its barrier
269    */
270   void memberFinishedBarrier(String procName, final String member) {
271     Procedure proc = procedures.get(procName);
272     if (proc == null) {
273       LOG.warn("Member '"+ member +"' is trying to release an unknown procedure '"+ procName +"'");
274       return;
275     }
276     proc.barrierReleasedByMember(member);
277   }
278 
279   /**
280    * @return the rpcs implementation for all current procedures
281    */
282   ProcedureCoordinatorRpcs getRpcs() {
283     return rpcs;
284   }
285 
286   /**
287    * Returns the procedure.  This Procedure is a live instance so should not be modified but can
288    * be inspected.
289    * @param name Name of the procedure
290    * @return Procedure or null if not present any more
291    */
292   public Procedure getProcedure(String name) {
293     return procedures.get(name);
294   }
295 
296   /**
297    * @return Return set of all procedure names.
298    */
299   public Set<String> getProcedureNames() {
300     return new HashSet<String>(procedures.keySet());
301   }
302 }