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.master.snapshot;
19  
20  import java.io.FileNotFoundException;
21  import java.io.IOException;
22  import java.util.ArrayList;
23  import java.util.Collections;
24  import java.util.HashMap;
25  import java.util.HashSet;
26  import java.util.Iterator;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.Set;
30  import java.util.concurrent.ThreadPoolExecutor;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.fs.FSDataInputStream;
36  import org.apache.hadoop.fs.FileStatus;
37  import org.apache.hadoop.fs.FileSystem;
38  import org.apache.hadoop.fs.Path;
39  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
40  import org.apache.hadoop.hbase.HConstants;
41  import org.apache.hadoop.hbase.HTableDescriptor;
42  import org.apache.hadoop.hbase.MetaTableAccessor;
43  import org.apache.hadoop.hbase.Stoppable;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.classification.InterfaceAudience;
46  import org.apache.hadoop.hbase.classification.InterfaceStability;
47  import org.apache.hadoop.hbase.client.TableState;
48  import org.apache.hadoop.hbase.errorhandling.ForeignException;
49  import org.apache.hadoop.hbase.executor.ExecutorService;
50  import org.apache.hadoop.hbase.ipc.RpcServer;
51  import org.apache.hadoop.hbase.master.AssignmentManager;
52  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
53  import org.apache.hadoop.hbase.master.MasterFileSystem;
54  import org.apache.hadoop.hbase.master.MasterServices;
55  import org.apache.hadoop.hbase.master.MetricsMaster;
56  import org.apache.hadoop.hbase.master.SnapshotSentinel;
57  import org.apache.hadoop.hbase.master.cleaner.HFileCleaner;
58  import org.apache.hadoop.hbase.master.cleaner.HFileLinkCleaner;
59  import org.apache.hadoop.hbase.master.procedure.CloneSnapshotProcedure;
60  import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
61  import org.apache.hadoop.hbase.master.procedure.RestoreSnapshotProcedure;
62  import org.apache.hadoop.hbase.procedure.MasterProcedureManager;
63  import org.apache.hadoop.hbase.procedure.Procedure;
64  import org.apache.hadoop.hbase.procedure.ProcedureCoordinator;
65  import org.apache.hadoop.hbase.procedure.ProcedureCoordinatorRpcs;
66  import org.apache.hadoop.hbase.procedure.ZKProcedureCoordinatorRpcs;
67  import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
68  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
69  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ProcedureDescription;
70  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
71  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription.Type;
72  import org.apache.hadoop.hbase.security.AccessDeniedException;
73  import org.apache.hadoop.hbase.security.User;
74  import org.apache.hadoop.hbase.snapshot.ClientSnapshotDescriptionUtils;
75  import org.apache.hadoop.hbase.snapshot.HBaseSnapshotException;
76  import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
77  import org.apache.hadoop.hbase.snapshot.SnapshotCreationException;
78  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
79  import org.apache.hadoop.hbase.snapshot.SnapshotDoesNotExistException;
80  import org.apache.hadoop.hbase.snapshot.SnapshotExistsException;
81  import org.apache.hadoop.hbase.snapshot.SnapshotManifest;
82  import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
83  import org.apache.hadoop.hbase.snapshot.TablePartiallyOpenException;
84  import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
85  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
86  import org.apache.hadoop.hbase.util.FSUtils;
87  import org.apache.zookeeper.KeeperException;
88  
89  /**
90   * This class manages the procedure of taking and restoring snapshots. There is only one
91   * SnapshotManager for the master.
92   * <p>
93   * The class provides methods for monitoring in-progress snapshot actions.
94   * <p>
95   * Note: Currently there can only be one snapshot being taken at a time over the cluster. This is a
96   * simplification in the current implementation.
97   */
98  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
99  @InterfaceStability.Unstable
100 public class SnapshotManager extends MasterProcedureManager implements Stoppable {
101   private static final Log LOG = LogFactory.getLog(SnapshotManager.class);
102 
103   /** By default, check to see if the snapshot is complete every WAKE MILLIS (ms) */
104   private static final int SNAPSHOT_WAKE_MILLIS_DEFAULT = 500;
105 
106   /**
107    * Wait time before removing a finished sentinel from the in-progress map
108    *
109    * NOTE: This is used as a safety auto cleanup.
110    * The snapshot and restore handlers map entries are removed when a user asks if a snapshot or
111    * restore is completed. This operation is part of the HBaseAdmin snapshot/restore API flow.
112    * In case something fails on the client side and the snapshot/restore state is not reclaimed
113    * after a default timeout, the entry is removed from the in-progress map.
114    * At this point, if the user asks for the snapshot/restore status, the result will be
115    * snapshot done if exists or failed if it doesn't exists.
116    */
117   private static final int SNAPSHOT_SENTINELS_CLEANUP_TIMEOUT = 60 * 1000;
118 
119   /** Enable or disable snapshot support */
120   public static final String HBASE_SNAPSHOT_ENABLED = "hbase.snapshot.enabled";
121 
122   /**
123    * Conf key for # of ms elapsed between checks for snapshot errors while waiting for
124    * completion.
125    */
126   private static final String SNAPSHOT_WAKE_MILLIS_KEY = "hbase.snapshot.master.wakeMillis";
127 
128   /** Name of the operation to use in the controller */
129   public static final String ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION = "online-snapshot";
130 
131   /** Conf key for # of threads used by the SnapshotManager thread pool */
132   private static final String SNAPSHOT_POOL_THREADS_KEY = "hbase.snapshot.master.threads";
133 
134   /** number of current operations running on the master */
135   private static final int SNAPSHOT_POOL_THREADS_DEFAULT = 1;
136 
137   private boolean stopped;
138   private MasterServices master;  // Needed by TableEventHandlers
139   private ProcedureCoordinator coordinator;
140 
141   // Is snapshot feature enabled?
142   private boolean isSnapshotSupported = false;
143 
144   // Snapshot handlers map, with table name as key.
145   // The map is always accessed and modified under the object lock using synchronized.
146   // snapshotTable() will insert an Handler in the table.
147   // isSnapshotDone() will remove the handler requested if the operation is finished.
148   private Map<TableName, SnapshotSentinel> snapshotHandlers =
149       new HashMap<TableName, SnapshotSentinel>();
150 
151   // Restore map, with table name as key, procedure ID as value.
152   // The map is always accessed and modified under the object lock using synchronized.
153   // restoreSnapshot()/cloneSnapshot() will insert a procedure ID in the map.
154   //
155   // TODO: just as the Apache HBase 1.x implementation, this map would not survive master
156   // restart/failover. This is just a stopgap implementation until implementation of taking
157   // snapshot using Procedure-V2.
158   private Map<TableName, Long> restoreTableToProcIdMap = new HashMap<TableName, Long>();
159 
160   private Path rootDir;
161   private ExecutorService executorService;
162 
163   public SnapshotManager() {}
164 
165   /**
166    * Fully specify all necessary components of a snapshot manager. Exposed for testing.
167    * @param master services for the master where the manager is running
168    * @param coordinator procedure coordinator instance.  exposed for testing.
169    * @param pool HBase ExecutorServcie instance, exposed for testing.
170    */
171   public SnapshotManager(final MasterServices master, final MetricsMaster metricsMaster,
172       ProcedureCoordinator coordinator, ExecutorService pool)
173       throws IOException, UnsupportedOperationException {
174     this.master = master;
175 
176     this.rootDir = master.getMasterFileSystem().getRootDir();
177     checkSnapshotSupport(master.getConfiguration(), master.getMasterFileSystem());
178 
179     this.coordinator = coordinator;
180     this.executorService = pool;
181     resetTempDir();
182   }
183 
184   /**
185    * Gets the list of all completed snapshots.
186    * @return list of SnapshotDescriptions
187    * @throws IOException File system exception
188    */
189   public List<SnapshotDescription> getCompletedSnapshots() throws IOException {
190     return getCompletedSnapshots(SnapshotDescriptionUtils.getSnapshotsDir(rootDir));
191   }
192 
193   /**
194    * Gets the list of all completed snapshots.
195    * @param snapshotDir snapshot directory
196    * @return list of SnapshotDescriptions
197    * @throws IOException File system exception
198    */
199   private List<SnapshotDescription> getCompletedSnapshots(Path snapshotDir) throws IOException {
200     List<SnapshotDescription> snapshotDescs = new ArrayList<SnapshotDescription>();
201     // first create the snapshot root path and check to see if it exists
202     FileSystem fs = master.getMasterFileSystem().getFileSystem();
203     if (snapshotDir == null) snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
204 
205     // if there are no snapshots, return an empty list
206     if (!fs.exists(snapshotDir)) {
207       return snapshotDescs;
208     }
209 
210     // ignore all the snapshots in progress
211     FileStatus[] snapshots = fs.listStatus(snapshotDir,
212       new SnapshotDescriptionUtils.CompletedSnaphotDirectoriesFilter(fs));
213     MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
214     // loop through all the completed snapshots
215     for (FileStatus snapshot : snapshots) {
216       Path info = new Path(snapshot.getPath(), SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
217       // if the snapshot is bad
218       if (!fs.exists(info)) {
219         LOG.error("Snapshot information for " + snapshot.getPath() + " doesn't exist");
220         continue;
221       }
222       FSDataInputStream in = null;
223       try {
224         in = fs.open(info);
225         SnapshotDescription desc = SnapshotDescription.parseFrom(in);
226         if (cpHost != null) {
227           try {
228             cpHost.preListSnapshot(desc);
229           } catch (AccessDeniedException e) {
230             LOG.warn("Current user does not have access to " + desc.getName() + " snapshot. "
231                 + "Either you should be owner of this snapshot or admin user.");
232             // Skip this and try for next snapshot
233             continue;
234           }
235         }
236         snapshotDescs.add(desc);
237 
238         // call coproc post hook
239         if (cpHost != null) {
240           cpHost.postListSnapshot(desc);
241         }
242       } catch (IOException e) {
243         LOG.warn("Found a corrupted snapshot " + snapshot.getPath(), e);
244       } finally {
245         if (in != null) {
246           in.close();
247         }
248       }
249     }
250     return snapshotDescs;
251   }
252 
253   /**
254    * Cleans up any snapshots in the snapshot/.tmp directory that were left from failed
255    * snapshot attempts.
256    *
257    * @throws IOException if we can't reach the filesystem
258    */
259   void resetTempDir() throws IOException {
260     // cleanup any existing snapshots.
261     Path tmpdir = SnapshotDescriptionUtils.getWorkingSnapshotDir(rootDir);
262     if (master.getMasterFileSystem().getFileSystem().exists(tmpdir)) {
263       if (!master.getMasterFileSystem().getFileSystem().delete(tmpdir, true)) {
264         LOG.warn("Couldn't delete working snapshot directory: " + tmpdir);
265       }
266     }
267   }
268 
269   /**
270    * Delete the specified snapshot
271    * @param snapshot
272    * @throws SnapshotDoesNotExistException If the specified snapshot does not exist.
273    * @throws IOException For filesystem IOExceptions
274    */
275   public void deleteSnapshot(SnapshotDescription snapshot) throws SnapshotDoesNotExistException, IOException {
276     // check to see if it is completed
277     if (!isSnapshotCompleted(snapshot)) {
278       throw new SnapshotDoesNotExistException(snapshot);
279     }
280 
281     String snapshotName = snapshot.getName();
282     // first create the snapshot description and check to see if it exists
283     FileSystem fs = master.getMasterFileSystem().getFileSystem();
284     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
285     // Get snapshot info from file system. The one passed as parameter is a "fake" snapshotInfo with
286     // just the "name" and it does not contains the "real" snapshot information
287     snapshot = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
288 
289     // call coproc pre hook
290     MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
291     if (cpHost != null) {
292       cpHost.preDeleteSnapshot(snapshot);
293     }
294 
295     LOG.debug("Deleting snapshot: " + snapshotName);
296     // delete the existing snapshot
297     if (!fs.delete(snapshotDir, true)) {
298       throw new HBaseSnapshotException("Failed to delete snapshot directory: " + snapshotDir);
299     }
300 
301     // call coproc post hook
302     if (cpHost != null) {
303       cpHost.postDeleteSnapshot(snapshot);
304     }
305 
306   }
307 
308   /**
309    * Check if the specified snapshot is done
310    *
311    * @param expected
312    * @return true if snapshot is ready to be restored, false if it is still being taken.
313    * @throws IOException IOException if error from HDFS or RPC
314    * @throws UnknownSnapshotException if snapshot is invalid or does not exist.
315    */
316   public boolean isSnapshotDone(SnapshotDescription expected) throws IOException {
317     // check the request to make sure it has a snapshot
318     if (expected == null) {
319       throw new UnknownSnapshotException(
320          "No snapshot name passed in request, can't figure out which snapshot you want to check.");
321     }
322 
323     String ssString = ClientSnapshotDescriptionUtils.toString(expected);
324 
325     // check to see if the sentinel exists,
326     // and if the task is complete removes it from the in-progress snapshots map.
327     SnapshotSentinel handler = removeSentinelIfFinished(this.snapshotHandlers, expected);
328 
329     // stop tracking "abandoned" handlers
330     cleanupSentinels();
331 
332     if (handler == null) {
333       // If there's no handler in the in-progress map, it means one of the following:
334       //   - someone has already requested the snapshot state
335       //   - the requested snapshot was completed long time ago (cleanupSentinels() timeout)
336       //   - the snapshot was never requested
337       // In those cases returns to the user the "done state" if the snapshots exists on disk,
338       // otherwise raise an exception saying that the snapshot is not running and doesn't exist.
339       if (!isSnapshotCompleted(expected)) {
340         throw new UnknownSnapshotException("Snapshot " + ssString
341             + " is not currently running or one of the known completed snapshots.");
342       }
343       // was done, return true;
344       return true;
345     }
346 
347     // pass on any failure we find in the sentinel
348     try {
349       handler.rethrowExceptionIfFailed();
350     } catch (ForeignException e) {
351       // Give some procedure info on an exception.
352       String status;
353       Procedure p = coordinator.getProcedure(expected.getName());
354       if (p != null) {
355         status = p.getStatus();
356       } else {
357         status = expected.getName() + " not found in proclist " + coordinator.getProcedureNames();
358       }
359       throw new HBaseSnapshotException("Snapshot " + ssString +  " had an error.  " + status, e,
360           expected);
361     }
362 
363     // check to see if we are done
364     if (handler.isFinished()) {
365       LOG.debug("Snapshot '" + ssString + "' has completed, notifying client.");
366       return true;
367     } else if (LOG.isDebugEnabled()) {
368       LOG.debug("Snapshoting '" + ssString + "' is still in progress!");
369     }
370     return false;
371   }
372 
373   /**
374    * Check to see if there is a snapshot in progress with the same name or on the same table.
375    * Currently we have a limitation only allowing a single snapshot per table at a time. Also we
376    * don't allow snapshot with the same name.
377    * @param snapshot description of the snapshot being checked.
378    * @return <tt>true</tt> if there is a snapshot in progress with the same name or on the same
379    *         table.
380    */
381   synchronized boolean isTakingSnapshot(final SnapshotDescription snapshot) {
382     TableName snapshotTable = TableName.valueOf(snapshot.getTable());
383     if (isTakingSnapshot(snapshotTable)) {
384       return true;
385     }
386     Iterator<Map.Entry<TableName, SnapshotSentinel>> it = this.snapshotHandlers.entrySet().iterator();
387     while (it.hasNext()) {
388       Map.Entry<TableName, SnapshotSentinel> entry = it.next();
389       SnapshotSentinel sentinel = entry.getValue();
390       if (snapshot.getName().equals(sentinel.getSnapshot().getName()) && !sentinel.isFinished()) {
391         return true;
392       }
393     }
394     return false;
395   }
396 
397   /**
398    * Check to see if the specified table has a snapshot in progress.  Currently we have a
399    * limitation only allowing a single snapshot per table at a time.
400    * @param tableName name of the table being snapshotted.
401    * @return <tt>true</tt> if there is a snapshot in progress on the specified table.
402    */
403   synchronized boolean isTakingSnapshot(final TableName tableName) {
404     SnapshotSentinel handler = this.snapshotHandlers.get(tableName);
405     return handler != null && !handler.isFinished();
406   }
407 
408   /**
409    * Check to make sure that we are OK to run the passed snapshot. Checks to make sure that we
410    * aren't already running a snapshot or restore on the requested table.
411    * @param snapshot description of the snapshot we want to start
412    * @throws HBaseSnapshotException if the filesystem could not be prepared to start the snapshot
413    */
414   private synchronized void prepareToTakeSnapshot(SnapshotDescription snapshot)
415       throws HBaseSnapshotException {
416     FileSystem fs = master.getMasterFileSystem().getFileSystem();
417     Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir);
418     TableName snapshotTable =
419         TableName.valueOf(snapshot.getTable());
420 
421     // make sure we aren't already running a snapshot
422     if (isTakingSnapshot(snapshot)) {
423       SnapshotSentinel handler = this.snapshotHandlers.get(snapshotTable);
424       throw new SnapshotCreationException("Rejected taking "
425           + ClientSnapshotDescriptionUtils.toString(snapshot)
426           + " because we are already running another snapshot "
427           + (handler != null ? ("on the same table " +
428               ClientSnapshotDescriptionUtils.toString(handler.getSnapshot()))
429               : "with the same name"), snapshot);
430     }
431 
432     // make sure we aren't running a restore on the same table
433     if (isRestoringTable(snapshotTable)) {
434       throw new SnapshotCreationException("Rejected taking "
435           + ClientSnapshotDescriptionUtils.toString(snapshot)
436           + " because we are already have a restore in progress on the same snapshot.");
437     }
438 
439     try {
440       // delete the working directory, since we aren't running the snapshot. Likely leftovers
441       // from a failed attempt.
442       fs.delete(workingDir, true);
443 
444       // recreate the working directory for the snapshot
445       if (!fs.mkdirs(workingDir)) {
446         throw new SnapshotCreationException("Couldn't create working directory (" + workingDir
447             + ") for snapshot" , snapshot);
448       }
449     } catch (HBaseSnapshotException e) {
450       throw e;
451     } catch (IOException e) {
452       throw new SnapshotCreationException(
453           "Exception while checking to see if snapshot could be started.", e, snapshot);
454     }
455   }
456 
457   /**
458    * Take a snapshot of a disabled table.
459    * @param snapshot description of the snapshot to take. Modified to be {@link Type#DISABLED}.
460    * @throws HBaseSnapshotException if the snapshot could not be started
461    */
462   private synchronized void snapshotDisabledTable(SnapshotDescription snapshot)
463       throws HBaseSnapshotException {
464     // setup the snapshot
465     prepareToTakeSnapshot(snapshot);
466 
467     // set the snapshot to be a disabled snapshot, since the client doesn't know about that
468     snapshot = snapshot.toBuilder().setType(Type.DISABLED).build();
469 
470     // Take the snapshot of the disabled table
471     DisabledTableSnapshotHandler handler =
472         new DisabledTableSnapshotHandler(snapshot, master);
473     snapshotTable(snapshot, handler);
474   }
475 
476   /**
477    * Take a snapshot of an enabled table.
478    * @param snapshot description of the snapshot to take.
479    * @throws HBaseSnapshotException if the snapshot could not be started
480    */
481   private synchronized void snapshotEnabledTable(SnapshotDescription snapshot)
482       throws HBaseSnapshotException {
483     // setup the snapshot
484     prepareToTakeSnapshot(snapshot);
485 
486     // Take the snapshot of the enabled table
487     EnabledTableSnapshotHandler handler =
488         new EnabledTableSnapshotHandler(snapshot, master, this);
489     snapshotTable(snapshot, handler);
490   }
491 
492   /**
493    * Take a snapshot using the specified handler.
494    * On failure the snapshot temporary working directory is removed.
495    * NOTE: prepareToTakeSnapshot() called before this one takes care of the rejecting the
496    *       snapshot request if the table is busy with another snapshot/restore operation.
497    * @param snapshot the snapshot description
498    * @param handler the snapshot handler
499    */
500   private synchronized void snapshotTable(SnapshotDescription snapshot,
501       final TakeSnapshotHandler handler) throws HBaseSnapshotException {
502     try {
503       handler.prepare();
504       this.executorService.submit(handler);
505       this.snapshotHandlers.put(TableName.valueOf(snapshot.getTable()), handler);
506     } catch (Exception e) {
507       // cleanup the working directory by trying to delete it from the fs.
508       Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, rootDir);
509       try {
510         if (!this.master.getMasterFileSystem().getFileSystem().delete(workingDir, true)) {
511           LOG.error("Couldn't delete working directory (" + workingDir + " for snapshot:" +
512               ClientSnapshotDescriptionUtils.toString(snapshot));
513         }
514       } catch (IOException e1) {
515         LOG.error("Couldn't delete working directory (" + workingDir + " for snapshot:" +
516             ClientSnapshotDescriptionUtils.toString(snapshot));
517       }
518       // fail the snapshot
519       throw new SnapshotCreationException("Could not build snapshot handler", e, snapshot);
520     }
521   }
522 
523   /**
524    * Take a snapshot based on the enabled/disabled state of the table.
525    *
526    * @param snapshot
527    * @throws HBaseSnapshotException when a snapshot specific exception occurs.
528    * @throws IOException when some sort of generic IO exception occurs.
529    */
530   public void takeSnapshot(SnapshotDescription snapshot) throws IOException {
531     // check to see if we already completed the snapshot
532     if (isSnapshotCompleted(snapshot)) {
533       throw new SnapshotExistsException("Snapshot '" + snapshot.getName()
534           + "' already stored on the filesystem.", snapshot);
535     }
536 
537     LOG.debug("No existing snapshot, attempting snapshot...");
538 
539     // stop tracking "abandoned" handlers
540     cleanupSentinels();
541 
542     // check to see if the table exists
543     HTableDescriptor desc = null;
544     try {
545       desc = master.getTableDescriptors().get(
546           TableName.valueOf(snapshot.getTable()));
547     } catch (FileNotFoundException e) {
548       String msg = "Table:" + snapshot.getTable() + " info doesn't exist!";
549       LOG.error(msg);
550       throw new SnapshotCreationException(msg, e, snapshot);
551     } catch (IOException e) {
552       throw new SnapshotCreationException("Error while geting table description for table "
553           + snapshot.getTable(), e, snapshot);
554     }
555     if (desc == null) {
556       throw new SnapshotCreationException("Table '" + snapshot.getTable()
557           + "' doesn't exist, can't take snapshot.", snapshot);
558     }
559     SnapshotDescription.Builder builder = snapshot.toBuilder();
560     // if not specified, set the snapshot format
561     if (!snapshot.hasVersion()) {
562       builder.setVersion(SnapshotDescriptionUtils.SNAPSHOT_LAYOUT_VERSION);
563     }
564     User user = RpcServer.getRequestUser();
565     if (User.isHBaseSecurityEnabled(master.getConfiguration()) && user != null) {
566       builder.setOwner(user.getShortName());
567     }
568     snapshot = builder.build();
569 
570     // call pre coproc hook
571     MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
572     if (cpHost != null) {
573       cpHost.preSnapshot(snapshot, desc);
574     }
575 
576     // if the table is enabled, then have the RS run actually the snapshot work
577     TableName snapshotTable = TableName.valueOf(snapshot.getTable());
578     AssignmentManager assignmentMgr = master.getAssignmentManager();
579     if (assignmentMgr.getTableStateManager().isTableState(snapshotTable,
580         TableState.State.ENABLED)) {
581       LOG.debug("Table enabled, starting distributed snapshot.");
582       snapshotEnabledTable(snapshot);
583       LOG.debug("Started snapshot: " + ClientSnapshotDescriptionUtils.toString(snapshot));
584     }
585     // For disabled table, snapshot is created by the master
586     else if (assignmentMgr.getTableStateManager().isTableState(snapshotTable,
587         TableState.State.DISABLED)) {
588       LOG.debug("Table is disabled, running snapshot entirely on master.");
589       snapshotDisabledTable(snapshot);
590       LOG.debug("Started snapshot: " + ClientSnapshotDescriptionUtils.toString(snapshot));
591     } else {
592       LOG.error("Can't snapshot table '" + snapshot.getTable()
593           + "', isn't open or closed, we don't know what to do!");
594       TablePartiallyOpenException tpoe = new TablePartiallyOpenException(snapshot.getTable()
595           + " isn't fully open.");
596       throw new SnapshotCreationException("Table is not entirely open or closed", tpoe, snapshot);
597     }
598 
599     // call post coproc hook
600     if (cpHost != null) {
601       cpHost.postSnapshot(snapshot, desc);
602     }
603   }
604 
605   /**
606    * Set the handler for the current snapshot
607    * <p>
608    * Exposed for TESTING
609    * @param tableName
610    * @param handler handler the master should use
611    *
612    * TODO get rid of this if possible, repackaging, modify tests.
613    */
614   public synchronized void setSnapshotHandlerForTesting(
615       final TableName tableName,
616       final SnapshotSentinel handler) {
617     if (handler != null) {
618       this.snapshotHandlers.put(tableName, handler);
619     } else {
620       this.snapshotHandlers.remove(tableName);
621     }
622   }
623 
624   /**
625    * @return distributed commit coordinator for all running snapshots
626    */
627   ProcedureCoordinator getCoordinator() {
628     return coordinator;
629   }
630 
631   /**
632    * Check to see if the snapshot is one of the currently completed snapshots
633    * Returns true if the snapshot exists in the "completed snapshots folder".
634    *
635    * @param snapshot expected snapshot to check
636    * @return <tt>true</tt> if the snapshot is stored on the {@link FileSystem}, <tt>false</tt> if is
637    *         not stored
638    * @throws IOException if the filesystem throws an unexpected exception,
639    * @throws IllegalArgumentException if snapshot name is invalid.
640    */
641   private boolean isSnapshotCompleted(SnapshotDescription snapshot) throws IOException {
642     try {
643       final Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshot, rootDir);
644       FileSystem fs = master.getMasterFileSystem().getFileSystem();
645       // check to see if the snapshot already exists
646       return fs.exists(snapshotDir);
647     } catch (IllegalArgumentException iae) {
648       throw new UnknownSnapshotException("Unexpected exception thrown", iae);
649     }
650   }
651 
652   /**
653    * Clone the specified snapshot.
654    * The clone will fail if the destination table has a snapshot or restore in progress.
655    *
656    * @param reqSnapshot Snapshot Descriptor from request
657    * @param tableName table to clone
658    * @param snapshot Snapshot Descriptor
659    * @param snapshotTableDesc Table Descriptor
660    * @param nonceGroup unique value to prevent duplicated RPC
661    * @param nonce unique value to prevent duplicated RPC
662    * @return procId the ID of the clone snapshot procedure
663    * @throws IOException
664    */
665   private long cloneSnapshot(
666       final SnapshotDescription reqSnapshot,
667       final TableName tableName,
668       final SnapshotDescription snapshot,
669       final HTableDescriptor snapshotTableDesc,
670       final long nonceGroup,
671       final long nonce) throws IOException {
672     MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
673     HTableDescriptor htd = new HTableDescriptor(tableName, snapshotTableDesc);
674     if (cpHost != null) {
675       cpHost.preCloneSnapshot(reqSnapshot, htd);
676     }
677     long procId;
678     try {
679       procId = cloneSnapshot(snapshot, htd, nonceGroup, nonce);
680     } catch (IOException e) {
681       LOG.error("Exception occurred while cloning the snapshot " + snapshot.getName()
682         + " as table " + tableName.getNameAsString(), e);
683       throw e;
684     }
685     LOG.info("Clone snapshot=" + snapshot.getName() + " as table=" + tableName);
686 
687     if (cpHost != null) {
688       cpHost.postCloneSnapshot(reqSnapshot, htd);
689     }
690     return procId;
691   }
692 
693   /**
694    * Clone the specified snapshot into a new table.
695    * The operation will fail if the destination table has a snapshot or restore in progress.
696    *
697    * @param snapshot Snapshot Descriptor
698    * @param hTableDescriptor Table Descriptor of the table to create
699    * @param nonceGroup unique value to prevent duplicated RPC
700    * @param nonce unique value to prevent duplicated RPC
701    * @return procId the ID of the clone snapshot procedure
702    */
703   synchronized long cloneSnapshot(
704       final SnapshotDescription snapshot,
705       final HTableDescriptor hTableDescriptor,
706       final long nonceGroup,
707       final long nonce) throws HBaseSnapshotException {
708     TableName tableName = hTableDescriptor.getTableName();
709 
710     // make sure we aren't running a snapshot on the same table
711     if (isTakingSnapshot(tableName)) {
712       throw new RestoreSnapshotException("Snapshot in progress on the restore table=" + tableName);
713     }
714 
715     // make sure we aren't running a restore on the same table
716     if (isRestoringTable(tableName)) {
717       throw new RestoreSnapshotException("Restore already in progress on the table=" + tableName);
718     }
719 
720     try {
721       long procId = master.getMasterProcedureExecutor().submitProcedure(
722         new CloneSnapshotProcedure(
723           master.getMasterProcedureExecutor().getEnvironment(), hTableDescriptor, snapshot),
724         nonceGroup,
725         nonce);
726       this.restoreTableToProcIdMap.put(tableName, procId);
727       return procId;
728     } catch (Exception e) {
729       String msg = "Couldn't clone the snapshot="
730         + ClientSnapshotDescriptionUtils.toString(snapshot) + " on table=" + tableName;
731       LOG.error(msg, e);
732       throw new RestoreSnapshotException(msg, e);
733     }
734   }
735 
736   /**
737    * Restore or Clone the specified snapshot
738    * @param reqSnapshot
739    * @param nonceGroup unique value to prevent duplicated RPC
740    * @param nonce unique value to prevent duplicated RPC
741    * @throws IOException
742    */
743   public long restoreOrCloneSnapshot(
744       SnapshotDescription reqSnapshot,
745       final long nonceGroup,
746       final long nonce) throws IOException {
747     FileSystem fs = master.getMasterFileSystem().getFileSystem();
748     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(reqSnapshot, rootDir);
749 
750     // check if the snapshot exists
751     if (!fs.exists(snapshotDir)) {
752       LOG.error("A Snapshot named '" + reqSnapshot.getName() + "' does not exist.");
753       throw new SnapshotDoesNotExistException(reqSnapshot);
754     }
755 
756     // Get snapshot info from file system. The reqSnapshot is a "fake" snapshotInfo with
757     // just the snapshot "name" and table name to restore. It does not contains the "real" snapshot
758     // information.
759     SnapshotDescription snapshot = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
760     SnapshotManifest manifest = SnapshotManifest.open(master.getConfiguration(), fs,
761         snapshotDir, snapshot);
762     HTableDescriptor snapshotTableDesc = manifest.getTableDescriptor();
763     TableName tableName = TableName.valueOf(reqSnapshot.getTable());
764 
765     // stop tracking "abandoned" handlers
766     cleanupSentinels();
767 
768     // Verify snapshot validity
769     SnapshotReferenceUtil.verifySnapshot(master.getConfiguration(), fs, manifest);
770 
771     // Execute the restore/clone operation
772     long procId;
773     if (MetaTableAccessor.tableExists(master.getConnection(), tableName)) {
774       procId = restoreSnapshot(
775         reqSnapshot, tableName, snapshot, snapshotTableDesc, nonceGroup, nonce);
776     } else {
777       procId = cloneSnapshot(
778         reqSnapshot, tableName, snapshot, snapshotTableDesc, nonceGroup, nonce);
779     }
780     return procId;
781   }
782 
783   /**
784    * Restore the specified snapshot.
785    * The restore will fail if the destination table has a snapshot or restore in progress.
786    *
787    * @param reqSnapshot Snapshot Descriptor from request
788    * @param tableName table to restore
789    * @param snapshot Snapshot Descriptor
790    * @param snapshotTableDesc Table Descriptor
791    * @param nonceGroup unique value to prevent duplicated RPC
792    * @param nonce unique value to prevent duplicated RPC
793    * @return procId the ID of the restore snapshot procedure
794    * @throws IOException
795    */
796   private long restoreSnapshot(
797       final SnapshotDescription reqSnapshot,
798       final TableName tableName,
799       final SnapshotDescription snapshot,
800       final HTableDescriptor snapshotTableDesc,
801       final long nonceGroup,
802       final long nonce) throws IOException {
803     MasterCoprocessorHost cpHost = master.getMasterCoprocessorHost();
804 
805     if (master.getTableStateManager().isTableState(
806       TableName.valueOf(snapshot.getTable()), TableState.State.ENABLED)) {
807       throw new UnsupportedOperationException("Table '" +
808         TableName.valueOf(snapshot.getTable()) + "' must be disabled in order to " +
809         "perform a restore operation.");
810     }
811 
812     // call Coprocessor pre hook
813     if (cpHost != null) {
814       cpHost.preRestoreSnapshot(reqSnapshot, snapshotTableDesc);
815     }
816 
817     long procId;
818     try {
819       procId = restoreSnapshot(snapshot, snapshotTableDesc, nonceGroup, nonce);
820     } catch (IOException e) {
821       LOG.error("Exception occurred while restoring the snapshot " + snapshot.getName()
822         + " as table " + tableName.getNameAsString(), e);
823       throw e;
824     }
825     LOG.info("Restore snapshot=" + snapshot.getName() + " as table=" + tableName);
826 
827     if (cpHost != null) {
828       cpHost.postRestoreSnapshot(reqSnapshot, snapshotTableDesc);
829     }
830 
831     return procId;
832   }
833 
834   /**
835    * Restore the specified snapshot.
836    * The restore will fail if the destination table has a snapshot or restore in progress.
837    *
838    * @param snapshot Snapshot Descriptor
839    * @param hTableDescriptor Table Descriptor
840    * @param nonceGroup unique value to prevent duplicated RPC
841    * @param nonce unique value to prevent duplicated RPC
842    * @return procId the ID of the restore snapshot procedure
843    */
844   private synchronized long restoreSnapshot(
845       final SnapshotDescription snapshot,
846       final HTableDescriptor hTableDescriptor,
847       final long nonceGroup,
848       final long nonce) throws HBaseSnapshotException {
849     TableName tableName = hTableDescriptor.getTableName();
850 
851     // make sure we aren't running a snapshot on the same table
852     if (isTakingSnapshot(tableName)) {
853       throw new RestoreSnapshotException("Snapshot in progress on the restore table=" + tableName);
854     }
855 
856     // make sure we aren't running a restore on the same table
857     if (isRestoringTable(tableName)) {
858       throw new RestoreSnapshotException("Restore already in progress on the table=" + tableName);
859     }
860 
861     try {
862       long procId = master.getMasterProcedureExecutor().submitProcedure(
863         new RestoreSnapshotProcedure(
864           master.getMasterProcedureExecutor().getEnvironment(), hTableDescriptor, snapshot),
865         nonceGroup,
866         nonce);
867       this.restoreTableToProcIdMap.put(tableName, procId);
868       return procId;
869     } catch (Exception e) {
870       String msg = "Couldn't restore the snapshot=" + ClientSnapshotDescriptionUtils.toString(
871           snapshot)  +
872           " on table=" + tableName;
873       LOG.error(msg, e);
874       throw new RestoreSnapshotException(msg, e);
875     }
876   }
877 
878   /**
879    * Verify if the restore of the specified table is in progress.
880    *
881    * @param tableName table under restore
882    * @return <tt>true</tt> if there is a restore in progress of the specified table.
883    */
884   private synchronized boolean isRestoringTable(final TableName tableName) {
885     Long procId = this.restoreTableToProcIdMap.get(tableName);
886     if (procId == null) {
887       return false;
888     }
889     ProcedureExecutor<MasterProcedureEnv> procExec = master.getMasterProcedureExecutor();
890     if (procExec.isRunning() && !procExec.isFinished(procId)) {
891       return true;
892     } else {
893       this.restoreTableToProcIdMap.remove(tableName);
894       return false;
895     }
896 
897   }
898 
899   /**
900    * Return the handler if it is currently live and has the same snapshot target name.
901    * The handler is removed from the sentinels map if completed.
902    * @param sentinels live handlers
903    * @param snapshot snapshot description
904    * @return null if doesn't match, else a live handler.
905    */
906   private synchronized SnapshotSentinel removeSentinelIfFinished(
907       final Map<TableName, SnapshotSentinel> sentinels,
908       final SnapshotDescription snapshot) {
909     if (!snapshot.hasTable()) {
910       return null;
911     }
912 
913     TableName snapshotTable = TableName.valueOf(snapshot.getTable());
914     SnapshotSentinel h = sentinels.get(snapshotTable);
915     if (h == null) {
916       return null;
917     }
918 
919     if (!h.getSnapshot().getName().equals(snapshot.getName())) {
920       // specified snapshot is to the one currently running
921       return null;
922     }
923 
924     // Remove from the "in-progress" list once completed
925     if (h.isFinished()) {
926       sentinels.remove(snapshotTable);
927     }
928 
929     return h;
930   }
931 
932   /**
933    * Removes "abandoned" snapshot/restore requests.
934    * As part of the HBaseAdmin snapshot/restore API the operation status is checked until completed,
935    * and the in-progress maps are cleaned up when the status of a completed task is requested.
936    * To avoid having sentinels staying around for long time if something client side is failed,
937    * each operation tries to clean up the in-progress maps sentinels finished from a long time.
938    */
939   private void cleanupSentinels() {
940     cleanupSentinels(this.snapshotHandlers);
941     cleanupCompletedRestoreInMap();
942   }
943 
944   /**
945    * Remove the sentinels that are marked as finished and the completion time
946    * has exceeded the removal timeout.
947    * @param sentinels map of sentinels to clean
948    */
949   private synchronized void cleanupSentinels(final Map<TableName, SnapshotSentinel> sentinels) {
950     long currentTime = EnvironmentEdgeManager.currentTime();
951     Iterator<Map.Entry<TableName, SnapshotSentinel>> it =
952         sentinels.entrySet().iterator();
953     while (it.hasNext()) {
954       Map.Entry<TableName, SnapshotSentinel> entry = it.next();
955       SnapshotSentinel sentinel = entry.getValue();
956       if (sentinel.isFinished() &&
957           (currentTime - sentinel.getCompletionTimestamp()) > SNAPSHOT_SENTINELS_CLEANUP_TIMEOUT)
958       {
959         it.remove();
960       }
961     }
962   }
963 
964   /**
965    * Remove the procedures that are marked as finished
966    */
967   private synchronized void cleanupCompletedRestoreInMap() {
968     ProcedureExecutor<MasterProcedureEnv> procExec = master.getMasterProcedureExecutor();
969     Iterator<Map.Entry<TableName, Long>> it = restoreTableToProcIdMap.entrySet().iterator();
970     while (it.hasNext()) {
971       Map.Entry<TableName, Long> entry = it.next();
972       Long procId = entry.getValue();
973       if (procExec.isRunning() && procExec.isFinished(procId)) {
974         it.remove();
975       }
976     }
977   }
978 
979   //
980   // Implementing Stoppable interface
981   //
982 
983   @Override
984   public void stop(String why) {
985     // short circuit
986     if (this.stopped) return;
987     // make sure we get stop
988     this.stopped = true;
989     // pass the stop onto take snapshot handlers
990     for (SnapshotSentinel snapshotHandler: this.snapshotHandlers.values()) {
991       snapshotHandler.cancel(why);
992     }
993 
994     try {
995       if (coordinator != null) {
996         coordinator.close();
997       }
998     } catch (IOException e) {
999       LOG.error("stop ProcedureCoordinator error", e);
1000     }
1001   }
1002 
1003   @Override
1004   public boolean isStopped() {
1005     return this.stopped;
1006   }
1007 
1008   /**
1009    * Throws an exception if snapshot operations (take a snapshot, restore, clone) are not supported.
1010    * Called at the beginning of snapshot() and restoreSnapshot() methods.
1011    * @throws UnsupportedOperationException if snapshot are not supported
1012    */
1013   public void checkSnapshotSupport() throws UnsupportedOperationException {
1014     if (!this.isSnapshotSupported) {
1015       throw new UnsupportedOperationException(
1016         "To use snapshots, You must add to the hbase-site.xml of the HBase Master: '" +
1017           HBASE_SNAPSHOT_ENABLED + "' property with value 'true'.");
1018     }
1019   }
1020 
1021   /**
1022    * Called at startup, to verify if snapshot operation is supported, and to avoid
1023    * starting the master if there're snapshots present but the cleaners needed are missing.
1024    * Otherwise we can end up with snapshot data loss.
1025    * @param conf The {@link Configuration} object to use
1026    * @param mfs The MasterFileSystem to use
1027    * @throws IOException in case of file-system operation failure
1028    * @throws UnsupportedOperationException in case cleaners are missing and
1029    *         there're snapshot in the system
1030    */
1031   private void checkSnapshotSupport(final Configuration conf, final MasterFileSystem mfs)
1032       throws IOException, UnsupportedOperationException {
1033     // Verify if snapshot is disabled by the user
1034     String enabled = conf.get(HBASE_SNAPSHOT_ENABLED);
1035     boolean snapshotEnabled = conf.getBoolean(HBASE_SNAPSHOT_ENABLED, false);
1036     boolean userDisabled = (enabled != null && enabled.trim().length() > 0 && !snapshotEnabled);
1037 
1038     // Extract cleaners from conf
1039     Set<String> hfileCleaners = new HashSet<String>();
1040     String[] cleaners = conf.getStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS);
1041     if (cleaners != null) Collections.addAll(hfileCleaners, cleaners);
1042 
1043     Set<String> logCleaners = new HashSet<String>();
1044     cleaners = conf.getStrings(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS);
1045     if (cleaners != null) Collections.addAll(logCleaners, cleaners);
1046 
1047     // check if an older version of snapshot directory was present
1048     Path oldSnapshotDir = new Path(mfs.getRootDir(), HConstants.OLD_SNAPSHOT_DIR_NAME);
1049     FileSystem fs = mfs.getFileSystem();
1050     List<SnapshotDescription> ss = getCompletedSnapshots(new Path(rootDir, oldSnapshotDir));
1051     if (ss != null && !ss.isEmpty()) {
1052       LOG.error("Snapshots from an earlier release were found under: " + oldSnapshotDir);
1053       LOG.error("Please rename the directory as " + HConstants.SNAPSHOT_DIR_NAME);
1054     }
1055 
1056     // If the user has enabled the snapshot, we force the cleaners to be present
1057     // otherwise we still need to check if cleaners are enabled or not and verify
1058     // that there're no snapshot in the .snapshot folder.
1059     if (snapshotEnabled) {
1060       // Inject snapshot cleaners, if snapshot.enable is true
1061       hfileCleaners.add(SnapshotHFileCleaner.class.getName());
1062       hfileCleaners.add(HFileLinkCleaner.class.getName());
1063 
1064       // Set cleaners conf
1065       conf.setStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS,
1066         hfileCleaners.toArray(new String[hfileCleaners.size()]));
1067       conf.setStrings(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS,
1068         logCleaners.toArray(new String[logCleaners.size()]));
1069     } else {
1070       // Verify if cleaners are present
1071       snapshotEnabled =
1072         hfileCleaners.contains(SnapshotHFileCleaner.class.getName()) &&
1073         hfileCleaners.contains(HFileLinkCleaner.class.getName());
1074 
1075       // Warn if the cleaners are enabled but the snapshot.enabled property is false/not set.
1076       if (snapshotEnabled) {
1077         LOG.warn("Snapshot log and hfile cleaners are present in the configuration, " +
1078           "but the '" + HBASE_SNAPSHOT_ENABLED + "' property " +
1079           (userDisabled ? "is set to 'false'." : "is not set."));
1080       }
1081     }
1082 
1083     // Mark snapshot feature as enabled if cleaners are present and user has not disabled it.
1084     this.isSnapshotSupported = snapshotEnabled && !userDisabled;
1085 
1086     // If cleaners are not enabled, verify that there're no snapshot in the .snapshot folder
1087     // otherwise we end up with snapshot data loss.
1088     if (!snapshotEnabled) {
1089       LOG.info("Snapshot feature is not enabled, missing log and hfile cleaners.");
1090       Path snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(mfs.getRootDir());
1091       if (fs.exists(snapshotDir)) {
1092         FileStatus[] snapshots = FSUtils.listStatus(fs, snapshotDir,
1093           new SnapshotDescriptionUtils.CompletedSnaphotDirectoriesFilter(fs));
1094         if (snapshots != null) {
1095           LOG.error("Snapshots are present, but cleaners are not enabled.");
1096           checkSnapshotSupport();
1097         }
1098       }
1099     }
1100   }
1101 
1102   @Override
1103   public void initialize(MasterServices master, MetricsMaster metricsMaster) throws KeeperException,
1104       IOException, UnsupportedOperationException {
1105     this.master = master;
1106 
1107     this.rootDir = master.getMasterFileSystem().getRootDir();
1108     checkSnapshotSupport(master.getConfiguration(), master.getMasterFileSystem());
1109 
1110     // get the configuration for the coordinator
1111     Configuration conf = master.getConfiguration();
1112     long wakeFrequency = conf.getInt(SNAPSHOT_WAKE_MILLIS_KEY, SNAPSHOT_WAKE_MILLIS_DEFAULT);
1113     long timeoutMillis = Math.max(conf.getLong(SnapshotDescriptionUtils.SNAPSHOT_TIMEOUT_MILLIS_KEY,
1114                     SnapshotDescriptionUtils.SNAPSHOT_TIMEOUT_MILLIS_DEFAULT),
1115             conf.getLong(SnapshotDescriptionUtils.MASTER_SNAPSHOT_TIMEOUT_MILLIS,
1116                     SnapshotDescriptionUtils.DEFAULT_MAX_WAIT_TIME));
1117     int opThreads = conf.getInt(SNAPSHOT_POOL_THREADS_KEY, SNAPSHOT_POOL_THREADS_DEFAULT);
1118 
1119     // setup the default procedure coordinator
1120     String name = master.getServerName().toString();
1121     ThreadPoolExecutor tpool = ProcedureCoordinator.defaultPool(name, opThreads);
1122     ProcedureCoordinatorRpcs comms = new ZKProcedureCoordinatorRpcs(
1123         master.getZooKeeper(), SnapshotManager.ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION, name);
1124 
1125     this.coordinator = new ProcedureCoordinator(comms, tpool, timeoutMillis, wakeFrequency);
1126     this.executorService = master.getExecutorService();
1127     resetTempDir();
1128   }
1129 
1130   @Override
1131   public String getProcedureSignature() {
1132     return ONLINE_SNAPSHOT_CONTROLLER_DESCRIPTION;
1133   }
1134 
1135   @Override
1136   public void execProcedure(ProcedureDescription desc) throws IOException {
1137     takeSnapshot(toSnapshotDescription(desc));
1138   }
1139 
1140   @Override
1141   public boolean isProcedureDone(ProcedureDescription desc) throws IOException {
1142     return isSnapshotDone(toSnapshotDescription(desc));
1143   }
1144 
1145   private SnapshotDescription toSnapshotDescription(ProcedureDescription desc)
1146       throws IOException {
1147     SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
1148     if (!desc.hasInstance()) {
1149       throw new IOException("Snapshot name is not defined: " + desc.toString());
1150     }
1151     String snapshotName = desc.getInstance();
1152     List<NameStringPair> props = desc.getConfigurationList();
1153     String table = null;
1154     for (NameStringPair prop : props) {
1155       if ("table".equalsIgnoreCase(prop.getName())) {
1156         table = prop.getValue();
1157       }
1158     }
1159     if (table == null) {
1160       throw new IOException("Snapshot table is not defined: " + desc.toString());
1161     }
1162     TableName tableName = TableName.valueOf(table);
1163     builder.setTable(tableName.getNameAsString());
1164     builder.setName(snapshotName);
1165     builder.setType(SnapshotDescription.Type.FLUSH);
1166     return builder.build();
1167   }
1168 }