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  package org.apache.hadoop.hbase.master.cleaner;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertFalse;
22  import static org.junit.Assert.assertTrue;
23  import static org.junit.Assert.fail;
24  
25  import java.io.IOException;
26  import java.util.Collection;
27  import java.util.List;
28  import java.util.Set;
29  import java.util.regex.Pattern;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.fs.FileSystem;
35  import org.apache.hadoop.fs.Path;
36  import org.apache.hadoop.hbase.HBaseTestingUtility;
37  import org.apache.hadoop.hbase.HConstants;
38  import org.apache.hadoop.hbase.HTableDescriptor;
39  import org.apache.hadoop.hbase.Waiter.Predicate;
40  import org.apache.hadoop.hbase.client.Put;
41  import org.apache.hadoop.hbase.client.Table;
42  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
43  import org.apache.hadoop.hbase.testclassification.MediumTests;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.client.Admin;
46  import org.apache.hadoop.hbase.master.HMaster;
47  import org.apache.hadoop.hbase.master.snapshot.DisabledTableSnapshotHandler;
48  import org.apache.hadoop.hbase.master.snapshot.SnapshotHFileCleaner;
49  import org.apache.hadoop.hbase.master.snapshot.SnapshotManager;
50  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.DeleteSnapshotRequest;
51  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsRequest;
52  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
53  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneRequest;
54  import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.IsSnapshotDoneResponse;
55  import org.apache.hadoop.hbase.regionserver.CompactedHFilesDischarger;
56  import org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy;
57  import org.apache.hadoop.hbase.regionserver.HRegion;
58  import org.apache.hadoop.hbase.regionserver.HRegionServer;
59  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
60  import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
61  import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils;
62  import org.apache.hadoop.hbase.snapshot.UnknownSnapshotException;
63  import org.apache.hadoop.hbase.util.Bytes;
64  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
65  import org.apache.hadoop.hbase.util.FSUtils;
66  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
67  import org.junit.After;
68  import org.junit.AfterClass;
69  import org.junit.Before;
70  import org.junit.BeforeClass;
71  import org.junit.Test;
72  import org.junit.experimental.categories.Category;
73  import org.mockito.Mockito;
74  
75  import com.google.common.collect.Lists;
76  import com.google.protobuf.ServiceException;
77  
78  /**
79   * Test the master-related aspects of a snapshot
80   */
81  @Category(MediumTests.class)
82  public class TestSnapshotFromMaster {
83  
84    private static final Log LOG = LogFactory.getLog(TestSnapshotFromMaster.class);
85    private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
86    private static final int NUM_RS = 2;
87    private static Path rootDir;
88    private static FileSystem fs;
89    private static HMaster master;
90  
91    // for hfile archiving test.
92    private static Path archiveDir;
93    private static final byte[] TEST_FAM = Bytes.toBytes("fam");
94    private static final TableName TABLE_NAME =
95        TableName.valueOf("test");
96    // refresh the cache every 1/2 second
97    private static final long cacheRefreshPeriod = 500;
98  
99    /**
100    * Setup the config for the cluster
101    */
102   @BeforeClass
103   public static void setupCluster() throws Exception {
104     setupConf(UTIL.getConfiguration());
105     UTIL.startMiniCluster(NUM_RS);
106     fs = UTIL.getDFSCluster().getFileSystem();
107     master = UTIL.getMiniHBaseCluster().getMaster();
108     rootDir = master.getMasterFileSystem().getRootDir();
109     archiveDir = new Path(rootDir, HConstants.HFILE_ARCHIVE_DIRECTORY);
110   }
111 
112   private static void setupConf(Configuration conf) {
113     // disable the ui
114     conf.setInt("hbase.regionsever.info.port", -1);
115     // change the flush size to a small amount, regulating number of store files
116     conf.setInt("hbase.hregion.memstore.flush.size", 25000);
117     // so make sure we get a compaction when doing a load, but keep around some
118     // files in the store
119     conf.setInt("hbase.hstore.compaction.min", 2);
120     conf.setInt("hbase.hstore.compactionThreshold", 5);
121     // block writes if we get to 12 store files
122     conf.setInt("hbase.hstore.blockingStoreFiles", 12);
123     // Ensure no extra cleaners on by default (e.g. TimeToLiveHFileCleaner)
124     conf.set(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, "");
125     conf.set(HConstants.HBASE_MASTER_LOGCLEANER_PLUGINS, "");
126     // Enable snapshot
127     conf.setBoolean(SnapshotManager.HBASE_SNAPSHOT_ENABLED, true);
128     conf.setLong(SnapshotManager.HBASE_SNAPSHOT_SENTINELS_CLEANUP_TIMEOUT_MILLIS, 3 * 1000L);
129     conf.setLong(SnapshotHFileCleaner.HFILE_CACHE_REFRESH_PERIOD_CONF_KEY, cacheRefreshPeriod);
130     conf.set(HConstants.HBASE_REGION_SPLIT_POLICY_KEY,
131       ConstantSizeRegionSplitPolicy.class.getName());
132     conf.setInt("hbase.hfile.compactions.cleaner.interval", 20 * 1000);
133   }
134 
135   @Before
136   public void setup() throws Exception {
137     UTIL.createTable(TABLE_NAME, TEST_FAM);
138     master.getSnapshotManager().setSnapshotHandlerForTesting(TABLE_NAME, null);
139   }
140 
141   @After
142   public void tearDown() throws Exception {
143     UTIL.deleteTable(TABLE_NAME);
144     SnapshotTestingUtils.deleteAllSnapshots(UTIL.getHBaseAdmin());
145     SnapshotTestingUtils.deleteArchiveDirectory(UTIL);
146   }
147 
148   @AfterClass
149   public static void cleanupTest() throws Exception {
150     try {
151       UTIL.shutdownMiniCluster();
152     } catch (Exception e) {
153       // NOOP;
154     }
155   }
156 
157   /**
158    * Test that the contract from the master for checking on a snapshot are valid.
159    * <p>
160    * <ol>
161    * <li>If a snapshot fails with an error, we expect to get the source error.</li>
162    * <li>If there is no snapshot name supplied, we should get an error.</li>
163    * <li>If asking about a snapshot has hasn't occurred, you should get an error.</li>
164    * </ol>
165    */
166   @Test(timeout = 300000)
167   public void testIsDoneContract() throws Exception {
168 
169     IsSnapshotDoneRequest.Builder builder = IsSnapshotDoneRequest.newBuilder();
170 
171     String snapshotName = "asyncExpectedFailureTest";
172 
173     // check that we get an exception when looking up snapshot where one hasn't happened
174     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
175       UnknownSnapshotException.class);
176 
177     // and that we get the same issue, even if we specify a name
178     SnapshotDescription desc = SnapshotDescription.newBuilder()
179       .setName(snapshotName).setTable(TABLE_NAME.getNameAsString()).build();
180     builder.setSnapshot(desc);
181     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
182       UnknownSnapshotException.class);
183 
184     // set a mock handler to simulate a snapshot
185     DisabledTableSnapshotHandler mockHandler = Mockito.mock(DisabledTableSnapshotHandler.class);
186     Mockito.when(mockHandler.getException()).thenReturn(null);
187     Mockito.when(mockHandler.getSnapshot()).thenReturn(desc);
188     Mockito.when(mockHandler.isFinished()).thenReturn(new Boolean(true));
189     Mockito.when(mockHandler.getCompletionTimestamp())
190       .thenReturn(EnvironmentEdgeManager.currentTime());
191 
192     master.getSnapshotManager()
193         .setSnapshotHandlerForTesting(TABLE_NAME, mockHandler);
194 
195     // if we do a lookup without a snapshot name, we should fail - you should always know your name
196     builder = IsSnapshotDoneRequest.newBuilder();
197     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
198       UnknownSnapshotException.class);
199 
200     // then do the lookup for the snapshot that it is done
201     builder.setSnapshot(desc);
202     IsSnapshotDoneResponse response =
203       master.getMasterRpcServices().isSnapshotDone(null, builder.build());
204     assertTrue("Snapshot didn't complete when it should have.", response.getDone());
205 
206     // now try the case where we are looking for a snapshot we didn't take
207     builder.setSnapshot(SnapshotDescription.newBuilder().setName("Not A Snapshot").build());
208     SnapshotTestingUtils.expectSnapshotDoneException(master, builder.build(),
209       UnknownSnapshotException.class);
210 
211     // then create a snapshot to the fs and make sure that we can find it when checking done
212     snapshotName = "completed";
213     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
214     desc = desc.toBuilder().setName(snapshotName).build();
215     SnapshotDescriptionUtils.writeSnapshotInfo(desc, snapshotDir, fs);
216 
217     builder.setSnapshot(desc);
218     response = master.getMasterRpcServices().isSnapshotDone(null, builder.build());
219     assertTrue("Completed, on-disk snapshot not found", response.getDone());
220   }
221 
222   @Test(timeout = 300000)
223   public void testGetCompletedSnapshots() throws Exception {
224     // first check when there are no snapshots
225     GetCompletedSnapshotsRequest request = GetCompletedSnapshotsRequest.newBuilder().build();
226     GetCompletedSnapshotsResponse response =
227       master.getMasterRpcServices().getCompletedSnapshots(null, request);
228     assertEquals("Found unexpected number of snapshots", 0, response.getSnapshotsCount());
229 
230     // write one snapshot to the fs
231     String snapshotName = "completed";
232     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
233     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
234     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
235 
236     // check that we get one snapshot
237     response = master.getMasterRpcServices().getCompletedSnapshots(null, request);
238     assertEquals("Found unexpected number of snapshots", 1, response.getSnapshotsCount());
239     List<SnapshotDescription> snapshots = response.getSnapshotsList();
240     List<SnapshotDescription> expected = Lists.newArrayList(snapshot);
241     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
242 
243     // write a second snapshot
244     snapshotName = "completed_two";
245     snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
246     snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
247     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
248     expected.add(snapshot);
249 
250     // check that we get one snapshot
251     response = master.getMasterRpcServices().getCompletedSnapshots(null, request);
252     assertEquals("Found unexpected number of snapshots", 2, response.getSnapshotsCount());
253     snapshots = response.getSnapshotsList();
254     assertEquals("Returned snapshots don't match created snapshots", expected, snapshots);
255   }
256 
257   @Test(timeout = 300000)
258   public void testDeleteSnapshot() throws Exception {
259 
260     String snapshotName = "completed";
261     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName).build();
262 
263     DeleteSnapshotRequest request = DeleteSnapshotRequest.newBuilder().setSnapshot(snapshot)
264         .build();
265     try {
266       master.getMasterRpcServices().deleteSnapshot(null, request);
267       fail("Master didn't throw exception when attempting to delete snapshot that doesn't exist");
268     } catch (ServiceException e) {
269       LOG.debug("Correctly failed delete of non-existant snapshot:" + e.getMessage());
270     }
271 
272     // write one snapshot to the fs
273     Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
274     SnapshotDescriptionUtils.writeSnapshotInfo(snapshot, snapshotDir, fs);
275 
276     // then delete the existing snapshot,which shouldn't cause an exception to be thrown
277     master.getMasterRpcServices().deleteSnapshot(null, request);
278   }
279 
280   /**
281    * Test that the snapshot hfile archive cleaner works correctly. HFiles that are in snapshots
282    * should be retained, while those that are not in a snapshot should be deleted.
283    * @throws Exception on failure
284    */
285   @Test(timeout = 300000)
286   public void testSnapshotHFileArchiving() throws Exception {
287     Admin admin = UTIL.getHBaseAdmin();
288     // make sure we don't fail on listing snapshots
289     SnapshotTestingUtils.assertNoSnapshots(admin);
290 
291     // recreate test table with disabled compactions; otherwise compaction may happen before
292     // snapshot, the call after snapshot will be a no-op and checks will fail
293     UTIL.deleteTable(TABLE_NAME);
294     HTableDescriptor htd = new HTableDescriptor(TABLE_NAME);
295     htd.setCompactionEnabled(false);
296 
297     UTIL.createTable(htd, new byte[][] { TEST_FAM }, null);
298 
299     // load the table (creates at least 4 hfiles)
300     for ( int i = 0; i < 5; i++) {
301       UTIL.loadTable(UTIL.getConnection().getTable(TABLE_NAME), TEST_FAM);
302       UTIL.flush(TABLE_NAME);
303     }
304 
305     // disable the table so we can take a snapshot
306     admin.disableTable(TABLE_NAME);
307     htd.setCompactionEnabled(true);
308 
309     // take a snapshot of the table
310     String snapshotName = "snapshot";
311     byte[] snapshotNameBytes = Bytes.toBytes(snapshotName);
312     admin.snapshot(snapshotNameBytes, TABLE_NAME);
313 
314     LOG.info("After snapshot File-System state");
315     FSUtils.logFileSystemState(fs, rootDir, LOG);
316 
317     // ensure we only have one snapshot
318     SnapshotTestingUtils.assertOneSnapshotThatMatches(admin, snapshotNameBytes, TABLE_NAME);
319 
320     // enable compactions now
321     admin.modifyTable(TABLE_NAME, htd);
322 
323     // renable the table so we can compact the regions
324     admin.enableTable(TABLE_NAME);
325 
326     // compact the files so we get some archived files for the table we just snapshotted
327     List<HRegion> regions = UTIL.getHBaseCluster().getRegions(TABLE_NAME);
328     for (HRegion region : regions) {
329       region.waitForFlushesAndCompactions(); // enable can trigger a compaction, wait for it.
330       region.compactStores(); // min is 2 so will compact and archive
331     }
332     List<RegionServerThread> regionServerThreads = UTIL.getMiniHBaseCluster()
333         .getRegionServerThreads();
334     HRegionServer hrs = null;
335     for (RegionServerThread rs : regionServerThreads) {
336       if (!rs.getRegionServer().getOnlineRegions(TABLE_NAME).isEmpty()) {
337         hrs = rs.getRegionServer();
338         break;
339       }
340     }
341     CompactedHFilesDischarger cleaner = new CompactedHFilesDischarger(100, null, hrs, false);
342     cleaner.chore();
343     LOG.info("After compaction File-System state");
344     FSUtils.logFileSystemState(fs, rootDir, LOG);
345 
346     // make sure the cleaner has run
347     LOG.debug("Running hfile cleaners");
348     ensureHFileCleanersRun();
349     LOG.info("After cleaners File-System state: " + rootDir);
350     FSUtils.logFileSystemState(fs, rootDir, LOG);
351 
352     // get the snapshot files for the table
353     Path snapshotTable = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir);
354     Set<String> snapshotHFiles = SnapshotReferenceUtil.getHFileNames(
355         UTIL.getConfiguration(), fs, snapshotTable);
356     // check that the files in the archive contain the ones that we need for the snapshot
357     LOG.debug("Have snapshot hfiles:");
358     for (String fileName : snapshotHFiles) {
359       LOG.debug(fileName);
360     }
361     // get the archived files for the table
362     Collection<String> files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);
363 
364     // and make sure that there is a proper subset
365     for (String fileName : snapshotHFiles) {
366       assertTrue("Archived hfiles " + files + " is missing snapshot file:" + fileName,
367         files.contains(fileName));
368     }
369 
370     // delete the existing snapshot
371     admin.deleteSnapshot(snapshotNameBytes);
372     SnapshotTestingUtils.assertNoSnapshots(admin);
373 
374     // make sure that we don't keep around the hfiles that aren't in a snapshot
375     // make sure we wait long enough to refresh the snapshot hfile
376     List<BaseHFileCleanerDelegate> delegates = UTIL.getMiniHBaseCluster().getMaster()
377         .getHFileCleaner().cleanersChain;
378     for (BaseHFileCleanerDelegate delegate: delegates) {
379       if (delegate instanceof SnapshotHFileCleaner) {
380         ((SnapshotHFileCleaner)delegate).getFileCacheForTesting().triggerCacheRefreshForTesting();
381       }
382     }
383     // run the cleaner again
384     LOG.debug("Running hfile cleaners");
385     ensureHFileCleanersRun();
386     LOG.info("After delete snapshot cleaners run File-System state");
387     FSUtils.logFileSystemState(fs, rootDir, LOG);
388 
389     files = getArchivedHFiles(archiveDir, rootDir, fs, TABLE_NAME);
390     assertEquals("Still have some hfiles in the archive, when their snapshot has been deleted.", 0,
391       files.size());
392   }
393 
394   /**
395    * @return all the HFiles for a given table that have been archived
396    * @throws IOException on expected failure
397    */
398   private final Collection<String> getArchivedHFiles(Path archiveDir, Path rootDir,
399       FileSystem fs, TableName tableName) throws IOException {
400     Path tableArchive = FSUtils.getTableDir(archiveDir, tableName);
401     return SnapshotTestingUtils.listHFileNames(fs, tableArchive);
402   }
403 
404   /**
405    * Make sure the {@link HFileCleaner HFileCleaners} run at least once
406    */
407   private static void ensureHFileCleanersRun() {
408     UTIL.getHBaseCluster().getMaster().getHFileCleaner().chore();
409   }
410 
411   @Test
412   public void testAsyncSnapshotWillNotBlockSnapshotHFileCleaner() throws Exception {
413     // Write some data
414     Table table = UTIL.getConnection().getTable(TABLE_NAME);
415     for (int i = 0; i < 10; i++) {
416       Put put = new Put(Bytes.toBytes(i)).addColumn(TEST_FAM, Bytes.toBytes("q"), Bytes.toBytes(i));
417       table.put(put);
418     }
419     final String snapshotName = "testAsyncSnapshotWillNotBlockSnapshotHFileCleaner01";
420     SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName(snapshotName)
421         .setTable(TABLE_NAME.getNameAsString()).setType(SnapshotDescription.Type.FLUSH).build();
422     UTIL.getHBaseAdmin().takeSnapshotAsync(snapshot);
423     UTIL.waitFor(10 * 1000L, 200L, new Predicate<Exception>() {
424       @Override
425       public boolean evaluate() throws Exception {
426         return UTIL.getHBaseAdmin().listSnapshots(Pattern.compile(snapshotName)).size() == 1;
427       }
428     });
429     assertTrue(master.getSnapshotManager().isTakingAnySnapshot());
430     Thread.sleep(11 * 1000L);
431     assertFalse(master.getSnapshotManager().isTakingAnySnapshot());
432   }
433 }