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.util;
019
020import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.CONF_CONTINUOUS_BACKUP_WAL_DIR;
021import static org.apache.hadoop.hbase.backup.BackupRestoreConstants.CONTINUOUS_BACKUP_REPLICATION_PEER;
022import static org.apache.hadoop.hbase.backup.replication.ContinuousBackupReplicationEndpoint.ONE_DAY_IN_MILLISECONDS;
023import static org.apache.hadoop.hbase.backup.util.BackupFileSystemManager.WALS_DIR;
024import static org.apache.hadoop.hbase.replication.regionserver.ReplicationMarkerChore.REPLICATION_MARKER_ENABLED_DEFAULT;
025import static org.apache.hadoop.hbase.replication.regionserver.ReplicationMarkerChore.REPLICATION_MARKER_ENABLED_KEY;
026
027import java.io.FileNotFoundException;
028import java.io.IOException;
029import java.net.URLDecoder;
030import java.text.ParseException;
031import java.text.SimpleDateFormat;
032import java.time.ZoneOffset;
033import java.util.ArrayList;
034import java.util.Collection;
035import java.util.Collections;
036import java.util.Comparator;
037import java.util.Date;
038import java.util.HashMap;
039import java.util.List;
040import java.util.Locale;
041import java.util.Map;
042import java.util.Map.Entry;
043import java.util.Set;
044import java.util.TimeZone;
045import java.util.TreeSet;
046import java.util.function.Predicate;
047import java.util.stream.Collectors;
048import java.util.stream.Stream;
049import org.apache.hadoop.conf.Configuration;
050import org.apache.hadoop.fs.FSDataOutputStream;
051import org.apache.hadoop.fs.FileStatus;
052import org.apache.hadoop.fs.FileSystem;
053import org.apache.hadoop.fs.LocatedFileStatus;
054import org.apache.hadoop.fs.Path;
055import org.apache.hadoop.fs.PathFilter;
056import org.apache.hadoop.fs.RemoteIterator;
057import org.apache.hadoop.fs.permission.FsPermission;
058import org.apache.hadoop.hbase.HBaseConfiguration;
059import org.apache.hadoop.hbase.HConstants;
060import org.apache.hadoop.hbase.MetaTableAccessor;
061import org.apache.hadoop.hbase.ServerName;
062import org.apache.hadoop.hbase.TableName;
063import org.apache.hadoop.hbase.backup.BackupInfo;
064import org.apache.hadoop.hbase.backup.BackupRestoreConstants;
065import org.apache.hadoop.hbase.backup.HBackupFileSystem;
066import org.apache.hadoop.hbase.backup.RestoreRequest;
067import org.apache.hadoop.hbase.backup.impl.BackupManifest;
068import org.apache.hadoop.hbase.backup.impl.BackupManifest.BackupImage;
069import org.apache.hadoop.hbase.backup.impl.BackupSystemTable;
070import org.apache.hadoop.hbase.backup.master.LogRollMasterProcedureManager;
071import org.apache.hadoop.hbase.client.Admin;
072import org.apache.hadoop.hbase.client.Connection;
073import org.apache.hadoop.hbase.client.RegionInfo;
074import org.apache.hadoop.hbase.client.TableDescriptor;
075import org.apache.hadoop.hbase.master.region.MasterRegionFactory;
076import org.apache.hadoop.hbase.replication.ReplicationException;
077import org.apache.hadoop.hbase.replication.ReplicationGroupOffset;
078import org.apache.hadoop.hbase.replication.ReplicationQueueId;
079import org.apache.hadoop.hbase.replication.ReplicationQueueStorage;
080import org.apache.hadoop.hbase.replication.ReplicationStorageFactory;
081import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
082import org.apache.hadoop.hbase.util.CommonFSUtils;
083import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
084import org.apache.hadoop.hbase.util.FSTableDescriptors;
085import org.apache.hadoop.hbase.util.FSUtils;
086import org.apache.hadoop.hbase.wal.AbstractFSWALProvider;
087import org.apache.yetus.audience.InterfaceAudience;
088import org.slf4j.Logger;
089import org.slf4j.LoggerFactory;
090
091import org.apache.hbase.thirdparty.com.google.common.base.Splitter;
092import org.apache.hbase.thirdparty.com.google.common.base.Strings;
093import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
094import org.apache.hbase.thirdparty.com.google.common.collect.Iterables;
095import org.apache.hbase.thirdparty.com.google.common.collect.Iterators;
096
097/**
098 * A collection for methods used by multiple classes to backup HBase tables.
099 */
100@InterfaceAudience.Private
101public final class BackupUtils {
102  private static final Logger LOG = LoggerFactory.getLogger(BackupUtils.class);
103  public static final String LOGNAME_SEPARATOR = ".";
104  public static final int MILLISEC_IN_HOUR = 3600000;
105  public static final String DATE_FORMAT = "yyyy-MM-dd";
106
107  private BackupUtils() {
108    throw new AssertionError("Instantiating utility class...");
109  }
110
111  /**
112   * Returns the key under which the backup code tracks a region server. The key is the server's
113   * host:port with the hostname lowercased. WAL file names contain the lowercased hostname (see
114   * {@link ServerName#toString()}), while {@link ServerName#getAddress()} keeps the hostname's
115   * original case, so both spellings must map to the same key.
116   * @param hostAndPort host:port of a region server, in any case
117   * @return the lowercased host:port
118   */
119  public static String toHostKey(String hostAndPort) {
120    return hostAndPort.toLowerCase(Locale.ROOT);
121  }
122
123  /**
124   * Loop through the RS log timestamp map for the tables, for each RS, find the min timestamp value
125   * for the RS among the tables.
126   * @param rsLogTimestampMap timestamp map
127   * @return the min timestamp of each RS
128   */
129  public static Map<String, Long>
130    getRSLogTimestampMins(Map<TableName, Map<String, Long>> rsLogTimestampMap) {
131    return rsLogTimestampMap.values().stream().flatMap(map -> map.entrySet().stream())
132      .collect(Collectors.toMap(Entry::getKey, Entry::getValue, Math::min));
133  }
134
135  /**
136   * copy out Table RegionInfo into incremental backup image need to consider move this logic into
137   * HBackupFileSystem
138   * @param conn       connection
139   * @param backupInfo backup info
140   * @param conf       configuration
141   * @throws IOException exception
142   */
143  public static void copyTableRegionInfo(Connection conn, BackupInfo backupInfo, Configuration conf)
144    throws IOException {
145    Path rootDir = CommonFSUtils.getRootDir(conf);
146    FileSystem fs = rootDir.getFileSystem(conf);
147
148    // for each table in the table set, copy out the table info and region
149    // info files in the correct directory structure
150    try (Admin admin = conn.getAdmin()) {
151      for (TableName table : backupInfo.getTables()) {
152        if (!admin.tableExists(table)) {
153          LOG.warn("Table " + table + " does not exists, skipping it.");
154          continue;
155        }
156        TableDescriptor orig = FSTableDescriptors.getTableDescriptorFromFs(fs, rootDir, table);
157
158        // write a copy of descriptor to the target directory
159        Path target = new Path(backupInfo.getTableBackupDir(table));
160        FileSystem targetFs = target.getFileSystem(conf);
161        try (FSTableDescriptors descriptors =
162          new FSTableDescriptors(targetFs, CommonFSUtils.getRootDir(conf))) {
163          descriptors.createTableDescriptorForTableDirectory(target, orig, false);
164        }
165        LOG.debug("Attempting to copy table info for:" + table + " target: " + target
166          + " descriptor: " + orig);
167        LOG.debug("Finished copying tableinfo.");
168        List<RegionInfo> regions = MetaTableAccessor.getTableRegions(conn, table);
169        // For each region, write the region info to disk
170        LOG.debug("Starting to write region info for table " + table);
171        for (RegionInfo regionInfo : regions) {
172          Path regionDir = FSUtils
173            .getRegionDirFromTableDir(new Path(backupInfo.getTableBackupDir(table)), regionInfo);
174          regionDir = new Path(backupInfo.getTableBackupDir(table), regionDir.getName());
175          writeRegioninfoOnFilesystem(conf, targetFs, regionDir, regionInfo);
176        }
177        LOG.debug("Finished writing region info for table " + table);
178      }
179    }
180  }
181
182  /**
183   * Write the .regioninfo file on-disk.
184   */
185  public static void writeRegioninfoOnFilesystem(final Configuration conf, final FileSystem fs,
186    final Path regionInfoDir, RegionInfo regionInfo) throws IOException {
187    final byte[] content = RegionInfo.toDelimitedByteArray(regionInfo);
188    Path regionInfoFile = new Path(regionInfoDir, "." + HConstants.REGIONINFO_QUALIFIER_STR);
189    // First check to get the permissions
190    FsPermission perms = CommonFSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
191    // Write the RegionInfo file content
192    FSDataOutputStream out = FSUtils.create(conf, fs, regionInfoFile, perms, null);
193    try {
194      out.write(content);
195    } finally {
196      out.close();
197    }
198  }
199
200  /**
201   * Parses hostname:port from WAL file path
202   * @param p path to WAL file
203   * @return hostname:port
204   */
205  public static String parseHostNameFromLogFile(Path p) {
206    try {
207      if (AbstractFSWALProvider.isArchivedLogFile(p)) {
208        return BackupUtils.parseHostFromOldLog(p);
209      } else {
210        ServerName sname = AbstractFSWALProvider.getServerNameFromWALDirectoryName(p);
211        if (sname != null) {
212          return toHostKey(sname.getAddress().toString());
213        } else {
214          LOG.error("Skip log file (can't parse): " + p);
215          return null;
216        }
217      }
218    } catch (Exception e) {
219      LOG.error("Skip log file (can't parse): " + p, e);
220      return null;
221    }
222  }
223
224  /**
225   * Returns the log roll result of every region server that took part in the log roll that happened
226   * between reading {@code previousLogRolls} and {@code latestLogRolls}. A region server that did
227   * not take part (for example because it is offline) keeps its old roll result, which is never
228   * removed, so it is recognized by its roll result not changing.
229   * @param previousLogRolls roll results by host, read before the log roll
230   * @param latestLogRolls   roll results by host, read after the log roll
231   * @return roll results by host, for the hosts that took part in the log roll
232   */
233  public static Map<String, Long> getRolledHosts(Map<String, Long> previousLogRolls,
234    Map<String, Long> latestLogRolls) {
235    return latestLogRolls.entrySet().stream()
236      .filter(entry -> !entry.getValue().equals(previousLogRolls.get(entry.getKey())))
237      .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
238  }
239
240  /**
241   * Computes the per-host log boundaries stored by a backup that has no previous boundaries to
242   * carry forward, such as a full backup. See
243   * {@link #computeLogBoundaries(Map, Map, Set, Collection, Collection)}.
244   */
245  public static Map<String, Long> computeLogBoundaries(Map<String, Long> rolledHosts,
246    Collection<String> coveredLogs, Collection<String> pendingLogs) throws IOException {
247    return computeLogBoundaries(rolledHosts, Collections.emptyMap(), Collections.emptySet(),
248      coveredLogs, pendingLogs);
249  }
250
251  /**
252   * Computes the per-host log boundaries stored by a backup. Everything up to a host's boundary is
253   * covered by backups, so later incremental backups only include that host's logs that are newer.
254   * <ul>
255   * <li>A host that took part in the backup's log roll gets its roll result.</li>
256   * <li>Any other host gets the creation time of its newest covered log, capped to just below its
257   * oldest pending log, so that pending logs are included in a later backup.</li>
258   * <li>A host without covered or pending logs keeps its previous boundary while it still has logs,
259   * and otherwise gets no boundary.</li>
260   * </ul>
261   * Capping is needed because a host's logs can still be pending while some of its newer logs are
262   * already covered, for example when a dead server's logs are split and archived out of order. As
263   * a result, the next backup includes the covered logs that are newer than the cap a second time:
264   * losing the pending logs is worse than repeating edits that are already backed up. A host is
265   * also kept while any of its logs are pending, even if none are covered, because without a
266   * boundary the next backup would treat it as unknown and skip its older logs. For the same reason
267   * a host keeps its previous boundary while it still has logs: without it, the next backup would
268   * include its logs that are already covered, which can bring back deleted data.
269   * @param rolledHosts        roll results of the hosts that took part in the log roll
270   * @param previousBoundaries boundaries stored by the previous backup
271   * @param hostsWithLogs      hosts that still have logs, whether or not this backup includes them
272   * @param coveredLogs        logs whose edits are included in the backup
273   * @param pendingLogs        logs whose edits are not to be included in the backup
274   * @return boundaries by host
275   */
276  public static Map<String, Long> computeLogBoundaries(Map<String, Long> rolledHosts,
277    Map<String, Long> previousBoundaries, Set<String> hostsWithLogs, Collection<String> coveredLogs,
278    Collection<String> pendingLogs) throws IOException {
279    Map<String, Long> otherHosts = new HashMap<>();
280    for (String log : coveredLogs) {
281      Path path = new Path(log);
282      String host = parseHostNameFromLogFile(path);
283      if (host != null && !rolledHosts.containsKey(host)) {
284        otherHosts.merge(host, getCreationTime(path), Math::max);
285      }
286    }
287    for (String log : pendingLogs) {
288      Path path = new Path(log);
289      String host = parseHostNameFromLogFile(path);
290      if (host != null && !rolledHosts.containsKey(host)) {
291        otherHosts.merge(host, getCreationTime(path) - 1, Math::min);
292      }
293    }
294    Map<String, Long> boundaries = new HashMap<>(rolledHosts);
295    boundaries.putAll(otherHosts);
296    for (Entry<String, Long> previous : previousBoundaries.entrySet()) {
297      if (hostsWithLogs.contains(previous.getKey())) {
298        boundaries.putIfAbsent(previous.getKey(), previous.getValue());
299      }
300    }
301    return boundaries;
302  }
303
304  /**
305   * Returns WAL file name
306   * @param walFileName WAL file name
307   * @return WAL file name
308   */
309  public static String getUniqueWALFileNamePart(String walFileName) {
310    return getUniqueWALFileNamePart(new Path(walFileName));
311  }
312
313  /**
314   * Returns WAL file name
315   * @param p WAL file path
316   * @return WAL file name
317   */
318  public static String getUniqueWALFileNamePart(Path p) {
319    return p.getName();
320  }
321
322  /**
323   * Get the total length of files under the given directory recursively.
324   * @param fs  The hadoop file system
325   * @param dir The target directory
326   * @return the total length of files
327   * @throws IOException exception
328   */
329  public static long getFilesLength(FileSystem fs, Path dir) throws IOException {
330    long totalLength = 0;
331    FileStatus[] files = CommonFSUtils.listStatus(fs, dir);
332    if (files != null) {
333      for (FileStatus fileStatus : files) {
334        if (fileStatus.isDirectory()) {
335          totalLength += getFilesLength(fs, fileStatus.getPath());
336        } else {
337          totalLength += fileStatus.getLen();
338        }
339      }
340    }
341    return totalLength;
342  }
343
344  /**
345   * Get list of all old WAL files (WALs and archive)
346   * @param c                configuration
347   * @param hostTimestampMap {host,timestamp} map
348   * @return list of WAL files
349   * @throws IOException exception
350   */
351  public static List<String> getWALFilesOlderThan(final Configuration c,
352    final HashMap<String, Long> hostTimestampMap) throws IOException {
353    Path walRootDir = CommonFSUtils.getWALRootDir(c);
354    Path logDir = new Path(walRootDir, HConstants.HREGION_LOGDIR_NAME);
355    Path oldLogDir = new Path(walRootDir, HConstants.HREGION_OLDLOGDIR_NAME);
356    List<String> logFiles = new ArrayList<>();
357
358    PathFilter filter = p -> {
359      try {
360        if (AbstractFSWALProvider.isMetaFile(p)) {
361          return false;
362        }
363        String host = parseHostNameFromLogFile(p);
364        if (host == null) {
365          return false;
366        }
367        Long oldTimestamp = hostTimestampMap.get(host);
368        Long currentLogTS = BackupUtils.getCreationTime(p);
369        return currentLogTS <= oldTimestamp;
370      } catch (Exception e) {
371        LOG.warn("Can not parse" + p, e);
372        return false;
373      }
374    };
375    FileSystem walFs = CommonFSUtils.getWALFileSystem(c);
376    logFiles = BackupUtils.getFiles(walFs, logDir, logFiles, filter);
377    logFiles = BackupUtils.getFiles(walFs, oldLogDir, logFiles, filter);
378    return logFiles;
379  }
380
381  public static TableName[] parseTableNames(String tables) {
382    if (tables == null) {
383      return null;
384    }
385    return Splitter.on(BackupRestoreConstants.TABLENAME_DELIMITER_IN_COMMAND).splitToStream(tables)
386      .map(TableName::valueOf).toArray(TableName[]::new);
387  }
388
389  /**
390   * Check whether the backup path exist
391   * @param backupStr backup
392   * @param conf      configuration
393   * @return Yes if path exists
394   * @throws IOException exception
395   */
396  public static boolean checkPathExist(String backupStr, Configuration conf) throws IOException {
397    boolean isExist = false;
398    Path backupPath = new Path(backupStr);
399    FileSystem fileSys = backupPath.getFileSystem(conf);
400    String targetFsScheme = fileSys.getUri().getScheme();
401    if (LOG.isTraceEnabled()) {
402      LOG.trace("Schema of given url: " + backupStr + " is: " + targetFsScheme);
403    }
404    if (fileSys.exists(backupPath)) {
405      isExist = true;
406    }
407    return isExist;
408  }
409
410  /**
411   * Check target path first, confirm it doesn't exist before backup
412   * @param backupRootPath backup destination path
413   * @param conf           configuration
414   * @throws IOException exception
415   */
416  public static void checkTargetDir(String backupRootPath, Configuration conf) throws IOException {
417    boolean targetExists;
418    try {
419      targetExists = checkPathExist(backupRootPath, conf);
420    } catch (IOException e) {
421      String expMsg = e.getMessage();
422      String newMsg = null;
423      if (expMsg.contains("No FileSystem for scheme")) {
424        newMsg =
425          "Unsupported filesystem scheme found in the backup target url. Error Message: " + expMsg;
426        LOG.error(newMsg);
427        throw new IOException(newMsg);
428      } else {
429        throw e;
430      }
431    }
432
433    if (targetExists) {
434      LOG.info("Using existing backup root dir: " + backupRootPath);
435    } else {
436      LOG.info("Backup root dir " + backupRootPath + " does not exist. Will be created.");
437    }
438  }
439
440  /**
441   * Get the min value for all the Values a map.
442   * @param map map
443   * @return the min value
444   */
445  public static <T> Long getMinValue(Map<T, Long> map) {
446    Long minTimestamp = null;
447    if (map != null) {
448      ArrayList<Long> timestampList = new ArrayList<>(map.values());
449      Collections.sort(timestampList);
450      // The min among all the RS log timestamps will be kept in backup system table table.
451      minTimestamp = timestampList.get(0);
452    }
453    return minTimestamp;
454  }
455
456  /**
457   * Parses host name:port from archived WAL path
458   * @param p path
459   * @return host name
460   */
461  public static String parseHostFromOldLog(Path p) {
462    // Skip master wals
463    if (p.getName().endsWith(MasterRegionFactory.ARCHIVED_WAL_SUFFIX)) {
464      return null;
465    }
466    Path parent = p.getParent();
467    if (parent != null && ServerName.isFullServerName(parent.getName())) {
468      return toHostKey(ServerName.valueOf(parent.getName()).getAddress().toString());
469    }
470    try {
471      String urlDecodedName = URLDecoder.decode(p.getName(), "UTF8");
472      Iterable<String> nameSplitsOnComma = Splitter.on(",").split(urlDecodedName);
473      String host = Iterables.get(nameSplitsOnComma, 0);
474      String port = Iterables.get(nameSplitsOnComma, 1);
475      return toHostKey(host + ":" + port);
476    } catch (Exception e) {
477      LOG.warn("Skip log file (can't parse): {}", p);
478      return null;
479    }
480  }
481
482  /**
483   * Given the log file, parse the timestamp from the file name. The timestamp is the last number.
484   * @param p a path to the log file
485   * @return the timestamp
486   * @throws IOException exception
487   */
488  public static Long getCreationTime(Path p) throws IOException {
489    int idx = p.getName().lastIndexOf(LOGNAME_SEPARATOR);
490    if (idx < 0) {
491      throw new IOException("Cannot parse timestamp from path " + p);
492    }
493    String ts = p.getName().substring(idx + 1);
494    return Long.parseLong(ts);
495  }
496
497  public static List<String> getFiles(FileSystem fs, Path rootDir, List<String> files,
498    PathFilter filter) throws IOException {
499    RemoteIterator<LocatedFileStatus> it = fs.listFiles(rootDir, true);
500
501    while (it.hasNext()) {
502      LocatedFileStatus lfs = it.next();
503      if (lfs.isDirectory()) {
504        continue;
505      }
506      // apply filter
507      if (filter.accept(lfs.getPath())) {
508        files.add(lfs.getPath().toString());
509      }
510    }
511    return files;
512  }
513
514  public static void cleanupBackupData(BackupInfo context, Configuration conf) throws IOException {
515    cleanupHLogDir(context, conf);
516    cleanupTargetDir(context, conf);
517  }
518
519  /**
520   * Clean up directories which are generated when DistCp copying hlogs
521   * @param backupInfo backup info
522   * @param conf       configuration
523   * @throws IOException exception
524   */
525  private static void cleanupHLogDir(BackupInfo backupInfo, Configuration conf) throws IOException {
526    String logDir = backupInfo.getHLogTargetDir();
527    if (logDir == null) {
528      LOG.warn("No log directory specified for " + backupInfo.getBackupId());
529      return;
530    }
531
532    Path rootPath = new Path(logDir).getParent();
533    FileSystem fs = FileSystem.get(rootPath.toUri(), conf);
534    FileStatus[] files = listStatus(fs, rootPath, null);
535    if (files == null) {
536      return;
537    }
538    for (FileStatus file : files) {
539      LOG.debug("Delete log files: " + file.getPath().getName());
540      fs.delete(file.getPath(), true);
541    }
542  }
543
544  /**
545   * Delete the data of a backup from its target directory.
546   * @throws IOException if the backup completion marker could not be removed. In that case no data
547   *                     is deleted and the caller must not remove the backup's metadata.
548   */
549  private static void cleanupTargetDir(BackupInfo backupInfo, Configuration conf)
550    throws IOException {
551    // clean up the data at target directory
552    LOG.debug("Trying to cleanup up target dir : " + backupInfo.getBackupId());
553    String targetDir = backupInfo.getBackupRootDir();
554    if (targetDir == null) {
555      LOG.warn("No target directory specified for " + backupInfo.getBackupId());
556      return;
557    }
558
559    // Delete the completion marker before any data so that a partial delete never leaves a marker
560    // on a backup with missing tables. If this fails, propagate the error before any data or
561    // metadata is removed: the marker, data, and system table record all remain, which is
562    // consistent, and the delete operation can be retried.
563    HBackupFileSystem.deleteBackupCompleteMarker(conf, targetDir, backupInfo.getBackupId());
564
565    try {
566      FileSystem outputFs = FileSystem.get(new Path(backupInfo.getBackupRootDir()).toUri(), conf);
567
568      for (TableName table : backupInfo.getTables()) {
569        Path targetDirPath = new Path(
570          getTableBackupDir(backupInfo.getBackupRootDir(), backupInfo.getBackupId(), table));
571        if (outputFs.delete(targetDirPath, true)) {
572          LOG.info("Cleaning up backup data at " + targetDirPath.toString() + " done.");
573        } else {
574          LOG.info("No data has been found in " + targetDirPath.toString() + ".");
575        }
576
577        Path tableDir = targetDirPath.getParent();
578        FileStatus[] backups = listStatus(outputFs, tableDir, null);
579        if (backups == null || backups.length == 0) {
580          outputFs.delete(tableDir, true);
581          LOG.debug(tableDir.toString() + " is empty, remove it.");
582        }
583      }
584      outputFs.delete(new Path(targetDir, backupInfo.getBackupId()), true);
585    } catch (IOException e1) {
586      LOG.error("Cleaning up backup data of " + backupInfo.getBackupId() + " at "
587        + backupInfo.getBackupRootDir() + " failed due to " + e1.getMessage() + ".");
588    }
589  }
590
591  /**
592   * Given the backup root dir, backup id and the table name, return the backup image location,
593   * which is also where the backup manifest file is. return value look like:
594   * "hdfs://backup.hbase.org:9000/user/biadmin/backup1/backup_1396650096738/default/t1_dn/"
595   * @param backupRootDir backup root directory
596   * @param backupId      backup id
597   * @param tableName     table name
598   * @return backupPath String for the particular table
599   */
600  public static String getTableBackupDir(String backupRootDir, String backupId,
601    TableName tableName) {
602    return backupRootDir + Path.SEPARATOR + backupId + Path.SEPARATOR
603      + tableName.getNamespaceAsString() + Path.SEPARATOR + tableName.getQualifierAsString()
604      + Path.SEPARATOR;
605  }
606
607  /**
608   * Calls fs.listStatus() and treats FileNotFoundException as non-fatal This accommodates
609   * differences between hadoop versions, where hadoop 1 does not throw a FileNotFoundException, and
610   * return an empty FileStatus[] while Hadoop 2 will throw FileNotFoundException.
611   * @param fs     file system
612   * @param dir    directory
613   * @param filter path filter
614   * @return null if dir is empty or doesn't exist, otherwise FileStatus array
615   */
616  public static FileStatus[] listStatus(final FileSystem fs, final Path dir,
617    final PathFilter filter) throws IOException {
618    FileStatus[] status = null;
619    try {
620      status = filter == null ? fs.listStatus(dir) : fs.listStatus(dir, filter);
621    } catch (FileNotFoundException fnfe) {
622      // if directory doesn't exist, return null
623      if (LOG.isTraceEnabled()) {
624        LOG.trace(dir + " doesn't exist");
625      }
626    }
627
628    if (status == null || status.length < 1) {
629      return null;
630    }
631
632    return status;
633  }
634
635  /**
636   * Return the 'path' component of a Path. In Hadoop, Path is a URI. This method returns the 'path'
637   * component of a Path's URI: e.g. If a Path is
638   * <code>hdfs://example.org:9000/hbase_trunk/TestTable/compaction.dir</code>, this method returns
639   * <code>/hbase_trunk/TestTable/compaction.dir</code>. This method is useful if you want to print
640   * out a Path without qualifying Filesystem instance.
641   * @param p file system Path whose 'path' component we are to return.
642   * @return Path portion of the Filesystem
643   */
644  public static String getPath(Path p) {
645    return p.toUri().getPath();
646  }
647
648  /**
649   * Given the backup root dir and the backup id, return the log file location for an incremental
650   * backup.
651   * @param backupRootDir backup root directory
652   * @param backupId      backup id
653   * @return logBackupDir: ".../user/biadmin/backup1/WALs/backup_1396650096738"
654   */
655  public static String getLogBackupDir(String backupRootDir, String backupId) {
656    return backupRootDir + Path.SEPARATOR + backupId + Path.SEPARATOR
657      + HConstants.HREGION_LOGDIR_NAME;
658  }
659
660  /**
661   * Loads all backup history as stored in files on the given backup root path.
662   * @return all backup history, from newest (most recent) to oldest (least recent)
663   */
664  private static List<BackupInfo> getHistory(Configuration conf, Path backupRootPath)
665    throws IOException {
666    // Get all (n) history from backup root destination
667
668    FileSystem fs = FileSystem.get(backupRootPath.toUri(), conf);
669    RemoteIterator<LocatedFileStatus> it;
670    try {
671      it = fs.listLocatedStatus(backupRootPath);
672    } catch (FileNotFoundException e) {
673      return Collections.emptyList();
674    }
675
676    List<BackupInfo> infos = new ArrayList<>();
677    while (it.hasNext()) {
678      LocatedFileStatus lfs = it.next();
679
680      if (!lfs.isDirectory()) {
681        continue;
682      }
683
684      String backupId = lfs.getPath().getName();
685      try {
686        BackupInfo info = loadBackupInfo(backupRootPath, backupId, fs);
687        infos.add(info);
688      } catch (IOException e) {
689        LOG.error("Can not load backup info from: " + lfs.getPath(), e);
690      }
691    }
692    // Sort
693    infos.sort(Comparator.<BackupInfo> naturalOrder().reversed());
694    return infos;
695  }
696
697  /**
698   * Loads all backup history as stored in files on the given backup root path, and returns the
699   * first n entries matching all given filters.
700   * @return (subset of) backup history, from newest (most recent) to oldest (least recent)
701   */
702  public static List<BackupInfo> getHistory(Configuration conf, int n, Path backupRootPath,
703    BackupInfo.Filter... filters) throws IOException {
704    List<BackupInfo> infos = getHistory(conf, backupRootPath);
705
706    Predicate<BackupInfo> combinedPredicate = Stream.of(filters)
707      .map(filter -> (Predicate<BackupInfo>) filter).reduce(Predicate::and).orElse(x -> true);
708
709    return infos.stream().filter(combinedPredicate).limit(n).toList();
710  }
711
712  public static BackupInfo loadBackupInfo(Path backupRootPath, String backupId, FileSystem fs)
713    throws IOException {
714    Path backupPath = new Path(backupRootPath, backupId);
715
716    RemoteIterator<LocatedFileStatus> it = fs.listFiles(backupPath, true);
717    while (it.hasNext()) {
718      LocatedFileStatus lfs = it.next();
719      if (lfs.getPath().getName().equals(BackupManifest.MANIFEST_FILE_NAME)) {
720        // Load BackupManifest
721        BackupManifest manifest = new BackupManifest(fs, lfs.getPath().getParent());
722        BackupInfo info = manifest.toBackupInfo();
723        return info;
724      }
725    }
726    return null;
727  }
728
729  /**
730   * Create restore request.
731   * @param backupRootDir backup root dir
732   * @param backupId      backup id
733   * @param check         check only
734   * @param fromTables    table list from
735   * @param toTables      table list to
736   * @param isOverwrite   overwrite data
737   * @return request obkect
738   */
739  public static RestoreRequest createRestoreRequest(String backupRootDir, String backupId,
740    boolean check, TableName[] fromTables, TableName[] toTables, boolean isOverwrite) {
741    return createRestoreRequest(backupRootDir, backupId, check, fromTables, toTables, isOverwrite,
742      false);
743  }
744
745  public static RestoreRequest createRestoreRequest(String backupRootDir, String backupId,
746    boolean check, TableName[] fromTables, TableName[] toTables, boolean isOverwrite,
747    boolean isKeepOriginalSplits) {
748    RestoreRequest.Builder builder = new RestoreRequest.Builder();
749    RestoreRequest request = builder.withBackupRootDir(backupRootDir).withBackupId(backupId)
750      .withCheck(check).withFromTables(fromTables).withToTables(toTables).withOverwrite(isOverwrite)
751      .withKeepOriginalSplits(isKeepOriginalSplits).build();
752    return request;
753  }
754
755  public static boolean validate(List<TableName> tables, BackupManifest backupManifest,
756    Configuration conf) throws IOException {
757    boolean isValid = true;
758
759    for (TableName table : tables) {
760      TreeSet<BackupImage> imageSet = new TreeSet<>();
761
762      ArrayList<BackupImage> depList = backupManifest.getDependentListByTable(table);
763      if (depList != null && !depList.isEmpty()) {
764        imageSet.addAll(depList);
765      }
766
767      LOG.info("Dependent image(s) from old to new:");
768      for (BackupImage image : imageSet) {
769        String imageDir =
770          HBackupFileSystem.getTableBackupDir(image.getRootDir(), image.getBackupId(), table);
771        if (!BackupUtils.checkPathExist(imageDir, conf)) {
772          LOG.error("ERROR: backup image does not exist: " + imageDir);
773          isValid = false;
774          break;
775        }
776        LOG.info("Backup image: " + image.getBackupId() + " for '" + table + "' is available");
777      }
778    }
779    return isValid;
780  }
781
782  public static Path getBulkOutputDir(Path restoreRootDir, String tableName, Configuration conf,
783    boolean deleteOnExit) throws IOException {
784    FileSystem fs = restoreRootDir.getFileSystem(conf);
785    Path path = new Path(restoreRootDir,
786      "bulk_output-" + tableName + "-" + EnvironmentEdgeManager.currentTime());
787    if (deleteOnExit) {
788      fs.deleteOnExit(path);
789    }
790    return path;
791  }
792
793  public static Path getBulkOutputDir(Path restoreRootDir, String tableName, Configuration conf)
794    throws IOException {
795    return getBulkOutputDir(restoreRootDir, tableName, conf, true);
796  }
797
798  public static Path getBulkOutputDir(String tableName, Configuration conf, boolean deleteOnExit)
799    throws IOException {
800    FileSystem fs = FileSystem.get(conf);
801    return getBulkOutputDir(getTmpRestoreOutputDir(fs, conf), tableName, conf, deleteOnExit);
802  }
803
804  /**
805   * Build temporary output path
806   * @param fs   filesystem for default output dir
807   * @param conf configuration
808   * @return output path
809   */
810  public static Path getTmpRestoreOutputDir(FileSystem fs, Configuration conf) {
811    String tmp =
812      conf.get(HConstants.TEMPORARY_FS_DIRECTORY_KEY, fs.getHomeDirectory() + "/hbase-staging");
813    return new Path(tmp);
814  }
815
816  public static String getFileNameCompatibleString(TableName table) {
817    return table.getNamespaceAsString() + "-" + table.getQualifierAsString();
818  }
819
820  public static boolean failed(int result) {
821    return result != 0;
822  }
823
824  public static boolean succeeded(int result) {
825    return result == 0;
826  }
827
828  public static BulkLoadHFiles createLoader(Configuration config) {
829    // set configuration for restore:
830    // LoadIncrementalHFile needs more time
831    // <name>hbase.rpc.timeout</name> <value>600000</value>
832    // calculates
833    Configuration conf = new Configuration(config);
834    conf.setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, MILLISEC_IN_HOUR);
835
836    // By default, it is 32 and loader will fail if # of files in any region exceed this
837    // limit. Bad for snapshot restore.
838    conf.setInt(BulkLoadHFiles.MAX_FILES_PER_REGION_PER_FAMILY, Integer.MAX_VALUE);
839    conf.set(BulkLoadHFiles.IGNORE_UNMATCHED_CF_CONF_KEY, "yes");
840    return BulkLoadHFiles.create(conf);
841  }
842
843  public static String findMostRecentBackupId(String[] backupIds) {
844    long recentTimestamp = Long.MIN_VALUE;
845    for (String backupId : backupIds) {
846      long ts = Long.parseLong(Iterators.get(Splitter.on('_').split(backupId).iterator(), 1));
847      if (ts > recentTimestamp) {
848        recentTimestamp = ts;
849      }
850    }
851    return BackupRestoreConstants.BACKUPID_PREFIX + recentTimestamp;
852  }
853
854  /**
855   * roll WAL writer for all region servers and record the newest log roll result
856   */
857  public static void logRoll(Connection conn, String backupRootDir, Configuration conf)
858    throws IOException {
859    boolean legacy = conf.getBoolean("hbase.backup.logroll.legacy.used", false);
860    if (legacy) {
861      logRollV1(conn, backupRootDir);
862    } else {
863      logRollV2(conn, backupRootDir);
864    }
865  }
866
867  private static void logRollV1(Connection conn, String backupRootDir) throws IOException {
868    try (Admin admin = conn.getAdmin()) {
869      admin.execProcedure(LogRollMasterProcedureManager.ROLLLOG_PROCEDURE_SIGNATURE,
870        LogRollMasterProcedureManager.ROLLLOG_PROCEDURE_NAME,
871        ImmutableMap.of("backupRoot", backupRootDir));
872    }
873  }
874
875  private static void logRollV2(Connection conn, String backupRootDir) throws IOException {
876    BackupSystemTable backupSystemTable = new BackupSystemTable(conn);
877    HashMap<String, Long> lastLogRollResult =
878      backupSystemTable.readRegionServerLastLogRollResult(backupRootDir);
879    try (Admin admin = conn.getAdmin()) {
880      Map<ServerName, Long> newLogRollResult = admin.rollAllWALWriters();
881
882      for (Map.Entry<ServerName, Long> entry : newLogRollResult.entrySet()) {
883        ServerName serverName = entry.getKey();
884        long newHighestWALFilenum = entry.getValue();
885
886        String address = toHostKey(serverName.getAddress().toString());
887        Long lastHighestWALFilenum = lastLogRollResult.get(address);
888        if (lastHighestWALFilenum != null && lastHighestWALFilenum > newHighestWALFilenum) {
889          LOG.warn("Won't update last roll log result for server {}: current = {}, new = {}",
890            serverName, lastHighestWALFilenum, newHighestWALFilenum);
891        } else {
892          backupSystemTable.writeRegionServerLastLogRollResult(address, newHighestWALFilenum,
893            backupRootDir);
894          if (LOG.isDebugEnabled()) {
895            LOG.debug("updated last roll log result for {} from {} to {}", serverName,
896              lastHighestWALFilenum, newHighestWALFilenum);
897          }
898        }
899      }
900    }
901  }
902
903  /**
904   * Calculates the replication checkpoint timestamp used for continuous backup.
905   * <p>
906   * A replication checkpoint is the earliest timestamp across all region servers such that every
907   * WAL entry before that point is known to be replicated to the target system. This is essential
908   * for features like Point-in-Time Restore (PITR) and incremental backups, where we want to
909   * confidently restore data to a consistent state without missing updates.
910   * <p>
911   * The checkpoint is calculated using a combination of:
912   * <ul>
913   * <li>The start timestamps of WAL files currently being replicated for each server.</li>
914   * <li>The latest successfully replicated timestamp recorded by the replication marker chore.</li>
915   * </ul>
916   * <p>
917   * We combine these two sources to handle the following challenges:
918   * <ul>
919   * <li><b>Stale WAL start times:</b> If replication traffic is low or WALs are long-lived, the
920   * replication offset may point to the same WAL for a long time, resulting in stale timestamps
921   * that underestimate progress. This could delay PITR unnecessarily.</li>
922   * <li><b>Limitations of marker-only tracking:</b> The replication marker chore stores the last
923   * successfully replicated timestamp per region server in a system table. However, this data may
924   * become stale if the server goes offline or region ownership changes. For example, if a region
925   * initially belonged to rs1 and was later moved to rs4 due to re-balancing, rs1’s marker would
926   * persist even though it no longer holds any regions. Relying solely on these stale markers could
927   * lead to incorrect or outdated checkpoints.</li>
928   * </ul>
929   * <p>
930   * To handle these limitations, the method:
931   * <ol>
932   * <li>Verifies that the continuous backup peer exists to ensure replication is enabled.</li>
933   * <li>Retrieves WAL replication queue information for the peer, collecting WAL start times per
934   * region server. This gives us a lower bound for replication progress.</li>
935   * <li>Reads the marker chore's replicated timestamps from the backup system table.</li>
936   * <li>For servers found in both sources, if the marker timestamp is more recent than the WAL's
937   * start timestamp, we use the marker (since replication has progressed beyond the WAL).</li>
938   * <li>We discard marker entries for region servers that are not present in WAL queues, assuming
939   * those servers are no longer relevant (e.g., decommissioned or reassigned).</li>
940   * <li>The checkpoint is the minimum of all chosen timestamps — i.e., the slowest replicating
941   * region server.</li>
942   * <li>Finally, we persist the updated marker information to include any newly participating
943   * region servers.</li>
944   * </ol>
945   * <p>
946   * Note: If the replication marker chore is disabled, we fall back to using only the WAL start
947   * times. This ensures correctness but may lead to conservative checkpoint estimates during idle
948   * periods.
949   * @param conn the HBase connection
950   * @return the calculated replication checkpoint timestamp
951   * @throws IOException if reading replication queues or updating the backup system table fails
952   */
953  public static long getReplicationCheckpoint(Connection conn) throws IOException {
954    Configuration conf = conn.getConfiguration();
955    long checkpoint = EnvironmentEdgeManager.getDelegate().currentTime();
956
957    // Step 1: Ensure the continuous backup replication peer exists
958    if (!continuousBackupReplicationPeerExists(conn.getAdmin())) {
959      String msg = "Replication peer '" + CONTINUOUS_BACKUP_REPLICATION_PEER
960        + "' not found. Continuous backup not enabled.";
961      LOG.error(msg);
962      throw new IOException(msg);
963    }
964
965    // Step 2: Get all replication queues for the continuous backup peer
966    ReplicationQueueStorage queueStorage =
967      ReplicationStorageFactory.getReplicationQueueStorage(conn, conf);
968
969    List<ReplicationQueueId> queueIds;
970    try {
971      queueIds = queueStorage.listAllQueueIds(CONTINUOUS_BACKUP_REPLICATION_PEER);
972    } catch (ReplicationException e) {
973      String msg = "Failed to retrieve replication queue IDs for peer '"
974        + CONTINUOUS_BACKUP_REPLICATION_PEER + "'";
975      LOG.error(msg, e);
976      throw new IOException(msg, e);
977    }
978
979    if (queueIds.isEmpty()) {
980      String msg = "Replication peer '" + CONTINUOUS_BACKUP_REPLICATION_PEER + "' has no queues. "
981        + "This may indicate that continuous backup replication is not initialized correctly.";
982      LOG.error(msg);
983      throw new IOException(msg);
984    }
985
986    // Step 3: Build a map of ServerName -> WAL start timestamp (lowest seen per server)
987    Map<ServerName, Long> serverToCheckpoint = new HashMap<>();
988    for (ReplicationQueueId queueId : queueIds) {
989      Map<String, ReplicationGroupOffset> offsets;
990      try {
991        offsets = queueStorage.getOffsets(queueId);
992      } catch (ReplicationException e) {
993        String msg = "Failed to fetch WAL offsets for replication queue: " + queueId;
994        LOG.error(msg, e);
995        throw new IOException(msg, e);
996      }
997
998      for (ReplicationGroupOffset offset : offsets.values()) {
999        String walFile = offset.getWal();
1000        long ts = AbstractFSWALProvider.getTimestamp(walFile); // WAL creation time
1001        ServerName server = queueId.getServerName();
1002        // Store the minimum timestamp per server (ts - 1 to avoid edge boundary issues)
1003        serverToCheckpoint.merge(server, ts - 1, Math::min);
1004      }
1005    }
1006
1007    // Step 4: If replication markers are enabled, overlay fresher timestamps from backup system
1008    // table
1009    boolean replicationMarkerEnabled =
1010      conf.getBoolean(REPLICATION_MARKER_ENABLED_KEY, REPLICATION_MARKER_ENABLED_DEFAULT);
1011    if (replicationMarkerEnabled) {
1012      try (BackupSystemTable backupSystemTable = new BackupSystemTable(conn)) {
1013        Map<ServerName, Long> markerTimestamps = backupSystemTable.getBackupCheckpointTimestamps();
1014
1015        for (Map.Entry<ServerName, Long> entry : markerTimestamps.entrySet()) {
1016          ServerName server = entry.getKey();
1017          long markerTs = entry.getValue();
1018
1019          // If marker timestamp is newer, override
1020          if (serverToCheckpoint.containsKey(server)) {
1021            long current = serverToCheckpoint.get(server);
1022            if (markerTs > current) {
1023              serverToCheckpoint.put(server, markerTs);
1024            }
1025          } else {
1026            // This server is no longer active (e.g., RS moved or removed); skip
1027            if (LOG.isDebugEnabled()) {
1028              LOG.debug("Skipping replication marker timestamp for inactive server: {}", server);
1029            }
1030          }
1031        }
1032
1033        // Step 5: Persist current server timestamps into backup system table
1034        for (Map.Entry<ServerName, Long> entry : serverToCheckpoint.entrySet()) {
1035          backupSystemTable.updateBackupCheckpointTimestamp(entry.getKey(), entry.getValue());
1036        }
1037      }
1038    } else {
1039      LOG.warn(
1040        "Replication marker chore is disabled. Using WAL-based timestamps only for checkpoint calculation.");
1041    }
1042
1043    // Step 6: Calculate final checkpoint as minimum timestamp across all active servers
1044    for (long ts : serverToCheckpoint.values()) {
1045      checkpoint = Math.min(checkpoint, ts);
1046    }
1047
1048    return checkpoint;
1049  }
1050
1051  private static boolean continuousBackupReplicationPeerExists(Admin admin) throws IOException {
1052    return admin.listReplicationPeers().stream()
1053      .anyMatch(peer -> peer.getPeerId().equals(CONTINUOUS_BACKUP_REPLICATION_PEER));
1054  }
1055
1056  /**
1057   * Convert dayInMillis to "yyyy-MM-dd" format
1058   */
1059  public static String formatToDateString(long dayInMillis) {
1060    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
1061    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
1062    return dateFormat.format(new Date(dayInMillis));
1063  }
1064
1065  /**
1066   * Fetches bulkload filepaths based on the given time range from backup WAL directory.
1067   */
1068  public static List<Path> collectBulkFiles(Connection conn, TableName sourceTable,
1069    TableName targetTable, long startTime, long endTime, Path restoreRootDir, List<String> walDirs)
1070    throws IOException {
1071
1072    if (walDirs.isEmpty()) {
1073      String walBackupDir = conn.getConfiguration().get(CONF_CONTINUOUS_BACKUP_WAL_DIR);
1074      if (Strings.isNullOrEmpty(walBackupDir)) {
1075        throw new IOException(
1076          "WAL backup directory is not configured " + CONF_CONTINUOUS_BACKUP_WAL_DIR);
1077      }
1078      Path walDirPath = new Path(walBackupDir);
1079      walDirs =
1080        BackupUtils.getValidWalDirs(conn.getConfiguration(), walDirPath, startTime, endTime);
1081    }
1082
1083    if (walDirs.isEmpty()) {
1084      LOG.warn("No valid WAL directories found for range {} - {}. Skipping bulk-file collection.",
1085        startTime, endTime);
1086      return Collections.emptyList();
1087    }
1088
1089    LOG.info(
1090      "Starting WAL bulk-file collection for source: {}, target: {}, time range: {} - {}, WAL "
1091        + "backup dir: {}, restore root: {}",
1092      sourceTable, targetTable, startTime, endTime, walDirs, restoreRootDir);
1093    String walDirsCsv = String.join(",", walDirs);
1094
1095    return BulkFilesCollector.collectFromWalDirs(HBaseConfiguration.create(conn.getConfiguration()),
1096      walDirsCsv, restoreRootDir, sourceTable, targetTable, startTime, endTime);
1097  }
1098
1099  /**
1100   * Fetches valid WAL directories based on the given time range.
1101   */
1102  public static List<String> getValidWalDirs(Configuration conf, Path walBackupDir, long startTime,
1103    long endTime) throws IOException {
1104    FileSystem backupFs = FileSystem.get(walBackupDir.toUri(), conf);
1105    FileStatus[] dayDirs = backupFs.listStatus(new Path(walBackupDir, WALS_DIR));
1106
1107    List<String> validDirs = new ArrayList<>();
1108    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
1109    dateFormat.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
1110
1111    for (FileStatus dayDir : dayDirs) {
1112      if (!dayDir.isDirectory()) {
1113        continue; // Skip files, only process directories
1114      }
1115
1116      String dirName = dayDir.getPath().getName();
1117      try {
1118        Date dirDate = dateFormat.parse(dirName);
1119        long dirStartTime = dirDate.getTime(); // Start of that day (00:00:00)
1120        long dirEndTime = dirStartTime + ONE_DAY_IN_MILLISECONDS - 1; // End time of day (23:59:59)
1121
1122        // Check if this day's WAL files overlap with the required time range
1123        if (dirEndTime >= startTime && dirStartTime <= endTime) {
1124          validDirs.add(dayDir.getPath().toString());
1125        }
1126      } catch (ParseException e) {
1127        LOG.warn("Skipping invalid directory name: {}", dirName, e);
1128      }
1129    }
1130    return validDirs;
1131  }
1132}