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.regionserver.snapshot;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.List;
24  import java.util.concurrent.Callable;
25  import java.util.concurrent.ExecutionException;
26  import java.util.concurrent.ExecutorCompletionService;
27  import java.util.concurrent.Future;
28  import java.util.concurrent.LinkedBlockingQueue;
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.classification.InterfaceAudience;
35  import org.apache.hadoop.classification.InterfaceStability;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.hbase.DaemonThreadFactory;
38  import org.apache.hadoop.hbase.TableName;
39  import org.apache.hadoop.hbase.errorhandling.ForeignException;
40  import org.apache.hadoop.hbase.errorhandling.ForeignExceptionDispatcher;
41  import org.apache.hadoop.hbase.master.snapshot.MasterSnapshotVerifier;
42  import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
43  import org.apache.hadoop.hbase.procedure.ProcedureMember;
44  import org.apache.hadoop.hbase.procedure.ProcedureMemberRpcs;
45  import org.apache.hadoop.hbase.procedure.RegionServerProcedureManager;
46  import org.apache.hadoop.hbase.procedure.Subprocedure;
47  import org.apache.hadoop.hbase.procedure.SubprocedureFactory;
48  import org.apache.hadoop.hbase.procedure.ZKProcedureMemberRpcs;
49  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
50  import org.apache.hadoop.hbase.regionserver.HRegion;
51  import org.apache.hadoop.hbase.regionserver.HRegionServer;
52  import org.apache.hadoop.hbase.regionserver.RegionServerServices;
53  import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
54  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
55  import org.apache.zookeeper.KeeperException;
56  
57  import com.google.protobuf.InvalidProtocolBufferException;
58  
59  /**
60   * This manager class handles the work dealing with snapshots for a {@link HRegionServer}.
61   * <p>
62   * This provides the mechanism necessary to kick off a online snapshot specific
63   * {@link Subprocedure} that is responsible for the regions being served by this region server.
64   * If any failures occur with the subprocedure, the RegionSeverSnapshotManager's subprocedure
65   * handler, {@link ProcedureMember}, notifies the master's ProcedureCoordinator to abort all
66   * others.
67   * <p>
68   * On startup, requires {@link #start()} to be called.
69   * <p>
70   * On shutdown, requires {@link #stop(boolean)} to be called
71   */
72  @InterfaceAudience.Private
73  @InterfaceStability.Unstable
74  public class RegionServerSnapshotManager extends RegionServerProcedureManager {
75    private static final Log LOG = LogFactory.getLog(RegionServerSnapshotManager.class);
76  
77    /** Maximum number of snapshot region tasks that can run concurrently */
78    private static final String CONCURENT_SNAPSHOT_TASKS_KEY = "hbase.snapshot.region.concurrentTasks";
79    private static final int DEFAULT_CONCURRENT_SNAPSHOT_TASKS = 3;
80  
81    /** Conf key for number of request threads to start snapshots on regionservers */
82    public static final String SNAPSHOT_REQUEST_THREADS_KEY = "hbase.snapshot.region.pool.threads";
83    /** # of threads for snapshotting regions on the rs. */
84    public static final int SNAPSHOT_REQUEST_THREADS_DEFAULT = 10;
85  
86    /** Conf key for max time to keep threads in snapshot request pool waiting */
87    public static final String SNAPSHOT_TIMEOUT_MILLIS_KEY = "hbase.snapshot.region.timeout";
88    /** Keep threads alive in request pool for max of 60 seconds */
89    public static final long SNAPSHOT_TIMEOUT_MILLIS_DEFAULT = 60000;
90  
91    /** Conf key for millis between checks to see if snapshot completed or if there are errors*/
92    public static final String SNAPSHOT_REQUEST_WAKE_MILLIS_KEY = "hbase.snapshot.region.wakefrequency";
93    /** Default amount of time to check for errors while regions finish snapshotting */
94    private static final long SNAPSHOT_REQUEST_WAKE_MILLIS_DEFAULT = 500;
95  
96    private RegionServerServices rss;
97    private ProcedureMemberRpcs memberRpcs;
98    private ProcedureMember member;
99  
100   /**
101    * Exposed for testing.
102    * @param conf HBase configuration.
103    * @param parent parent running the snapshot handler
104    * @param memberRpc use specified memberRpc instance
105    * @param procMember use specified ProcedureMember
106    */
107    RegionServerSnapshotManager(Configuration conf, HRegionServer parent,
108       ProcedureMemberRpcs memberRpc, ProcedureMember procMember) {
109     this.rss = parent;
110     this.memberRpcs = memberRpc;
111     this.member = procMember;
112   }
113 
114   public RegionServerSnapshotManager() {}
115 
116   /**
117    * Start accepting snapshot requests.
118    */
119   @Override
120   public void start() {
121     LOG.debug("Start Snapshot Manager " + rss.getServerName().toString());
122     this.memberRpcs.start(rss.getServerName().toString(), member);
123   }
124 
125   /**
126    * Close <tt>this</tt> and all running snapshot tasks
127    * @param force forcefully stop all running tasks
128    * @throws IOException
129    */
130   @Override
131   public void stop(boolean force) throws IOException {
132     String mode = force ? "abruptly" : "gracefully";
133     LOG.info("Stopping RegionServerSnapshotManager " + mode + ".");
134 
135     try {
136       this.member.close();
137     } finally {
138       this.memberRpcs.close();
139     }
140   }
141 
142   /**
143    * If in a running state, creates the specified subprocedure for handling an online snapshot.
144    *
145    * Because this gets the local list of regions to snapshot and not the set the master had,
146    * there is a possibility of a race where regions may be missed.  This detected by the master in
147    * the snapshot verification step.
148    *
149    * @param snapshot
150    * @return Subprocedure to submit to the ProcedureMemeber.
151    */
152   public Subprocedure buildSubprocedure(SnapshotDescription snapshot) {
153 
154     // don't run a snapshot if the parent is stop(ping)
155     if (rss.isStopping() || rss.isStopped()) {
156       throw new IllegalStateException("Can't start snapshot on RS: " + rss.getServerName()
157           + ", because stopping/stopped!");
158     }
159 
160     // check to see if this server is hosting any regions for the snapshots
161     // check to see if we have regions for the snapshot
162     List<HRegion> involvedRegions;
163     try {
164       involvedRegions = getRegionsToSnapshot(snapshot);
165     } catch (IOException e1) {
166       throw new IllegalStateException("Failed to figure out if we should handle a snapshot - "
167           + "something has gone awry with the online regions.", e1);
168     }
169 
170     // We need to run the subprocedure even if we have no relevant regions.  The coordinator
171     // expects participation in the procedure and without sending message the snapshot attempt
172     // will hang and fail.
173 
174     LOG.debug("Launching subprocedure for snapshot " + snapshot.getName() + " from table "
175         + snapshot.getTable());
176     ForeignExceptionDispatcher exnDispatcher = new ForeignExceptionDispatcher(snapshot.getName());
177     Configuration conf = rss.getConfiguration();
178     long timeoutMillis = conf.getLong(SNAPSHOT_TIMEOUT_MILLIS_KEY,
179         SNAPSHOT_TIMEOUT_MILLIS_DEFAULT);
180     long wakeMillis = conf.getLong(SNAPSHOT_REQUEST_WAKE_MILLIS_KEY,
181         SNAPSHOT_REQUEST_WAKE_MILLIS_DEFAULT);
182 
183     switch (snapshot.getType()) {
184     case FLUSH:
185       SnapshotSubprocedurePool taskManager =
186         new SnapshotSubprocedurePool(rss.getServerName().toString(), conf);
187       return new FlushSnapshotSubprocedure(member, exnDispatcher, wakeMillis,
188           timeoutMillis, involvedRegions, snapshot, taskManager);
189     case SKIPFLUSH:
190         /*
191          * This is to take an online-snapshot without force a coordinated flush to prevent pause
192          * The snapshot type is defined inside the snapshot description. FlushSnapshotSubprocedure
193          * should be renamed to distributedSnapshotSubprocedure, and the flush() behavior can be
194          * turned on/off based on the flush type.
195          * To minimized the code change, class name is not changed.
196          */
197         SnapshotSubprocedurePool taskManager2 =
198             new SnapshotSubprocedurePool(rss.getServerName().toString(), conf);
199         return new FlushSnapshotSubprocedure(member, exnDispatcher, wakeMillis,
200             timeoutMillis, involvedRegions, snapshot, taskManager2);
201 
202     default:
203       throw new UnsupportedOperationException("Unrecognized snapshot type:" + snapshot.getType());
204     }
205   }
206 
207   /**
208    * Determine if the snapshot should be handled on this server
209    *
210    * NOTE: This is racy -- the master expects a list of regionservers.
211    * This means if a region moves somewhere between the calls we'll miss some regions.
212    * For example, a region move during a snapshot could result in a region to be skipped or done
213    * twice.  This is manageable because the {@link MasterSnapshotVerifier} will double check the
214    * region lists after the online portion of the snapshot completes and will explicitly fail the
215    * snapshot.
216    *
217    * @param snapshot
218    * @return the list of online regions. Empty list is returned if no regions are responsible for
219    *         the given snapshot.
220    * @throws IOException
221    */
222   private List<HRegion> getRegionsToSnapshot(SnapshotDescription snapshot) throws IOException {
223     return rss.getOnlineRegions(TableName.valueOf(snapshot.getTable()));
224   }
225 
226   /**
227    * Build the actual snapshot runner that will do all the 'hard' work
228    */
229   public class SnapshotSubprocedureBuilder implements SubprocedureFactory {
230 
231     @Override
232     public Subprocedure buildSubprocedure(String name, byte[] data) {
233       try {
234         // unwrap the snapshot information
235         SnapshotDescription snapshot = SnapshotDescription.parseFrom(data);
236         return RegionServerSnapshotManager.this.buildSubprocedure(snapshot);
237       } catch (InvalidProtocolBufferException e) {
238         throw new IllegalArgumentException("Could not read snapshot information from request.");
239       }
240     }
241 
242   }
243 
244   /**
245    * We use the SnapshotSubprocedurePool, a class specific thread pool instead of
246    * {@link org.apache.hadoop.hbase.executor.ExecutorService}.
247    *
248    * It uses a {@link java.util.concurrent.ExecutorCompletionService} which provides queuing of
249    * completed tasks which lets us efficiently cancel pending tasks upon the earliest operation
250    * failures.
251    *
252    * HBase's ExecutorService (different from {@link java.util.concurrent.ExecutorService}) isn't
253    * really built for coordinated tasks where multiple threads as part of one larger task.  In
254    * RS's the HBase Executor services are only used for open and close and not other threadpooled
255    * operations such as compactions and replication  sinks.
256    */
257   static class SnapshotSubprocedurePool {
258     private final ExecutorCompletionService<Void> taskPool;
259     private final ThreadPoolExecutor executor;
260     private volatile boolean stopped;
261     private final List<Future<Void>> futures = new ArrayList<Future<Void>>();
262     private final String name;
263 
264     SnapshotSubprocedurePool(String name, Configuration conf) {
265       // configure the executor service
266       long keepAlive = conf.getLong(
267         RegionServerSnapshotManager.SNAPSHOT_TIMEOUT_MILLIS_KEY,
268         RegionServerSnapshotManager.SNAPSHOT_TIMEOUT_MILLIS_DEFAULT);
269       int threads = conf.getInt(CONCURENT_SNAPSHOT_TASKS_KEY, DEFAULT_CONCURRENT_SNAPSHOT_TASKS);
270       this.name = name;
271       executor = new ThreadPoolExecutor(1, threads, keepAlive, TimeUnit.MILLISECONDS,
272           new LinkedBlockingQueue<Runnable>(), new DaemonThreadFactory("rs("
273               + name + ")-snapshot-pool"));
274       taskPool = new ExecutorCompletionService<Void>(executor);
275     }
276 
277     boolean hasTasks() {
278       return futures.size() != 0;
279     }
280 
281     /**
282      * Submit a task to the pool.
283      *
284      * NOTE: all must be submitted before you can safely {@link #waitForOutstandingTasks()}. This
285      * version does not support issuing tasks from multiple concurrent table snapshots requests.
286      */
287     void submitTask(final Callable<Void> task) {
288       Future<Void> f = this.taskPool.submit(task);
289       futures.add(f);
290     }
291 
292     /**
293      * Wait for all of the currently outstanding tasks submitted via {@link #submitTask(Callable)}.
294      * This *must* be called after all tasks are submitted via submitTask.
295      *
296      * @return <tt>true</tt> on success, <tt>false</tt> otherwise
297      * @throws InterruptedException
298      * @throws SnapshotCreationException if the snapshot failed while we were waiting
299      */
300     boolean waitForOutstandingTasks() throws ForeignException, InterruptedException {
301       LOG.debug("Waiting for local region snapshots to finish.");
302 
303       int sz = futures.size();
304       try {
305         // Using the completion service to process the futures that finish first first.
306         for (int i = 0; i < sz; i++) {
307           Future<Void> f = taskPool.take();
308           f.get();
309           if (!futures.remove(f)) {
310             LOG.warn("unexpected future" + f);
311           }
312           LOG.debug("Completed " + (i+1) + "/" + sz +  " local region snapshots.");
313         }
314         LOG.debug("Completed " + sz +  " local region snapshots.");
315         return true;
316       } catch (InterruptedException e) {
317         LOG.warn("Got InterruptedException in SnapshotSubprocedurePool", e);
318         if (!stopped) {
319           Thread.currentThread().interrupt();
320           throw new ForeignException("SnapshotSubprocedurePool", e);
321         }
322         // we are stopped so we can just exit.
323       } catch (ExecutionException e) {
324         if (e.getCause() instanceof ForeignException) {
325           LOG.warn("Rethrowing ForeignException from SnapshotSubprocedurePool", e);
326           throw (ForeignException)e.getCause();
327         }
328         LOG.warn("Got Exception in SnapshotSubprocedurePool", e);
329         throw new ForeignException(name, e.getCause());
330       } finally {
331         cancelTasks();
332       }
333       return false;
334     }
335 
336     /**
337      * This attempts to cancel out all pending and in progress tasks (interruptions issues)
338      * @throws InterruptedException
339      */
340     void cancelTasks() throws InterruptedException {
341       Collection<Future<Void>> tasks = futures;
342       LOG.debug("cancelling " + tasks.size() + " tasks for snapshot " + name);
343       for (Future<Void> f: tasks) {
344         // TODO Ideally we'd interrupt hbase threads when we cancel.  However it seems that there
345         // are places in the HBase code where row/region locks are taken and not released in a
346         // finally block.  Thus we cancel without interrupting.  Cancellations will be slower to
347         // complete but we won't suffer from unreleased locks due to poor code discipline.
348         f.cancel(false);
349       }
350 
351       // evict remaining tasks and futures from taskPool.
352       while (!futures.isEmpty()) {
353         // block to remove cancelled futures;
354         LOG.warn("Removing cancelled elements from taskPool");
355         futures.remove(taskPool.take());
356       }
357       stop();
358     }
359 
360     /**
361      * Abruptly shutdown the thread pool.  Call when exiting a region server.
362      */
363     void stop() {
364       if (this.stopped) return;
365 
366       this.stopped = true;
367       this.executor.shutdownNow();
368     }
369   }
370 
371   /**
372    * Create a default snapshot handler - uses a zookeeper based member controller.
373    * @param rss region server running the handler
374    * @throws KeeperException if the zookeeper cluster cannot be reached
375    */
376   @Override
377   public void initialize(RegionServerServices rss) throws KeeperException {
378     this.rss = rss;
379     ZooKeeperWatcher zkw = rss.getZooKeeper();
380     this.memberRpcs = new ZKProcedureMemberRpcs(zkw,
381         SnapshotManager.ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION);
382 
383     // read in the snapshot request configuration properties
384     Configuration conf = rss.getConfiguration();
385     long keepAlive = conf.getLong(SNAPSHOT_TIMEOUT_MILLIS_KEY, SNAPSHOT_TIMEOUT_MILLIS_DEFAULT);
386     int opThreads = conf.getInt(SNAPSHOT_REQUEST_THREADS_KEY, SNAPSHOT_REQUEST_THREADS_DEFAULT);
387 
388     // create the actual snapshot procedure member
389     ThreadPoolExecutor pool = ProcedureMember.defaultPool(rss.getServerName().toString(),
390       opThreads, keepAlive);
391     this.member = new ProcedureMember(memberRpcs, pool, new SnapshotSubprocedureBuilder());
392   }
393 
394   @Override
395   public String getProcedureSignature() {
396     return SnapshotManager.ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION;
397   }
398 
399 }