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