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.client;
20  
21  import static org.mockito.Matchers.anyObject;
22  import static org.mockito.Mockito.doReturn;
23  import static org.mockito.Mockito.mock;
24  import static org.mockito.Mockito.reset;
25  import static org.mockito.Mockito.times;
26  import static org.mockito.Mockito.verify;
27  import static org.mockito.Mockito.when;
28  
29  import java.math.BigDecimal;
30  import java.util.List;
31  import java.util.NavigableMap;
32  import java.util.Random;
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.hbase.TableName;
38  import org.apache.hadoop.hbase.HBaseTestingUtility;
39  import org.apache.hadoop.hbase.HConstants;
40  import org.apache.hadoop.hbase.HRegionInfo;
41  import org.apache.hadoop.hbase.MediumTests;
42  import org.apache.hadoop.hbase.ServerName;
43  import org.apache.hadoop.hbase.catalog.CatalogTracker;
44  import org.apache.hadoop.hbase.catalog.MetaEditor;
45  import org.apache.hadoop.hbase.util.Bytes;
46  import org.apache.hadoop.hbase.util.StoppableImplementation;
47  import org.apache.hadoop.hbase.util.Threads;
48  import org.apache.hadoop.util.StringUtils;
49  import org.junit.After;
50  import org.junit.Assert;
51  import org.junit.Test;
52  import org.junit.experimental.categories.Category;
53  @Category(MediumTests.class)
54  public class TestMetaScanner {
55    final Log LOG = LogFactory.getLog(getClass());
56    private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
57  
58    public void setUp() throws Exception {
59      TEST_UTIL.startMiniCluster(1);
60    }
61  
62    @After
63    public void tearDown() throws Exception {
64      TEST_UTIL.shutdownMiniCluster();
65    }
66  
67    @Test
68    public void testMetaScanner() throws Exception {
69      LOG.info("Starting testMetaScanner");
70      setUp();
71      final TableName TABLENAME =
72          TableName.valueOf("testMetaScanner");
73      final byte[] FAMILY = Bytes.toBytes("family");
74      TEST_UTIL.createTable(TABLENAME, FAMILY);
75      Configuration conf = TEST_UTIL.getConfiguration();
76      HTable table = new HTable(conf, TABLENAME);
77      TEST_UTIL.createMultiRegions(conf, table, FAMILY,
78          new byte[][]{
79            HConstants.EMPTY_START_ROW,
80            Bytes.toBytes("region_a"),
81            Bytes.toBytes("region_b")});
82      // Make sure all the regions are deployed
83      TEST_UTIL.countRows(table);
84  
85      MetaScanner.MetaScannerVisitor visitor =
86        mock(MetaScanner.MetaScannerVisitor.class);
87      doReturn(true).when(visitor).processRow((Result)anyObject());
88  
89      // Scanning the entire table should give us three rows
90      MetaScanner.metaScan(conf, null, visitor, TABLENAME);
91      verify(visitor, times(3)).processRow((Result)anyObject());
92  
93      // Scanning the table with a specified empty start row should also
94      // give us three hbase:meta rows
95      reset(visitor);
96      doReturn(true).when(visitor).processRow((Result)anyObject());
97      MetaScanner.metaScan(conf, visitor, TABLENAME, HConstants.EMPTY_BYTE_ARRAY, 1000);
98      verify(visitor, times(3)).processRow((Result)anyObject());
99  
100     // Scanning the table starting in the middle should give us two rows:
101     // region_a and region_b
102     reset(visitor);
103     doReturn(true).when(visitor).processRow((Result)anyObject());
104     MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1000);
105     verify(visitor, times(2)).processRow((Result)anyObject());
106 
107     // Scanning with a limit of 1 should only give us one row
108     reset(visitor);
109     doReturn(true).when(visitor).processRow((Result)anyObject());
110     MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1);
111     verify(visitor, times(1)).processRow((Result)anyObject());
112     table.close();
113   }
114 
115   @Test
116   public void testConcurrentMetaScannerAndCatalogJanitor() throws Throwable {
117     /* TEST PLAN: start with only one region in a table. Have a splitter
118      * thread  and metascanner threads that continously scan the meta table for regions.
119      * CatalogJanitor from master will run frequently to clean things up
120      */
121     TEST_UTIL.getConfiguration().setLong("hbase.catalogjanitor.interval", 500);
122     setUp();
123 
124     final long runtime = 30 * 1000; //30 sec
125     LOG.info("Starting testConcurrentMetaScannerAndCatalogJanitor");
126     final TableName TABLENAME =
127         TableName.valueOf("testConcurrentMetaScannerAndCatalogJanitor");
128     final byte[] FAMILY = Bytes.toBytes("family");
129     TEST_UTIL.createTable(TABLENAME, FAMILY);
130     final CatalogTracker catalogTracker = mock(CatalogTracker.class);
131     when(catalogTracker.getConnection()).thenReturn(TEST_UTIL.getHBaseAdmin().getConnection());
132 
133     class RegionMetaSplitter extends StoppableImplementation implements Runnable {
134       Random random = new Random();
135       Throwable ex = null;
136       @Override
137       public void run() {
138         while (!isStopped()) {
139           try {
140             List<HRegionInfo> regions = MetaScanner.listAllRegions(
141               TEST_UTIL.getConfiguration(), false);
142 
143             //select a random region
144             HRegionInfo parent = regions.get(random.nextInt(regions.size()));
145             if (parent == null || !TABLENAME.equals(parent.getTable())) {
146               continue;
147             }
148 
149             long startKey = 0, endKey = Long.MAX_VALUE;
150             byte[] start = parent.getStartKey();
151             byte[] end = parent.getEndKey();
152             if (!Bytes.equals(HConstants.EMPTY_START_ROW, parent.getStartKey())) {
153               startKey = Bytes.toLong(parent.getStartKey());
154             }
155             if (!Bytes.equals(HConstants.EMPTY_END_ROW, parent.getEndKey())) {
156               endKey = Bytes.toLong(parent.getEndKey());
157             }
158             if (startKey == endKey) {
159               continue;
160             }
161 
162             long midKey = BigDecimal.valueOf(startKey).add(BigDecimal.valueOf(endKey))
163                 .divideToIntegralValue(BigDecimal.valueOf(2)).longValue();
164 
165             HRegionInfo splita = new HRegionInfo(TABLENAME,
166               start,
167               Bytes.toBytes(midKey));
168             HRegionInfo splitb = new HRegionInfo(TABLENAME,
169               Bytes.toBytes(midKey),
170               end);
171 
172             MetaEditor.splitRegion(catalogTracker, parent, splita, splitb, ServerName.valueOf("fooserver", 1, 0));
173 
174             Threads.sleep(random.nextInt(200));
175           } catch (Throwable e) {
176             ex = e;
177             Assert.fail(StringUtils.stringifyException(e));
178           }
179         }
180       }
181       void rethrowExceptionIfAny() throws Throwable {
182         if (ex != null) { throw ex; }
183       }
184     }
185 
186     class MetaScannerVerifier extends StoppableImplementation implements Runnable {
187       Random random = new Random();
188       Throwable ex = null;
189       @Override
190       public void run() {
191          while(!isStopped()) {
192            try {
193             NavigableMap<HRegionInfo, ServerName> regions =
194                 MetaScanner.allTableRegions(TEST_UTIL.getConfiguration(), null, TABLENAME, false);
195 
196             LOG.info("-------");
197             byte[] lastEndKey = HConstants.EMPTY_START_ROW;
198             for (HRegionInfo hri: regions.navigableKeySet()) {
199               long startKey = 0, endKey = Long.MAX_VALUE;
200               if (!Bytes.equals(HConstants.EMPTY_START_ROW, hri.getStartKey())) {
201                 startKey = Bytes.toLong(hri.getStartKey());
202               }
203               if (!Bytes.equals(HConstants.EMPTY_END_ROW, hri.getEndKey())) {
204                 endKey = Bytes.toLong(hri.getEndKey());
205               }
206               LOG.info("start:" + startKey + " end:" + endKey + " hri:" + hri);
207               Assert.assertTrue("lastEndKey=" + Bytes.toString(lastEndKey) + ", startKey=" +
208                 Bytes.toString(hri.getStartKey()), Bytes.equals(lastEndKey, hri.getStartKey()));
209               lastEndKey = hri.getEndKey();
210             }
211             Assert.assertTrue(Bytes.equals(lastEndKey, HConstants.EMPTY_END_ROW));
212             LOG.info("-------");
213             Threads.sleep(10 + random.nextInt(50));
214           } catch (Throwable e) {
215             ex = e;
216             Assert.fail(StringUtils.stringifyException(e));
217           }
218          }
219       }
220       void rethrowExceptionIfAny() throws Throwable {
221         if (ex != null) { throw ex; }
222       }
223     }
224 
225     RegionMetaSplitter regionMetaSplitter = new RegionMetaSplitter();
226     MetaScannerVerifier metaScannerVerifier = new MetaScannerVerifier();
227 
228     Thread regionMetaSplitterThread = new Thread(regionMetaSplitter);
229     Thread metaScannerVerifierThread = new Thread(metaScannerVerifier);
230 
231     regionMetaSplitterThread.start();
232     metaScannerVerifierThread.start();
233 
234     Threads.sleep(runtime);
235 
236     regionMetaSplitter.stop("test finished");
237     metaScannerVerifier.stop("test finished");
238 
239     regionMetaSplitterThread.join();
240     metaScannerVerifierThread.join();
241 
242     regionMetaSplitter.rethrowExceptionIfAny();
243     metaScannerVerifier.rethrowExceptionIfAny();
244   }
245 
246 }
247