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