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.impl;
019
020import static org.apache.hadoop.hbase.backup.BackupInfo.withState;
021
022import java.io.IOException;
023import java.util.ArrayList;
024import java.util.Collections;
025import java.util.HashSet;
026import java.util.List;
027import java.util.Map;
028import java.util.Objects;
029import java.util.Set;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.fs.FileStatus;
032import org.apache.hadoop.fs.FileSystem;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.TableName;
035import org.apache.hadoop.hbase.backup.BackupInfo;
036import org.apache.hadoop.hbase.backup.BackupInfo.BackupPhase;
037import org.apache.hadoop.hbase.backup.BackupInfo.BackupState;
038import org.apache.hadoop.hbase.backup.BackupRequest;
039import org.apache.hadoop.hbase.backup.BackupRestoreConstants;
040import org.apache.hadoop.hbase.backup.BackupType;
041import org.apache.hadoop.hbase.backup.HBackupFileSystem;
042import org.apache.hadoop.hbase.backup.impl.BackupManifest.BackupImage;
043import org.apache.hadoop.hbase.client.Admin;
044import org.apache.hadoop.hbase.client.Connection;
045import org.apache.hadoop.hbase.util.CommonFSUtils;
046import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
047import org.apache.yetus.audience.InterfaceAudience;
048import org.slf4j.Logger;
049import org.slf4j.LoggerFactory;
050
051/**
052 * Base class for backup operation. Concrete implementation for full and incremental backup are
053 * delegated to corresponding sub-classes: {@link FullTableBackupClient} and
054 * {@link IncrementalTableBackupClient}
055 */
056@InterfaceAudience.Private
057public abstract class TableBackupClient {
058
059  public static final String BACKUP_CLIENT_IMPL_CLASS = "backup.client.impl.class";
060
061  public static final String BACKUP_TEST_MODE_STAGE = "backup.test.mode.stage";
062
063  private static final Logger LOG = LoggerFactory.getLogger(TableBackupClient.class);
064
065  protected Configuration conf;
066  protected Connection conn;
067  protected String backupId;
068  protected List<TableName> tableList;
069  protected Map<String, Long> newTimestamps = null;
070
071  protected BackupManager backupManager;
072  protected BackupInfo backupInfo;
073  protected FileSystem fs;
074
075  public TableBackupClient() {
076  }
077
078  public TableBackupClient(final Connection conn, final String backupId, BackupRequest request)
079    throws IOException {
080    init(conn, backupId, request);
081  }
082
083  public void init(final Connection conn, final String backupId, BackupRequest request)
084    throws IOException {
085    if (request.getBackupType() == BackupType.FULL) {
086      backupManager = new BackupManager(conn, conn.getConfiguration());
087    } else {
088      backupManager = new IncrementalBackupManager(conn, conn.getConfiguration());
089    }
090    this.backupId = backupId;
091    this.tableList = request.getTableList();
092    this.conn = conn;
093    this.conf = conn.getConfiguration();
094    this.fs = CommonFSUtils.getCurrentFileSystem(conf);
095    backupInfo = backupManager.createBackupInfo(backupId, request.getBackupType(), tableList,
096      request.getTargetRootDir(), request.getTotalTasks(), request.getBandwidth(),
097      request.getNoChecksumVerify(), request.isContinuousBackupEnabled());
098    if (tableList == null || tableList.isEmpty()) {
099      this.tableList = new ArrayList<>(backupInfo.getTables());
100    }
101    // Start new session
102    backupManager.startBackupSession();
103  }
104
105  /**
106   * Begin the overall backup.
107   * @param backupInfo backup info
108   * @throws IOException exception
109   */
110  protected void beginBackup(BackupManager backupManager, BackupInfo backupInfo)
111    throws IOException {
112
113    BackupSystemTable.snapshot(conn);
114    backupManager.setBackupInfo(backupInfo);
115    // set the start timestamp of the overall backup
116    long startTs = EnvironmentEdgeManager.currentTime();
117    backupInfo.setStartTs(startTs);
118    // set overall backup status: ongoing
119    backupInfo.setState(BackupState.RUNNING);
120    backupInfo.setPhase(BackupPhase.REQUEST);
121    LOG.info("Backup " + backupInfo.getBackupId() + " started at " + startTs + ".");
122
123    backupManager.updateBackupInfo(backupInfo);
124    if (LOG.isDebugEnabled()) {
125      LOG.debug("Backup session " + backupInfo.getBackupId() + " has been started.");
126    }
127  }
128
129  protected String getMessage(Exception e) {
130    String msg = e.getMessage();
131    if (msg == null || msg.equals("")) {
132      msg = e.getClass().getName();
133    }
134    return msg;
135  }
136
137  /**
138   * Delete HBase snapshot for backup.
139   * @param backupInfo backup info
140   * @throws IOException exception
141   */
142  protected static void deleteSnapshots(final Connection conn, BackupInfo backupInfo,
143    Configuration conf) throws IOException {
144    LOG.debug("Trying to delete snapshot for full backup.");
145    for (String snapshotName : backupInfo.getSnapshotNames()) {
146      if (snapshotName == null) {
147        continue;
148      }
149      LOG.debug("Trying to delete snapshot: " + snapshotName);
150
151      try (Admin admin = conn.getAdmin()) {
152        admin.deleteSnapshot(snapshotName);
153      }
154      LOG.debug("Deleting the snapshot " + snapshotName + " for backup " + backupInfo.getBackupId()
155        + " succeeded.");
156    }
157  }
158
159  /**
160   * Clean up directories with prefix "exportSnapshot-", which are generated when exporting
161   * snapshots.
162   * @throws IOException exception
163   */
164  protected static void cleanupExportSnapshotLog(Configuration conf) throws IOException {
165    FileSystem fs = CommonFSUtils.getCurrentFileSystem(conf);
166    Path stagingDir = new Path(
167      conf.get(BackupRestoreConstants.CONF_STAGING_ROOT, fs.getWorkingDirectory().toString()));
168    FileStatus[] files = CommonFSUtils.listStatus(fs, stagingDir);
169    if (files == null) {
170      return;
171    }
172    for (FileStatus file : files) {
173      if (file.getPath().getName().startsWith("exportSnapshot-")) {
174        LOG.debug("Delete log files of exporting snapshot: " + file.getPath().getName());
175        if (CommonFSUtils.delete(fs, file.getPath(), true) == false) {
176          LOG.warn("Can not delete " + file.getPath());
177        }
178      }
179    }
180  }
181
182  /**
183   * Clean up the uncompleted data at target directory if the ongoing backup has already entered the
184   * copy phase.
185   */
186  protected static void cleanupTargetDir(BackupInfo backupInfo, Configuration conf) {
187    try {
188      // clean up the uncompleted data at target directory if the ongoing backup has already entered
189      // the copy phase
190      LOG.debug("Trying to cleanup up target dir. Current backup phase: " + backupInfo.getPhase());
191      if (
192        backupInfo.getPhase().equals(BackupPhase.SNAPSHOTCOPY)
193          || backupInfo.getPhase().equals(BackupPhase.INCREMENTAL_COPY)
194          || backupInfo.getPhase().equals(BackupPhase.STORE_MANIFEST)
195      ) {
196        FileSystem outputFs = FileSystem.get(new Path(backupInfo.getBackupRootDir()).toUri(), conf);
197
198        // now treat one backup as a transaction, clean up data that has been partially copied at
199        // table level
200        for (TableName table : backupInfo.getTables()) {
201          Path targetDirPath = new Path(HBackupFileSystem
202            .getTableBackupDir(backupInfo.getBackupRootDir(), backupInfo.getBackupId(), table));
203          if (outputFs.delete(targetDirPath, true)) {
204            LOG.debug(
205              "Cleaning up uncompleted backup data at " + targetDirPath.toString() + " done.");
206          } else {
207            LOG.debug("No data has been copied to " + targetDirPath.toString() + ".");
208          }
209
210          Path tableDir = targetDirPath.getParent();
211          FileStatus[] backups = CommonFSUtils.listStatus(outputFs, tableDir);
212          if (backups == null || backups.length == 0) {
213            outputFs.delete(tableDir, true);
214            LOG.debug(tableDir.toString() + " is empty, remove it.");
215          }
216        }
217      }
218
219    } catch (IOException e1) {
220      LOG.error("Cleaning up uncompleted backup data of " + backupInfo.getBackupId() + " at "
221        + backupInfo.getBackupRootDir() + " failed due to " + e1.getMessage() + ".");
222    }
223  }
224
225  /**
226   * Fail the overall backup.
227   * @param backupInfo backup info
228   * @param e          exception
229   * @throws IOException exception
230   */
231  protected void failBackup(Connection conn, BackupInfo backupInfo, BackupManager backupManager,
232    Exception e, String msg, BackupType type, Configuration conf) throws IOException {
233    try {
234      LOG.error(msg + getMessage(e), e);
235      // If this is a cancel exception, then we've already cleaned.
236      // set the failure timestamp of the overall backup
237      backupInfo.setCompleteTs(EnvironmentEdgeManager.currentTime());
238      // set failure message
239      backupInfo.setFailedMsg(e.getMessage());
240      // set overall backup status: failed
241      backupInfo.setState(BackupState.FAILED);
242      // compose the backup failed data
243      String backupFailedData = "BackupId=" + backupInfo.getBackupId() + ",startts="
244        + backupInfo.getStartTs() + ",failedts=" + backupInfo.getCompleteTs() + ",failedphase="
245        + backupInfo.getPhase() + ",failedmessage=" + backupInfo.getFailedMsg();
246      LOG.error(backupFailedData);
247      cleanupAndRestoreBackupSystem(conn, backupInfo, conf);
248      // If backup session is updated to FAILED state - means we
249      // processed recovery already.
250      backupManager.updateBackupInfo(backupInfo);
251      backupManager.finishBackupSession();
252      LOG.error("Backup " + backupInfo.getBackupId() + " failed.");
253    } catch (IOException ee) {
254      LOG.error("Please run backup repair tool manually to restore backup system integrity");
255      throw ee;
256    }
257  }
258
259  public static void cleanupAndRestoreBackupSystem(Connection conn, BackupInfo backupInfo,
260    Configuration conf) throws IOException {
261    // The .backup.complete marker should not exist for a failed backup, but remove it in case it
262    // does. This must happen before any destructive recovery step: restoring the backup system
263    // table from its snapshot removes the RUNNING backup record. If the marker cannot be removed,
264    // fail here while the RUNNING record, the system table snapshot, the backup data, and the
265    // exclusive lock are all still intact. Later, a "backup repair" can find and retry this backup.
266    HBackupFileSystem.deleteBackupCompleteMarker(conf, backupInfo.getBackupRootDir(),
267      backupInfo.getBackupId());
268
269    BackupType type = backupInfo.getType();
270    // if full backup, then delete HBase snapshots if there already are snapshots taken
271    // and also clean up export snapshot log files if exist
272    if (type == BackupType.FULL) {
273      deleteSnapshots(conn, backupInfo, conf);
274      cleanupExportSnapshotLog(conf);
275    }
276    BackupSystemTable.restoreFromSnapshot(conn);
277    BackupSystemTable.deleteSnapshot(conn);
278    // clean up the uncompleted data at target directory if the ongoing backup has already entered
279    // the copy phase
280    // For incremental backup, DistCp logs will be cleaned with the targetDir.
281    cleanupTargetDir(backupInfo, conf);
282  }
283
284  /**
285   * Creates a manifest based on the provided info, and store it in the backup-specific directory.
286   * @param backupInfo The current backup info
287   * @throws IOException exception
288   */
289  protected void addManifest(BackupInfo backupInfo, BackupType type, Configuration conf)
290    throws IOException {
291    // set the overall backup phase : store manifest
292    backupInfo.setPhase(BackupPhase.STORE_MANIFEST);
293
294    BackupManifest manifest = new BackupManifest(backupInfo);
295    if (type == BackupType.INCREMENTAL) {
296      // set the table region server start and end timestamps for incremental backup
297      manifest.setIncrTimestampMap(backupInfo.getIncrTimestampMap());
298    }
299    List<BackupImage> ancestors = getAncestors(backupInfo);
300    for (BackupImage image : ancestors) {
301      manifest.addDependentImage(image);
302    }
303    manifest.store(conf);
304  }
305
306  /**
307   * Gets the direct ancestors of the currently being created backup.
308   * @param backupInfo The backup info for the backup being created
309   */
310  protected List<BackupImage> getAncestors(BackupInfo backupInfo) throws IOException {
311    LOG.debug("Getting the direct ancestors of the current backup {}", backupInfo.getBackupId());
312
313    // Full backups do not have ancestors
314    if (backupInfo.getType() == BackupType.FULL) {
315      LOG.debug("Current backup is a full backup, no direct ancestor for it.");
316      return Collections.emptyList();
317    }
318
319    List<BackupImage> ancestors = new ArrayList<>();
320    Set<TableName> tablesToCover = new HashSet<>(backupInfo.getTables());
321
322    // Go over the backup history list from newest to oldest
323    List<BackupInfo> allHistoryList =
324      backupManager.getBackupHistory(withState(BackupState.COMPLETE));
325    for (BackupInfo backup : allHistoryList) {
326      // If the image has a different rootDir, it cannot be an ancestor.
327      if (!Objects.equals(backup.getBackupRootDir(), backupInfo.getBackupRootDir())) {
328        continue;
329      }
330
331      BackupImage.Builder builder = BackupImage.newBuilder();
332      BackupImage image = builder.withBackupId(backup.getBackupId()).withType(backup.getType())
333        .withRootDir(backup.getBackupRootDir()).withTableList(backup.getTableNames())
334        .withStartTime(backup.getStartTs()).withCompleteTime(backup.getCompleteTs()).build();
335
336      // The ancestors consist of the most recent FULL backups that cover the list of tables
337      // required in the new backup and all INCREMENTAL backups that came after one of those FULL
338      // backups.
339      if (backup.getType().equals(BackupType.INCREMENTAL)) {
340        ancestors.add(image);
341        LOG.debug("Dependent incremental backup image: {BackupID={}}", image.getBackupId());
342      } else {
343        if (tablesToCover.removeAll(new HashSet<>(image.getTableNames()))) {
344          ancestors.add(image);
345          LOG.debug("Dependent full backup image: {BackupID={}}", image.getBackupId());
346
347          if (tablesToCover.isEmpty()) {
348            LOG.debug("Got {} ancestors for the current backup.", ancestors.size());
349            return Collections.unmodifiableList(ancestors);
350          }
351        }
352      }
353    }
354
355    throw new IllegalStateException(
356      "Unable to find full backup that contains tables: " + tablesToCover);
357  }
358
359  /**
360   * Get backup request meta data dir as string.
361   * @param backupInfo backup info
362   * @return meta data dir
363   */
364  protected String obtainBackupMetaDataStr(BackupInfo backupInfo) {
365    StringBuilder sb = new StringBuilder();
366    sb.append("type=" + backupInfo.getType() + ",tablelist=");
367    for (TableName table : backupInfo.getTables()) {
368      sb.append(table + ";");
369    }
370    if (sb.lastIndexOf(";") > 0) {
371      sb.delete(sb.lastIndexOf(";"), sb.lastIndexOf(";") + 1);
372    }
373    sb.append(",targetRootDir=" + backupInfo.getBackupRootDir());
374
375    return sb.toString();
376  }
377
378  /**
379   * Complete the overall backup.
380   * @param backupInfo backup info
381   * @throws IOException exception
382   */
383  protected void completeBackup(final Connection conn, BackupInfo backupInfo, BackupType type,
384    Configuration conf) throws IOException {
385    // set the complete timestamp of the overall backup
386    backupInfo.setCompleteTs(EnvironmentEdgeManager.currentTime());
387    // set overall backup status: complete
388    backupInfo.setState(BackupState.COMPLETE);
389    backupInfo.setProgress(100);
390    // add and store the manifest for the backup
391    addManifest(backupInfo, type, conf);
392
393    // compose the backup complete data
394    String backupCompleteData =
395      obtainBackupMetaDataStr(backupInfo) + ",startts=" + backupInfo.getStartTs() + ",completets="
396        + backupInfo.getCompleteTs() + ",bytescopied=" + backupInfo.getTotalBytesCopied();
397    if (LOG.isDebugEnabled()) {
398      LOG.debug("Backup " + backupInfo.getBackupId() + " finished: " + backupCompleteData);
399    }
400
401    // when full backup is done:
402    // - delete HBase snapshot
403    // - clean up directories with prefix "exportSnapshot-", which are generated when exporting
404    // snapshots
405    // incremental backups use distcp, which handles cleaning up its own directories
406    if (type == BackupType.FULL) {
407      deleteSnapshots(conn, backupInfo, conf);
408      cleanupExportSnapshotLog(conf);
409    }
410    BackupSystemTable.deleteSnapshot(conn);
411    backupManager.updateBackupInfo(backupInfo);
412
413    // Write the completion marker while still holding the exclusive lock, so a concurrent delete or
414    // merge cannot run before the marker is written and leave a stale marker behind
415    HBackupFileSystem.writeBackupCompleteMarker(conf, backupInfo.getBackupRootDir(),
416      backupInfo.getBackupId());
417
418    // Finish active session
419    backupManager.finishBackupSession();
420
421    LOG.info("Backup " + backupInfo.getBackupId() + " completed.");
422  }
423
424  /**
425   * Backup request execution.
426   * @throws IOException if the execution of the backup fails
427   */
428  public abstract void execute() throws IOException;
429
430  protected Stage getTestStage() {
431    return Stage.valueOf("stage_" + conf.getInt(BACKUP_TEST_MODE_STAGE, 0));
432  }
433
434  protected void failStageIf(Stage stage) throws IOException {
435    Stage current = getTestStage();
436    if (current == stage) {
437      throw new IOException("Failed stage " + stage + " in testing");
438    }
439  }
440
441  public enum Stage {
442    stage_0,
443    stage_1,
444    stage_2,
445    stage_3,
446    stage_4
447  }
448}