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.mapreduce;
019
020import static org.apache.hadoop.hbase.backup.util.BackupUtils.succeeded;
021
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.util.ArrayDeque;
026import java.util.ArrayList;
027import java.util.Deque;
028import java.util.HashSet;
029import java.util.List;
030import java.util.Set;
031import org.apache.commons.io.IOUtils;
032import org.apache.commons.lang3.StringUtils;
033import org.apache.hadoop.conf.Configuration;
034import org.apache.hadoop.fs.FileStatus;
035import org.apache.hadoop.fs.FileSystem;
036import org.apache.hadoop.fs.LocatedFileStatus;
037import org.apache.hadoop.fs.Path;
038import org.apache.hadoop.fs.RemoteIterator;
039import org.apache.hadoop.hbase.TableName;
040import org.apache.hadoop.hbase.backup.BackupInfo;
041import org.apache.hadoop.hbase.backup.BackupMergeJob;
042import org.apache.hadoop.hbase.backup.HBackupFileSystem;
043import org.apache.hadoop.hbase.backup.impl.BackupManifest;
044import org.apache.hadoop.hbase.backup.impl.BackupSystemTable;
045import org.apache.hadoop.hbase.backup.util.BackupUtils;
046import org.apache.hadoop.hbase.client.Connection;
047import org.apache.hadoop.hbase.client.ConnectionFactory;
048import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
049import org.apache.hadoop.hbase.util.FSTableDescriptors;
050import org.apache.hadoop.hbase.util.Pair;
051import org.apache.hadoop.util.Tool;
052import org.apache.yetus.audience.InterfaceAudience;
053import org.slf4j.Logger;
054import org.slf4j.LoggerFactory;
055
056/**
057 * MapReduce implementation of {@link BackupMergeJob} Must be initialized with configuration of a
058 * backup destination cluster
059 */
060@InterfaceAudience.Private
061public class MapReduceBackupMergeJob implements BackupMergeJob {
062  public static final Logger LOG = LoggerFactory.getLogger(MapReduceBackupMergeJob.class);
063
064  protected Tool player;
065  protected Configuration conf;
066
067  public MapReduceBackupMergeJob() {
068  }
069
070  @Override
071  public Configuration getConf() {
072    return conf;
073  }
074
075  @Override
076  public void setConf(Configuration conf) {
077    this.conf = conf;
078  }
079
080  @Override
081  public void run(String[] backupIds) throws IOException {
082    String bulkOutputConfKey;
083
084    // TODO : run player on remote cluster
085    player = new MapReduceHFileSplitterJob();
086    bulkOutputConfKey = MapReduceHFileSplitterJob.BULK_OUTPUT_CONF_KEY;
087    // Player reads all files in arbitrary directory structure and creates
088    // a Map task for each file
089    String bids = StringUtils.join(backupIds, ",");
090
091    if (LOG.isDebugEnabled()) {
092      LOG.debug("Merge backup images " + bids);
093    }
094
095    List<Pair<TableName, Path>> processedTableList = new ArrayList<>();
096    boolean finishedTables = false;
097    Connection conn = ConnectionFactory.createConnection(getConf());
098    BackupSystemTable table = new BackupSystemTable(conn);
099    FileSystem fs = null;
100
101    try {
102
103      // Get exclusive lock on backup system
104      table.startBackupExclusiveOperation();
105      // Start merge operation
106      table.startMergeOperation(backupIds);
107
108      // Select most recent backup id
109      String mergedBackupId = BackupUtils.findMostRecentBackupId(backupIds);
110
111      TableName[] tableNames = getTableNamesInBackupImages(backupIds);
112
113      BackupInfo bInfo = table.readBackupInfo(backupIds[0]);
114      String backupRoot = bInfo.getBackupRootDir();
115      Path backupRootPath = new Path(backupRoot);
116      fs = backupRootPath.getFileSystem(conf);
117
118      for (int i = 0; i < tableNames.length; i++) {
119        LOG.info("Merge backup images for " + tableNames[i]);
120
121        // Find input directories for table
122        Path[] dirPaths = findInputDirectories(fs, backupRoot, tableNames[i], backupIds);
123        String dirs = StringUtils.join(dirPaths, ",");
124
125        // bulkOutputPath should be on the same filesystem as backupRoot
126        Path tmpRestoreOutputDir = HBackupFileSystem.getBackupTmpDirPath(backupRoot);
127        Path bulkOutputPath = BackupUtils.getBulkOutputDir(tmpRestoreOutputDir,
128          BackupUtils.getFileNameCompatibleString(tableNames[i]), getConf(), false);
129        // Delete content if exists
130        if (fs.exists(bulkOutputPath)) {
131          if (!fs.delete(bulkOutputPath, true)) {
132            LOG.warn("Can not delete: " + bulkOutputPath);
133          }
134        }
135        Configuration conf = getConf();
136        conf.set(bulkOutputConfKey, bulkOutputPath.toString());
137        String[] playerArgs = { dirs, tableNames[i].getNameAsString() };
138
139        player.setConf(getConf());
140        int result = player.run(playerArgs);
141        if (!succeeded(result)) {
142          throw new IOException("Can not merge backup images for " + dirs
143            + " (check Hadoop/MR and HBase logs). Player return code =" + result);
144        }
145        // Add to processed table list
146        processedTableList.add(new Pair<>(tableNames[i], bulkOutputPath));
147        LOG.debug("Merge Job finished:" + result);
148      }
149      List<TableName> tableList = toTableNameList(processedTableList);
150      table.updateProcessedTablesForMerge(tableList);
151      finishedTables = true;
152
153      // PHASE 2 (modification of a backup file system)
154      // Move existing mergedBackupId data into tmp directory
155      // we will need it later in case of a failure
156      Path tmpBackupDir =
157        HBackupFileSystem.getBackupTmpDirPathForBackupId(backupRoot, mergedBackupId);
158      Path backupDirPath = HBackupFileSystem.getBackupPath(backupRoot, mergedBackupId);
159
160      if (!fs.rename(backupDirPath, tmpBackupDir)) {
161        throw new IOException("Failed to rename " + backupDirPath + " to " + tmpBackupDir);
162      } else {
163        LOG.debug("Renamed " + backupDirPath + " to " + tmpBackupDir);
164      }
165      // Move new data into backup dest
166      for (Pair<TableName, Path> tn : processedTableList) {
167        moveData(fs, backupRoot, tn.getSecond(), tn.getFirst(), mergedBackupId);
168      }
169      // Update backup manifest
170      List<String> backupsToDelete = getBackupIdsToDelete(backupIds, mergedBackupId);
171      updateBackupManifest(tmpBackupDir.getParent().toString(), mergedBackupId, backupsToDelete);
172      // Copy meta files back from tmp to the backup dir
173      copyMetaData(fs, tmpBackupDir, backupDirPath);
174      // Delete tmp dir (Rename back during repair)
175      if (!fs.delete(tmpBackupDir, true)) {
176        // WARN and ignore
177        LOG.warn("Could not delete tmp dir: " + tmpBackupDir);
178      }
179      // Delete old data
180      deleteBackupImages(backupsToDelete, conn, fs, backupRoot);
181      // Finish merge session
182      table.finishMergeOperation();
183      // Write the completion marker after the merge is finalized so external consumers never
184      // observe it on a partially-merged backup. The completion marker is written before the lock
185      // is released so a concurrent delete or merge cannot run before the marker is written and
186      // leave a stale marker behind.
187      HBackupFileSystem.writeBackupCompleteMarker(conf, backupRoot, mergedBackupId);
188      // Release lock
189      table.finishBackupExclusiveOperation();
190    } catch (RuntimeException e) {
191
192      throw e;
193    } catch (Exception e) {
194      LOG.error(e.toString(), e);
195      if (!finishedTables) {
196        // cleanup bulk directories and finish merge
197        // merge MUST be repeated (no need for repair)
198        if (fs != null) {
199          cleanupBulkLoadDirs(fs, toPathList(processedTableList));
200        }
201        table.finishMergeOperation();
202        table.finishBackupExclusiveOperation();
203        throw new IOException("Backup merge operation failed, you should try it again", e);
204      } else {
205        // backup repair must be run
206        throw new IOException(
207          "Backup merge operation failed, run backup repair tool to restore system's integrity", e);
208      }
209    } finally {
210      table.close();
211      conn.close();
212    }
213  }
214
215  /**
216   * Copy metadata of a backup session
217   * @param fs            file system
218   * @param tmpBackupDir  temp backup directory, where meta is located
219   * @param backupDirPath new path for backup
220   * @throws IOException exception
221   */
222  protected void copyMetaData(FileSystem fs, Path tmpBackupDir, Path backupDirPath)
223    throws IOException {
224    RemoteIterator<LocatedFileStatus> it = fs.listFiles(tmpBackupDir, true);
225    List<Path> toKeep = new ArrayList<Path>();
226    while (it.hasNext()) {
227      Path p = it.next().getPath();
228      if (fs.isDirectory(p)) {
229        continue;
230      }
231      // Keep meta
232      String fullPath = p.toString();
233      String baseName = p.getName();
234      // TABLEINFO_DIR is a directory that might have a name like ".tableinfo.0000000001.367", so
235      // we can't rely on an exact match. The other constants are files with those exact names, so
236      // an exact match is preferred.
237      if (
238        fullPath.indexOf(FSTableDescriptors.TABLEINFO_DIR) > 0
239          || HRegionFileSystem.REGION_INFO_FILE.equals(baseName)
240          || BackupManifest.MANIFEST_FILE_NAME.equals(baseName)
241      ) {
242        toKeep.add(p);
243      }
244    }
245    // Copy meta to destination
246    for (Path p : toKeep) {
247      Path newPath = convertToDest(p, backupDirPath);
248      LOG.info("Copying tmp metadata from {} to {}", p, newPath);
249      copyFile(fs, p, newPath);
250    }
251  }
252
253  /**
254   * Copy file in DFS from p to newPath
255   * @param fs      file system
256   * @param p       old path
257   * @param newPath new path
258   * @throws IOException exception
259   */
260  protected void copyFile(FileSystem fs, Path p, Path newPath) throws IOException {
261    try (InputStream in = fs.open(p); OutputStream out = fs.create(newPath, true)) {
262      IOUtils.copy(in, out);
263    }
264    boolean exists = fs.exists(newPath);
265    if (!exists) {
266      throw new IOException("Failed to copy meta file to: " + newPath);
267    }
268  }
269
270  /**
271   * Converts path before copying
272   * @param p             path
273   * @param backupDirPath backup root
274   * @return converted path
275   */
276  protected Path convertToDest(Path p, Path backupDirPath) {
277    String backupId = backupDirPath.getName();
278    Deque<String> stack = new ArrayDeque<String>();
279    String name = null;
280    while (true) {
281      name = p.getName();
282      if (!name.equals(backupId)) {
283        stack.push(name);
284        p = p.getParent();
285      } else {
286        break;
287      }
288    }
289    Path newPath = new Path(backupDirPath.toString());
290    while (!stack.isEmpty()) {
291      newPath = new Path(newPath, stack.pop());
292    }
293    return newPath;
294  }
295
296  protected List<Path> toPathList(List<Pair<TableName, Path>> processedTableList) {
297    ArrayList<Path> list = new ArrayList<>();
298    for (Pair<TableName, Path> p : processedTableList) {
299      list.add(p.getSecond());
300    }
301    return list;
302  }
303
304  protected List<TableName> toTableNameList(List<Pair<TableName, Path>> processedTableList) {
305    ArrayList<TableName> list = new ArrayList<>();
306    for (Pair<TableName, Path> p : processedTableList) {
307      list.add(p.getFirst());
308    }
309    return list;
310  }
311
312  protected void cleanupBulkLoadDirs(FileSystem fs, List<Path> pathList) throws IOException {
313    for (Path path : pathList) {
314      if (!fs.delete(path, true)) {
315        LOG.warn("Can't delete " + path);
316      }
317    }
318  }
319
320  protected void updateBackupManifest(String backupRoot, String mergedBackupId,
321    List<String> backupsToDelete) throws IllegalArgumentException, IOException {
322    BackupManifest manifest =
323      HBackupFileSystem.getManifest(conf, new Path(backupRoot), mergedBackupId);
324    LOG.info("Removing ancestors from merged backup {} : {}", mergedBackupId, backupsToDelete);
325    manifest.getBackupImage().removeAncestors(backupsToDelete);
326    // save back
327    LOG.info("Creating new manifest file for merged backup {} at root {}", mergedBackupId,
328      backupRoot);
329    manifest.store(conf);
330  }
331
332  protected void deleteBackupImages(List<String> backupIds, Connection conn, FileSystem fs,
333    String backupRoot) throws IOException {
334    // Delete completion markers first, so a merged-away backup never keeps a marker if its
335    // directory delete below fails
336    for (String backupId : backupIds) {
337      HBackupFileSystem.deleteBackupCompleteMarker(conf, backupRoot, backupId);
338    }
339
340    // Delete from backup system table
341    try (BackupSystemTable table = new BackupSystemTable(conn)) {
342      for (String backupId : backupIds) {
343        LOG.info("Removing metadata for backup {}", backupId);
344        table.deleteBackupInfo(backupId);
345      }
346    }
347
348    // Delete from file system
349    for (String backupId : backupIds) {
350      LOG.info("Purging backup {} from FileSystem", backupId);
351      Path backupDirPath = HBackupFileSystem.getBackupPath(backupRoot, backupId);
352
353      if (!fs.delete(backupDirPath, true)) {
354        LOG.warn("Could not delete {}", backupDirPath);
355      }
356    }
357  }
358
359  protected List<String> getBackupIdsToDelete(String[] backupIds, String mergedBackupId) {
360    List<String> list = new ArrayList<>();
361    for (String id : backupIds) {
362      if (id.equals(mergedBackupId)) {
363        continue;
364      }
365      list.add(id);
366    }
367    return list;
368  }
369
370  protected void moveData(FileSystem fs, String backupRoot, Path bulkOutputPath,
371    TableName tableName, String mergedBackupId) throws IllegalArgumentException, IOException {
372    Path dest =
373      new Path(HBackupFileSystem.getTableBackupDir(backupRoot, mergedBackupId, tableName));
374
375    FileStatus[] fsts = fs.listStatus(bulkOutputPath);
376    for (FileStatus fst : fsts) {
377      if (fst.isDirectory()) {
378        String family = fst.getPath().getName();
379        Path newDst = new Path(dest, family);
380        if (fs.exists(newDst)) {
381          if (!fs.delete(newDst, true)) {
382            throw new IOException("failed to delete :" + newDst);
383          }
384        } else {
385          fs.mkdirs(dest);
386        }
387        boolean result = fs.rename(fst.getPath(), dest);
388        LOG.debug("MoveData from " + fst.getPath() + " to " + dest + " result=" + result);
389      }
390    }
391  }
392
393  protected TableName[] getTableNamesInBackupImages(String[] backupIds) throws IOException {
394    Set<TableName> allSet = new HashSet<>();
395
396    try (Connection conn = ConnectionFactory.createConnection(conf);
397      BackupSystemTable table = new BackupSystemTable(conn)) {
398      for (String backupId : backupIds) {
399        BackupInfo bInfo = table.readBackupInfo(backupId);
400
401        allSet.addAll(bInfo.getTableNames());
402      }
403    }
404
405    TableName[] ret = new TableName[allSet.size()];
406    return allSet.toArray(ret);
407  }
408
409  protected Path[] findInputDirectories(FileSystem fs, String backupRoot, TableName tableName,
410    String[] backupIds) throws IOException {
411    List<Path> dirs = new ArrayList<>();
412
413    for (String backupId : backupIds) {
414      Path fileBackupDirPath =
415        new Path(HBackupFileSystem.getTableBackupDir(backupRoot, backupId, tableName));
416      if (fs.exists(fileBackupDirPath)) {
417        dirs.add(fileBackupDirPath);
418      } else {
419        if (LOG.isDebugEnabled()) {
420          LOG.debug("File: " + fileBackupDirPath + " does not exist.");
421        }
422      }
423    }
424    Path[] ret = new Path[dirs.size()];
425    return dirs.toArray(ret);
426  }
427}