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;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertNotNull;
24  import static org.junit.Assert.assertNull;
25  import static org.junit.Assert.assertTrue;
26  
27  import java.io.IOException;
28  import java.util.List;
29  import java.util.Random;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.hbase.client.Admin;
35  import org.apache.hadoop.hbase.client.Connection;
36  import org.apache.hadoop.hbase.client.ConnectionFactory;
37  import org.apache.hadoop.hbase.client.Get;
38  import org.apache.hadoop.hbase.client.HTable;
39  import org.apache.hadoop.hbase.client.RegionLocator;
40  import org.apache.hadoop.hbase.client.Result;
41  import org.apache.hadoop.hbase.client.Table;
42  import org.apache.hadoop.hbase.testclassification.MediumTests;
43  import org.apache.hadoop.hbase.util.Bytes;
44  import org.apache.hadoop.hbase.util.Pair;
45  import org.junit.AfterClass;
46  import org.junit.Assert;
47  import org.junit.BeforeClass;
48  import org.junit.Test;
49  import org.junit.experimental.categories.Category;
50  
51  import com.google.common.collect.Lists;
52  
53  /**
54   * Test {@link org.apache.hadoop.hbase.MetaTableAccessor}.
55   */
56  @Category(MediumTests.class)
57  public class TestMetaTableAccessor {
58    private static final Log LOG = LogFactory.getLog(TestMetaTableAccessor.class);
59    private static final  HBaseTestingUtility UTIL = new HBaseTestingUtility();
60    private static Connection connection;
61    private Random random = new Random();
62  
63    @BeforeClass public static void beforeClass() throws Exception {
64      UTIL.startMiniCluster(3);
65  
66      Configuration c = new Configuration(UTIL.getConfiguration());
67      // Tests to 4 retries every 5 seconds. Make it try every 1 second so more
68      // responsive.  1 second is default as is ten retries.
69      c.setLong("hbase.client.pause", 1000);
70      c.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 10);
71      connection = ConnectionFactory.createConnection(c);
72    }
73  
74    @AfterClass public static void afterClass() throws Exception {
75      connection.close();
76      UTIL.shutdownMiniCluster();
77    }
78  
79    /**
80     * Does {@link MetaTableAccessor#getRegion(Connection, byte[])} and a write
81     * against hbase:meta while its hosted server is restarted to prove our retrying
82     * works.
83     * @throws IOException
84     * @throws InterruptedException
85     */
86    @Test public void testRetrying()
87    throws IOException, InterruptedException {
88      final TableName name =
89          TableName.valueOf("testRetrying");
90      LOG.info("Started " + name);
91      HTable t = UTIL.createMultiRegionTable(name, HConstants.CATALOG_FAMILY);
92      int regionCount = -1;
93      try (RegionLocator r = t.getRegionLocator()) {
94        regionCount = r.getStartKeys().length;
95      }
96      // Test it works getting a region from just made user table.
97      final List<HRegionInfo> regions =
98        testGettingTableRegions(connection, name, regionCount);
99      MetaTask reader = new MetaTask(connection, "reader") {
100       @Override
101       void metaTask() throws Throwable {
102         testGetRegion(connection, regions.get(0));
103         LOG.info("Read " + regions.get(0).getEncodedName());
104       }
105     };
106     MetaTask writer = new MetaTask(connection, "writer") {
107       @Override
108       void metaTask() throws Throwable {
109         MetaTableAccessor.addRegionToMeta(connection, regions.get(0));
110         LOG.info("Wrote " + regions.get(0).getEncodedName());
111       }
112     };
113     reader.start();
114     writer.start();
115 
116     // We're gonna check how it takes. If it takes too long, we will consider
117     //  it as a fail. We can't put that in the @Test tag as we want to close
118     //  the threads nicely
119     final long timeOut = 180000;
120     long startTime = System.currentTimeMillis();
121 
122     try {
123       // Make sure reader and writer are working.
124       assertTrue(reader.isProgressing());
125       assertTrue(writer.isProgressing());
126 
127       // Kill server hosting meta -- twice  . See if our reader/writer ride over the
128       // meta moves.  They'll need to retry.
129       for (int i = 0; i < 2; i++) {
130         LOG.info("Restart=" + i);
131         UTIL.ensureSomeRegionServersAvailable(2);
132         int index = -1;
133         do {
134           index = UTIL.getMiniHBaseCluster().getServerWithMeta();
135         } while (index == -1 &&
136           startTime + timeOut < System.currentTimeMillis());
137 
138         if (index != -1){
139           UTIL.getMiniHBaseCluster().abortRegionServer(index);
140           UTIL.getMiniHBaseCluster().waitOnRegionServer(index);
141         }
142       }
143 
144       assertTrue("reader: " + reader.toString(), reader.isProgressing());
145       assertTrue("writer: " + writer.toString(), writer.isProgressing());
146     } catch (IOException e) {
147       throw e;
148     } finally {
149       reader.stop = true;
150       writer.stop = true;
151       reader.join();
152       writer.join();
153       t.close();
154     }
155     long exeTime = System.currentTimeMillis() - startTime;
156     assertTrue("Timeout: test took " + exeTime / 1000 + " sec", exeTime < timeOut);
157   }
158 
159   /**
160    * Thread that runs a MetaTableAccessor task until asked stop.
161    */
162   abstract static class MetaTask extends Thread {
163     boolean stop = false;
164     int count = 0;
165     Throwable t = null;
166     final Connection connection;
167 
168     MetaTask(final Connection connection, final String name) {
169       super(name);
170       this.connection = connection;
171     }
172 
173     @Override
174     public void run() {
175       try {
176         while(!this.stop) {
177           LOG.info("Before " + this.getName()+ ", count=" + this.count);
178           metaTask();
179           this.count += 1;
180           LOG.info("After " + this.getName() + ", count=" + this.count);
181           Thread.sleep(100);
182         }
183       } catch (Throwable t) {
184         LOG.info(this.getName() + " failed", t);
185         this.t = t;
186       }
187     }
188 
189     boolean isProgressing() throws InterruptedException {
190       int currentCount = this.count;
191       while(currentCount == this.count) {
192         if (!isAlive()) return false;
193         if (this.t != null) return false;
194         Thread.sleep(10);
195       }
196       return true;
197     }
198 
199     @Override
200     public String toString() {
201       return "count=" + this.count + ", t=" +
202         (this.t == null? "null": this.t.toString());
203     }
204 
205     abstract void metaTask() throws Throwable;
206   }
207 
208   @Test public void testGetRegionsCatalogTables()
209   throws IOException, InterruptedException {
210     List<HRegionInfo> regions =
211       MetaTableAccessor.getTableRegions(UTIL.getZooKeeperWatcher(),
212         connection, TableName.META_TABLE_NAME);
213     assertTrue(regions.size() >= 1);
214     assertTrue(MetaTableAccessor.getTableRegionsAndLocations(UTIL.getZooKeeperWatcher(),
215       connection,TableName.META_TABLE_NAME).size() >= 1);
216   }
217 
218   @Test public void testTableExists() throws IOException {
219     final TableName name =
220         TableName.valueOf("testTableExists");
221     assertFalse(MetaTableAccessor.tableExists(connection, name));
222     UTIL.createTable(name, HConstants.CATALOG_FAMILY);
223     assertTrue(MetaTableAccessor.tableExists(connection, name));
224     Admin admin = UTIL.getHBaseAdmin();
225     admin.disableTable(name);
226     admin.deleteTable(name);
227     assertFalse(MetaTableAccessor.tableExists(connection, name));
228     assertTrue(MetaTableAccessor.tableExists(connection,
229       TableName.META_TABLE_NAME));
230   }
231 
232   @Test public void testGetRegion() throws IOException, InterruptedException {
233     final String name = "testGetRegion";
234     LOG.info("Started " + name);
235     // Test get on non-existent region.
236     Pair<HRegionInfo, ServerName> pair =
237       MetaTableAccessor.getRegion(connection, Bytes.toBytes("nonexistent-region"));
238     assertNull(pair);
239     LOG.info("Finished " + name);
240   }
241 
242   // Test for the optimization made in HBASE-3650
243   @Test public void testScanMetaForTable()
244   throws IOException, InterruptedException {
245     final TableName name =
246         TableName.valueOf("testScanMetaForTable");
247     LOG.info("Started " + name);
248 
249     /** Create 2 tables
250      - testScanMetaForTable
251      - testScanMetaForTablf
252     **/
253 
254     UTIL.createTable(name, HConstants.CATALOG_FAMILY);
255     // name that is +1 greater than the first one (e+1=f)
256     TableName greaterName =
257         TableName.valueOf("testScanMetaForTablf");
258     UTIL.createTable(greaterName, HConstants.CATALOG_FAMILY);
259 
260     // Now make sure we only get the regions from 1 of the tables at a time
261 
262     assertEquals(1, MetaTableAccessor.getTableRegions(UTIL.getZooKeeperWatcher(),
263       connection, name).size());
264     assertEquals(1, MetaTableAccessor.getTableRegions(UTIL.getZooKeeperWatcher(),
265       connection, greaterName).size());
266   }
267 
268   private static List<HRegionInfo> testGettingTableRegions(final Connection connection,
269       final TableName name, final int regionCount)
270   throws IOException, InterruptedException {
271     List<HRegionInfo> regions = MetaTableAccessor.getTableRegions(UTIL.getZooKeeperWatcher(),
272       connection, name);
273     assertEquals(regionCount, regions.size());
274     Pair<HRegionInfo, ServerName> pair =
275       MetaTableAccessor.getRegion(connection, regions.get(0).getRegionName());
276     assertEquals(regions.get(0).getEncodedName(),
277       pair.getFirst().getEncodedName());
278     return regions;
279   }
280 
281   private static void testGetRegion(final Connection connection,
282       final HRegionInfo region)
283   throws IOException, InterruptedException {
284     Pair<HRegionInfo, ServerName> pair =
285       MetaTableAccessor.getRegion(connection, region.getRegionName());
286     assertEquals(region.getEncodedName(),
287       pair.getFirst().getEncodedName());
288   }
289 
290   @Test
291   public void testParseReplicaIdFromServerColumn() {
292     String column1 = HConstants.SERVER_QUALIFIER_STR;
293     assertEquals(0, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column1)));
294     String column2 = column1 + MetaTableAccessor.META_REPLICA_ID_DELIMITER;
295     assertEquals(-1, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column2)));
296     String column3 = column2 + "00";
297     assertEquals(-1, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column3)));
298     String column4 = column3 + "2A";
299     assertEquals(42, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column4)));
300     String column5 = column4 + "2A";
301     assertEquals(-1, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column5)));
302     String column6 = HConstants.STARTCODE_QUALIFIER_STR;
303     assertEquals(-1, MetaTableAccessor.parseReplicaIdFromServerColumn(Bytes.toBytes(column6)));
304   }
305 
306   @Test
307   public void testMetaReaderGetColumnMethods() {
308     Assert.assertArrayEquals(HConstants.SERVER_QUALIFIER, MetaTableAccessor.getServerColumn(0));
309     Assert.assertArrayEquals(Bytes.toBytes(HConstants.SERVER_QUALIFIER_STR
310       + MetaTableAccessor.META_REPLICA_ID_DELIMITER + "002A"),
311       MetaTableAccessor.getServerColumn(42));
312 
313     Assert.assertArrayEquals(HConstants.STARTCODE_QUALIFIER,
314       MetaTableAccessor.getStartCodeColumn(0));
315     Assert.assertArrayEquals(Bytes.toBytes(HConstants.STARTCODE_QUALIFIER_STR
316       + MetaTableAccessor.META_REPLICA_ID_DELIMITER + "002A"),
317       MetaTableAccessor.getStartCodeColumn(42));
318 
319     Assert.assertArrayEquals(HConstants.SEQNUM_QUALIFIER,
320       MetaTableAccessor.getSeqNumColumn(0));
321     Assert.assertArrayEquals(Bytes.toBytes(HConstants.SEQNUM_QUALIFIER_STR
322       + MetaTableAccessor.META_REPLICA_ID_DELIMITER + "002A"),
323       MetaTableAccessor.getSeqNumColumn(42));
324   }
325 
326   @Test
327   public void testMetaLocationsForRegionReplicas() throws IOException {
328     ServerName serverName0 = ServerName.valueOf("foo", 60010, random.nextLong());
329     ServerName serverName1 = ServerName.valueOf("bar", 60010, random.nextLong());
330     ServerName serverName100 = ServerName.valueOf("baz", 60010, random.nextLong());
331 
332     long regionId = System.currentTimeMillis();
333     HRegionInfo primary = new HRegionInfo(TableName.valueOf("table_foo"),
334       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId, 0);
335     HRegionInfo replica1 = new HRegionInfo(TableName.valueOf("table_foo"),
336       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId, 1);
337     HRegionInfo replica100 = new HRegionInfo(TableName.valueOf("table_foo"),
338       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId, 100);
339 
340     long seqNum0 = random.nextLong();
341     long seqNum1 = random.nextLong();
342     long seqNum100 = random.nextLong();
343 
344 
345     Table meta = MetaTableAccessor.getMetaHTable(connection);
346     try {
347       MetaTableAccessor.updateRegionLocation(connection, primary, serverName0, seqNum0);
348 
349       // assert that the server, startcode and seqNum columns are there for the primary region
350       assertMetaLocation(meta, primary.getRegionName(), serverName0, seqNum0, 0, true);
351 
352       // add replica = 1
353       MetaTableAccessor.updateRegionLocation(connection, replica1, serverName1, seqNum1);
354       // check whether the primary is still there
355       assertMetaLocation(meta, primary.getRegionName(), serverName0, seqNum0, 0, true);
356       // now check for replica 1
357       assertMetaLocation(meta, primary.getRegionName(), serverName1, seqNum1, 1, true);
358 
359       // add replica = 1
360       MetaTableAccessor.updateRegionLocation(connection, replica100, serverName100, seqNum100);
361       // check whether the primary is still there
362       assertMetaLocation(meta, primary.getRegionName(), serverName0, seqNum0, 0, true);
363       // check whether the replica 1 is still there
364       assertMetaLocation(meta, primary.getRegionName(), serverName1, seqNum1, 1, true);
365       // now check for replica 1
366       assertMetaLocation(meta, primary.getRegionName(), serverName100, seqNum100, 100, true);
367     } finally {
368       meta.close();
369     }
370   }
371 
372   public static void assertMetaLocation(Table meta, byte[] row, ServerName serverName,
373       long seqNum, int replicaId, boolean checkSeqNum) throws IOException {
374     Get get = new Get(row);
375     Result result = meta.get(get);
376     assertTrue(Bytes.equals(
377       result.getValue(HConstants.CATALOG_FAMILY, MetaTableAccessor.getServerColumn(replicaId)),
378       Bytes.toBytes(serverName.getHostAndPort())));
379     assertTrue(Bytes.equals(
380       result.getValue(HConstants.CATALOG_FAMILY, MetaTableAccessor.getStartCodeColumn(replicaId)),
381       Bytes.toBytes(serverName.getStartcode())));
382     if (checkSeqNum) {
383       assertTrue(Bytes.equals(
384         result.getValue(HConstants.CATALOG_FAMILY, MetaTableAccessor.getSeqNumColumn(replicaId)),
385         Bytes.toBytes(seqNum)));
386     }
387   }
388 
389   public static void assertEmptyMetaLocation(Table meta, byte[] row, int replicaId)
390       throws IOException {
391     Get get = new Get(row);
392     Result result = meta.get(get);
393     Cell serverCell = result.getColumnLatestCell(HConstants.CATALOG_FAMILY,
394       MetaTableAccessor.getServerColumn(replicaId));
395     Cell startCodeCell = result.getColumnLatestCell(HConstants.CATALOG_FAMILY,
396       MetaTableAccessor.getStartCodeColumn(replicaId));
397     assertNotNull(serverCell);
398     assertNotNull(startCodeCell);
399     assertEquals(0, serverCell.getValueLength());
400     assertEquals(0, startCodeCell.getValueLength());
401   }
402 
403   @Test
404   public void testMetaLocationForRegionReplicasIsAddedAtTableCreation() throws IOException {
405     long regionId = System.currentTimeMillis();
406     HRegionInfo primary = new HRegionInfo(TableName.valueOf("table_foo"),
407       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId, 0);
408 
409     Table meta = MetaTableAccessor.getMetaHTable(connection);
410     try {
411       List<HRegionInfo> regionInfos = Lists.newArrayList(primary);
412       MetaTableAccessor.addRegionsToMeta(connection, regionInfos, 3);
413 
414       assertEmptyMetaLocation(meta, primary.getRegionName(), 1);
415       assertEmptyMetaLocation(meta, primary.getRegionName(), 2);
416     } finally {
417       meta.close();
418     }
419   }
420 
421   @Test
422   public void testMetaLocationForRegionReplicasIsAddedAtRegionSplit() throws IOException {
423     long regionId = System.currentTimeMillis();
424     ServerName serverName0 = ServerName.valueOf("foo", 60010, random.nextLong());
425     HRegionInfo parent = new HRegionInfo(TableName.valueOf("table_foo"),
426       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId, 0);
427     HRegionInfo splitA = new HRegionInfo(TableName.valueOf("table_foo"),
428       HConstants.EMPTY_START_ROW, Bytes.toBytes("a"), false, regionId+1, 0);
429     HRegionInfo splitB = new HRegionInfo(TableName.valueOf("table_foo"),
430       Bytes.toBytes("a"), HConstants.EMPTY_END_ROW, false, regionId+1, 0);
431 
432 
433     Table meta = MetaTableAccessor.getMetaHTable(connection);
434     try {
435       List<HRegionInfo> regionInfos = Lists.newArrayList(parent);
436       MetaTableAccessor.addRegionsToMeta(connection, regionInfos, 3);
437 
438       MetaTableAccessor.splitRegion(connection, parent, splitA, splitB, serverName0, 3);
439 
440       assertEmptyMetaLocation(meta, splitA.getRegionName(), 1);
441       assertEmptyMetaLocation(meta, splitA.getRegionName(), 2);
442       assertEmptyMetaLocation(meta, splitB.getRegionName(), 1);
443       assertEmptyMetaLocation(meta, splitB.getRegionName(), 2);
444     } finally {
445       meta.close();
446     }
447   }
448 
449   @Test
450   public void testMetaLocationForRegionReplicasIsAddedAtRegionMerge() throws IOException {
451     long regionId = System.currentTimeMillis();
452     ServerName serverName0 = ServerName.valueOf("foo", 60010, random.nextLong());
453 
454     HRegionInfo parentA = new HRegionInfo(TableName.valueOf("table_foo"),
455       Bytes.toBytes("a"), HConstants.EMPTY_END_ROW, false, regionId, 0);
456     HRegionInfo parentB = new HRegionInfo(TableName.valueOf("table_foo"),
457       HConstants.EMPTY_START_ROW, Bytes.toBytes("a"), false, regionId, 0);
458     HRegionInfo merged = new HRegionInfo(TableName.valueOf("table_foo"),
459       HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, false, regionId+1, 0);
460 
461     Table meta = MetaTableAccessor.getMetaHTable(connection);
462     try {
463       List<HRegionInfo> regionInfos = Lists.newArrayList(parentA, parentB);
464       MetaTableAccessor.addRegionsToMeta(connection, regionInfos, 3);
465 
466       MetaTableAccessor.mergeRegions(connection, merged, parentA, parentB, serverName0, 3);
467 
468       assertEmptyMetaLocation(meta, merged.getRegionName(), 1);
469       assertEmptyMetaLocation(meta, merged.getRegionName(), 2);
470     } finally {
471       meta.close();
472     }
473   }
474 }
475