View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.snapshot;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertTrue;
23  
24  import java.io.IOException;
25  import java.net.URI;
26  import java.util.ArrayList;
27  import java.util.Arrays;
28  import java.util.HashSet;
29  import java.util.List;
30  import java.util.Set;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.fs.FSDataOutputStream;
36  import org.apache.hadoop.fs.FileStatus;
37  import org.apache.hadoop.fs.FileSystem;
38  import org.apache.hadoop.fs.FileUtil;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.HBaseTestingUtility;
41  import org.apache.hadoop.hbase.HColumnDescriptor;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.HRegionInfo;
44  import org.apache.hadoop.hbase.HTableDescriptor;
45  import org.apache.hadoop.hbase.MediumTests;
46  import org.apache.hadoop.hbase.TableName;
47  import org.apache.hadoop.hbase.client.HBaseAdmin;
48  import org.apache.hadoop.hbase.client.HTable;
49  import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
50  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
51  import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
52  import org.apache.hadoop.hbase.util.Bytes;
53  import org.apache.hadoop.hbase.util.FSUtils;
54  import org.apache.hadoop.hbase.util.Pair;
55  import org.junit.After;
56  import org.junit.AfterClass;
57  import org.junit.Before;
58  import org.junit.BeforeClass;
59  import org.junit.Test;
60  import org.junit.experimental.categories.Category;
61  
62  /**
63   * Test Export Snapshot Tool
64   */
65  @Category(MediumTests.class)
66  public class TestExportSnapshot {
67    private final Log LOG = LogFactory.getLog(getClass());
68  
69    protected final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
70  
71    private final static byte[] FAMILY = Bytes.toBytes("cf");
72  
73    private byte[] emptySnapshotName;
74    private byte[] snapshotName;
75    private TableName tableName;
76    private HBaseAdmin admin;
77  
78    public static void setUpBaseConf(Configuration conf) {
79      conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
80      conf.setInt("hbase.regionserver.msginterval", 100);
81      conf.setInt("hbase.client.pause", 250);
82      conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6);
83      conf.setBoolean("hbase.master.enabletable.roundrobin", true);
84      conf.setInt("mapreduce.map.max.attempts", 10);
85      conf.setInt("mapred.map.max.attempts", 10);
86    }
87  
88    @BeforeClass
89    public static void setUpBeforeClass() throws Exception {
90      setUpBaseConf(TEST_UTIL.getConfiguration());
91      TEST_UTIL.startMiniCluster(3);
92      TEST_UTIL.startMiniMapReduceCluster();
93    }
94  
95    @AfterClass
96    public static void tearDownAfterClass() throws Exception {
97      TEST_UTIL.shutdownMiniMapReduceCluster();
98      TEST_UTIL.shutdownMiniCluster();
99    }
100 
101   /**
102    * Create a table and take a snapshot of the table used by the export test.
103    */
104   @Before
105   public void setUp() throws Exception {
106     this.admin = TEST_UTIL.getHBaseAdmin();
107 
108     long tid = System.currentTimeMillis();
109     tableName = TableName.valueOf("testtb-" + tid);
110     snapshotName = Bytes.toBytes("snaptb0-" + tid);
111     emptySnapshotName = Bytes.toBytes("emptySnaptb0-" + tid);
112 
113     // create Table
114     SnapshotTestingUtils.createTable(TEST_UTIL, tableName, FAMILY);
115 
116     // Take an empty snapshot
117     admin.snapshot(emptySnapshotName, tableName);
118 
119     // Add some rows
120     HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);
121     SnapshotTestingUtils.loadData(TEST_UTIL, tableName, 1000, FAMILY);
122 
123     // take a snapshot
124     admin.snapshot(snapshotName, tableName);
125   }
126 
127   @After
128   public void tearDown() throws Exception {
129     TEST_UTIL.deleteTable(tableName);
130     SnapshotTestingUtils.deleteAllSnapshots(TEST_UTIL.getHBaseAdmin());
131     SnapshotTestingUtils.deleteArchiveDirectory(TEST_UTIL);
132   }
133 
134 
135   /**
136    * Verfy the result of getBalanceSplits() method.
137    * The result are groups of files, used as input list for the "export" mappers.
138    * All the groups should have similar amount of data.
139    *
140    * The input list is a pair of file path and length.
141    * The getBalanceSplits() function sort it by length,
142    * and assign to each group a file, going back and forth through the groups.
143    */
144   @Test
145   public void testBalanceSplit() throws Exception {
146     // Create a list of files
147     List<Pair<Path, Long>> files = new ArrayList<Pair<Path, Long>>();
148     for (long i = 0; i <= 20; i++) {
149       files.add(new Pair<Path, Long>(new Path("file-" + i), i));
150     }
151 
152     // Create 5 groups (total size 210)
153     //    group 0: 20, 11, 10,  1 (total size: 42)
154     //    group 1: 19, 12,  9,  2 (total size: 42)
155     //    group 2: 18, 13,  8,  3 (total size: 42)
156     //    group 3: 17, 12,  7,  4 (total size: 42)
157     //    group 4: 16, 11,  6,  5 (total size: 42)
158     List<List<Path>> splits = ExportSnapshot.getBalancedSplits(files, 5);
159     assertEquals(5, splits.size());
160     assertEquals(Arrays.asList(new Path("file-20"), new Path("file-11"),
161       new Path("file-10"), new Path("file-1"), new Path("file-0")), splits.get(0));
162     assertEquals(Arrays.asList(new Path("file-19"), new Path("file-12"),
163       new Path("file-9"), new Path("file-2")), splits.get(1));
164     assertEquals(Arrays.asList(new Path("file-18"), new Path("file-13"),
165       new Path("file-8"), new Path("file-3")), splits.get(2));
166     assertEquals(Arrays.asList(new Path("file-17"), new Path("file-14"),
167       new Path("file-7"), new Path("file-4")), splits.get(3));
168     assertEquals(Arrays.asList(new Path("file-16"), new Path("file-15"),
169       new Path("file-6"), new Path("file-5")), splits.get(4));
170   }
171 
172   /**
173    * Verify if exported snapshot and copied files matches the original one.
174    */
175   @Test
176   public void testExportFileSystemState() throws Exception {
177     testExportFileSystemState(tableName, snapshotName, 2);
178   }
179 
180   @Test
181   public void testEmptyExportFileSystemState() throws Exception {
182     testExportFileSystemState(tableName, emptySnapshotName, 1);
183   }
184 
185   @Test
186   public void testConsecutiveExports() throws Exception {
187     Path copyDir = getLocalDestinationDir();
188     testExportFileSystemState(tableName, snapshotName, 2, copyDir, false);
189     testExportFileSystemState(tableName, snapshotName, 2, copyDir, true);
190     removeExportDir(copyDir);
191   }
192 
193   /**
194    * Mock a snapshot with files in the archive dir,
195    * two regions, and one reference file.
196    */
197   @Test
198   public void testSnapshotWithRefsExportFileSystemState() throws Exception {
199     Configuration conf = TEST_UTIL.getConfiguration();
200 
201     final TableName tableWithRefsName =
202         TableName.valueOf("tableWithRefs");
203     final String snapshotName = "tableWithRefs";
204     final String TEST_FAMILY = Bytes.toString(FAMILY);
205     final String TEST_HFILE = "abc";
206 
207     final SnapshotDescription sd = SnapshotDescription.newBuilder()
208         .setName(snapshotName)
209         .setTable(tableWithRefsName.getNameAsString()).build();
210 
211     FileSystem fs = TEST_UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem();
212     Path rootDir = TEST_UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
213     Path archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
214 
215     // First region, simple with one plain hfile.
216     HRegionInfo hri = new HRegionInfo(tableWithRefsName);
217     HRegionFileSystem r0fs = HRegionFileSystem.createRegionOnFileSystem(conf,
218       fs, FSUtils.getTableDir(archiveDir, hri.getTable()), hri);
219     Path storeFile = new Path(rootDir, TEST_HFILE);
220     FSDataOutputStream out = fs.create(storeFile);
221     out.write(Bytes.toBytes("Test Data"));
222     out.close();
223     r0fs.commitStoreFile(TEST_FAMILY, storeFile);
224 
225     // Second region, used to test the split case.
226     // This region contains a reference to the hfile in the first region.
227     hri = new HRegionInfo(tableWithRefsName);
228     HRegionFileSystem r1fs = HRegionFileSystem.createRegionOnFileSystem(conf,
229       fs, new Path(archiveDir, hri.getTable().getNameAsString()), hri);
230     storeFile = new Path(rootDir, TEST_HFILE + '.' + r0fs.getRegionInfo().getEncodedName());
231     out = fs.create(storeFile);
232     out.write(Bytes.toBytes("Test Data"));
233     out.close();
234     r1fs.commitStoreFile(TEST_FAMILY, storeFile);
235 
236     Path tableDir = FSUtils.getTableDir(archiveDir, tableWithRefsName);
237     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
238     FileUtil.copy(fs, tableDir, fs, snapshotDir, false, conf);
239     SnapshotDescriptionUtils.writeSnapshotInfo(sd, snapshotDir, fs);
240 
241     testExportFileSystemState(tableWithRefsName, Bytes.toBytes(snapshotName), 2);
242   }
243 
244   private void testExportFileSystemState(final TableName tableName, final byte[] snapshotName,
245       int filesExpected) throws Exception {
246     Path copyDir = getHdfsDestinationDir();
247     testExportFileSystemState(tableName, snapshotName, filesExpected, copyDir, false);
248     removeExportDir(copyDir);
249   }
250 
251   /**
252    * Test ExportSnapshot
253    */
254   private void testExportFileSystemState(final TableName tableName, final byte[] snapshotName,
255       int filesExpected, Path copyDir, boolean overwrite) throws Exception {
256     URI hdfsUri = FileSystem.get(TEST_UTIL.getConfiguration()).getUri();
257     FileSystem fs = FileSystem.get(copyDir.toUri(), new Configuration());
258     copyDir = copyDir.makeQualified(fs);
259 
260     List<String> opts = new ArrayList<String>();
261     opts.add("-snapshot");
262     opts.add(Bytes.toString(snapshotName));
263     opts.add("-copy-to");
264     opts.add(copyDir.toString());
265     if (overwrite) opts.add("-overwrite");
266 
267     // Export Snapshot
268     int res = ExportSnapshot.innerMain(TEST_UTIL.getConfiguration(),
269         opts.toArray(new String[opts.size()]));
270     assertEquals(0, res);
271 
272     // Verify File-System state
273     FileStatus[] rootFiles = fs.listStatus(copyDir);
274     assertEquals(filesExpected, rootFiles.length);
275     for (FileStatus fileStatus: rootFiles) {
276       String name = fileStatus.getPath().getName();
277       assertTrue(fileStatus.isDir());
278       assertTrue(name.equals(HConstants.SNAPSHOT_DIR_NAME) ||
279                  name.equals(HConstants.HFILE_ARCHIVE_DIRECTORY));
280     }
281 
282     // compare the snapshot metadata and verify the hfiles
283     final FileSystem hdfs = FileSystem.get(hdfsUri, TEST_UTIL.getConfiguration());
284     final Path snapshotDir = new Path(HConstants.SNAPSHOT_DIR_NAME, Bytes.toString(snapshotName));
285     verifySnapshot(hdfs, new Path(TEST_UTIL.getDefaultRootDirPath(), snapshotDir),
286         fs, new Path(copyDir, snapshotDir));
287     verifyArchive(fs, copyDir, tableName, Bytes.toString(snapshotName));
288     FSUtils.logFileSystemState(hdfs, snapshotDir, LOG);
289   }
290 
291   /**
292    * Check that ExportSnapshot will return a failure if something fails.
293    */
294   @Test
295   public void testExportFailure() throws Exception {
296     assertEquals(1, runExportAndInjectFailures(snapshotName, false));
297   }
298 
299   /**
300    * Check that ExportSnapshot will succede if something fails but the retry succede.
301    */
302   @Test
303   public void testExportRetry() throws Exception {
304     assertEquals(0, runExportAndInjectFailures(snapshotName, true));
305   }
306 
307   /*
308    * Execute the ExportSnapshot job injecting failures
309    */
310   private int runExportAndInjectFailures(final byte[] snapshotName, boolean retry)
311       throws Exception {
312     Path copyDir = getLocalDestinationDir();
313     URI hdfsUri = FileSystem.get(TEST_UTIL.getConfiguration()).getUri();
314     FileSystem fs = FileSystem.get(copyDir.toUri(), new Configuration());
315     copyDir = copyDir.makeQualified(fs);
316 
317     Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
318     conf.setBoolean(ExportSnapshot.CONF_TEST_FAILURE, true);
319     conf.setBoolean(ExportSnapshot.CONF_TEST_RETRY, retry);
320 
321     // Export Snapshot
322     int res = ExportSnapshot.innerMain(conf, new String[] {
323       "-snapshot", Bytes.toString(snapshotName),
324       "-copy-to", copyDir.toString()
325     });
326     return res;
327   }
328 
329   /*
330    * verify if the snapshot folder on file-system 1 match the one on file-system 2
331    */
332   private void verifySnapshot(final FileSystem fs1, final Path root1,
333       final FileSystem fs2, final Path root2) throws IOException {
334     Set<String> s = new HashSet<String>();
335     assertEquals(listFiles(fs1, root1, root1), listFiles(fs2, root2, root2));
336   }
337 
338   /*
339    * Verify if the files exists
340    */
341   private void verifyArchive(final FileSystem fs, final Path rootDir,
342       final TableName tableName, final String snapshotName) throws IOException {
343     final Path exportedSnapshot = new Path(rootDir,
344       new Path(HConstants.SNAPSHOT_DIR_NAME, snapshotName));
345     final Path exportedArchive = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
346     LOG.debug(listFiles(fs, exportedArchive, exportedArchive));
347     SnapshotReferenceUtil.visitReferencedFiles(fs, exportedSnapshot,
348         new SnapshotReferenceUtil.FileVisitor() {
349         public void storeFile (final String region, final String family, final String hfile)
350             throws IOException {
351           verifyNonEmptyFile(new Path(exportedArchive,
352             new Path(FSUtils.getTableDir(new Path("./"), tableName),
353                 new Path(region, new Path(family, hfile)))));
354         }
355 
356         public void recoveredEdits (final String region, final String logfile)
357             throws IOException {
358           verifyNonEmptyFile(new Path(exportedSnapshot,
359             new Path(tableName.getNameAsString(), new Path(region, logfile))));
360         }
361 
362         public void logFile (final String server, final String logfile)
363             throws IOException {
364           verifyNonEmptyFile(new Path(exportedSnapshot, new Path(server, logfile)));
365         }
366 
367         private void verifyNonEmptyFile(final Path path) throws IOException {
368           assertTrue(path + " should exists", fs.exists(path));
369           assertTrue(path + " should not be empty", fs.getFileStatus(path).getLen() > 0);
370         }
371     });
372   }
373 
374   private Set<String> listFiles(final FileSystem fs, final Path root, final Path dir)
375       throws IOException {
376     Set<String> files = new HashSet<String>();
377     int rootPrefix = root.toString().length();
378     FileStatus[] list = FSUtils.listStatus(fs, dir);
379     if (list != null) {
380       for (FileStatus fstat: list) {
381         LOG.debug(fstat.getPath());
382         if (fstat.isDir()) {
383           files.addAll(listFiles(fs, root, fstat.getPath()));
384         } else {
385           files.add(fstat.getPath().toString().substring(rootPrefix));
386         }
387       }
388     }
389     return files;
390   }
391 
392   private Path getHdfsDestinationDir() {
393     Path rootDir = TEST_UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
394     Path path = new Path(new Path(rootDir, "export-test"), "export-" + System.currentTimeMillis());
395     LOG.info("HDFS export destination path: " + path);
396     return path;
397   }
398 
399   private Path getLocalDestinationDir() {
400     Path path = TEST_UTIL.getDataTestDir("local-export-" + System.currentTimeMillis());
401     LOG.info("Local export destination path: " + path);
402     return path;
403   }
404 
405   private void removeExportDir(final Path path) throws IOException {
406     FileSystem fs = FileSystem.get(path.toUri(), new Configuration());
407     FSUtils.logFileSystemState(fs, path, LOG);
408     fs.delete(path, true);
409   }
410 }