View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master;
20  
21  import static org.apache.hadoop.hbase.util.HFileArchiveTestingUtil.assertArchiveEqualToOriginal;
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertFalse;
24  import static org.junit.Assert.assertTrue;
25  import static org.mockito.Mockito.doReturn;
26  import static org.mockito.Mockito.spy;
27  
28  import java.io.IOException;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.SortedMap;
32  import java.util.TreeMap;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FSDataOutputStream;
38  import org.apache.hadoop.fs.FileStatus;
39  import org.apache.hadoop.fs.FileSystem;
40  import org.apache.hadoop.fs.Path;
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.HColumnDescriptor;
45  import org.apache.hadoop.hbase.HConstants;
46  import org.apache.hadoop.hbase.HRegionInfo;
47  import org.apache.hadoop.hbase.HTableDescriptor;
48  import org.apache.hadoop.hbase.MetaMockingUtil;
49  import org.apache.hadoop.hbase.NamespaceDescriptor;
50  import org.apache.hadoop.hbase.NotAllMetaRegionsOnlineException;
51  import org.apache.hadoop.hbase.Server;
52  import org.apache.hadoop.hbase.ServerName;
53  import org.apache.hadoop.hbase.testclassification.SmallTests;
54  import org.apache.hadoop.hbase.TableDescriptors;
55  import org.apache.hadoop.hbase.TableName;
56  import org.apache.hadoop.hbase.client.ClusterConnection;
57  import org.apache.hadoop.hbase.client.HConnectionTestingUtility;
58  import org.apache.hadoop.hbase.client.Result;
59  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
60  import org.apache.hadoop.hbase.coordination.SplitLogManagerCoordination;
61  import org.apache.hadoop.hbase.coordination.SplitLogManagerCoordination.SplitLogManagerDetails;
62  import org.apache.hadoop.hbase.executor.ExecutorService;
63  import org.apache.hadoop.hbase.io.Reference;
64  import org.apache.hadoop.hbase.master.CatalogJanitor.SplitParentFirstComparator;
65  import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
66  import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
67  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
68  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
69  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
70  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiRequest;
71  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MultiResponse;
72  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateRequest;
73  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutateResponse;
74  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionAction;
75  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.RegionActionResult;
76  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ResultOrException;
77  import org.apache.hadoop.hbase.quotas.MasterQuotaManager;
78  import org.apache.hadoop.hbase.regionserver.HStore;
79  import org.apache.hadoop.hbase.util.Bytes;
80  import org.apache.hadoop.hbase.util.FSUtils;
81  import org.apache.hadoop.hbase.util.HFileArchiveUtil;
82  import org.apache.hadoop.hbase.util.Triple;
83  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
84  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
85  import org.junit.Test;
86  import org.junit.experimental.categories.Category;
87  import org.mockito.Mockito;
88  import org.mockito.invocation.InvocationOnMock;
89  import org.mockito.stubbing.Answer;
90  
91  import com.google.protobuf.RpcController;
92  import com.google.protobuf.Service;
93  import com.google.protobuf.ServiceException;
94  
95  @Category(SmallTests.class)
96  public class TestCatalogJanitor {
97    private static final Log LOG = LogFactory.getLog(TestCatalogJanitor.class);
98  
99    /**
100    * Pseudo server for below tests.
101    * Be sure to call stop on the way out else could leave some mess around.
102    */
103   class MockServer implements Server {
104     private final ClusterConnection connection;
105     private final Configuration c;
106 
107     MockServer(final HBaseTestingUtility htu)
108     throws NotAllMetaRegionsOnlineException, IOException, InterruptedException {
109       this.c = htu.getConfiguration();
110       ClientProtos.ClientService.BlockingInterface ri =
111         Mockito.mock(ClientProtos.ClientService.BlockingInterface.class);
112       MutateResponse.Builder builder = MutateResponse.newBuilder();
113       builder.setProcessed(true);
114       try {
115         Mockito.when(ri.mutate(
116           (RpcController)Mockito.any(), (MutateRequest)Mockito.any())).
117             thenReturn(builder.build());
118       } catch (ServiceException se) {
119         throw ProtobufUtil.getRemoteException(se);
120       }
121       try {
122         Mockito.when(ri.multi(
123           (RpcController)Mockito.any(), (MultiRequest)Mockito.any())).
124             thenAnswer(new Answer<MultiResponse>() {
125               @Override
126               public MultiResponse answer(InvocationOnMock invocation) throws Throwable {
127                 return buildMultiResponse( (MultiRequest)invocation.getArguments()[1]);
128               }
129             });
130       } catch (ServiceException se) {
131         throw ProtobufUtil.getRemoteException(se);
132       }
133       // Mock an HConnection and a AdminProtocol implementation.  Have the
134       // HConnection return the HRI.  Have the HRI return a few mocked up responses
135       // to make our test work.
136       this.connection =
137         HConnectionTestingUtility.getMockedConnectionAndDecorate(this.c,
138           Mockito.mock(AdminProtos.AdminService.BlockingInterface.class), ri,
139             ServerName.valueOf("example.org,12345,6789"),
140           HRegionInfo.FIRST_META_REGIONINFO);
141       // Set hbase.rootdir into test dir.
142       FileSystem fs = FileSystem.get(this.c);
143       Path rootdir = FSUtils.getRootDir(this.c);
144       FSUtils.setRootDir(this.c, rootdir);
145       AdminProtos.AdminService.BlockingInterface hri =
146         Mockito.mock(AdminProtos.AdminService.BlockingInterface.class);
147     }
148 
149     @Override
150     public ClusterConnection getConnection() {
151       return this.connection;
152     }
153 
154     @Override
155     public MetaTableLocator getMetaTableLocator() {
156       return null;
157     }
158 
159     @Override
160     public Configuration getConfiguration() {
161       return this.c;
162     }
163 
164     @Override
165     public ServerName getServerName() {
166       return ServerName.valueOf("mockserver.example.org", 1234, -1L);
167     }
168 
169     @Override
170     public ZooKeeperWatcher getZooKeeper() {
171       return null;
172     }
173 
174     @Override
175     public CoordinatedStateManager getCoordinatedStateManager() {
176       BaseCoordinatedStateManager m = Mockito.mock(BaseCoordinatedStateManager.class);
177       SplitLogManagerCoordination c = Mockito.mock(SplitLogManagerCoordination.class);
178       Mockito.when(m.getSplitLogManagerCoordination()).thenReturn(c);
179       SplitLogManagerDetails d = Mockito.mock(SplitLogManagerDetails.class);
180       Mockito.when(c.getDetails()).thenReturn(d);
181       return m;
182     }
183 
184     @Override
185     public void abort(String why, Throwable e) {
186       //no-op
187     }
188 
189     @Override
190     public boolean isAborted() {
191       return false;
192     }
193 
194     @Override
195     public boolean isStopped() {
196       return false;
197     }
198 
199     @Override
200     public void stop(String why) {
201     }
202 
203     @Override
204     public ChoreService getChoreService() {
205       return null;
206     }
207   }
208 
209   /**
210    * Mock MasterServices for tests below.
211    */
212   class MockMasterServices implements MasterServices {
213     private final MasterFileSystem mfs;
214     private final AssignmentManager asm;
215 
216     MockMasterServices(final Server server) throws IOException {
217       this.mfs = new MasterFileSystem(server, this);
218       this.asm = Mockito.mock(AssignmentManager.class);
219     }
220 
221     @Override
222     public void checkTableModifiable(TableName tableName) throws IOException {
223       //no-op
224     }
225 
226     @Override
227     public boolean isMasterProcedureExecutorEnabled() {
228       return true;
229     }
230 
231     @Override
232     public long createTable(HTableDescriptor desc, byte[][] splitKeys)
233         throws IOException {
234       // no-op
235       return -1;
236     }
237 
238     @Override
239     public AssignmentManager getAssignmentManager() {
240       return this.asm;
241     }
242 
243     @Override
244     public ExecutorService getExecutorService() {
245       return null;
246     }
247 
248     @Override
249     public ChoreService getChoreService() {
250       return null;
251     }
252 
253     @Override
254     public MasterFileSystem getMasterFileSystem() {
255       return this.mfs;
256     }
257 
258     @Override
259     public MasterCoprocessorHost getMasterCoprocessorHost() {
260       return null;
261     }
262     
263     @Override
264     public MasterQuotaManager getMasterQuotaManager() {
265       return null;
266     }
267 
268     @Override
269     public ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() {
270       return null;
271     }
272 
273     @Override
274     public ServerManager getServerManager() {
275       return null;
276     }
277 
278     @Override
279     public ZooKeeperWatcher getZooKeeper() {
280       return null;
281     }
282 
283     @Override
284     public CoordinatedStateManager getCoordinatedStateManager() {
285       return null;
286     }
287 
288     @Override
289     public MetaTableLocator getMetaTableLocator() {
290       return null;
291     }
292 
293     @Override
294     public ClusterConnection getConnection() {
295       return null;
296     }
297 
298     @Override
299     public Configuration getConfiguration() {
300       return mfs.conf;
301     }
302 
303     @Override
304     public ServerName getServerName() {
305       return null;
306     }
307 
308     @Override
309     public void abort(String why, Throwable e) {
310       //no-op
311     }
312 
313     @Override
314     public boolean isAborted() {
315       return false;
316     }
317 
318     private boolean stopped = false;
319 
320     @Override
321     public void stop(String why) {
322       stopped = true;
323     }
324 
325     @Override
326     public boolean isStopped() {
327       return stopped;
328     }
329 
330     @Override
331     public TableDescriptors getTableDescriptors() {
332       return new TableDescriptors() {
333         @Override
334         public HTableDescriptor remove(TableName tablename) throws IOException {
335           // TODO Auto-generated method stub
336           return null;
337         }
338 
339         @Override
340         public Map<String, HTableDescriptor> getAll() throws IOException {
341           // TODO Auto-generated method stub
342           return null;
343         }
344 
345         @Override
346         public HTableDescriptor get(TableName tablename)
347         throws IOException {
348           return createHTableDescriptor();
349         }
350 
351         @Override
352         public Map<String, HTableDescriptor> getByNamespace(String name) throws IOException {
353           return null;
354         }
355 
356         @Override
357         public void add(HTableDescriptor htd) throws IOException {
358           // TODO Auto-generated method stub
359 
360         }
361         @Override
362         public void setCacheOn() throws IOException {
363         }
364 
365         @Override
366         public void setCacheOff() throws IOException {
367         }
368       };
369     }
370 
371     @Override
372     public boolean isServerShutdownHandlerEnabled() {
373       return true;
374     }
375 
376     @Override
377     public boolean registerService(Service instance) {
378       return false;
379     }
380 
381     @Override
382     public void createNamespace(NamespaceDescriptor descriptor) throws IOException {
383       //To change body of implemented methods use File | Settings | File Templates.
384     }
385 
386     @Override
387     public void modifyNamespace(NamespaceDescriptor descriptor) throws IOException {
388       //To change body of implemented methods use File | Settings | File Templates.
389     }
390 
391     @Override
392     public void deleteNamespace(String name) throws IOException {
393       //To change body of implemented methods use File | Settings | File Templates.
394     }
395 
396     @Override
397     public NamespaceDescriptor getNamespaceDescriptor(String name) throws IOException {
398       return null;  //To change body of implemented methods use File | Settings | File Templates.
399     }
400 
401     @Override
402     public List<NamespaceDescriptor> listNamespaceDescriptors() throws IOException {
403       return null;  //To change body of implemented methods use File | Settings | File Templates.
404     }
405 
406     @Override
407     public List<HTableDescriptor> listTableDescriptorsByNamespace(String name) throws IOException {
408       return null;  //To change body of implemented methods use File | Settings | File Templates.
409     }
410 
411     @Override
412     public List<TableName> listTableNamesByNamespace(String name) throws IOException {
413       return null;
414     }
415 
416     @Override
417     public long deleteTable(TableName tableName) throws IOException {
418       return -1;
419     }
420 
421     @Override
422     public void truncateTable(TableName tableName, boolean preserveSplits) throws IOException { }
423 
424 
425     @Override
426     public void modifyTable(TableName tableName, HTableDescriptor descriptor)
427         throws IOException { }
428 
429     @Override
430     public long enableTable(TableName tableName) throws IOException {
431       return -1;
432     }
433 
434     @Override
435     public long disableTable(TableName tableName) throws IOException {
436       return -1;
437     }
438 
439     @Override
440     public void addColumn(TableName tableName, HColumnDescriptor column)
441         throws IOException { }
442 
443     @Override
444     public void modifyColumn(TableName tableName, HColumnDescriptor descriptor)
445         throws IOException { }
446 
447     @Override
448     public void deleteColumn(TableName tableName, byte[] columnName)
449         throws IOException { }
450 
451     @Override
452     public TableLockManager getTableLockManager() {
453       return null;
454     }
455 
456     @Override
457     public void dispatchMergingRegions(HRegionInfo region_a, HRegionInfo region_b,
458         boolean forcible) throws IOException {
459     }
460 
461     @Override
462     public boolean isInitialized() {
463       // Auto-generated method stub
464       return false;
465     }
466 
467     @Override
468     public long getLastMajorCompactionTimestamp(TableName table) throws IOException {
469       // Auto-generated method stub
470       return 0;
471     }
472 
473     @Override
474     public long getLastMajorCompactionTimestampForRegion(byte[] regionName) throws IOException {
475       // Auto-generated method stub
476       return 0;
477     }
478   }
479 
480   @Test
481   public void testCleanParent() throws IOException, InterruptedException {
482     HBaseTestingUtility htu = new HBaseTestingUtility();
483     setRootDirAndCleanIt(htu, "testCleanParent");
484     Server server = new MockServer(htu);
485     try {
486       MasterServices services = new MockMasterServices(server);
487       CatalogJanitor janitor = new CatalogJanitor(server, services);
488       // Create regions.
489       HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("table"));
490       htd.addFamily(new HColumnDescriptor("f"));
491       HRegionInfo parent =
492         new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
493             Bytes.toBytes("eee"));
494       HRegionInfo splita =
495         new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
496             Bytes.toBytes("ccc"));
497       HRegionInfo splitb =
498         new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"),
499             Bytes.toBytes("eee"));
500       // Test that when both daughter regions are in place, that we do not
501       // remove the parent.
502       Result r = createResult(parent, splita, splitb);
503       // Add a reference under splitA directory so we don't clear out the parent.
504       Path rootdir = services.getMasterFileSystem().getRootDir();
505       Path tabledir =
506         FSUtils.getTableDir(rootdir, htd.getTableName());
507       Path storedir = HStore.getStoreHomedir(tabledir, splita,
508           htd.getColumnFamilies()[0].getName());
509       Reference ref = Reference.createTopReference(Bytes.toBytes("ccc"));
510       long now = System.currentTimeMillis();
511       // Reference name has this format: StoreFile#REF_NAME_PARSER
512       Path p = new Path(storedir, Long.toString(now) + "." + parent.getEncodedName());
513       FileSystem fs = services.getMasterFileSystem().getFileSystem();
514       Path path = ref.write(fs, p);
515       assertTrue(fs.exists(path));
516       assertFalse(janitor.cleanParent(parent, r));
517       // Remove the reference file and try again.
518       assertTrue(fs.delete(p, true));
519       assertTrue(janitor.cleanParent(parent, r));
520     } finally {
521       server.stop("shutdown");
522     }
523   }
524 
525   /**
526    * Make sure parent gets cleaned up even if daughter is cleaned up before it.
527    * @throws IOException
528    * @throws InterruptedException
529    */
530   @Test
531   public void testParentCleanedEvenIfDaughterGoneFirst()
532   throws IOException, InterruptedException {
533     parentWithSpecifiedEndKeyCleanedEvenIfDaughterGoneFirst(
534       "testParentCleanedEvenIfDaughterGoneFirst", Bytes.toBytes("eee"));
535   }
536 
537   /**
538    * Make sure last parent with empty end key gets cleaned up even if daughter is cleaned up before it.
539    * @throws IOException
540    * @throws InterruptedException
541    */
542   @Test
543   public void testLastParentCleanedEvenIfDaughterGoneFirst()
544   throws IOException, InterruptedException {
545     parentWithSpecifiedEndKeyCleanedEvenIfDaughterGoneFirst(
546       "testLastParentCleanedEvenIfDaughterGoneFirst", new byte[0]);
547   }
548 
549   /**
550    * Make sure parent with specified end key gets cleaned up even if daughter is cleaned up before it.
551    *
552    * @param rootDir the test case name, used as the HBase testing utility root
553    * @param lastEndKey the end key of the split parent
554    * @throws IOException
555    * @throws InterruptedException
556    */
557   private void parentWithSpecifiedEndKeyCleanedEvenIfDaughterGoneFirst(
558   final String rootDir, final byte[] lastEndKey)
559   throws IOException, InterruptedException {
560     HBaseTestingUtility htu = new HBaseTestingUtility();
561     setRootDirAndCleanIt(htu, rootDir);
562     Server server = new MockServer(htu);
563     MasterServices services = new MockMasterServices(server);
564     CatalogJanitor janitor = new CatalogJanitor(server, services);
565     final HTableDescriptor htd = createHTableDescriptor();
566 
567     // Create regions: aaa->{lastEndKey}, aaa->ccc, aaa->bbb, bbb->ccc, etc.
568 
569     // Parent
570     HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
571       lastEndKey);
572     // Sleep a second else the encoded name on these regions comes out
573     // same for all with same start key and made in same second.
574     Thread.sleep(1001);
575 
576     // Daughter a
577     HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
578       Bytes.toBytes("ccc"));
579     Thread.sleep(1001);
580     // Make daughters of daughter a; splitaa and splitab.
581     HRegionInfo splitaa = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
582       Bytes.toBytes("bbb"));
583     HRegionInfo splitab = new HRegionInfo(htd.getTableName(), Bytes.toBytes("bbb"),
584       Bytes.toBytes("ccc"));
585 
586     // Daughter b
587     HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"),
588       lastEndKey);
589     Thread.sleep(1001);
590     // Make Daughters of daughterb; splitba and splitbb.
591     HRegionInfo splitba = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"),
592       Bytes.toBytes("ddd"));
593     HRegionInfo splitbb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ddd"),
594     lastEndKey);
595 
596     // First test that our Comparator works right up in CatalogJanitor.
597     // Just fo kicks.
598     SortedMap<HRegionInfo, Result> regions =
599       new TreeMap<HRegionInfo, Result>(new CatalogJanitor.SplitParentFirstComparator());
600     // Now make sure that this regions map sorts as we expect it to.
601     regions.put(parent, createResult(parent, splita, splitb));
602     regions.put(splitb, createResult(splitb, splitba, splitbb));
603     regions.put(splita, createResult(splita, splitaa, splitab));
604     // Assert its properly sorted.
605     int index = 0;
606     for (Map.Entry<HRegionInfo, Result> e: regions.entrySet()) {
607       if (index == 0) {
608         assertTrue(e.getKey().getEncodedName().equals(parent.getEncodedName()));
609       } else if (index == 1) {
610         assertTrue(e.getKey().getEncodedName().equals(splita.getEncodedName()));
611       } else if (index == 2) {
612         assertTrue(e.getKey().getEncodedName().equals(splitb.getEncodedName()));
613       }
614       index++;
615     }
616 
617     // Now play around with the cleanParent function.  Create a ref from splita
618     // up to the parent.
619     Path splitaRef =
620       createReferences(services, htd, parent, splita, Bytes.toBytes("ccc"), false);
621     // Make sure actual super parent sticks around because splita has a ref.
622     assertFalse(janitor.cleanParent(parent, regions.get(parent)));
623 
624     //splitba, and split bb, do not have dirs in fs.  That means that if
625     // we test splitb, it should get cleaned up.
626     assertTrue(janitor.cleanParent(splitb, regions.get(splitb)));
627 
628     // Now remove ref from splita to parent... so parent can be let go and so
629     // the daughter splita can be split (can't split if still references).
630     // BUT make the timing such that the daughter gets cleaned up before we
631     // can get a chance to let go of the parent.
632     FileSystem fs = FileSystem.get(htu.getConfiguration());
633     assertTrue(fs.delete(splitaRef, true));
634     // Create the refs from daughters of splita.
635     Path splitaaRef =
636       createReferences(services, htd, splita, splitaa, Bytes.toBytes("bbb"), false);
637     Path splitabRef =
638       createReferences(services, htd, splita, splitab, Bytes.toBytes("bbb"), true);
639 
640     // Test splita.  It should stick around because references from splitab, etc.
641     assertFalse(janitor.cleanParent(splita, regions.get(splita)));
642 
643     // Now clean up parent daughter first.  Remove references from its daughters.
644     assertTrue(fs.delete(splitaaRef, true));
645     assertTrue(fs.delete(splitabRef, true));
646     assertTrue(janitor.cleanParent(splita, regions.get(splita)));
647 
648     // Super parent should get cleaned up now both splita and splitb are gone.
649     assertTrue(janitor.cleanParent(parent, regions.get(parent)));
650 
651     services.stop("test finished");
652     janitor.cancel(true);
653   }
654 
655   /**
656    * CatalogJanitor.scan() should not clean parent regions if their own
657    * parents are still referencing them. This ensures that grandfather regions
658    * do not point to deleted parent regions.
659    */
660   @Test
661   public void testScanDoesNotCleanRegionsWithExistingParents() throws Exception {
662     HBaseTestingUtility htu = new HBaseTestingUtility();
663     setRootDirAndCleanIt(htu, "testScanDoesNotCleanRegionsWithExistingParents");
664     Server server = new MockServer(htu);
665     MasterServices services = new MockMasterServices(server);
666 
667     final HTableDescriptor htd = createHTableDescriptor();
668 
669     // Create regions: aaa->{lastEndKey}, aaa->ccc, aaa->bbb, bbb->ccc, etc.
670 
671     // Parent
672     HRegionInfo parent = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
673       new byte[0], true);
674     // Sleep a second else the encoded name on these regions comes out
675     // same for all with same start key and made in same second.
676     Thread.sleep(1001);
677 
678     // Daughter a
679     HRegionInfo splita = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
680       Bytes.toBytes("ccc"), true);
681     Thread.sleep(1001);
682     // Make daughters of daughter a; splitaa and splitab.
683     HRegionInfo splitaa = new HRegionInfo(htd.getTableName(), Bytes.toBytes("aaa"),
684       Bytes.toBytes("bbb"), false);
685     HRegionInfo splitab = new HRegionInfo(htd.getTableName(), Bytes.toBytes("bbb"),
686       Bytes.toBytes("ccc"), false);
687 
688     // Daughter b
689     HRegionInfo splitb = new HRegionInfo(htd.getTableName(), Bytes.toBytes("ccc"),
690         new byte[0]);
691     Thread.sleep(1001);
692 
693     final Map<HRegionInfo, Result> splitParents =
694         new TreeMap<HRegionInfo, Result>(new SplitParentFirstComparator());
695     splitParents.put(parent, createResult(parent, splita, splitb));
696     splita.setOffline(true); //simulate that splita goes offline when it is split
697     splitParents.put(splita, createResult(splita, splitaa,splitab));
698 
699     final Map<HRegionInfo, Result> mergedRegions = new TreeMap<HRegionInfo, Result>();
700     CatalogJanitor janitor = spy(new CatalogJanitor(server, services));
701     doReturn(new Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>>(
702             10, mergedRegions, splitParents)).when(janitor)
703         .getMergedRegionsAndSplitParents();
704 
705     //create ref from splita to parent
706     Path splitaRef =
707         createReferences(services, htd, parent, splita, Bytes.toBytes("ccc"), false);
708 
709     //parent and A should not be removed
710     assertEquals(0, janitor.scan());
711 
712     //now delete the ref
713     FileSystem fs = FileSystem.get(htu.getConfiguration());
714     assertTrue(fs.delete(splitaRef, true));
715 
716     //now, both parent, and splita can be deleted
717     assertEquals(2, janitor.scan());
718 
719     services.stop("test finished");
720     janitor.cancel(true);
721   }
722 
723   /**
724    * Test that we correctly archive all the storefiles when a region is deleted
725    * @throws Exception
726    */
727   @Test
728   public void testSplitParentFirstComparator() {
729     SplitParentFirstComparator comp = new SplitParentFirstComparator();
730     final HTableDescriptor htd = createHTableDescriptor();
731 
732     /*  Region splits:
733      *
734      *  rootRegion --- firstRegion --- firstRegiona
735      *              |               |- firstRegionb
736      *              |
737      *              |- lastRegion --- lastRegiona  --- lastRegionaa
738      *                             |                |- lastRegionab
739      *                             |- lastRegionb
740      *
741      *  rootRegion   :   []  - []
742      *  firstRegion  :   []  - bbb
743      *  lastRegion   :   bbb - []
744      *  firstRegiona :   []  - aaa
745      *  firstRegionb :   aaa - bbb
746      *  lastRegiona  :   bbb - ddd
747      *  lastRegionb  :   ddd - []
748      */
749 
750     // root region
751     HRegionInfo rootRegion = new HRegionInfo(htd.getTableName(),
752       HConstants.EMPTY_START_ROW,
753       HConstants.EMPTY_END_ROW, true);
754     HRegionInfo firstRegion = new HRegionInfo(htd.getTableName(),
755       HConstants.EMPTY_START_ROW,
756       Bytes.toBytes("bbb"), true);
757     HRegionInfo lastRegion = new HRegionInfo(htd.getTableName(),
758       Bytes.toBytes("bbb"),
759       HConstants.EMPTY_END_ROW, true);
760 
761     assertTrue(comp.compare(rootRegion, rootRegion) == 0);
762     assertTrue(comp.compare(firstRegion, firstRegion) == 0);
763     assertTrue(comp.compare(lastRegion, lastRegion) == 0);
764     assertTrue(comp.compare(rootRegion, firstRegion) < 0);
765     assertTrue(comp.compare(rootRegion, lastRegion) < 0);
766     assertTrue(comp.compare(firstRegion, lastRegion) < 0);
767 
768     //first region split into a, b
769     HRegionInfo firstRegiona = new HRegionInfo(htd.getTableName(),
770       HConstants.EMPTY_START_ROW,
771       Bytes.toBytes("aaa"), true);
772     HRegionInfo firstRegionb = new HRegionInfo(htd.getTableName(),
773         Bytes.toBytes("aaa"),
774       Bytes.toBytes("bbb"), true);
775     //last region split into a, b
776     HRegionInfo lastRegiona = new HRegionInfo(htd.getTableName(),
777       Bytes.toBytes("bbb"),
778       Bytes.toBytes("ddd"), true);
779     HRegionInfo lastRegionb = new HRegionInfo(htd.getTableName(),
780       Bytes.toBytes("ddd"),
781       HConstants.EMPTY_END_ROW, true);
782 
783     assertTrue(comp.compare(firstRegiona, firstRegiona) == 0);
784     assertTrue(comp.compare(firstRegionb, firstRegionb) == 0);
785     assertTrue(comp.compare(rootRegion, firstRegiona) < 0);
786     assertTrue(comp.compare(rootRegion, firstRegionb) < 0);
787     assertTrue(comp.compare(firstRegion, firstRegiona) < 0);
788     assertTrue(comp.compare(firstRegion, firstRegionb) < 0);
789     assertTrue(comp.compare(firstRegiona, firstRegionb) < 0);
790 
791     assertTrue(comp.compare(lastRegiona, lastRegiona) == 0);
792     assertTrue(comp.compare(lastRegionb, lastRegionb) == 0);
793     assertTrue(comp.compare(rootRegion, lastRegiona) < 0);
794     assertTrue(comp.compare(rootRegion, lastRegionb) < 0);
795     assertTrue(comp.compare(lastRegion, lastRegiona) < 0);
796     assertTrue(comp.compare(lastRegion, lastRegionb) < 0);
797     assertTrue(comp.compare(lastRegiona, lastRegionb) < 0);
798 
799     assertTrue(comp.compare(firstRegiona, lastRegiona) < 0);
800     assertTrue(comp.compare(firstRegiona, lastRegionb) < 0);
801     assertTrue(comp.compare(firstRegionb, lastRegiona) < 0);
802     assertTrue(comp.compare(firstRegionb, lastRegionb) < 0);
803 
804     HRegionInfo lastRegionaa = new HRegionInfo(htd.getTableName(),
805       Bytes.toBytes("bbb"),
806       Bytes.toBytes("ccc"), false);
807     HRegionInfo lastRegionab = new HRegionInfo(htd.getTableName(),
808       Bytes.toBytes("ccc"),
809       Bytes.toBytes("ddd"), false);
810 
811     assertTrue(comp.compare(lastRegiona, lastRegionaa) < 0);
812     assertTrue(comp.compare(lastRegiona, lastRegionab) < 0);
813     assertTrue(comp.compare(lastRegionaa, lastRegionab) < 0);
814 
815   }
816 
817   @Test
818   public void testArchiveOldRegion() throws Exception {
819     String table = "table";
820     HBaseTestingUtility htu = new HBaseTestingUtility();
821     setRootDirAndCleanIt(htu, "testCleanParent");
822     Server server = new MockServer(htu);
823     MasterServices services = new MockMasterServices(server);
824 
825     // create the janitor
826     CatalogJanitor janitor = new CatalogJanitor(server, services);
827 
828     // Create regions.
829     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table));
830     htd.addFamily(new HColumnDescriptor("f"));
831     HRegionInfo parent = new HRegionInfo(htd.getTableName(),
832         Bytes.toBytes("aaa"), Bytes.toBytes("eee"));
833     HRegionInfo splita = new HRegionInfo(htd.getTableName(),
834         Bytes.toBytes("aaa"), Bytes.toBytes("ccc"));
835     HRegionInfo splitb = new HRegionInfo(htd.getTableName(),
836         Bytes.toBytes("ccc"),
837         Bytes.toBytes("eee"));
838 
839     // Test that when both daughter regions are in place, that we do not
840     // remove the parent.
841     Result parentMetaRow = createResult(parent, splita, splitb);
842     FileSystem fs = FileSystem.get(htu.getConfiguration());
843     Path rootdir = services.getMasterFileSystem().getRootDir();
844     // have to set the root directory since we use it in HFileDisposer to figure out to get to the
845     // archive directory. Otherwise, it just seems to pick the first root directory it can find (so
846     // the single test passes, but when the full suite is run, things get borked).
847     FSUtils.setRootDir(fs.getConf(), rootdir);
848     Path tabledir = FSUtils.getTableDir(rootdir, htd.getTableName());
849     Path storedir = HStore.getStoreHomedir(tabledir, parent, htd.getColumnFamilies()[0].getName());
850     Path storeArchive = HFileArchiveUtil.getStoreArchivePath(services.getConfiguration(), parent,
851       tabledir, htd.getColumnFamilies()[0].getName());
852     LOG.debug("Table dir:" + tabledir);
853     LOG.debug("Store dir:" + storedir);
854     LOG.debug("Store archive dir:" + storeArchive);
855 
856     // add a couple of store files that we can check for
857     FileStatus[] mockFiles = addMockStoreFiles(2, services, storedir);
858     // get the current store files for comparison
859     FileStatus[] storeFiles = fs.listStatus(storedir);
860     int index = 0;
861     for (FileStatus file : storeFiles) {
862       LOG.debug("Have store file:" + file.getPath());
863       assertEquals("Got unexpected store file", mockFiles[index].getPath(),
864         storeFiles[index].getPath());
865       index++;
866     }
867 
868     // do the cleaning of the parent
869     assertTrue(janitor.cleanParent(parent, parentMetaRow));
870     LOG.debug("Finished cleanup of parent region");
871 
872     // and now check to make sure that the files have actually been archived
873     FileStatus[] archivedStoreFiles = fs.listStatus(storeArchive);
874     logFiles("archived files", storeFiles);
875     logFiles("archived files", archivedStoreFiles);
876 
877     assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs);
878 
879     // cleanup
880     FSUtils.delete(fs, rootdir, true);
881     services.stop("Test finished");
882     server.stop("Test finished");
883     janitor.cancel(true);
884   }
885 
886   /**
887    * @param description description of the files for logging
888    * @param storeFiles the status of the files to log
889    */
890   private void logFiles(String description, FileStatus[] storeFiles) {
891     LOG.debug("Current " + description + ": ");
892     for (FileStatus file : storeFiles) {
893       LOG.debug(file.getPath());
894     }
895   }
896 
897   /**
898    * Test that if a store file with the same name is present as those already backed up cause the
899    * already archived files to be timestamped backup
900    */
901   @Test
902   public void testDuplicateHFileResolution() throws Exception {
903     String table = "table";
904     HBaseTestingUtility htu = new HBaseTestingUtility();
905     setRootDirAndCleanIt(htu, "testCleanParent");
906     Server server = new MockServer(htu);
907     MasterServices services = new MockMasterServices(server);
908 
909     // create the janitor
910 
911     CatalogJanitor janitor = new CatalogJanitor(server, services);
912 
913     // Create regions.
914     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(table));
915     htd.addFamily(new HColumnDescriptor("f"));
916     HRegionInfo parent = new HRegionInfo(htd.getTableName(),
917         Bytes.toBytes("aaa"), Bytes.toBytes("eee"));
918     HRegionInfo splita = new HRegionInfo(htd.getTableName(),
919         Bytes.toBytes("aaa"), Bytes.toBytes("ccc"));
920     HRegionInfo splitb = new HRegionInfo(htd.getTableName(),
921         Bytes.toBytes("ccc"), Bytes.toBytes("eee"));
922     // Test that when both daughter regions are in place, that we do not
923     // remove the parent.
924     Result r = createResult(parent, splita, splitb);
925 
926     FileSystem fs = FileSystem.get(htu.getConfiguration());
927 
928     Path rootdir = services.getMasterFileSystem().getRootDir();
929     // have to set the root directory since we use it in HFileDisposer to figure out to get to the
930     // archive directory. Otherwise, it just seems to pick the first root directory it can find (so
931     // the single test passes, but when the full suite is run, things get borked).
932     FSUtils.setRootDir(fs.getConf(), rootdir);
933     Path tabledir = FSUtils.getTableDir(rootdir, parent.getTable());
934     Path storedir = HStore.getStoreHomedir(tabledir, parent, htd.getColumnFamilies()[0].getName());
935     System.out.println("Old root:" + rootdir);
936     System.out.println("Old table:" + tabledir);
937     System.out.println("Old store:" + storedir);
938 
939     Path storeArchive = HFileArchiveUtil.getStoreArchivePath(services.getConfiguration(), parent,
940       tabledir, htd.getColumnFamilies()[0].getName());
941     System.out.println("Old archive:" + storeArchive);
942 
943     // enable archiving, make sure that files get archived
944     addMockStoreFiles(2, services, storedir);
945     // get the current store files for comparison
946     FileStatus[] storeFiles = fs.listStatus(storedir);
947     // do the cleaning of the parent
948     assertTrue(janitor.cleanParent(parent, r));
949 
950     // and now check to make sure that the files have actually been archived
951     FileStatus[] archivedStoreFiles = fs.listStatus(storeArchive);
952     assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs);
953 
954     // now add store files with the same names as before to check backup
955     // enable archiving, make sure that files get archived
956     addMockStoreFiles(2, services, storedir);
957 
958     // do the cleaning of the parent
959     assertTrue(janitor.cleanParent(parent, r));
960 
961     // and now check to make sure that the files have actually been archived
962     archivedStoreFiles = fs.listStatus(storeArchive);
963     assertArchiveEqualToOriginal(storeFiles, archivedStoreFiles, fs, true);
964 
965     // cleanup
966     services.stop("Test finished");
967     server.stop("shutdown");
968     janitor.cancel(true);
969   }
970 
971   private FileStatus[] addMockStoreFiles(int count, MasterServices services, Path storedir)
972       throws IOException {
973     // get the existing store files
974     FileSystem fs = services.getMasterFileSystem().getFileSystem();
975     fs.mkdirs(storedir);
976     // create the store files in the parent
977     for (int i = 0; i < count; i++) {
978       Path storeFile = new Path(storedir, "_store" + i);
979       FSDataOutputStream dos = fs.create(storeFile, true);
980       dos.writeBytes("Some data: " + i);
981       dos.close();
982     }
983     LOG.debug("Adding " + count + " store files to the storedir:" + storedir);
984     // make sure the mock store files are there
985     FileStatus[] storeFiles = fs.listStatus(storedir);
986     assertEquals("Didn't have expected store files", count, storeFiles.length);
987     return storeFiles;
988   }
989 
990   private String setRootDirAndCleanIt(final HBaseTestingUtility htu,
991       final String subdir)
992   throws IOException {
993     Path testdir = htu.getDataTestDir(subdir);
994     FileSystem fs = FileSystem.get(htu.getConfiguration());
995     if (fs.exists(testdir)) assertTrue(fs.delete(testdir, true));
996     FSUtils.setRootDir(htu.getConfiguration(), testdir);
997     return FSUtils.getRootDir(htu.getConfiguration()).toString();
998   }
999 
1000   /**
1001    * @param services Master services instance.
1002    * @param htd
1003    * @param parent
1004    * @param daughter
1005    * @param midkey
1006    * @param top True if we are to write a 'top' reference.
1007    * @return Path to reference we created.
1008    * @throws IOException
1009    */
1010   private Path createReferences(final MasterServices services,
1011       final HTableDescriptor htd, final HRegionInfo parent,
1012       final HRegionInfo daughter, final byte [] midkey, final boolean top)
1013   throws IOException {
1014     Path rootdir = services.getMasterFileSystem().getRootDir();
1015     Path tabledir = FSUtils.getTableDir(rootdir, parent.getTable());
1016     Path storedir = HStore.getStoreHomedir(tabledir, daughter,
1017       htd.getColumnFamilies()[0].getName());
1018     Reference ref =
1019       top? Reference.createTopReference(midkey): Reference.createBottomReference(midkey);
1020     long now = System.currentTimeMillis();
1021     // Reference name has this format: StoreFile#REF_NAME_PARSER
1022     Path p = new Path(storedir, Long.toString(now) + "." + parent.getEncodedName());
1023     FileSystem fs = services.getMasterFileSystem().getFileSystem();
1024     ref.write(fs, p);
1025     return p;
1026   }
1027 
1028   private Result createResult(final HRegionInfo parent, final HRegionInfo a,
1029       final HRegionInfo b)
1030   throws IOException {
1031     return MetaMockingUtil.getMetaTableRowResult(parent, null, a, b);
1032   }
1033 
1034   private HTableDescriptor createHTableDescriptor() {
1035     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("t"));
1036     htd.addFamily(new HColumnDescriptor("f"));
1037     return htd;
1038   }
1039 
1040   private MultiResponse buildMultiResponse(MultiRequest req) {
1041     MultiResponse.Builder builder = MultiResponse.newBuilder();
1042     RegionActionResult.Builder regionActionResultBuilder =
1043         RegionActionResult.newBuilder();
1044     ResultOrException.Builder roeBuilder = ResultOrException.newBuilder();
1045     for (RegionAction regionAction: req.getRegionActionList()) {
1046       regionActionResultBuilder.clear();
1047       for (ClientProtos.Action action: regionAction.getActionList()) {
1048         roeBuilder.clear();
1049         roeBuilder.setResult(ClientProtos.Result.getDefaultInstance());
1050         roeBuilder.setIndex(action.getIndex());
1051         regionActionResultBuilder.addResultOrException(roeBuilder.build());
1052       }
1053       builder.addRegionActionResult(regionActionResultBuilder.build());
1054     }
1055     return builder.build();
1056   }
1057 
1058 }
1059