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