001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.snapshot;
019
020import java.io.IOException;
021import java.security.PrivilegedExceptionAction;
022import java.util.Collections;
023
024import org.apache.hadoop.conf.Configuration;
025import org.apache.hadoop.fs.FSDataInputStream;
026import org.apache.hadoop.fs.FSDataOutputStream;
027import org.apache.hadoop.fs.FileSystem;
028import org.apache.hadoop.fs.Path;
029import org.apache.hadoop.fs.permission.FsPermission;
030import org.apache.hadoop.hbase.HConstants;
031import org.apache.hadoop.hbase.TableName;
032import org.apache.hadoop.hbase.client.Admin;
033import org.apache.hadoop.hbase.client.Connection;
034import org.apache.hadoop.hbase.client.ConnectionFactory;
035import org.apache.hadoop.hbase.security.User;
036import org.apache.hadoop.hbase.security.access.AccessControlLists;
037import org.apache.hadoop.hbase.security.access.ShadedAccessControlUtil;
038import org.apache.hadoop.hbase.security.access.UserPermission;
039import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
040import org.apache.hadoop.hbase.util.FSUtils;
041import org.apache.yetus.audience.InterfaceAudience;
042import org.slf4j.Logger;
043import org.slf4j.LoggerFactory;
044
045import org.apache.hbase.thirdparty.com.google.common.collect.ListMultimap;
046import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
047import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos.SnapshotDescription;
048
049/**
050 * Utility class to help manage {@link SnapshotDescription SnapshotDesriptions}.
051 * <p>
052 * Snapshots are laid out on disk like this:
053 *
054 * <pre>
055 * /hbase/.snapshots
056 *          /.tmp                &lt;---- working directory
057 *          /[snapshot name]     &lt;----- completed snapshot
058 * </pre>
059 *
060 * A completed snapshot named 'completed' then looks like (multiple regions, servers, files, etc.
061 * signified by '...' on the same directory depth).
062 *
063 * <pre>
064 * /hbase/.snapshots/completed
065 *                   .snapshotinfo          &lt;--- Description of the snapshot
066 *                   .tableinfo             &lt;--- Copy of the tableinfo
067 *                    /.logs
068 *                        /[server_name]
069 *                            /... [log files]
070 *                         ...
071 *                   /[region name]           &lt;---- All the region's information
072 *                   .regioninfo              &lt;---- Copy of the HRegionInfo
073 *                      /[column family name]
074 *                          /[hfile name]     &lt;--- name of the hfile in the real region
075 *                          ...
076 *                      ...
077 *                    ...
078 * </pre>
079 *
080 * Utility methods in this class are useful for getting the correct locations for different parts of
081 * the snapshot, as well as moving completed snapshots into place (see
082 * {@link #completeSnapshot}, and writing the
083 * {@link SnapshotDescription} to the working snapshot directory.
084 */
085@InterfaceAudience.Private
086public final class SnapshotDescriptionUtils {
087
088  /**
089   * Filter that only accepts completed snapshot directories
090   */
091  public static class CompletedSnaphotDirectoriesFilter extends FSUtils.BlackListDirFilter {
092
093    /**
094     * @param fs
095     */
096    public CompletedSnaphotDirectoriesFilter(FileSystem fs) {
097      super(fs, Collections.singletonList(SNAPSHOT_TMP_DIR_NAME));
098    }
099  }
100
101  private static final Logger LOG = LoggerFactory.getLogger(SnapshotDescriptionUtils.class);
102  /**
103   * Version of the fs layout for a snapshot. Future snapshots may have different file layouts,
104   * which we may need to read in differently.
105   */
106  public static final int SNAPSHOT_LAYOUT_VERSION = SnapshotManifestV2.DESCRIPTOR_VERSION;
107
108  // snapshot directory constants
109  /**
110   * The file contains the snapshot basic information and it is under the directory of a snapshot.
111   */
112  public static final String SNAPSHOTINFO_FILE = ".snapshotinfo";
113
114  /** Temporary directory under the snapshot directory to store in-progress snapshots */
115  public static final String SNAPSHOT_TMP_DIR_NAME = ".tmp";
116
117  /**
118   * The configuration property that determines the filepath of the snapshot
119   * base working directory
120   */
121  public static final String SNAPSHOT_WORKING_DIR = "hbase.snapshot.working.dir";
122
123  // snapshot operation values
124  /** Default value if no start time is specified */
125  public static final long NO_SNAPSHOT_START_TIME_SPECIFIED = 0;
126
127
128  public static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS = "hbase.snapshot.master.timeout.millis";
129
130  /** By default, wait 300 seconds for a snapshot to complete */
131  public static final long DEFAULT_MAX_WAIT_TIME = 60000 * 5 ;
132
133
134  /**
135   * By default, check to see if the snapshot is complete (ms)
136   * @deprecated Use {@link #DEFAULT_MAX_WAIT_TIME} instead.
137   * */
138  @Deprecated
139  public static final int SNAPSHOT_TIMEOUT_MILLIS_DEFAULT = 60000 * 5;
140
141  /**
142   * Conf key for # of ms elapsed before injecting a snapshot timeout error when waiting for
143   * completion.
144   * @deprecated Use {@link #MASTER_SNAPSHOT_TIMEOUT_MILLIS} instead.
145   */
146  @Deprecated
147  public static final String SNAPSHOT_TIMEOUT_MILLIS_KEY = "hbase.snapshot.master.timeoutMillis";
148
149  private SnapshotDescriptionUtils() {
150    // private constructor for utility class
151  }
152
153  /**
154   * @param conf {@link Configuration} from which to check for the timeout
155   * @param type type of snapshot being taken
156   * @param defaultMaxWaitTime Default amount of time to wait, if none is in the configuration
157   * @return the max amount of time the master should wait for a snapshot to complete
158   */
159  public static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type,
160      long defaultMaxWaitTime) {
161    String confKey;
162    switch (type) {
163    case DISABLED:
164    default:
165      confKey = MASTER_SNAPSHOT_TIMEOUT_MILLIS;
166    }
167    return Math.max(conf.getLong(confKey, defaultMaxWaitTime),
168        conf.getLong(SNAPSHOT_TIMEOUT_MILLIS_KEY, defaultMaxWaitTime));
169  }
170
171  /**
172   * Get the snapshot root directory. All the snapshots are kept under this directory, i.e.
173   * ${hbase.rootdir}/.snapshot
174   * @param rootDir hbase root directory
175   * @return the base directory in which all snapshots are kept
176   */
177  public static Path getSnapshotRootDir(final Path rootDir) {
178    return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
179  }
180
181  /**
182   * Get the directory for a specified snapshot. This directory is a sub-directory of snapshot root
183   * directory and all the data files for a snapshot are kept under this directory.
184   * @param snapshot snapshot being taken
185   * @param rootDir hbase root directory
186   * @return the final directory for the completed snapshot
187   */
188  public static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir) {
189    return getCompletedSnapshotDir(snapshot.getName(), rootDir);
190  }
191
192  /**
193   * Get the directory for a completed snapshot. This directory is a sub-directory of snapshot root
194   * directory and all the data files for a snapshot are kept under this directory.
195   * @param snapshotName name of the snapshot being taken
196   * @param rootDir hbase root directory
197   * @return the final directory for the completed snapshot
198   */
199  public static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir) {
200    return getSpecifiedSnapshotDir(getSnapshotsDir(rootDir), snapshotName);
201  }
202
203  /**
204   * Get the general working directory for snapshots - where they are built, where they are
205   * temporarily copied on export, etc.
206   * @param rootDir root directory of the HBase installation
207   * @param conf Configuration of the HBase instance
208   * @return Path to the snapshot tmp directory, relative to the passed root directory
209   */
210  public static Path getWorkingSnapshotDir(final Path rootDir, final Configuration conf) {
211    return new Path(conf.get(SNAPSHOT_WORKING_DIR,
212        getDefaultWorkingSnapshotDir(rootDir).toString()));
213  }
214
215  /**
216   * Get the directory to build a snapshot, before it is finalized
217   * @param snapshot snapshot that will be built
218   * @param rootDir root directory of the hbase installation
219   * @param conf Configuration of the HBase instance
220   * @return {@link Path} where one can build a snapshot
221   */
222  public static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir,
223      Configuration conf) {
224    return getWorkingSnapshotDir(snapshot.getName(), rootDir, conf);
225  }
226
227  /**
228   * Get the directory to build a snapshot, before it is finalized
229   * @param snapshotName name of the snapshot
230   * @param rootDir root directory of the hbase installation
231   * @param conf Configuration of the HBase instance
232   * @return {@link Path} where one can build a snapshot
233   */
234  public static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir,
235      Configuration conf) {
236    return getSpecifiedSnapshotDir(getWorkingSnapshotDir(rootDir, conf), snapshotName);
237  }
238
239  /**
240   * Get the directory within the given filepath to store the snapshot instance
241   * @param snapshotsDir directory to store snapshot directory within
242   * @param snapshotName name of the snapshot to take
243   * @return the final directory for the snapshot in the given filepath
244   */
245  private static final Path getSpecifiedSnapshotDir(final Path snapshotsDir, String snapshotName) {
246    return new Path(snapshotsDir, snapshotName);
247  }
248
249  /**
250   * @param rootDir hbase root directory
251   * @return the directory for all completed snapshots;
252   */
253  public static final Path getSnapshotsDir(Path rootDir) {
254    return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
255  }
256
257  /**
258   * Determines if the given workingDir is a subdirectory of the given "root directory"
259   * @param workingDir a directory to check
260   * @param rootDir root directory of the HBase installation
261   * @return true if the given workingDir is a subdirectory of the given root directory,
262   *   false otherwise
263   */
264  public static boolean isSubDirectoryOf(final Path workingDir, final Path rootDir) {
265    return workingDir.toString().startsWith(rootDir.toString() + Path.SEPARATOR);
266  }
267
268  /**
269   * Determines if the given workingDir is a subdirectory of the default working snapshot directory
270   * @param workingDir a directory to check
271   * @param conf configuration for the HBase cluster
272   * @return true if the given workingDir is a subdirectory of the default working directory for
273   *   snapshots, false otherwise
274   */
275  public static boolean isWithinDefaultWorkingDir(final Path workingDir, Configuration conf) {
276    Path defaultWorkingDir = getDefaultWorkingSnapshotDir(new Path(conf.get(HConstants.HBASE_DIR)));
277    return workingDir.equals(defaultWorkingDir) || isSubDirectoryOf(workingDir, defaultWorkingDir);
278  }
279
280  /**
281   * Get the default working directory for snapshots - where they are built, where they are
282   * temporarily copied on export, etc.
283   * @param rootDir root directory of the HBase installation
284   * @return Path to the default snapshot tmp directory, relative to the passed root directory
285   */
286  private static Path getDefaultWorkingSnapshotDir(final Path rootDir) {
287    return new Path(getSnapshotsDir(rootDir), SNAPSHOT_TMP_DIR_NAME);
288  }
289
290  /**
291   * Convert the passed snapshot description into a 'full' snapshot description based on default
292   * parameters, if none have been supplied. This resolves any 'optional' parameters that aren't
293   * supplied to their default values.
294   * @param snapshot general snapshot descriptor
295   * @param conf Configuration to read configured snapshot defaults if snapshot is not complete
296   * @return a valid snapshot description
297   * @throws IllegalArgumentException if the {@link SnapshotDescription} is not a complete
298   *           {@link SnapshotDescription}.
299   */
300  public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf)
301      throws IllegalArgumentException, IOException {
302    if (!snapshot.hasTable()) {
303      throw new IllegalArgumentException(
304          "Descriptor doesn't apply to a table, so we can't build it.");
305    }
306
307    // set the creation time, if one hasn't been set
308    long time = snapshot.getCreationTime();
309    if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) {
310      time = EnvironmentEdgeManager.currentTime();
311      LOG.debug("Creation time not specified, setting to:" + time + " (current time:"
312          + EnvironmentEdgeManager.currentTime() + ").");
313      SnapshotDescription.Builder builder = snapshot.toBuilder();
314      builder.setCreationTime(time);
315      snapshot = builder.build();
316    }
317
318    // set the acl to snapshot if security feature is enabled.
319    if (isSecurityAvailable(conf)) {
320      snapshot = writeAclToSnapshotDescription(snapshot, conf);
321    }
322    return snapshot;
323  }
324
325  /**
326   * Write the snapshot description into the working directory of a snapshot
327   * @param snapshot description of the snapshot being taken
328   * @param workingDir working directory of the snapshot
329   * @param fs {@link FileSystem} on which the snapshot should be taken
330   * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on
331   *           failure
332   */
333  public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs)
334      throws IOException {
335    FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
336      HConstants.DATA_FILE_UMASK_KEY);
337    Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
338    try {
339      FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true);
340      try {
341        snapshot.writeTo(out);
342      } finally {
343        out.close();
344      }
345    } catch (IOException e) {
346      // if we get an exception, try to remove the snapshot info
347      if (!fs.delete(snapshotInfo, false)) {
348        String msg = "Couldn't delete snapshot info file: " + snapshotInfo;
349        LOG.error(msg);
350        throw new IOException(msg);
351      }
352    }
353  }
354
355  /**
356   * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory
357   * @param fs filesystem where the snapshot was taken
358   * @param snapshotDir directory where the snapshot was stored
359   * @return the stored snapshot description
360   * @throws CorruptedSnapshotException if the
361   * snapshot cannot be read
362   */
363  public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir)
364      throws CorruptedSnapshotException {
365    Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE);
366    try {
367      FSDataInputStream in = null;
368      try {
369        in = fs.open(snapshotInfo);
370        SnapshotDescription desc = SnapshotDescription.parseFrom(in);
371        return desc;
372      } finally {
373        if (in != null) in.close();
374      }
375    } catch (IOException e) {
376      throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e);
377    }
378  }
379
380  /**
381   * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot
382   * as 'complete'.
383   * @param snapshot description of the snapshot being tabken
384   * @param rootdir root directory of the hbase installation
385   * @param workingDir directory where the in progress snapshot was built
386   * @param fs {@link FileSystem} where the snapshot was built
387   * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the
388   * snapshot could not be moved
389   * @throws IOException the filesystem could not be reached
390   */
391  public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
392      FileSystem fs) throws SnapshotCreationException, IOException {
393    Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir);
394    LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to "
395        + finishedDir);
396    if (!fs.rename(workingDir, finishedDir)) {
397      throw new SnapshotCreationException(
398          "Failed to move working directory(" + workingDir + ") to completed directory("
399              + finishedDir + ").", ProtobufUtil.createSnapshotDesc(snapshot));
400    }
401  }
402
403  /**
404   * Check if the user is this table snapshot's owner
405   * @param snapshot the table snapshot description
406   * @param user the user
407   * @return true if the user is the owner of the snapshot,
408   *         false otherwise or the snapshot owner field is not present.
409   */
410  public static boolean isSnapshotOwner(org.apache.hadoop.hbase.client.SnapshotDescription snapshot,
411      User user) {
412    if (user == null) return false;
413    return user.getShortName().equals(snapshot.getOwner());
414  }
415
416  public static boolean isSecurityAvailable(Configuration conf) throws IOException {
417    try (Connection conn = ConnectionFactory.createConnection(conf)) {
418      try (Admin admin = conn.getAdmin()) {
419        return admin.tableExists(AccessControlLists.ACL_TABLE_NAME);
420      }
421    }
422  }
423
424  private static SnapshotDescription writeAclToSnapshotDescription(SnapshotDescription snapshot,
425      Configuration conf) throws IOException {
426    ListMultimap<String, UserPermission> perms =
427        User.runAsLoginUser(new PrivilegedExceptionAction<ListMultimap<String, UserPermission>>() {
428          @Override
429          public ListMultimap<String, UserPermission> run() throws Exception {
430            return AccessControlLists.getTablePermissions(conf,
431              TableName.valueOf(snapshot.getTable()));
432          }
433        });
434    return snapshot.toBuilder()
435        .setUsersAndPermissions(ShadedAccessControlUtil.toUserTablePermissions(perms)).build();
436  }
437}