1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.snapshot;
19
20 import static org.junit.Assert.assertEquals;
21 import static org.junit.Assert.assertFalse;
22 import static org.junit.Assert.assertTrue;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.HashSet;
31 import java.util.TreeSet;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.hadoop.fs.FileStatus;
36 import org.apache.hadoop.fs.FileSystem;
37 import org.apache.hadoop.fs.Path;
38 import org.apache.hadoop.fs.PathFilter;
39 import org.apache.hadoop.hbase.HBaseTestingUtility;
40 import org.apache.hadoop.hbase.HColumnDescriptor;
41 import org.apache.hadoop.hbase.HConstants;
42 import org.apache.hadoop.hbase.HRegionInfo;
43 import org.apache.hadoop.hbase.HTableDescriptor;
44 import org.apache.hadoop.hbase.TableName;
45 import org.apache.hadoop.hbase.TableNotEnabledException;
46 import org.apache.hadoop.hbase.client.Durability;
47 import org.apache.hadoop.hbase.client.HBaseAdmin;
48 import org.apache.hadoop.hbase.client.HTable;
49 import org.apache.hadoop.hbase.client.Put;
50 import org.apache.hadoop.hbase.io.HFileLink;
51 import org.apache.hadoop.hbase.master.HMaster;
52 import org.apache.hadoop.hbase.master.MasterFileSystem;
53 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
54 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
55 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
56 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
57 import org.apache.hadoop.hbase.regionserver.HRegion;
58 import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
59 import org.apache.hadoop.hbase.regionserver.HRegionServer;
60 import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
61 import org.apache.hadoop.hbase.util.Bytes;
62 import org.apache.hadoop.hbase.util.FSTableDescriptors;
63 import org.apache.hadoop.hbase.util.FSUtils;
64 import org.apache.hadoop.hbase.util.FSVisitor;
65 import org.apache.hadoop.hbase.util.MD5Hash;
66 import org.junit.Assert;
67
68 import com.google.protobuf.ServiceException;
69
70
71
72
73 public class SnapshotTestingUtils {
74
75 private static final Log LOG = LogFactory.getLog(SnapshotTestingUtils.class);
76 private static byte[] KEYS = Bytes.toBytes("0123456789");
77
78
79
80
81
82
83
84 public static void assertNoSnapshots(HBaseAdmin admin) throws IOException {
85 assertEquals("Have some previous snapshots", 0, admin.listSnapshots()
86 .size());
87 }
88
89
90
91
92
93 public static List<SnapshotDescription> assertExistsMatchingSnapshot(
94 HBaseAdmin admin, String snapshotName, TableName tableName)
95 throws IOException {
96
97 List<SnapshotDescription> snapshots = admin.listSnapshots();
98
99 List<SnapshotDescription> returnedSnapshots = new ArrayList<SnapshotDescription>();
100 for (SnapshotDescription sd : snapshots) {
101 if (snapshotName.equals(sd.getName()) &&
102 tableName.equals(TableName.valueOf(sd.getTable()))) {
103 returnedSnapshots.add(sd);
104 }
105 }
106
107 Assert.assertTrue("No matching snapshots found.", returnedSnapshots.size()>0);
108 return returnedSnapshots;
109 }
110
111
112
113
114 public static void assertOneSnapshotThatMatches(HBaseAdmin admin,
115 SnapshotDescription snapshot) throws IOException {
116 assertOneSnapshotThatMatches(admin, snapshot.getName(),
117 TableName.valueOf(snapshot.getTable()));
118 }
119
120
121
122
123
124 public static List<SnapshotDescription> assertOneSnapshotThatMatches(
125 HBaseAdmin admin, String snapshotName, TableName tableName)
126 throws IOException {
127
128 List<SnapshotDescription> snapshots = admin.listSnapshots();
129
130 assertEquals("Should only have 1 snapshot", 1, snapshots.size());
131 assertEquals(snapshotName, snapshots.get(0).getName());
132 assertEquals(tableName, TableName.valueOf(snapshots.get(0).getTable()));
133
134 return snapshots;
135 }
136
137
138
139
140
141 public static List<SnapshotDescription> assertOneSnapshotThatMatches(
142 HBaseAdmin admin, byte[] snapshot, TableName tableName) throws IOException {
143 return assertOneSnapshotThatMatches(admin, Bytes.toString(snapshot),
144 tableName);
145 }
146
147
148
149
150
151 public static void confirmSnapshotValid(
152 SnapshotDescription snapshotDescriptor, TableName tableName,
153 byte[] testFamily, Path rootDir, HBaseAdmin admin, FileSystem fs,
154 boolean requireLogs, Path logsDir, Set<String> snapshotServers)
155 throws IOException {
156 ArrayList nonEmptyTestFamilies = new ArrayList(1);
157 nonEmptyTestFamilies.add(testFamily);
158 confirmSnapshotValid(snapshotDescriptor, tableName,
159 nonEmptyTestFamilies, null, rootDir, admin, fs, requireLogs,
160 logsDir, snapshotServers);
161 }
162
163
164
165
166 public static void confirmEmptySnapshotValid(
167 SnapshotDescription snapshotDescriptor, TableName tableName,
168 byte[] testFamily, Path rootDir, HBaseAdmin admin, FileSystem fs,
169 boolean requireLogs, Path logsDir, Set<String> snapshotServers)
170 throws IOException {
171 ArrayList emptyTestFamilies = new ArrayList(1);
172 emptyTestFamilies.add(testFamily);
173 confirmSnapshotValid(snapshotDescriptor, tableName,
174 null, emptyTestFamilies, rootDir, admin, fs, requireLogs,
175 logsDir, snapshotServers);
176 }
177
178
179
180
181
182
183
184 public static void confirmSnapshotValid(
185 SnapshotDescription snapshotDescriptor, TableName tableName,
186 List<byte[]> nonEmptyTestFamilies, List<byte[]> emptyTestFamilies,
187 Path rootDir, HBaseAdmin admin, FileSystem fs, boolean requireLogs,
188 Path logsDir, Set<String> snapshotServers) throws IOException {
189
190 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(
191 snapshotDescriptor, rootDir);
192 assertTrue(fs.exists(snapshotDir));
193
194
195 Path snapshotinfo = new Path(snapshotDir, SnapshotDescriptionUtils.SNAPSHOTINFO_FILE);
196 assertTrue(fs.exists(snapshotinfo));
197
198
199 if (requireLogs) {
200 TakeSnapshotUtils.verifyAllLogsGotReferenced(fs, logsDir,
201 snapshotServers, snapshotDescriptor, new Path(snapshotDir,
202 HConstants.HREGION_LOGDIR_NAME));
203 }
204
205
206 HTableDescriptor desc = FSTableDescriptors.getTableDescriptorFromFs(fs, rootDir, tableName);
207 HTableDescriptor snapshotDesc = FSTableDescriptors.getTableDescriptorFromFs(fs, snapshotDir);
208 assertEquals(desc, snapshotDesc);
209
210
211 final Set<String> snapshotRegions = new HashSet<String>();
212 final Set<byte[]> snapshotFamilies = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
213 FSVisitor.visitRegions(fs, snapshotDir, new FSVisitor.RegionVisitor() {
214 @Override
215 public void region(String region) throws IOException {
216 snapshotRegions.add(region);
217 }
218 });
219 FSVisitor.visitTableStoreFiles(fs, snapshotDir, new FSVisitor.StoreFileVisitor() {
220 @Override
221 public void storeFile(final String region, final String family, final String hfileName)
222 throws IOException {
223 snapshotFamilies.add(Bytes.toBytes(family));
224 }
225 });
226
227
228 if (nonEmptyTestFamilies != null) {
229 for (final byte[] familyName: nonEmptyTestFamilies) {
230 assertTrue(snapshotFamilies.contains(familyName));
231 }
232 }
233
234
235 if (emptyTestFamilies != null) {
236 for (final byte[] familyName: emptyTestFamilies) {
237 assertFalse(snapshotFamilies.contains(familyName));
238 }
239 }
240
241
242 List<HRegionInfo> regions = admin.getTableRegions(tableName);
243 assertEquals(regions.size(), snapshotRegions.size());
244
245
246 for (HRegionInfo info : regions) {
247 String regionName = info.getEncodedName();
248 assertTrue(snapshotRegions.contains(regionName));
249
250 Path regionDir = new Path(snapshotDir, regionName);
251 HRegionInfo snapshotRegionInfo = HRegionFileSystem.loadRegionInfoFileContent(fs, regionDir);
252 assertEquals(info, snapshotRegionInfo);
253 }
254 }
255
256
257
258
259
260
261
262
263
264
265 public static void waitForSnapshotToComplete(HMaster master,
266 SnapshotDescription snapshot, long sleep) throws ServiceException {
267 final IsSnapshotDoneRequest request = IsSnapshotDoneRequest.newBuilder()
268 .setSnapshot(snapshot).build();
269 IsSnapshotDoneResponse done = IsSnapshotDoneResponse.newBuilder()
270 .buildPartial();
271 while (!done.getDone()) {
272 done = master.isSnapshotDone(null, request);
273 try {
274 Thread.sleep(sleep);
275 } catch (InterruptedException e) {
276 throw new ServiceException(e);
277 }
278 }
279 }
280
281
282
283
284
285 public static void snapshot(HBaseAdmin admin,
286 final String snapshotName, final String tableName,
287 SnapshotDescription.Type type, int numTries) throws IOException {
288 int tries = 0;
289 CorruptedSnapshotException lastEx = null;
290 while (tries++ < numTries) {
291 try {
292 admin.snapshot(snapshotName, tableName, type);
293 return;
294 } catch (CorruptedSnapshotException cse) {
295 LOG.warn("Got CorruptedSnapshotException", cse);
296 lastEx = cse;
297 }
298 }
299 throw lastEx;
300 }
301
302 public static void cleanupSnapshot(HBaseAdmin admin, byte[] tableName)
303 throws IOException {
304 SnapshotTestingUtils.cleanupSnapshot(admin, Bytes.toString(tableName));
305 }
306
307 public static void cleanupSnapshot(HBaseAdmin admin, String snapshotName)
308 throws IOException {
309
310 admin.deleteSnapshot(snapshotName);
311 assertNoSnapshots(admin);
312 }
313
314
315
316
317
318
319
320
321
322 public static void expectSnapshotDoneException(HMaster master,
323 IsSnapshotDoneRequest snapshot,
324 Class<? extends HBaseSnapshotException> clazz) {
325 try {
326 master.isSnapshotDone(null, snapshot);
327 Assert.fail("didn't fail to lookup a snapshot");
328 } catch (ServiceException se) {
329 try {
330 throw ProtobufUtil.getRemoteException(se);
331 } catch (HBaseSnapshotException e) {
332 assertEquals("Threw wrong snapshot exception!", clazz, e.getClass());
333 } catch (Throwable t) {
334 Assert.fail("Threw an unexpected exception:" + t);
335 }
336 }
337 }
338
339
340
341
342
343
344
345
346
347 public static Path[] listHFiles(final FileSystem fs, final Path tableDir)
348 throws IOException {
349 final ArrayList<Path> hfiles = new ArrayList<Path>();
350 FSVisitor.visitTableStoreFiles(fs, tableDir, new FSVisitor.StoreFileVisitor() {
351 @Override
352 public void storeFile(final String region, final String family, final String hfileName)
353 throws IOException {
354 hfiles.add(new Path(tableDir, new Path(region, new Path(family, hfileName))));
355 }
356 });
357 return hfiles.toArray(new Path[hfiles.size()]);
358 }
359
360
361
362
363
364
365 public static void createSnapshotAndValidate(HBaseAdmin admin,
366 TableName tableName, String familyName, String snapshotNameString,
367 Path rootDir, FileSystem fs, boolean onlineSnapshot)
368 throws Exception {
369 ArrayList<byte[]> nonEmptyFamilyNames = new ArrayList<byte[]>(1);
370 nonEmptyFamilyNames.add(Bytes.toBytes(familyName));
371 createSnapshotAndValidate(admin, tableName, nonEmptyFamilyNames,
372 snapshotNameString, rootDir, fs, onlineSnapshot);
373 }
374
375
376
377
378
379 public static void createSnapshotAndValidate(HBaseAdmin admin,
380 TableName tableName, List<byte[]> nonEmptyFamilyNames, List<byte[]> emptyFamilyNames,
381 String snapshotNameString, Path rootDir, FileSystem fs, boolean onlineSnapshot)
382 throws Exception {
383 if (!onlineSnapshot) {
384 try {
385 admin.disableTable(tableName);
386 } catch (TableNotEnabledException tne) {
387 LOG.info("In attempting to disable " + tableName + " it turns out that the this table is " +
388 "already disabled.");
389 }
390 }
391 admin.snapshot(snapshotNameString, tableName);
392
393 List<SnapshotDescription> snapshots = SnapshotTestingUtils.assertExistsMatchingSnapshot(admin,
394 snapshotNameString, tableName);
395 if (snapshots == null || snapshots.size() != 1) {
396 Assert.fail("Incorrect number of snapshots for table " + tableName);
397 }
398
399 SnapshotTestingUtils.confirmSnapshotValid(snapshots.get(0), tableName, nonEmptyFamilyNames,
400 emptyFamilyNames, rootDir, admin, fs, false,
401 new Path(rootDir, HConstants.HREGION_LOGDIR_NAME), null);
402 }
403
404
405
406
407
408
409
410
411
412 public static ArrayList corruptSnapshot(final HBaseTestingUtility util, final String snapshotName)
413 throws IOException {
414 final MasterFileSystem mfs = util.getHBaseCluster().getMaster().getMasterFileSystem();
415 final FileSystem fs = mfs.getFileSystem();
416
417 Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName,
418 mfs.getRootDir());
419 SnapshotDescription snapshotDesc = SnapshotDescriptionUtils.readSnapshotInfo(fs, snapshotDir);
420 final TableName table = TableName.valueOf(snapshotDesc.getTable());
421
422 final ArrayList corruptedFiles = new ArrayList();
423 SnapshotReferenceUtil.visitTableStoreFiles(fs, snapshotDir, new FSVisitor.StoreFileVisitor() {
424 @Override
425 public void storeFile (final String region, final String family, final String hfile)
426 throws IOException {
427 HFileLink link = HFileLink.create(util.getConfiguration(), table, region, family, hfile);
428 if (corruptedFiles.size() % 2 == 0) {
429 fs.delete(link.getAvailablePath(fs));
430 corruptedFiles.add(hfile);
431 }
432 }
433 });
434
435 assertTrue(corruptedFiles.size() > 0);
436 return corruptedFiles;
437 }
438
439
440
441
442 public static void waitForTableToBeOnline(final HBaseTestingUtility util,
443 final TableName tableName)
444 throws IOException, InterruptedException {
445 HRegionServer rs = util.getRSForFirstRegionInTable(tableName);
446 List<HRegion> onlineRegions = rs.getOnlineRegions(tableName);
447 for (HRegion region : onlineRegions) {
448 region.waitForFlushesAndCompactions();
449 }
450 util.getHBaseAdmin().isTableAvailable(tableName);
451 }
452
453 public static void createTable(final HBaseTestingUtility util, final TableName tableName,
454 final byte[]... families) throws IOException, InterruptedException {
455 HTableDescriptor htd = new HTableDescriptor(tableName);
456 for (byte[] family: families) {
457 HColumnDescriptor hcd = new HColumnDescriptor(family);
458 htd.addFamily(hcd);
459 }
460 byte[][] splitKeys = new byte[KEYS.length-2][];
461 for (int i = 0; i < splitKeys.length; ++i) {
462 splitKeys[i] = new byte[] { KEYS[i+1] };
463 }
464 util.getHBaseAdmin().createTable(htd, splitKeys);
465 waitForTableToBeOnline(util, tableName);
466 assertEquals(KEYS.length-1, util.getHBaseAdmin().getTableRegions(tableName).size());
467 }
468
469 public static void loadData(final HBaseTestingUtility util, final TableName tableName, int rows,
470 byte[]... families) throws IOException, InterruptedException {
471 loadData(util, new HTable(util.getConfiguration(), tableName), rows, families);
472 }
473
474 public static void loadData(final HBaseTestingUtility util, final HTable table, int rows,
475 byte[]... families) throws IOException, InterruptedException {
476 table.setAutoFlush(false, true);
477
478
479 assertTrue(rows >= KEYS.length);
480 for (byte k0: KEYS) {
481 byte[] k = new byte[] { k0 };
482 byte[] value = Bytes.add(Bytes.toBytes(System.currentTimeMillis()), k);
483 byte[] key = Bytes.add(k, Bytes.toBytes(MD5Hash.getMD5AsHex(value)));
484 putData(table, families, key, value);
485 rows--;
486 }
487
488
489 while (rows-- > 0) {
490 byte[] value = Bytes.add(Bytes.toBytes(System.currentTimeMillis()), Bytes.toBytes(rows));
491 byte[] key = Bytes.toBytes(MD5Hash.getMD5AsHex(value));
492 putData(table, families, key, value);
493 }
494 table.flushCommits();
495
496 waitForTableToBeOnline(util, table.getName());
497 }
498
499 private static void putData(final HTable table, final byte[][] families,
500 final byte[] key, final byte[] value) throws IOException {
501 byte[] q = Bytes.toBytes("q");
502 Put put = new Put(key);
503 put.setDurability(Durability.SKIP_WAL);
504 for (byte[] family: families) {
505 put.add(family, q, value);
506 }
507 table.put(put);
508 }
509
510 public static void deleteAllSnapshots(final HBaseAdmin admin)
511 throws IOException {
512
513 for (SnapshotDescription snapshot: admin.listSnapshots()) {
514 admin.deleteSnapshot(snapshot.getName());
515 }
516 SnapshotTestingUtils.assertNoSnapshots(admin);
517 }
518
519 public static void deleteArchiveDirectory(final HBaseTestingUtility util)
520 throws IOException {
521
522 MasterFileSystem mfs = util.getMiniHBaseCluster().getMaster().getMasterFileSystem();
523 Path archiveDir = new Path(mfs.getRootDir(), HConstants.HFILE_ARCHIVE_DIRECTORY);
524 mfs.getFileSystem().delete(archiveDir, true);
525 }
526
527 public static void verifyRowCount(final HBaseTestingUtility util, final TableName tableName,
528 long expectedRows) throws IOException {
529 HTable table = new HTable(util.getConfiguration(), tableName);
530 try {
531 assertEquals(expectedRows, util.countRows(table));
532 } finally {
533 table.close();
534 }
535 }
536 }