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.mockito.Mockito.doThrow;
24  import static org.mockito.Mockito.spy;
25  import static org.mockito.Mockito.doAnswer;
26  
27  import java.io.IOException;
28  import java.lang.reflect.Field;
29  import java.net.URLEncoder;
30  import java.util.Iterator;
31  import java.util.LinkedList;
32  import java.util.List;
33  import java.util.concurrent.atomic.AtomicBoolean;
34  
35  import com.google.common.collect.Lists;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FileStatus;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.Abortable;
41  import org.apache.hadoop.hbase.ChoreService;
42  import org.apache.hadoop.hbase.CoordinatedStateManager;
43  import org.apache.hadoop.hbase.HBaseTestingUtility;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.testclassification.MediumTests;
46  import org.apache.hadoop.hbase.Server;
47  import org.apache.hadoop.hbase.ServerName;
48  import org.apache.hadoop.hbase.Waiter;
49  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
50  import org.apache.hadoop.hbase.client.ClusterConnection;
51  import org.apache.hadoop.hbase.replication.ReplicationFactory;
52  import org.apache.hadoop.hbase.replication.ReplicationQueues;
53  import org.apache.hadoop.hbase.replication.ReplicationQueuesClient;
54  import org.apache.hadoop.hbase.replication.master.ReplicationLogCleaner;
55  import org.apache.hadoop.hbase.replication.regionserver.Replication;
56  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
57  import org.apache.hadoop.hbase.zookeeper.RecoverableZooKeeper;
58  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
59  import org.apache.zookeeper.KeeperException;
60  import org.junit.AfterClass;
61  import org.junit.BeforeClass;
62  import org.junit.Test;
63  import org.junit.experimental.categories.Category;
64  import org.mockito.Mockito;
65  import org.mockito.invocation.InvocationOnMock;
66  import org.mockito.stubbing.Answer;
67  
68  @Category(MediumTests.class)
69  public class TestLogsCleaner {
70  
71    private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
72  
73    /**
74     * @throws java.lang.Exception
75     */
76    @BeforeClass
77    public static void setUpBeforeClass() throws Exception {
78      TEST_UTIL.startMiniZKCluster();
79    }
80  
81    /**
82     * @throws java.lang.Exception
83     */
84    @AfterClass
85    public static void tearDownAfterClass() throws Exception {
86      TEST_UTIL.shutdownMiniZKCluster();
87    }
88  
89    @Test
90    public void testLogCleaning() throws Exception{
91      Configuration conf = TEST_UTIL.getConfiguration();
92      // set TTL
93      long ttl = 10000;
94      conf.setLong("hbase.master.logcleaner.ttl", ttl);
95      conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);
96      Replication.decorateMasterConfiguration(conf);
97      Server server = new DummyServer();
98      ReplicationQueues repQueues =
99          ReplicationFactory.getReplicationQueues(server.getZooKeeper(), conf, server);
100     repQueues.init(server.getServerName().toString());
101     final Path oldLogDir = new Path(TEST_UTIL.getDataTestDir(),
102         HConstants.HREGION_OLDLOGDIR_NAME);
103     String fakeMachineName =
104       URLEncoder.encode(server.getServerName().toString(), "UTF8");
105 
106     final FileSystem fs = FileSystem.get(conf);
107 
108     // Create 2 invalid files, 1 "recent" file, 1 very new file and 30 old files
109     long now = System.currentTimeMillis();
110     fs.delete(oldLogDir, true);
111     fs.mkdirs(oldLogDir);
112     // Case 1: 2 invalid files, which would be deleted directly
113     fs.createNewFile(new Path(oldLogDir, "a"));
114     fs.createNewFile(new Path(oldLogDir, fakeMachineName + "." + "a"));
115     // Case 2: 1 "recent" file, not even deletable for the first log cleaner
116     // (TimeToLiveLogCleaner), so we are not going down the chain
117     System.out.println("Now is: " + now);
118     for (int i = 1; i < 31; i++) {
119       // Case 3: old files which would be deletable for the first log cleaner
120       // (TimeToLiveLogCleaner), and also for the second (ReplicationLogCleaner)
121       Path fileName = new Path(oldLogDir, fakeMachineName + "." + (now - i) );
122       fs.createNewFile(fileName);
123       // Case 4: put 3 old log files in ZK indicating that they are scheduled
124       // for replication so these files would pass the first log cleaner
125       // (TimeToLiveLogCleaner) but would be rejected by the second
126       // (ReplicationLogCleaner)
127       if (i % (30/3) == 1) {
128         repQueues.addLog(fakeMachineName, fileName.getName());
129         System.out.println("Replication log file: " + fileName);
130       }
131     }
132 
133     // sleep for sometime to get newer modifcation time
134     Thread.sleep(ttl);
135     fs.createNewFile(new Path(oldLogDir, fakeMachineName + "." + now));
136 
137     // Case 2: 1 newer file, not even deletable for the first log cleaner
138     // (TimeToLiveLogCleaner), so we are not going down the chain
139     fs.createNewFile(new Path(oldLogDir, fakeMachineName + "." + (now + 10000) ));
140 
141     for (FileStatus stat : fs.listStatus(oldLogDir)) {
142       System.out.println(stat.getPath().toString());
143     }
144 
145     assertEquals(34, fs.listStatus(oldLogDir).length);
146 
147     LogCleaner cleaner  = new LogCleaner(1000, server, conf, fs, oldLogDir);
148 
149     cleaner.chore();
150 
151     // We end up with the current log file, a newer one and the 3 old log
152     // files which are scheduled for replication
153     TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
154       @Override
155       public boolean evaluate() throws Exception {
156         return 5 == fs.listStatus(oldLogDir).length;
157       }
158     });
159 
160     for (FileStatus file : fs.listStatus(oldLogDir)) {
161       System.out.println("Kept log files: " + file.getPath().getName());
162     }
163   }
164 
165   @Test(timeout=5000)
166   public void testZnodeCversionChange() throws Exception {
167     Configuration conf = TEST_UTIL.getConfiguration();
168     ReplicationLogCleaner cleaner = new ReplicationLogCleaner();
169     cleaner.setConf(conf);
170 
171     ReplicationQueuesClient rqcMock = Mockito.mock(ReplicationQueuesClient.class);
172     Mockito.when(rqcMock.getQueuesZNodeCversion()).thenReturn(1, 2, 3, 4);
173 
174     Field rqc = ReplicationLogCleaner.class.getDeclaredField("replicationQueues");
175     rqc.setAccessible(true);
176 
177     rqc.set(cleaner, rqcMock);
178 
179     // This should return eventually when cversion stabilizes
180     cleaner.getDeletableFiles(new LinkedList<FileStatus>());
181   }
182 
183   @Test(timeout=10000)
184   public void testZooKeeperAbortDuringGetListOfReplicators() throws Exception {
185     Configuration conf = TEST_UTIL.getConfiguration();
186 
187     ReplicationLogCleaner cleaner = new ReplicationLogCleaner();
188 
189     List<FileStatus> dummyFiles = Lists.newArrayList(
190         new FileStatus(100, false, 3, 100, System.currentTimeMillis(), new Path("log1")),
191         new FileStatus(100, false, 3, 100, System.currentTimeMillis(), new Path("log2"))
192     );
193 
194     FaultyZooKeeperWatcher faultyZK =
195         new FaultyZooKeeperWatcher(conf, "testZooKeeperAbort-faulty", null);
196     final AtomicBoolean getListOfReplicatorsFailed = new AtomicBoolean(false);
197 
198     try {
199       faultyZK.init();
200       ReplicationQueuesClient replicationQueuesClient = spy(ReplicationFactory.getReplicationQueuesClient(
201         faultyZK, conf, new ReplicationLogCleaner.WarnOnlyAbortable()));
202       doAnswer(new Answer<Object>() {
203         @Override
204         public Object answer(InvocationOnMock invocation) throws Throwable {
205           try {
206             return invocation.callRealMethod();
207           } catch (KeeperException.ConnectionLossException e) {
208             getListOfReplicatorsFailed.set(true);
209             throw e;
210           }
211         }
212       }).when(replicationQueuesClient).getListOfReplicators();
213       replicationQueuesClient.init();
214 
215       cleaner.setConf(conf, faultyZK, replicationQueuesClient);
216       // should keep all files due to a ConnectionLossException getting the queues znodes
217       Iterable<FileStatus> toDelete = cleaner.getDeletableFiles(dummyFiles);
218 
219       assertTrue(getListOfReplicatorsFailed.get());
220       assertFalse(toDelete.iterator().hasNext());
221       assertFalse(cleaner.isStopped());
222     } finally {
223       faultyZK.close();
224     }
225   }
226 
227   /**
228    * When zk is working both files should be returned
229    * @throws Exception
230    */
231   @Test(timeout=10000)
232   public void testZooKeeperNormal() throws Exception {
233     Configuration conf = TEST_UTIL.getConfiguration();
234     ReplicationLogCleaner cleaner = new ReplicationLogCleaner();
235 
236     List<FileStatus> dummyFiles = Lists.newArrayList(
237         new FileStatus(100, false, 3, 100, System.currentTimeMillis(), new Path("log1")),
238         new FileStatus(100, false, 3, 100, System.currentTimeMillis(), new Path("log2"))
239     );
240     
241     ZooKeeperWatcher zkw = new ZooKeeperWatcher(conf, "testZooKeeperAbort-normal", null);
242     try {
243       cleaner.setConf(conf, zkw);
244       Iterable<FileStatus> filesToDelete = cleaner.getDeletableFiles(dummyFiles);
245       Iterator<FileStatus> iter = filesToDelete.iterator();
246       assertTrue(iter.hasNext());
247       assertEquals(new Path("log1"), iter.next().getPath());
248       assertTrue(iter.hasNext());
249       assertEquals(new Path("log2"), iter.next().getPath());
250       assertFalse(iter.hasNext());
251     } finally {
252       zkw.close();
253     }
254   }
255 
256   static class DummyServer implements Server {
257 
258     @Override
259     public Configuration getConfiguration() {
260       return TEST_UTIL.getConfiguration();
261     }
262 
263     @Override
264     public ZooKeeperWatcher getZooKeeper() {
265       try {
266         return new ZooKeeperWatcher(getConfiguration(), "dummy server", this);
267       } catch (IOException e) {
268         e.printStackTrace();
269       }
270       return null;
271     }
272 
273     @Override
274     public CoordinatedStateManager getCoordinatedStateManager() {
275       return null;
276     }
277 
278     @Override
279     public ClusterConnection getConnection() {
280       return null;
281     }
282 
283     @Override
284     public MetaTableLocator getMetaTableLocator() {
285       return null;
286     }
287 
288     @Override
289     public ServerName getServerName() {
290       return ServerName.valueOf("regionserver,60020,000000");
291     }
292 
293     @Override
294     public void abort(String why, Throwable e) {}
295 
296     @Override
297     public boolean isAborted() {
298       return false;
299     }
300 
301     @Override
302     public void stop(String why) {}
303 
304     @Override
305     public boolean isStopped() {
306       return false;
307     }
308 
309     @Override
310     public ChoreService getChoreService() {
311       return null;
312     }
313   }
314 
315   static class FaultyZooKeeperWatcher extends ZooKeeperWatcher {
316     private RecoverableZooKeeper zk;
317 
318     public FaultyZooKeeperWatcher(Configuration conf, String identifier, Abortable abortable)
319         throws ZooKeeperConnectionException, IOException {
320       super(conf, identifier, abortable);
321     }
322 
323     public void init() throws Exception {
324       this.zk = spy(super.getRecoverableZooKeeper());
325       doThrow(new KeeperException.ConnectionLossException())
326         .when(zk).getChildren("/hbase/replication/rs", null);
327     }
328 
329     public RecoverableZooKeeper getRecoverableZooKeeper() {
330       return zk;
331     }
332   }
333 }