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