View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one or more
5    * contributor license agreements. See the NOTICE file distributed with this
6    * work for additional information regarding copyright ownership. The ASF
7    * licenses this file to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance with the License.
9    * 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, WITHOUT
15   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16   * License for the specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.hadoop.hbase.regionserver;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  import static org.junit.Assert.fail;
25  
26  import java.io.IOException;
27  import java.util.List;
28  
29  import org.apache.commons.lang.math.RandomUtils;
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.fs.FileSystem;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.TableName;
35  import org.apache.hadoop.hbase.HBaseTestingUtility;
36  import org.apache.hadoop.hbase.HConstants;
37  import org.apache.hadoop.hbase.HRegionInfo;
38  import org.apache.hadoop.hbase.HTableDescriptor;
39  import org.apache.hadoop.hbase.LargeTests;
40  import org.apache.hadoop.hbase.MiniHBaseCluster;
41  import org.apache.hadoop.hbase.ServerName;
42  import org.apache.hadoop.hbase.UnknownRegionException;
43  import org.apache.hadoop.hbase.catalog.MetaReader;
44  import org.apache.hadoop.hbase.client.HBaseAdmin;
45  import org.apache.hadoop.hbase.client.HTable;
46  import org.apache.hadoop.hbase.client.Put;
47  import org.apache.hadoop.hbase.client.Result;
48  import org.apache.hadoop.hbase.client.ResultScanner;
49  import org.apache.hadoop.hbase.client.Scan;
50  import org.apache.hadoop.hbase.exceptions.MergeRegionException;
51  import org.apache.hadoop.hbase.master.AssignmentManager;
52  import org.apache.hadoop.hbase.master.HMaster;
53  import org.apache.hadoop.hbase.master.RegionState.State;
54  import org.apache.hadoop.hbase.master.RegionStates;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.hbase.util.FSUtils;
57  import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
58  import org.apache.hadoop.hbase.util.Pair;
59  import org.apache.hadoop.hbase.util.PairOfSameType;
60  import org.junit.AfterClass;
61  import org.junit.BeforeClass;
62  import org.junit.Test;
63  import org.junit.experimental.categories.Category;
64  
65  import com.google.common.base.Joiner;
66  
67  /**
68   * Like {@link TestRegionMergeTransaction} in that we're testing
69   * {@link RegionMergeTransaction} only the below tests are against a running
70   * cluster where {@link TestRegionMergeTransaction} is tests against bare
71   * {@link HRegion}.
72   */
73  @Category(LargeTests.class)
74  public class TestRegionMergeTransactionOnCluster {
75    private static final Log LOG = LogFactory
76        .getLog(TestRegionMergeTransactionOnCluster.class);
77    private static final int NB_SERVERS = 3;
78  
79    private static final byte[] FAMILYNAME = Bytes.toBytes("fam");
80    private static final byte[] QUALIFIER = Bytes.toBytes("q");
81  
82    private static byte[] ROW = Bytes.toBytes("testRow");
83    private static final int INITIAL_REGION_NUM = 10;
84    private static final int ROWSIZE = 200;
85    private static byte[][] ROWS = makeN(ROW, ROWSIZE);
86  
87    private static int waitTime = 60 * 1000;
88  
89    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
90  
91    private static HMaster master;
92    private static HBaseAdmin admin;
93  
94    @BeforeClass
95    public static void beforeAllTests() throws Exception {
96      // Start a cluster
97      TEST_UTIL.startMiniCluster(NB_SERVERS);
98      MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
99      master = cluster.getMaster();
100     master.balanceSwitch(false);
101     admin = TEST_UTIL.getHBaseAdmin();
102   }
103 
104   @AfterClass
105   public static void afterAllTests() throws Exception {
106     TEST_UTIL.shutdownMiniCluster();
107   }
108 
109   @Test
110   public void testWholesomeMerge() throws Exception {
111     LOG.info("Starting testWholesomeMerge");
112     final TableName tableName =
113         TableName.valueOf("testWholesomeMerge");
114 
115     // Create table and load data.
116     HTable table = createTableAndLoadData(master, tableName);
117     // Merge 1st and 2nd region
118     mergeRegionsAndVerifyRegionNum(master, tableName, 0, 1,
119         INITIAL_REGION_NUM - 1);
120 
121     // Merge 2nd and 3th region
122     PairOfSameType<HRegionInfo> mergedRegions =
123       mergeRegionsAndVerifyRegionNum(master, tableName, 1, 2,
124         INITIAL_REGION_NUM - 2);
125 
126     verifyRowCount(table, ROWSIZE);
127 
128     // Randomly choose one of the two merged regions
129     HRegionInfo hri = RandomUtils.nextBoolean() ?
130       mergedRegions.getFirst() : mergedRegions.getSecond();
131     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
132     AssignmentManager am = cluster.getMaster().getAssignmentManager();
133     RegionStates regionStates = am.getRegionStates();
134     long start = EnvironmentEdgeManager.currentTimeMillis();
135     while (!regionStates.isRegionInState(hri, State.MERGED)) {
136       assertFalse("Timed out in waiting one merged region to be in state MERGED",
137         EnvironmentEdgeManager.currentTimeMillis() - start > 60000);
138       Thread.sleep(500);
139     }
140 
141     // We should not be able to assign it again
142     am.assign(hri, true, true);
143     assertFalse("Merged region should not be in transition again",
144       regionStates.isRegionInTransition(hri)
145         && regionStates.isRegionInState(hri, State.MERGED));
146 
147     table.close();
148   }
149 
150   @Test
151   public void testCleanMergeReference() throws Exception {
152     LOG.info("Starting testCleanMergeReference");
153     admin.enableCatalogJanitor(false);
154     try {
155       final TableName tableName =
156           TableName.valueOf("testCleanMergeReference");
157       // Create table and load data.
158       HTable table = createTableAndLoadData(master, tableName);
159       // Merge 1st and 2nd region
160       mergeRegionsAndVerifyRegionNum(master, tableName, 0, 1,
161           INITIAL_REGION_NUM - 1);
162       verifyRowCount(table, ROWSIZE);
163       table.close();
164 
165       List<Pair<HRegionInfo, ServerName>> tableRegions = MetaReader
166           .getTableRegionsAndLocations(master.getCatalogTracker(),
167               tableName);
168       HRegionInfo mergedRegionInfo = tableRegions.get(0).getFirst();
169       HTableDescriptor tableDescritor = master.getTableDescriptors().get(
170           tableName);
171       Result mergedRegionResult = MetaReader.getRegionResult(
172           master.getCatalogTracker(), mergedRegionInfo.getRegionName());
173 
174       // contains merge reference in META
175       assertTrue(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
176           HConstants.MERGEA_QUALIFIER) != null);
177       assertTrue(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
178           HConstants.MERGEB_QUALIFIER) != null);
179 
180       // merging regions' directory are in the file system all the same
181       HRegionInfo regionA = HRegionInfo.getHRegionInfo(mergedRegionResult,
182           HConstants.MERGEA_QUALIFIER);
183       HRegionInfo regionB = HRegionInfo.getHRegionInfo(mergedRegionResult,
184           HConstants.MERGEB_QUALIFIER);
185       FileSystem fs = master.getMasterFileSystem().getFileSystem();
186       Path rootDir = master.getMasterFileSystem().getRootDir();
187 
188       Path tabledir = FSUtils.getTableDir(rootDir, mergedRegionInfo.getTableName());
189       Path regionAdir = new Path(tabledir, regionA.getEncodedName());
190       Path regionBdir = new Path(tabledir, regionB.getEncodedName());
191       assertTrue(fs.exists(regionAdir));
192       assertTrue(fs.exists(regionBdir));
193 
194       admin.compact(mergedRegionInfo.getRegionName());
195       // wait until merged region doesn't have reference file
196       long timeout = System.currentTimeMillis() + waitTime;
197       HRegionFileSystem hrfs = new HRegionFileSystem(
198           TEST_UTIL.getConfiguration(), fs, tabledir, mergedRegionInfo);
199       while (System.currentTimeMillis() < timeout) {
200         if (!hrfs.hasReferences(tableDescritor)) {
201           break;
202         }
203         Thread.sleep(50);
204       }
205       assertFalse(hrfs.hasReferences(tableDescritor));
206 
207       // run CatalogJanitor to clean merge references in META and archive the
208       // files of merging regions
209       int cleaned = admin.runCatalogScan();
210       assertTrue(cleaned > 0);
211       assertFalse(fs.exists(regionAdir));
212       assertFalse(fs.exists(regionBdir));
213 
214       mergedRegionResult = MetaReader.getRegionResult(
215           master.getCatalogTracker(), mergedRegionInfo.getRegionName());
216       assertFalse(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
217           HConstants.MERGEA_QUALIFIER) != null);
218       assertFalse(mergedRegionResult.getValue(HConstants.CATALOG_FAMILY,
219           HConstants.MERGEB_QUALIFIER) != null);
220 
221     } finally {
222       admin.enableCatalogJanitor(true);
223     }
224   }
225 
226   /**
227    * This test tests 1, merging region not online;
228    * 2, merging same two regions; 3, merging unknown regions.
229    * They are in one test case so that we don't have to create
230    * many tables, and these tests are simple.
231    */
232   @Test
233   public void testMerge() throws Exception {
234     LOG.info("Starting testMerge");
235     final TableName tableName = TableName.valueOf("testMerge");
236 
237     try {
238       // Create table and load data.
239       HTable table = createTableAndLoadData(master, tableName);
240       RegionStates regionStates = master.getAssignmentManager().getRegionStates();
241       List<HRegionInfo> regions = regionStates.getRegionsOfTable(tableName);
242       // Fake offline one region
243       HRegionInfo a = regions.get(0);
244       HRegionInfo b = regions.get(1);
245       regionStates.regionOffline(a);
246       try {
247         // Merge offline region. Region a is offline here
248         admin.mergeRegions(a.getEncodedNameAsBytes(), b.getEncodedNameAsBytes(), false);
249         fail("Offline regions should not be able to merge");
250       } catch (IOException ie) {
251         assertTrue("Exception should mention regions not online",
252           ie.getMessage().contains("regions not online")
253             && ie instanceof MergeRegionException);
254       }
255       try {
256         // Merge the same region: b and b.
257         admin.mergeRegions(b.getEncodedNameAsBytes(), b.getEncodedNameAsBytes(), true);
258         fail("A region should not be able to merge with itself, even forcifully");
259       } catch (IOException ie) {
260         assertTrue("Exception should mention regions not online",
261           ie.getMessage().contains("region to itself")
262             && ie instanceof MergeRegionException);
263       }
264       try {
265         // Merge unknown regions
266         admin.mergeRegions(Bytes.toBytes("-f1"), Bytes.toBytes("-f2"), true);
267         fail("Unknown region could not be merged");
268       } catch (IOException ie) {
269         assertTrue("UnknownRegionException should be thrown",
270           ie instanceof UnknownRegionException);
271       }
272       table.close();
273     } finally {
274       TEST_UTIL.deleteTable(tableName);
275     }
276   }
277 
278   private PairOfSameType<HRegionInfo> mergeRegionsAndVerifyRegionNum(
279       HMaster master, TableName tablename,
280       int regionAnum, int regionBnum, int expectedRegionNum) throws Exception {
281     PairOfSameType<HRegionInfo> mergedRegions =
282       requestMergeRegion(master, tablename, regionAnum, regionBnum);
283     waitAndVerifyRegionNum(master, tablename, expectedRegionNum);
284     return mergedRegions;
285   }
286 
287   private PairOfSameType<HRegionInfo> requestMergeRegion(
288       HMaster master, TableName tablename,
289       int regionAnum, int regionBnum) throws Exception {
290     List<Pair<HRegionInfo, ServerName>> tableRegions = MetaReader
291         .getTableRegionsAndLocations(master.getCatalogTracker(),
292             tablename);
293     HRegionInfo regionA = tableRegions.get(regionAnum).getFirst();
294     HRegionInfo regionB = tableRegions.get(regionBnum).getFirst();
295     TEST_UTIL.getHBaseAdmin().mergeRegions(
296       regionA.getEncodedNameAsBytes(),
297       regionB.getEncodedNameAsBytes(), false);
298     return new PairOfSameType<HRegionInfo>(regionA, regionB);
299   }
300 
301   private void waitAndVerifyRegionNum(HMaster master, TableName tablename,
302       int expectedRegionNum) throws Exception {
303     List<Pair<HRegionInfo, ServerName>> tableRegionsInMeta;
304     List<HRegionInfo> tableRegionsInMaster;
305     long timeout = System.currentTimeMillis() + waitTime;
306     while (System.currentTimeMillis() < timeout) {
307       tableRegionsInMeta = MetaReader.getTableRegionsAndLocations(
308           master.getCatalogTracker(), tablename);
309       tableRegionsInMaster = master.getAssignmentManager().getRegionStates()
310           .getRegionsOfTable(tablename);
311       if (tableRegionsInMeta.size() == expectedRegionNum
312           && tableRegionsInMaster.size() == expectedRegionNum) {
313         break;
314       }
315       Thread.sleep(250);
316     }
317 
318     tableRegionsInMeta = MetaReader.getTableRegionsAndLocations(
319         master.getCatalogTracker(), tablename);
320     LOG.info("Regions after merge:" + Joiner.on(',').join(tableRegionsInMeta));
321     assertEquals(expectedRegionNum, tableRegionsInMeta.size());
322   }
323 
324   private HTable createTableAndLoadData(HMaster master, TableName tablename)
325       throws Exception {
326     return createTableAndLoadData(master, tablename, INITIAL_REGION_NUM);
327   }
328 
329   private HTable createTableAndLoadData(HMaster master, TableName tablename,
330       int numRegions) throws Exception {
331     assertTrue("ROWSIZE must > numregions:" + numRegions, ROWSIZE > numRegions);
332     byte[][] splitRows = new byte[numRegions - 1][];
333     for (int i = 0; i < splitRows.length; i++) {
334       splitRows[i] = ROWS[(i + 1) * ROWSIZE / numRegions];
335     }
336 
337     HTable table = TEST_UTIL.createTable(tablename, FAMILYNAME, splitRows);
338     loadData(table);
339     verifyRowCount(table, ROWSIZE);
340 
341     // sleep here is an ugly hack to allow region transitions to finish
342     long timeout = System.currentTimeMillis() + waitTime;
343     List<Pair<HRegionInfo, ServerName>> tableRegions;
344     while (System.currentTimeMillis() < timeout) {
345       tableRegions = MetaReader.getTableRegionsAndLocations(
346           master.getCatalogTracker(), tablename);
347       if (tableRegions.size() == numRegions)
348         break;
349       Thread.sleep(250);
350     }
351 
352     tableRegions = MetaReader.getTableRegionsAndLocations(
353         master.getCatalogTracker(), tablename);
354     LOG.info("Regions after load: " + Joiner.on(',').join(tableRegions));
355     assertEquals(numRegions, tableRegions.size());
356     return table;
357   }
358 
359   private static byte[][] makeN(byte[] base, int n) {
360     byte[][] ret = new byte[n][];
361     for (int i = 0; i < n; i++) {
362       ret[i] = Bytes.add(base, Bytes.toBytes(String.format("%04d", i)));
363     }
364     return ret;
365   }
366 
367   private void loadData(HTable table) throws IOException {
368     for (int i = 0; i < ROWSIZE; i++) {
369       Put put = new Put(ROWS[i]);
370       put.add(FAMILYNAME, QUALIFIER, Bytes.toBytes(i));
371       table.put(put);
372     }
373   }
374 
375   private void verifyRowCount(HTable table, int expectedRegionNum)
376       throws IOException {
377     ResultScanner scanner = table.getScanner(new Scan());
378     int rowCount = 0;
379     while (scanner.next() != null) {
380       rowCount++;
381     }
382     assertEquals(expectedRegionNum, rowCount);
383     scanner.close();
384   }
385 }
386