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