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.backup;
019
020import static org.apache.hadoop.hbase.HConstants.HBASE_TEMP_DIRECTORY;
021import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.BACKUPID_PREFIX;
022
023import com.google.errorprone.annotations.RestrictedApi;
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.Comparator;
027import java.util.List;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.fs.FileSystem;
030import org.apache.hadoop.fs.LocatedFileStatus;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.fs.RemoteIterator;
033import org.apache.hadoop.hbase.TableName;
034import org.apache.hadoop.hbase.backup.impl.BackupManifest;
035import org.apache.hadoop.hbase.backup.impl.BackupManifest.BackupImage;
036import org.apache.yetus.audience.InterfaceAudience;
037import org.slf4j.Logger;
038import org.slf4j.LoggerFactory;
039
040import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
041
042/**
043 * View to an on-disk Backup Image FileSytem Provides the set of methods necessary to interact with
044 * the on-disk Backup Image data.
045 */
046@InterfaceAudience.Private
047public final class HBackupFileSystem {
048  public static final Logger LOG = LoggerFactory.getLogger(HBackupFileSystem.class);
049  public static final String BACKUP_COMPLETE_FILE_NAME = ".backup.complete";
050
051  /**
052   * This is utility class.
053   */
054  private HBackupFileSystem() {
055  }
056
057  /**
058   * Given the backup root dir, backup id and the table name, return the backup image location.
059   * Return value look like:
060   * "hdfs://backup.hbase.org:9000/user/biadmin/backup/backup_1396650096738/default/t1_dn/", where
061   * "hdfs://backup.hbase.org:9000/user/biadmin/backup" is a backup root directory
062   * @param backupRootDir backup root directory
063   * @param backupId      backup id
064   * @param tableName     table name
065   * @return backupPath String for the particular table
066   */
067  public static String getTableBackupDir(String backupRootDir, String backupId,
068    TableName tableName) {
069    return backupRootDir + Path.SEPARATOR + backupId + Path.SEPARATOR
070      + tableName.getNamespaceAsString() + Path.SEPARATOR + tableName.getQualifierAsString()
071      + Path.SEPARATOR;
072  }
073
074  /**
075   * Get backup temporary directory
076   * @param backupRootDir backup root
077   * @return backup tmp directory path
078   */
079  public static Path getBackupTmpDirPath(String backupRootDir) {
080    return new Path(backupRootDir, ".tmp");
081  }
082
083  /**
084   * Get backup tmp directory for backupId
085   * @param backupRoot backup root
086   * @param backupId   backup id
087   * @return backup tmp directory path
088   */
089  public static Path getBackupTmpDirPathForBackupId(String backupRoot, String backupId) {
090    return new Path(getBackupTmpDirPath(backupRoot), backupId);
091  }
092
093  public static Path getBackupPath(String backupRootDir, String backupId) {
094    return new Path(backupRootDir + Path.SEPARATOR + backupId);
095  }
096
097  /**
098   * Write a completion marker file to signal a backup has completed successfully. This is a
099   * best-effort operation: if the write fails, the backup itself is still considered complete (the
100   * system table is the source of truth). The marker file is intended for external consumers (e.g.,
101   * another cluster) that cannot access the originating cluster's BackupSystemTable. A backup can
102   * still be complete even if the completion marker file is missing, but there is no way to verify
103   * this without using the originating cluster's BackupSystemTable.
104   * <p>
105   * The marker is always written last and deleted first: any operation that removes or modifies
106   * data in a backup directory (failed-backup cleanup, backup delete, merge, removing a table from
107   * a backup image when a dependent backup is deleted) deletes the marker before touching the data.
108   * A backup whose image was modified this way may therefore remain COMPLETE in the system table
109   * without a marker.
110   * @param conf          configuration
111   * @param backupRootDir backup root directory
112   * @param backupId      backup id
113   */
114  public static void writeBackupCompleteMarker(Configuration conf, String backupRootDir,
115    String backupId) {
116    Path backupDir = getBackupPath(backupRootDir, backupId);
117    Path markerPath = new Path(backupDir, BACKUP_COMPLETE_FILE_NAME);
118    try {
119      FileSystem fs = markerPath.getFileSystem(conf);
120      fs.create(markerPath, true).close();
121      LOG.info("Backup completion marker file written to: {}", markerPath);
122    } catch (IOException | RuntimeException e) {
123      LOG.warn("Failed to write {} marker file to backup directory: {}", BACKUP_COMPLETE_FILE_NAME,
124        backupDir, e);
125    }
126  }
127
128  /**
129   * Delete the completion marker file for the given backup, if it exists. Callers must invoke this
130   * before removing or modifying any data in the backup directory, so that the marker is never
131   * present on a backup whose data is incomplete.
132   * @param conf          configuration
133   * @param backupRootDir backup root directory
134   * @param backupId      backup id
135   * @throws IOException if the file system cannot be accessed or the marker could not be deleted
136   */
137  public static void deleteBackupCompleteMarker(Configuration conf, String backupRootDir,
138    String backupId) throws IOException {
139    Path markerPath = new Path(getBackupPath(backupRootDir, backupId), BACKUP_COMPLETE_FILE_NAME);
140    FileSystem fs = markerPath.getFileSystem(conf);
141    if (fs.delete(markerPath, false)) {
142      LOG.debug("Removed backup completion marker: {}", markerPath);
143    } else if (fs.exists(markerPath)) {
144      throw new IOException("Unable to delete backup completion marker: " + markerPath);
145    }
146  }
147
148  /**
149   * Check whether a backup completion marker file exists for the given backup.
150   * @param conf          configuration
151   * @param backupRootDir backup root directory
152   * @param backupId      backup id
153   * @return true if the marker file exists
154   * @throws IOException if the file system cannot be accessed
155   */
156  public static boolean isBackupComplete(Configuration conf, String backupRootDir, String backupId)
157    throws IOException {
158    Path markerPath = new Path(getBackupPath(backupRootDir, backupId), BACKUP_COMPLETE_FILE_NAME);
159    FileSystem fs = markerPath.getFileSystem(conf);
160    return fs.exists(markerPath);
161  }
162
163  /**
164   * Given the backup root dir, backup id and the table name, return the backup image location,
165   * which is also where the backup manifest file is. return value look like:
166   * "hdfs://backup.hbase.org:9000/user/biadmin/backup/backup_1396650096738/default/t1_dn/", where
167   * "hdfs://backup.hbase.org:9000/user/biadmin/backup" is a backup root directory
168   * @param backupRootPath backup root path
169   * @param tableName      table name
170   * @param backupId       backup Id
171   * @return backupPath for the particular table
172   */
173  public static Path getTableBackupPath(TableName tableName, Path backupRootPath, String backupId) {
174    return new Path(getTableBackupDir(backupRootPath.toString(), backupId, tableName));
175  }
176
177  private static Path getManifestPath(Configuration conf, Path backupRootPath, String backupId)
178    throws IOException {
179    return getManifestPath(conf, backupRootPath, backupId, true);
180  }
181
182  /* Visible for testing only */
183  @RestrictedApi(explanation = "Should only be called internally or in tests", link = "",
184      allowedOnPath = "(.*/src/test/.*|.*/org/apache/hadoop/hbase/backup/HBackupFileSystem.java)")
185  static Path getManifestPath(Configuration conf, Path backupRootPath, String backupId,
186    boolean throwIfNotFound) throws IOException {
187    FileSystem fs = backupRootPath.getFileSystem(conf);
188    Path manifestPath = new Path(getBackupPath(backupRootPath.toString(), backupId) + Path.SEPARATOR
189      + BackupManifest.MANIFEST_FILE_NAME);
190    if (throwIfNotFound && !fs.exists(manifestPath)) {
191      String errorMsg = "Could not find backup manifest " + BackupManifest.MANIFEST_FILE_NAME
192        + " for " + backupId + ". File " + manifestPath + " does not exists. Did " + backupId
193        + " correspond to previously taken backup ?";
194      throw new IOException(errorMsg);
195    }
196    return manifestPath;
197  }
198
199  public static Path getRootDirFromBackupPath(Path backupPath, String backupId) {
200    if (backupPath.getName().equals(BackupManifest.MANIFEST_FILE_NAME)) {
201      backupPath = backupPath.getParent();
202    }
203    Preconditions.checkArgument(backupPath.getName().equals(backupId),
204      String.format("Backup path %s must end in backupId %s", backupPath, backupId));
205    return backupPath.getParent();
206  }
207
208  public static BackupManifest getManifest(Configuration conf, Path backupRootPath, String backupId)
209    throws IOException {
210    BackupManifest manifest =
211      new BackupManifest(conf, getManifestPath(conf, backupRootPath, backupId));
212    return manifest;
213  }
214
215  public static List<BackupImage> getAllBackupImages(Configuration conf, Path backupRootPath)
216    throws IOException {
217    FileSystem fs = FileSystem.get(backupRootPath.toUri(), conf);
218    RemoteIterator<LocatedFileStatus> it = fs.listLocatedStatus(backupRootPath);
219
220    List<BackupImage> images = new ArrayList<>();
221
222    while (it.hasNext()) {
223      LocatedFileStatus lfs = it.next();
224      if (!lfs.isDirectory()) {
225        continue;
226      }
227
228      String backupId = lfs.getPath().getName();
229      if (HBASE_TEMP_DIRECTORY.equals(backupId)) {
230        continue;
231      }
232
233      try {
234        BackupManifest manifest = getManifest(conf, backupRootPath, backupId);
235        images.add(manifest.getBackupImage());
236      } catch (IOException e) {
237        LOG.error("Cannot load backup manifest from: {}", lfs.getPath(), e);
238      }
239    }
240
241    // Sort images by timestamp in descending order
242    images.sort(Comparator.comparingLong(m -> -getTimestamp(m.getBackupId())));
243
244    return images;
245  }
246
247  private static long getTimestamp(String backupId) {
248    return Long.parseLong(backupId.substring(BACKUPID_PREFIX.length()));
249  }
250}