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