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  // 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    return snapshot;
278  }
279
280  /**
281   * Write the snapshot description into the working directory of a snapshot
282   * @param snapshot description of the snapshot being taken
283   * @param workingDir working directory of the snapshot
284   * @param fs {@link FileSystem} on which the snapshot should be taken
285   * @throws IOException if we can't reach the filesystem and the file cannot be cleaned up on
286   *           failure
287   */
288  public static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs)
289      throws IOException {
290    FsPermission perms = FSUtils.getFilePermissions(fs, fs.getConf(),
291      HConstants.DATA_FILE_UMASK_KEY);
292    Path snapshotInfo = new Path(workingDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
293    try {
294      FSDataOutputStream out = FSUtils.create(fs, snapshotInfo, perms, true);
295      try {
296        snapshot.writeTo(out);
297      } finally {
298        out.close();
299      }
300    } catch (IOException e) {
301      // if we get an exception, try to remove the snapshot info
302      if (!fs.delete(snapshotInfo, false)) {
303        String msg = "Couldn't delete snapshot info file: " + snapshotInfo;
304        LOG.error(msg);
305        throw new IOException(msg);
306      }
307    }
308  }
309
310  /**
311   * Read in the {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} stored for the snapshot in the passed directory
312   * @param fs filesystem where the snapshot was taken
313   * @param snapshotDir directory where the snapshot was stored
314   * @return the stored snapshot description
315   * @throws CorruptedSnapshotException if the
316   * snapshot cannot be read
317   */
318  public static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir)
319      throws CorruptedSnapshotException {
320    Path snapshotInfo = new Path(snapshotDir, SNAPSHOTINFO_FILE);
321    try {
322      FSDataInputStream in = null;
323      try {
324        in = fs.open(snapshotInfo);
325        SnapshotDescription desc = SnapshotDescription.parseFrom(in);
326        return desc;
327      } finally {
328        if (in != null) in.close();
329      }
330    } catch (IOException e) {
331      throw new CorruptedSnapshotException("Couldn't read snapshot info from:" + snapshotInfo, e);
332    }
333  }
334
335  /**
336   * Move the finished snapshot to its final, publicly visible directory - this marks the snapshot
337   * as 'complete'.
338   * @param snapshot description of the snapshot being tabken
339   * @param rootdir root directory of the hbase installation
340   * @param workingDir directory where the in progress snapshot was built
341   * @param fs {@link FileSystem} where the snapshot was built
342   * @throws org.apache.hadoop.hbase.snapshot.SnapshotCreationException if the
343   * snapshot could not be moved
344   * @throws IOException the filesystem could not be reached
345   */
346  public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
347      FileSystem fs) throws SnapshotCreationException, IOException {
348    Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir);
349    LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to "
350        + finishedDir);
351    if (!fs.rename(workingDir, finishedDir)) {
352      throw new SnapshotCreationException(
353          "Failed to move working directory(" + workingDir + ") to completed directory("
354              + finishedDir + ").", ProtobufUtil.createSnapshotDesc(snapshot));
355    }
356  }
357
358  /**
359   * Check if the user is this table snapshot's owner
360   * @param snapshot the table snapshot description
361   * @param user the user
362   * @return true if the user is the owner of the snapshot,
363   *         false otherwise or the snapshot owner field is not present.
364   */
365  public static boolean isSnapshotOwner(org.apache.hadoop.hbase.client.SnapshotDescription snapshot,
366      User user) {
367    if (user == null) return false;
368    return user.getShortName().equals(snapshot.getOwner());
369  }
370
371  public static boolean isSecurityAvailable(Configuration conf) throws IOException {
372    try (Connection conn = ConnectionFactory.createConnection(conf)) {
373      try (Admin admin = conn.getAdmin()) {
374        return admin.tableExists(AccessControlLists.ACL_TABLE_NAME);
375      }
376    }
377  }
378
379  private static SnapshotDescription writeAclToSnapshotDescription(SnapshotDescription snapshot,
380      Configuration conf) throws IOException {
381    ListMultimap<String, TablePermission> perms =
382        User.runAsLoginUser(new PrivilegedExceptionAction<ListMultimap<String, TablePermission>>() {
383          @Override
384          public ListMultimap<String, TablePermission> run() throws Exception {
385            return AccessControlLists.getTablePermissions(conf,
386              TableName.valueOf(snapshot.getTable()));
387          }
388        });
389    return snapshot.toBuilder()
390        .setUsersAndPermissions(ShadedAccessControlUtil.toUserTablePermissions(perms)).build();
391  }
392}