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.TablePermission;
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  /** This tag will be created in in-progess snapshots */
118  public static final String SNAPSHOT_IN_PROGRESS = ".inprogress";
119  // snapshot operation values
120  /** Default value if no start time is specified */
121  public static final long NO_SNAPSHOT_START_TIME_SPECIFIED = 0;
122
123
124  public static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS = "hbase.snapshot.master.timeout.millis";
125
126  /** By default, wait 300 seconds for a snapshot to complete */
127  public static final long DEFAULT_MAX_WAIT_TIME = 60000 * 5 ;
128
129
130  /**
131   * By default, check to see if the snapshot is complete (ms)
132   * @deprecated Use {@link #DEFAULT_MAX_WAIT_TIME} instead.
133   * */
134  @Deprecated
135  public static final int SNAPSHOT_TIMEOUT_MILLIS_DEFAULT = 60000 * 5;
136
137  /**
138   * Conf key for # of ms elapsed before injecting a snapshot timeout error when waiting for
139   * completion.
140   * @deprecated Use {@link #MASTER_SNAPSHOT_TIMEOUT_MILLIS} instead.
141   */
142  @Deprecated
143  public static final String SNAPSHOT_TIMEOUT_MILLIS_KEY = "hbase.snapshot.master.timeoutMillis";
144
145  private SnapshotDescriptionUtils() {
146    // private constructor for utility class
147  }
148
149  /**
150   * @param conf {@link Configuration} from which to check for the timeout
151   * @param type type of snapshot being taken
152   * @param defaultMaxWaitTime Default amount of time to wait, if none is in the configuration
153   * @return the max amount of time the master should wait for a snapshot to complete
154   */
155  public static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type,
156      long defaultMaxWaitTime) {
157    String confKey;
158    switch (type) {
159    case DISABLED:
160    default:
161      confKey = MASTER_SNAPSHOT_TIMEOUT_MILLIS;
162    }
163    return Math.max(conf.getLong(confKey, defaultMaxWaitTime),
164        conf.getLong(SNAPSHOT_TIMEOUT_MILLIS_KEY, defaultMaxWaitTime));
165  }
166
167  /**
168   * Get the snapshot root directory. All the snapshots are kept under this directory, i.e.
169   * ${hbase.rootdir}/.snapshot
170   * @param rootDir hbase root directory
171   * @return the base directory in which all snapshots are kept
172   */
173  public static Path getSnapshotRootDir(final Path rootDir) {
174    return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
175  }
176
177  /**
178   * Get the directory for a specified snapshot. This directory is a sub-directory of snapshot root
179   * directory and all the data files for a snapshot are kept under this directory.
180   * @param snapshot snapshot being taken
181   * @param rootDir hbase root directory
182   * @return the final directory for the completed snapshot
183   */
184  public static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir) {
185    return getCompletedSnapshotDir(snapshot.getName(), rootDir);
186  }
187
188  /**
189   * Get the directory for a completed snapshot. This directory is a sub-directory of snapshot root
190   * directory and all the data files for a snapshot are kept under this directory.
191   * @param snapshotName name of the snapshot being taken
192   * @param rootDir hbase root directory
193   * @return the final directory for the completed snapshot
194   */
195  public static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir) {
196    return getCompletedSnapshotDir(getSnapshotsDir(rootDir), snapshotName);
197  }
198
199  /**
200   * Get the general working directory for snapshots - where they are built, where they are
201   * temporarily copied on export, etc.
202   * @param rootDir root directory of the HBase installation
203   * @return Path to the snapshot tmp directory, relative to the passed root directory
204   */
205  public static Path getWorkingSnapshotDir(final Path rootDir) {
206    return new Path(getSnapshotsDir(rootDir), SNAPSHOT_TMP_DIR_NAME);
207  }
208
209  /**
210   * Get the directory to build a snapshot, before it is finalized
211   * @param snapshot snapshot that will be built
212   * @param rootDir root directory of the hbase installation
213   * @return {@link Path} where one can build a snapshot
214   */
215  public static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir) {
216    return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshot.getName());
217  }
218
219  /**
220   * Get the directory to build a snapshot, before it is finalized
221   * @param snapshotName name of the snapshot
222   * @param rootDir root directory of the hbase installation
223   * @return {@link Path} where one can build a snapshot
224   */
225  public static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir) {
226    return getCompletedSnapshotDir(getWorkingSnapshotDir(rootDir), snapshotName);
227  }
228
229  /**
230   * Get the directory to store the snapshot instance
231   * @param snapshotsDir hbase-global directory for storing all snapshots
232   * @param snapshotName name of the snapshot to take
233   * @return the final directory for the completed snapshot
234   */
235  private static final Path getCompletedSnapshotDir(final Path snapshotsDir, String snapshotName) {
236    return new Path(snapshotsDir, snapshotName);
237  }
238
239  /**
240   * @param rootDir hbase root directory
241   * @return the directory for all completed snapshots;
242   */
243  public static final Path getSnapshotsDir(Path rootDir) {
244    return new Path(rootDir, HConstants.SNAPSHOT_DIR_NAME);
245  }
246
247  /**
248   * Convert the passed snapshot description into a 'full' snapshot description based on default
249   * parameters, if none have been supplied. This resolves any 'optional' parameters that aren't
250   * supplied to their default values.
251   * @param snapshot general snapshot descriptor
252   * @param conf Configuration to read configured snapshot defaults if snapshot is not complete
253   * @return a valid snapshot description
254   * @throws IllegalArgumentException if the {@link SnapshotDescription} is not a complete
255   *           {@link SnapshotDescription}.
256   */
257  public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf)
258      throws IllegalArgumentException, IOException {
259    if (!snapshot.hasTable()) {
260      throw new IllegalArgumentException(
261          "Descriptor doesn't apply to a table, so we can't build it.");
262    }
263
264    // set the creation time, if one hasn't been set
265    long time = snapshot.getCreationTime();
266    if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) {
267      time = EnvironmentEdgeManager.currentTime();
268      LOG.debug("Creation time not specified, setting to:" + time + " (current time:"
269          + EnvironmentEdgeManager.currentTime() + ").");
270      SnapshotDescription.Builder builder = snapshot.toBuilder();
271      builder.setCreationTime(time);
272      snapshot = builder.build();
273    }
274
275    // set the acl to snapshot if security feature is enabled.
276    if (isSecurityAvailable(conf)) {
277      snapshot = writeAclToSnapshotDescription(snapshot, conf);
278    }
279    return snapshot;
280  }
281
282  /**
283   * Write the snapshot description into the working directory of a snapshot
284   * @param snapshot description of the snapshot being taken
285   * @param workingDir working directory of the snapshot
286   * @param fs {@link FileSystem} on which the snapshot should be taken
287   * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on
288   *           failure
289   */
290  public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs)
291      throws IOException {
292    FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
293      HConstants.DATA_FILE_UMASK_KEY);
294    Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
295    try {
296      FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true);
297      try {
298        snapshot.writeTo(out);
299      } finally {
300        out.close();
301      }
302    } catch (IOException e) {
303      // if we get an exception, try to remove the snapshot info
304      if (!fs.delete(snapshotInfo, false)) {
305        String msg = "Couldn't delete snapshot info file: " + snapshotInfo;
306        LOG.error(msg);
307        throw new IOException(msg);
308      }
309    }
310  }
311
312  /**
313   * Create in-progress tag under .tmp of in-progress snapshot
314   * */
315  public static void createInProgressTag(Path workingDir, FileSystem fs) throws IOException {
316    FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
317      HConstants.DATA_FILE_UMASK_KEY);
318    Path snapshot_in_progress = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOT_IN_PROGRESS);
319    FSUtils.create(fs, snapshot_in_progress, perms, true);
320  }
321
322  /**
323   * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory
324   * @param fs filesystem where the snapshot was taken
325   * @param snapshotDir directory where the snapshot was stored
326   * @return the stored snapshot description
327   * @throws CorruptedSnapshotException if the
328   * snapshot cannot be read
329   */
330  public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir)
331      throws CorruptedSnapshotException {
332    Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE);
333    try {
334      FSDataInputStream in = null;
335      try {
336        in = fs.open(snapshotInfo);
337        SnapshotDescription desc = SnapshotDescription.parseFrom(in);
338        return desc;
339      } finally {
340        if (in != null) in.close();
341      }
342    } catch (IOException e) {
343      throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e);
344    }
345  }
346
347  /**
348   * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot
349   * as 'complete'.
350   * @param snapshot description of the snapshot being tabken
351   * @param rootdir root directory of the hbase installation
352   * @param workingDir directory where the in progress snapshot was built
353   * @param fs {@link FileSystem} where the snapshot was built
354   * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the
355   * snapshot could not be moved
356   * @throws IOException the filesystem could not be reached
357   */
358  public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
359      FileSystem fs) throws SnapshotCreationException, IOException {
360    Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir);
361    LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to "
362        + finishedDir);
363    if (!fs.rename(workingDir, finishedDir)) {
364      throw new SnapshotCreationException(
365          "Failed to move working directory(" + workingDir + ") to completed directory("
366              + finishedDir + ").", ProtobufUtil.createSnapshotDesc(snapshot));
367    }
368  }
369
370  /**
371   * Check if the user is this table snapshot's owner
372   * @param snapshot the table snapshot description
373   * @param user the user
374   * @return true if the user is the owner of the snapshot,
375   *         false otherwise or the snapshot owner field is not present.
376   */
377  public static boolean isSnapshotOwner(org.apache.hadoop.hbase.client.SnapshotDescription snapshot,
378      User user) {
379    if (user == null) return false;
380    return user.getShortName().equals(snapshot.getOwner());
381  }
382
383  public static boolean isSecurityAvailable(Configuration conf) throws IOException {
384    try (Connection conn = ConnectionFactory.createConnection(conf)) {
385      try (Admin admin = conn.getAdmin()) {
386        return admin.tableExists(AccessControlLists.ACL_TABLE_NAME);
387      }
388    }
389  }
390
391  private static SnapshotDescription writeAclToSnapshotDescription(SnapshotDescription snapshot,
392      Configuration conf) throws IOException {
393    ListMultimap<String, TablePermission> perms =
394        User.runAsLoginUser(new PrivilegedExceptionAction<ListMultimap<String, TablePermission>>() {
395          @Override
396          public ListMultimap<String, TablePermission> run() throws Exception {
397            return AccessControlLists.getTablePermissions(conf,
398              TableName.valueOf(snapshot.getTable()));
399          }
400        });
401    return snapshot.toBuilder()
402        .setUsersAndPermissions(ShadedAccessControlUtil.toUserTablePermissions(perms)).build();
403  }
404}