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