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   * @throws IOException if we can't get the root dir
275   */
276  public static boolean isWithinDefaultWorkingDir(final Path workingDir, Configuration conf)
277    throws IOException {
278    Path defaultWorkingDir = getDefaultWorkingSnapshotDir(FSUtils.getRootDir(conf));
279    return workingDir.equals(defaultWorkingDir) || isSubDirectoryOf(workingDir, defaultWorkingDir);
280  }
281
282  /**
283   * Get the default working directory for snapshots - where they are built, where they are
284   * temporarily copied on export, etc.
285   * @param rootDir root directory of the HBase installation
286   * @return Path to the default snapshot tmp directory, relative to the passed root directory
287   */
288  private static Path getDefaultWorkingSnapshotDir(final Path rootDir) {
289    return new Path(getSnapshotsDir(rootDir), SNAPSHOT_TMP_DIR_NAME);
290  }
291
292  /**
293   * Convert the passed snapshot description into a 'full' snapshot description based on default
294   * parameters, if none have been supplied. This resolves any 'optional' parameters that aren't
295   * supplied to their default values.
296   * @param snapshot general snapshot descriptor
297   * @param conf Configuration to read configured snapshot defaults if snapshot is not complete
298   * @return a valid snapshot description
299   * @throws IllegalArgumentException if the {@link SnapshotDescription} is not a complete
300   *           {@link SnapshotDescription}.
301   */
302  public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf)
303      throws IllegalArgumentException, IOException {
304    if (!snapshot.hasTable()) {
305      throw new IllegalArgumentException(
306          "Descriptor doesn't apply to a table, so we can't build it.");
307    }
308
309    // set the creation time, if one hasn't been set
310    long time = snapshot.getCreationTime();
311    if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) {
312      time = EnvironmentEdgeManager.currentTime();
313      LOG.debug("Creation time not specified, setting to:" + time + " (current time:"
314          + EnvironmentEdgeManager.currentTime() + ").");
315      SnapshotDescription.Builder builder = snapshot.toBuilder();
316      builder.setCreationTime(time);
317      snapshot = builder.build();
318    }
319
320    // set the acl to snapshot if security feature is enabled.
321    if (isSecurityAvailable(conf)) {
322      snapshot = writeAclToSnapshotDescription(snapshot, conf);
323    }
324    return snapshot;
325  }
326
327  /**
328   * Write the snapshot description into the working directory of a snapshot
329   * @param snapshot description of the snapshot being taken
330   * @param workingDir working directory of the snapshot
331   * @param fs {@link FileSystem} on which the snapshot should be taken
332   * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on
333   *           failure
334   */
335  public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs)
336      throws IOException {
337    FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
338      HConstants.DATA_FILE_UMASK_KEY);
339    Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
340    try {
341      FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true);
342      try {
343        snapshot.writeTo(out);
344      } finally {
345        out.close();
346      }
347    } catch (IOException e) {
348      // if we get an exception, try to remove the snapshot info
349      if (!fs.delete(snapshotInfo, false)) {
350        String msg = "Couldn't delete snapshot info file: " + snapshotInfo;
351        LOG.error(msg);
352        throw new IOException(msg);
353      }
354    }
355  }
356
357  /**
358   * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory
359   * @param fs filesystem where the snapshot was taken
360   * @param snapshotDir directory where the snapshot was stored
361   * @return the stored snapshot description
362   * @throws CorruptedSnapshotException if the
363   * snapshot cannot be read
364   */
365  public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir)
366      throws CorruptedSnapshotException {
367    Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE);
368    try {
369      FSDataInputStream in = null;
370      try {
371        in = fs.open(snapshotInfo);
372        SnapshotDescription desc = SnapshotDescription.parseFrom(in);
373        return desc;
374      } finally {
375        if (in != null) in.close();
376      }
377    } catch (IOException e) {
378      throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e);
379    }
380  }
381
382  /**
383   * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot
384   * as 'complete'.
385   * @param snapshot description of the snapshot being tabken
386   * @param rootdir root directory of the hbase installation
387   * @param workingDir directory where the in progress snapshot was built
388   * @param fs {@link FileSystem} where the snapshot was built
389   * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the
390   * snapshot could not be moved
391   * @throws IOException the filesystem could not be reached
392   */
393  public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
394      FileSystem fs) throws SnapshotCreationException, IOException {
395    Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir);
396    LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to "
397        + finishedDir);
398    if (!fs.rename(workingDir, finishedDir)) {
399      throw new SnapshotCreationException(
400          "Failed to move working directory(" + workingDir + ") to completed directory("
401              + finishedDir + ").", ProtobufUtil.createSnapshotDesc(snapshot));
402    }
403  }
404
405  /**
406   * Check if the user is this table snapshot's owner
407   * @param snapshot the table snapshot description
408   * @param user the user
409   * @return true if the user is the owner of the snapshot,
410   *         false otherwise or the snapshot owner field is not present.
411   */
412  public static boolean isSnapshotOwner(org.apache.hadoop.hbase.client.SnapshotDescription snapshot,
413      User user) {
414    if (user == null) return false;
415    return user.getShortName().equals(snapshot.getOwner());
416  }
417
418  public static boolean isSecurityAvailable(Configuration conf) throws IOException {
419    try (Connection conn = ConnectionFactory.createConnection(conf)) {
420      try (Admin admin = conn.getAdmin()) {
421        return admin.tableExists(AccessControlLists.ACL_TABLE_NAME);
422      }
423    }
424  }
425
426  private static SnapshotDescription writeAclToSnapshotDescription(SnapshotDescription snapshot,
427      Configuration conf) throws IOException {
428    ListMultimap<String, UserPermission> perms =
429        User.runAsLoginUser(new PrivilegedExceptionAction<ListMultimap<String, UserPermission>>() {
430          @Override
431          public ListMultimap<String, UserPermission> run() throws Exception {
432            return AccessControlLists.getTablePermissions(conf,
433              TableName.valueOf(snapshot.getTable()));
434          }
435        });
436    return snapshot.toBuilder()
437        .setUsersAndPermissions(ShadedAccessControlUtil.toUserTablePermissions(perms)).build();
438  }
439}