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.snapshot;
19  
20  import java.io.IOException;
21  import java.util.Collections;
22  
23  import org.apache.commons.logging.Log;
24  import org.apache.commons.logging.LogFactory;
25  import org.apache.hadoop.conf.Configuration;
26  import org.apache.hadoop.fs.FSDataInputStream;
27  import org.apache.hadoop.fs.FSDataOutputStream;
28  import org.apache.hadoop.fs.FileSystem;
29  import org.apache.hadoop.fs.Path;
30  import org.apache.hadoop.fs.permission.FsPermission;
31  import org.apache.hadoop.hbase.HConstants;
32  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
33  import org.apache.hadoop.hbase.snapshot.SnapshotManifestV2;
34  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
35  import org.apache.hadoop.hbase.util.FSUtils;
36  
37  /**
38   * Utility class to help manage {@link SnapshotDescription SnapshotDesriptions}.
39   * <p>
40   * Snapshots are laid out on disk like this:
41   *
42   * <pre>
43   * /hbase/.snapshots
44   *          /.tmp                <---- working directory
45   *          /[snapshot name]     <----- completed snapshot
46   * </pre>
47   *
48   * A completed snapshot named 'completed' then looks like (multiple regions, servers, files, etc.
49   * signified by '...' on the same directory depth).
50   *
51   * <pre>
52   * /hbase/.snapshots/completed
53   *                   .snapshotinfo          <--- Description of the snapshot
54   *                   .tableinfo             <--- Copy of the tableinfo
55   *                    /.logs
56   *                        /[server_name]
57   *                            /... [log files]
58   *                         ...
59   *                   /[region name]           <---- All the region's information
60   *                   .regioninfo              <---- Copy of the HRegionInfo
61   *                      /[column family name]
62   *                          /[hfile name]     <--- name of the hfile in the real region
63   *                          ...
64   *                      ...
65   *                    ...
66   * </pre>
67   *
68   * Utility methods in this class are useful for getting the correct locations for different parts of
69   * the snapshot, as well as moving completed snapshots into place (see
70   * {@link #completeSnapshot}, and writing the
71   * {@link SnapshotDescription} to the working snapshot directory.
72   */
73  public class SnapshotDescriptionUtils {
74  
75    /**
76     * Filter that only accepts completed snapshot directories
77     */
78    public static class CompletedSnaphotDirectoriesFilter extends FSUtils.BlackListDirFilter {
79  
80      /**
81       * @param fs
82       */
83      public CompletedSnaphotDirectoriesFilter(FileSystem fs) {
84        super(fs, Collections.singletonList(SNAPSHOT_TMP_DIR_NAME));
85      }
86    }
87  
88    private static final Log LOG = LogFactory.getLog(SnapshotDescriptionUtils.class);
89    /**
90     * Version of the fs layout for a snapshot. Future snapshots may have different file layouts,
91     * which we may need to read in differently.
92     */
93    public static final int SNAPSHOT_LAYOUT_VERSION = SnapshotManifestV2.DESCRIPTOR_VERSION;
94  
95    // snapshot directory constants
96    /**
97     * The file contains the snapshot basic information and it is under the directory of a snapshot.
98     */
99    public static final String SNAPSHOTINFO_FILE = ".snapshotinfo";
100 
101   /** Temporary directory under the snapshot directory to store in-progress snapshots */
102   public static final String SNAPSHOT_TMP_DIR_NAME = ".tmp";
103   // snapshot operation values
104   /** Default value if no start time is specified */
105   public static final long NO_SNAPSHOT_START_TIME_SPECIFIED = 0;
106 
107   public static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS = "hbase.snapshot.master.timeout.millis";
108 
109   /** By default, wait 60 seconds for a snapshot to complete */
110   public static final long DEFAULT_MAX_WAIT_TIME = 60000;
111 
112   private SnapshotDescriptionUtils() {
113     // private constructor for utility class
114   }
115 
116   /**
117    * @param conf {@link Configuration} from which to check for the timeout
118    * @param type type of snapshot being taken
119    * @param defaultMaxWaitTime Default amount of time to wait, if none is in the configuration
120    * @return the max amount of time the master should wait for a snapshot to complete
121    */
122   public static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type,
123       long defaultMaxWaitTime) {
124     String confKey;
125     switch (type) {
126     case DISABLED:
127     default:
128       confKey = MASTER_SNAPSHOT_TIMEOUT_MILLIS;
129     }
130     return conf.getLong(confKey, defaultMaxWaitTime);
131   }
132 
133   /**
134    * Get the snapshot root directory. All the snapshots are kept under this directory, i.e.
135    * ${hbase.rootdir}/.snapshot
136    * @param rootDir hbase root directory
137    * @return the base directory in which all snapshots are kept
138    */
139   public static Path getSnapshotRootDir(final Path rootDir) {
140     return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
141   }
142 
143   /**
144    * Get the directory for a specified snapshot. This directory is a sub-directory of snapshot root
145    * directory and all the data files for a snapshot are kept under this directory.
146    * @param snapshot snapshot being taken
147    * @param rootDir hbase root directory
148    * @return the final directory for the completed snapshot
149    */
150   public static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir) {
151     return getCompletedSnapshotDir(snapshot.getName(), rootDir);
152   }
153 
154   /**
155    * Get the directory for a completed snapshot. This directory is a sub-directory of snapshot root
156    * directory and all the data files for a snapshot are kept under this directory.
157    * @param snapshotName name of the snapshot being taken
158    * @param rootDir hbase root directory
159    * @return the final directory for the completed snapshot
160    */
161   public static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir) {
162     return getCompletedSnapshotDir(getSnapshotsDir(rootDir), snapshotName);
163   }
164 
165   /**
166    * Get the general working directory for snapshots - where they are built, where they are
167    * temporarily copied on export, etc.
168    * @param rootDir root directory of the HBase installation
169    * @return Path to the snapshot tmp directory, relative to the passed root directory
170    */
171   public static Path getWorkingSnapshotDir(final Path rootDir) {
172     return new Path(getSnapshotsDir(rootDir), SNAPSHOT_TMP_DIR_NAME);
173   }
174 
175   /**
176    * Get the directory to build a snapshot, before it is finalized
177    * @param snapshot snapshot that will be built
178    * @param rootDir root directory of the hbase installation
179    * @return {@link Path} where one can build a snapshot
180    */
181   public static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir) {
182     return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshot.getName());
183   }
184 
185   /**
186    * Get the directory to build a snapshot, before it is finalized
187    * @param snapshotName name of the snapshot
188    * @param rootDir root directory of the hbase installation
189    * @return {@link Path} where one can build a snapshot
190    */
191   public static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir) {
192     return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshotName);
193   }
194 
195   /**
196    * Get the directory to store the snapshot instance
197    * @param snapshotsDir hbase-global directory for storing all snapshots
198    * @param snapshotName name of the snapshot to take
199    * @return the final directory for the completed snapshot
200    */
201   private static final Path getCompletedSnapshotDir(final Path snapshotsDir, String snapshotName) {
202     return new Path(snapshotsDir, snapshotName);
203   }
204 
205   /**
206    * @param rootDir hbase root directory
207    * @return the directory for all completed snapshots;
208    */
209   public static final Path getSnapshotsDir(Path rootDir) {
210     return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
211   }
212 
213   /**
214    * Convert the passed snapshot description into a 'full' snapshot description based on default
215    * parameters, if none have been supplied. This resolves any 'optional' parameters that aren't
216    * supplied to their default values.
217    * @param snapshot general snapshot descriptor
218    * @param conf Configuration to read configured snapshot defaults if snapshot is not complete
219    * @return a valid snapshot description
220    * @throws IllegalArgumentException if the {@link SnapshotDescription} is not a complete
221    *           {@link SnapshotDescription}.
222    */
223   public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf)
224       throws IllegalArgumentException {
225     if (!snapshot.hasTable()) {
226       throw new IllegalArgumentException(
227         "Descriptor doesn't apply to a table, so we can't build it.");
228     }
229 
230     // set the creation time, if one hasn't been set
231     long time = snapshot.getCreationTime();
232     if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) {
233       time = EnvironmentEdgeManager.currentTime();
234       LOG.debug("Creation time not specified, setting to:" + time + " (current time:"
235           + EnvironmentEdgeManager.currentTime() + ").");
236       SnapshotDescription.Builder builder = snapshot.toBuilder();
237       builder.setCreationTime(time);
238       snapshot = builder.build();
239     }
240     return snapshot;
241   }
242 
243   /**
244    * Write the snapshot description into the working directory of a snapshot
245    * @param snapshot description of the snapshot being taken
246    * @param workingDir working directory of the snapshot
247    * @param fs {@link FileSystem} on which the snapshot should be taken
248    * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on
249    *           failure
250    */
251   public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs)
252       throws IOException {
253     FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
254       HConstants.DATA_FILE_UMASK_KEY);
255     Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
256     try {
257       FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true);
258       try {
259         snapshot.writeTo(out);
260       } finally {
261         out.close();
262       }
263     } catch (IOException e) {
264       // if we get an exception, try to remove the snapshot info
265       if (!fs.delete(snapshotInfo, false)) {
266         String msg = "Couldn't delete snapshot info file: " + snapshotInfo;
267         LOG.error(msg);
268         throw new IOException(msg);
269       }
270     }
271   }
272 
273   /**
274    * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory
275    * @param fs filesystem where the snapshot was taken
276    * @param snapshotDir directory where the snapshot was stored
277    * @return the stored snapshot description
278    * @throws CorruptedSnapshotException if the
279    * snapshot cannot be read
280    */
281   public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir)
282       throws CorruptedSnapshotException {
283     Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE);
284     try {
285       FSDataInputStream in = null;
286       try {
287         in = fs.open(snapshotInfo);
288         SnapshotDescription desc = SnapshotDescription.parseFrom(in);
289         return desc;
290       } finally {
291         if (in != null) in.close();
292       }
293     } catch (IOException e) {
294       throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e);
295     }
296   }
297 
298   /**
299    * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot
300    * as 'complete'.
301    * @param snapshot description of the snapshot being tabken
302    * @param rootdir root directory of the hbase installation
303    * @param workingDir directory where the in progress snapshot was built
304    * @param fs {@link FileSystem} where the snapshot was built
305    * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the
306    * snapshot could not be moved
307    * @throws IOException the filesystem could not be reached
308    */
309   public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
310       FileSystem fs) throws SnapshotCreationException, IOException {
311     Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir);
312     LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to "
313         + finishedDir);
314     if (!fs.rename(workingDir, finishedDir)) {
315       throw new SnapshotCreationException("Failed to move working directory(" + workingDir
316           + ") to completed directory(" + finishedDir + ").", snapshot);
317     }
318   }
319 
320 }