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.snapshot;
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.mockito.Mockito.mock;
24  import static org.mockito.Mockito.when;
25  
26  import java.io.IOException;
27  import java.util.*;
28  import java.util.concurrent.atomic.AtomicInteger;
29  
30  import com.google.common.collect.Iterables;
31  import com.google.common.collect.Lists;
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.fs.FileStatus;
35  import org.apache.hadoop.fs.FileSystem;
36  import org.apache.hadoop.fs.Path;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HRegionInfo;
39  import org.apache.hadoop.hbase.protobuf.generated.SnapshotProtos;
40  import org.apache.hadoop.hbase.testclassification.MediumTests;
41  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
42  import org.apache.hadoop.hbase.snapshot.SnapshotDescriptionUtils;
43  import org.apache.hadoop.hbase.snapshot.SnapshotReferenceUtil;
44  import org.apache.hadoop.hbase.snapshot.SnapshotTestingUtils.SnapshotMock;
45  import org.apache.hadoop.hbase.util.FSUtils;
46  import org.junit.After;
47  import org.junit.AfterClass;
48  import org.junit.BeforeClass;
49  import org.junit.Test;
50  import org.junit.experimental.categories.Category;
51  
52  /**
53   * Test that we correctly reload the cache, filter directories, etc.
54   */
55  @Category(MediumTests.class)
56  public class TestSnapshotFileCache {
57  
58    private static final Log LOG = LogFactory.getLog(TestSnapshotFileCache.class);
59    private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
60    private static long sequenceId = 0;
61    private static FileSystem fs;
62    private static Path rootDir;
63  
64    @BeforeClass
65    public static void startCluster() throws Exception {
66      UTIL.startMiniDFSCluster(1);
67      fs = UTIL.getDFSCluster().getFileSystem();
68      rootDir = UTIL.getDefaultRootDirPath();
69    }
70  
71    @AfterClass
72    public static void stopCluster() throws Exception {
73      UTIL.shutdownMiniDFSCluster();
74    }
75  
76    @After
77    public void cleanupFiles() throws Exception {
78      // cleanup the snapshot directory
79      Path snapshotDir = SnapshotDescriptionUtils.getSnapshotsDir(rootDir);
80      fs.delete(snapshotDir, true);
81    }
82  
83    @Test(timeout = 10000000)
84    public void testLoadAndDelete() throws IOException {
85      // don't refresh the cache unless we tell it to
86      long period = Long.MAX_VALUE;
87      SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000,
88          "test-snapshot-file-cache-refresh", new SnapshotFiles());
89  
90      createAndTestSnapshotV1(cache, "snapshot1a", false, true);
91      createAndTestSnapshotV1(cache, "snapshot1b", true, true);
92  
93      createAndTestSnapshotV2(cache, "snapshot2a", false, true);
94      createAndTestSnapshotV2(cache, "snapshot2b", true, true);
95    }
96  
97    @Test
98    public void testReloadModifiedDirectory() throws IOException {
99      // don't refresh the cache unless we tell it to
100     long period = Long.MAX_VALUE;
101     SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000,
102         "test-snapshot-file-cache-refresh", new SnapshotFiles());
103 
104     createAndTestSnapshotV1(cache, "snapshot1", false, true);
105     // now delete the snapshot and add a file with a different name
106     createAndTestSnapshotV1(cache, "snapshot1", false, false);
107 
108     createAndTestSnapshotV2(cache, "snapshot2", false, true);
109     // now delete the snapshot and add a file with a different name
110     createAndTestSnapshotV2(cache, "snapshot2", false, false);
111   }
112 
113   @Test
114   public void testSnapshotTempDirReload() throws IOException {
115     long period = Long.MAX_VALUE;
116     // This doesn't refresh cache until we invoke it explicitly
117     SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000,
118         "test-snapshot-file-cache-refresh", new SnapshotFiles());
119 
120     // Add a new non-tmp snapshot
121     createAndTestSnapshotV1(cache, "snapshot0v1", false, false);
122     createAndTestSnapshotV1(cache, "snapshot0v2", false, false);
123 
124     // Add a new tmp snapshot
125     createAndTestSnapshotV2(cache, "snapshot1", true, false);
126 
127     // Add another tmp snapshot
128     createAndTestSnapshotV2(cache, "snapshot2", true, false);
129   }
130 
131   @Test
132   public void testWeNeverCacheTmpDirAndLoadIt() throws Exception {
133 
134     final AtomicInteger count = new AtomicInteger(0);
135     // don't refresh the cache unless we tell it to
136     long period = Long.MAX_VALUE;
137     SnapshotFileCache cache = new SnapshotFileCache(fs, rootDir, period, 10000000,
138         "test-snapshot-file-cache-refresh", new SnapshotFiles()) {
139       @Override
140       List<String> getSnapshotsInProgress() throws IOException {
141         List<String> result = super.getSnapshotsInProgress();
142         count.incrementAndGet();
143         return result;
144       }
145 
146       @Override public void triggerCacheRefreshForTesting() {
147         super.triggerCacheRefreshForTesting();
148       }
149     };
150 
151     SnapshotMock.SnapshotBuilder complete =
152         createAndTestSnapshotV1(cache, "snapshot", false, false);
153 
154     SnapshotMock.SnapshotBuilder inProgress =
155         createAndTestSnapshotV1(cache, "snapshotInProgress", true, false);
156 
157     int countBeforeCheck = count.get();
158 
159     FSUtils.logFileSystemState(fs, rootDir, LOG);
160 
161     List<FileStatus> allStoreFiles = getStoreFilesForSnapshot(complete);
162     Iterable<FileStatus> deletableFiles = cache.getUnreferencedFiles(allStoreFiles);
163     assertTrue(Iterables.isEmpty(deletableFiles));
164     // no need for tmp dir check as all files are accounted for.
165     assertEquals(0, count.get() - countBeforeCheck);
166 
167 
168     // add a random file to make sure we refresh
169     FileStatus randomFile = mockStoreFile(UUID.randomUUID().toString());
170     allStoreFiles.add(randomFile);
171     deletableFiles = cache.getUnreferencedFiles(allStoreFiles);
172     assertEquals(randomFile, Iterables.getOnlyElement(deletableFiles));
173     assertEquals(1, count.get() - countBeforeCheck); // we check the tmp directory
174   }
175 
176   private List<FileStatus> getStoreFilesForSnapshot(SnapshotMock.SnapshotBuilder builder)
177       throws IOException {
178     final List<FileStatus> allStoreFiles = Lists.newArrayList();
179     SnapshotReferenceUtil
180         .visitReferencedFiles(UTIL.getConfiguration(), fs, builder.getSnapshotsDir(),
181             new SnapshotReferenceUtil.SnapshotVisitor() {
182               @Override public void storeFile(HRegionInfo regionInfo, String familyName,
183                   SnapshotProtos.SnapshotRegionManifest.StoreFile storeFile) throws IOException {
184                 FileStatus status = mockStoreFile(storeFile.getName());
185                 allStoreFiles.add(status);
186               }
187             });
188     return allStoreFiles;
189   }
190 
191   private FileStatus mockStoreFile(String storeFileName) {
192     FileStatus status = mock(FileStatus.class);
193     Path path = mock(Path.class);
194     when(path.getName()).thenReturn(storeFileName);
195     when(status.getPath()).thenReturn(path);
196     return status;
197   }
198 
199   class SnapshotFiles implements SnapshotFileCache.SnapshotFileInspector {
200     public Collection<String> filesUnderSnapshot(final Path snapshotDir) throws IOException {
201       Collection<String> files =  new HashSet<String>();
202       files.addAll(SnapshotReferenceUtil.getHFileNames(UTIL.getConfiguration(), fs, snapshotDir));
203       return files;
204     }
205   };
206 
207   private SnapshotMock.SnapshotBuilder createAndTestSnapshotV1(final SnapshotFileCache cache,
208       final String name, final boolean tmp, final boolean removeOnExit) throws IOException {
209     SnapshotMock snapshotMock = new SnapshotMock(UTIL.getConfiguration(), fs, rootDir);
210     SnapshotMock.SnapshotBuilder builder = snapshotMock.createSnapshotV1(name, name);
211     createAndTestSnapshot(cache, builder, tmp, removeOnExit);
212     return builder;
213   }
214 
215   private void createAndTestSnapshotV2(final SnapshotFileCache cache, final String name,
216       final boolean tmp, final boolean removeOnExit) throws IOException {
217     SnapshotMock snapshotMock = new SnapshotMock(UTIL.getConfiguration(), fs, rootDir);
218     SnapshotMock.SnapshotBuilder builder = snapshotMock.createSnapshotV2(name, name);
219     createAndTestSnapshot(cache, builder, tmp, removeOnExit);
220   }
221 
222   private void createAndTestSnapshot(final SnapshotFileCache cache,
223       final SnapshotMock.SnapshotBuilder builder,
224       final boolean tmp, final boolean removeOnExit) throws IOException {
225     List<Path> files = new ArrayList<Path>();
226     for (int i = 0; i < 3; ++i) {
227       for (Path filePath: builder.addRegion()) {
228         String fileName = filePath.getName();
229         if (tmp) {
230           // We should be able to find all the files while the snapshot creation is in-progress
231           FSUtils.logFileSystemState(fs, rootDir, LOG);
232           Iterable<FileStatus> nonSnapshot = getNonSnapshotFiles(cache, filePath);
233           assertFalse("Cache didn't find " + fileName, Iterables.contains(nonSnapshot, fileName));
234         }
235         files.add(filePath);
236       }
237     }
238 
239     // Finalize the snapshot
240     if (!tmp) {
241       builder.commit();
242     }
243 
244     // Make sure that all files are still present
245     for (Path path: files) {
246       Iterable<FileStatus> nonSnapshotFiles = getNonSnapshotFiles(cache, path);
247       assertFalse("Cache didn't find " + path.getName(),
248           Iterables.contains(nonSnapshotFiles, path.getName()));
249     }
250 
251     FSUtils.logFileSystemState(fs, rootDir, LOG);
252     if (removeOnExit) {
253       LOG.debug("Deleting snapshot.");
254       fs.delete(builder.getSnapshotsDir(), true);
255       FSUtils.logFileSystemState(fs, rootDir, LOG);
256 
257       // The files should be in cache until next refresh
258       for (Path filePath: files) {
259         Iterable<FileStatus> nonSnapshotFiles = getNonSnapshotFiles(cache, filePath);
260         assertFalse("Cache didn't find " + filePath.getName(), Iterables.contains(nonSnapshotFiles,
261             filePath.getName()));
262       }
263 
264       // then trigger a refresh
265       cache.triggerCacheRefreshForTesting();
266       // and not it shouldn't find those files
267       for (Path filePath: files) {
268         Iterable<FileStatus> nonSnapshotFiles = getNonSnapshotFiles(cache, filePath);
269         assertTrue("Cache found '" + filePath.getName() + "', but it shouldn't have.",
270             !Iterables.contains(nonSnapshotFiles, filePath.getName()));
271       }
272     }
273   }
274 
275   private Iterable<FileStatus> getNonSnapshotFiles(SnapshotFileCache cache, Path storeFile)
276       throws IOException {
277     return cache.getUnreferencedFiles(
278         Arrays.asList(FSUtils.listStatus(fs, storeFile.getParent()))
279     );
280   }
281 }