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.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.ArrayList;
28  import java.util.List;
29  import java.util.concurrent.atomic.AtomicInteger;
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.HBaseTestingUtility;
35  import org.apache.hadoop.hbase.HColumnDescriptor;
36  import org.apache.hadoop.hbase.HConstants;
37  import org.apache.hadoop.hbase.HRegionInfo;
38  import org.apache.hadoop.hbase.HRegionLocation;
39  import org.apache.hadoop.hbase.HTableDescriptor;
40  import org.apache.hadoop.hbase.testclassification.LargeTests;
41  import org.apache.hadoop.hbase.MasterNotRunningException;
42  import org.apache.hadoop.hbase.MiniHBaseCluster;
43  import org.apache.hadoop.hbase.NotServingRegionException;
44  import org.apache.hadoop.hbase.ServerName;
45  import org.apache.hadoop.hbase.TableExistsException;
46  import org.apache.hadoop.hbase.TableName;
47  import org.apache.hadoop.hbase.TableNotDisabledException;
48  import org.apache.hadoop.hbase.TableNotEnabledException;
49  import org.apache.hadoop.hbase.TableNotFoundException;
50  import org.apache.hadoop.hbase.ZooKeeperConnectionException;
51  import org.apache.hadoop.hbase.constraint.ConstraintException;
52  import org.apache.hadoop.hbase.master.AssignmentManager;
53  import org.apache.hadoop.hbase.master.HMaster;
54  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
55  import org.apache.hadoop.hbase.regionserver.HRegion;
56  import org.apache.hadoop.hbase.regionserver.HRegionServer;
57  import org.apache.hadoop.hbase.util.Bytes;
58  import org.apache.hadoop.hbase.util.Pair;
59  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
60  import org.junit.After;
61  import org.junit.AfterClass;
62  import org.junit.Assert;
63  import org.junit.Before;
64  import org.junit.BeforeClass;
65  import org.junit.Test;
66  import org.junit.experimental.categories.Category;
67  
68  import com.google.protobuf.ServiceException;
69  
70  
71  /**
72   * Class to test HBaseAdmin.
73   * Spins up the minicluster once at test start and then takes it down afterward.
74   * Add any testing of HBaseAdmin functionality here.
75   */
76  @Category(LargeTests.class)
77  public class TestAdmin2 {
78    final Log LOG = LogFactory.getLog(getClass());
79    private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
80    private Admin admin;
81  
82    @BeforeClass
83    public static void setUpBeforeClass() throws Exception {
84      TEST_UTIL.getConfiguration().setBoolean("hbase.online.schema.update.enable", true);
85      TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100);
86      TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250);
87      TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6);
88      TEST_UTIL.getConfiguration().setBoolean(
89          "hbase.master.enabletable.roundrobin", true);
90      TEST_UTIL.startMiniCluster(3);
91    }
92  
93    @AfterClass
94    public static void tearDownAfterClass() throws Exception {
95      TEST_UTIL.shutdownMiniCluster();
96    }
97  
98    @Before
99    public void setUp() throws Exception {
100     this.admin = TEST_UTIL.getHBaseAdmin();
101   }
102 
103   @After
104   public void tearDown() throws Exception {
105     for (HTableDescriptor htd : this.admin.listTables()) {
106       TEST_UTIL.deleteTable(htd.getName());
107     }
108   }
109 
110   @Test (timeout=300000)
111   public void testCreateBadTables() throws IOException {
112     String msg = null;
113     try {
114       this.admin.createTable(new HTableDescriptor(TableName.META_TABLE_NAME));
115     } catch(TableExistsException e) {
116       msg = e.toString();
117     }
118     assertTrue("Unexcepted exception message " + msg, msg != null &&
119       msg.startsWith(TableExistsException.class.getName()) &&
120       msg.contains(TableName.META_TABLE_NAME.getNameAsString()));
121 
122     // Now try and do concurrent creation with a bunch of threads.
123     final HTableDescriptor threadDesc =
124       new HTableDescriptor(TableName.valueOf("threaded_testCreateBadTables"));
125     threadDesc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
126     int count = 10;
127     Thread [] threads = new Thread [count];
128     final AtomicInteger successes = new AtomicInteger(0);
129     final AtomicInteger failures = new AtomicInteger(0);
130     final Admin localAdmin = this.admin;
131     for (int i = 0; i < count; i++) {
132       threads[i] = new Thread(Integer.toString(i)) {
133         @Override
134         public void run() {
135           try {
136             localAdmin.createTable(threadDesc);
137             successes.incrementAndGet();
138           } catch (TableExistsException e) {
139             failures.incrementAndGet();
140           } catch (IOException e) {
141             throw new RuntimeException("Failed threaded create" + getName(), e);
142           }
143         }
144       };
145     }
146     for (int i = 0; i < count; i++) {
147       threads[i].start();
148     }
149     for (int i = 0; i < count; i++) {
150       while(threads[i].isAlive()) {
151         try {
152           Thread.sleep(100);
153         } catch (InterruptedException e) {
154           // continue
155         }
156       }
157     }
158     // All threads are now dead.  Count up how many tables were created and
159     // how many failed w/ appropriate exception.
160     assertEquals(1, successes.get());
161     assertEquals(count - 1, failures.get());
162   }
163 
164   /**
165    * Test for hadoop-1581 'HBASE: Unopenable tablename bug'.
166    * @throws Exception
167    */
168   @Test (timeout=300000)
169   public void testTableNameClash() throws Exception {
170     String name = "testTableNameClash";
171     HTableDescriptor htd1 = new HTableDescriptor(TableName.valueOf(name + "SOMEUPPERCASE"));
172     HTableDescriptor htd2 = new HTableDescriptor(TableName.valueOf(name));
173     htd1.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
174     htd2.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
175     admin.createTable(htd1);
176     admin.createTable(htd2);
177     // Before fix, below would fail throwing a NoServerForRegionException.
178     new HTable(TEST_UTIL.getConfiguration(), htd2.getTableName()).close();
179   }
180 
181   /***
182    * HMaster.createTable used to be kind of synchronous call
183    * Thus creating of table with lots of regions can cause RPC timeout
184    * After the fix to make createTable truly async, RPC timeout shouldn't be an
185    * issue anymore
186    * @throws Exception
187    */
188   @Test (timeout=300000)
189   public void testCreateTableRPCTimeOut() throws Exception {
190     String name = "testCreateTableRPCTimeOut";
191     int oldTimeout = TEST_UTIL.getConfiguration().
192       getInt(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT);
193     TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 1500);
194     try {
195       int expectedRegions = 100;
196       // Use 80 bit numbers to make sure we aren't limited
197       byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
198       byte [] endKey =   { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
199       Admin hbaseadmin = new HBaseAdmin(TEST_UTIL.getConfiguration());
200       HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name));
201       htd.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
202       hbaseadmin.createTable(htd, startKey, endKey, expectedRegions);
203       hbaseadmin.close();
204     } finally {
205       TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, oldTimeout);
206     }
207   }
208 
209   /**
210    * Test read only tables
211    * @throws Exception
212    */
213   @Test (timeout=300000)
214   public void testReadOnlyTable() throws Exception {
215     TableName name = TableName.valueOf("testReadOnlyTable");
216     Table table = TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
217     byte[] value = Bytes.toBytes("somedata");
218     // This used to use an empty row... That must have been a bug
219     Put put = new Put(value);
220     put.add(HConstants.CATALOG_FAMILY, HConstants.CATALOG_FAMILY, value);
221     table.put(put);
222     table.close();
223   }
224 
225   /**
226    * Test that user table names can contain '-' and '.' so long as they do not
227    * start with same. HBASE-771
228    * @throws IOException
229    */
230   @Test (timeout=300000)
231   public void testTableNames() throws IOException {
232     byte[][] illegalNames = new byte[][] {
233         Bytes.toBytes("-bad"),
234         Bytes.toBytes(".bad")
235     };
236     for (byte[] illegalName : illegalNames) {
237       try {
238         new HTableDescriptor(TableName.valueOf(illegalName));
239         throw new IOException("Did not detect '" +
240             Bytes.toString(illegalName) + "' as an illegal user table name");
241       } catch (IllegalArgumentException e) {
242         // expected
243       }
244     }
245     byte[] legalName = Bytes.toBytes("g-oo.d");
246     try {
247       new HTableDescriptor(TableName.valueOf(legalName));
248     } catch (IllegalArgumentException e) {
249       throw new IOException("Legal user table name: '" +
250         Bytes.toString(legalName) + "' caused IllegalArgumentException: " +
251         e.getMessage());
252     }
253   }
254 
255   /**
256    * For HADOOP-2579
257    * @throws IOException
258    */
259   @Test (expected=TableExistsException.class, timeout=300000)
260   public void testTableExistsExceptionWithATable() throws IOException {
261     final TableName name = TableName.valueOf("testTableExistsExceptionWithATable");
262     TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY).close();
263     TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
264   }
265 
266   /**
267    * Can't disable a table if the table isn't in enabled state
268    * @throws IOException
269    */
270   @Test (expected=TableNotEnabledException.class, timeout=300000)
271   public void testTableNotEnabledExceptionWithATable() throws IOException {
272     final TableName name = TableName.valueOf("testTableNotEnabledExceptionWithATable");
273     TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY).close();
274     this.admin.disableTable(name);
275     this.admin.disableTable(name);
276   }
277 
278   /**
279    * Can't enable a table if the table isn't in disabled state
280    * @throws IOException
281    */
282   @Test (expected=TableNotDisabledException.class, timeout=300000)
283   public void testTableNotDisabledExceptionWithATable() throws IOException {
284     final TableName name = TableName.valueOf("testTableNotDisabledExceptionWithATable");
285     Table t = TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY);
286     try {
287     this.admin.enableTable(name);
288     }finally {
289        t.close();
290     }
291   }
292 
293   /**
294    * For HADOOP-2579
295    * @throws IOException
296    */
297   @Test (expected=TableNotFoundException.class, timeout=300000)
298   public void testTableNotFoundExceptionWithoutAnyTables() throws IOException {
299     TableName tableName = TableName
300         .valueOf("testTableNotFoundExceptionWithoutAnyTables");
301     Table ht = new HTable(TEST_UTIL.getConfiguration(), tableName);
302     ht.get(new Get("e".getBytes()));
303   }
304 
305 
306   @Test (timeout=300000)
307   public void testShouldCloseTheRegionBasedOnTheEncodedRegionName()
308       throws Exception {
309     TableName TABLENAME =
310         TableName.valueOf("TestHBACloseRegion");
311     createTableWithDefaultConf(TABLENAME);
312 
313     HRegionInfo info = null;
314     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TABLENAME);
315     List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
316     for (HRegionInfo regionInfo : onlineRegions) {
317       if (!regionInfo.getTable().isSystemTable()) {
318         info = regionInfo;
319         admin.closeRegionWithEncodedRegionName(regionInfo.getEncodedName(), rs
320             .getServerName().getServerName());
321       }
322     }
323     boolean isInList = ProtobufUtil.getOnlineRegions(
324       rs.getRSRpcServices()).contains(info);
325     long timeout = System.currentTimeMillis() + 10000;
326     while ((System.currentTimeMillis() < timeout) && (isInList)) {
327       Thread.sleep(100);
328       isInList = ProtobufUtil.getOnlineRegions(
329         rs.getRSRpcServices()).contains(info);
330     }
331 
332     assertFalse("The region should not be present in online regions list.",
333       isInList);
334   }
335 
336   @Test (timeout=300000)
337   public void testCloseRegionIfInvalidRegionNameIsPassed() throws Exception {
338     byte[] TABLENAME = Bytes.toBytes("TestHBACloseRegion1");
339     createTableWithDefaultConf(TABLENAME);
340 
341     HRegionInfo info = null;
342     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TableName.valueOf(TABLENAME));
343     List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
344     for (HRegionInfo regionInfo : onlineRegions) {
345       if (!regionInfo.isMetaTable()) {
346         if (regionInfo.getRegionNameAsString().contains("TestHBACloseRegion1")) {
347           info = regionInfo;
348           try {
349             admin.closeRegionWithEncodedRegionName("sample", rs.getServerName()
350               .getServerName());
351           } catch (NotServingRegionException nsre) {
352             // expected, ignore it
353           }
354         }
355       }
356     }
357     onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
358     assertTrue("The region should be present in online regions list.",
359         onlineRegions.contains(info));
360   }
361 
362   @Test (timeout=300000)
363   public void testCloseRegionThatFetchesTheHRIFromMeta() throws Exception {
364     TableName TABLENAME =
365         TableName.valueOf("TestHBACloseRegion2");
366     createTableWithDefaultConf(TABLENAME);
367 
368     HRegionInfo info = null;
369     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TABLENAME);
370     List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
371     for (HRegionInfo regionInfo : onlineRegions) {
372       if (!regionInfo.isMetaTable()) {
373 
374         if (regionInfo.getRegionNameAsString().contains("TestHBACloseRegion2")) {
375           info = regionInfo;
376           admin.closeRegion(regionInfo.getRegionNameAsString(), rs
377               .getServerName().getServerName());
378         }
379       }
380     }
381 
382     boolean isInList = ProtobufUtil.getOnlineRegions(
383       rs.getRSRpcServices()).contains(info);
384     long timeout = System.currentTimeMillis() + 10000;
385     while ((System.currentTimeMillis() < timeout) && (isInList)) {
386       Thread.sleep(100);
387       isInList = ProtobufUtil.getOnlineRegions(
388         rs.getRSRpcServices()).contains(info);
389     }
390 
391     assertFalse("The region should not be present in online regions list.",
392       isInList);
393   }
394 
395   @Test (timeout=300000)
396   public void testCloseRegionWhenServerNameIsNull() throws Exception {
397     byte[] TABLENAME = Bytes.toBytes("TestHBACloseRegion3");
398     createTableWithDefaultConf(TABLENAME);
399 
400     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TableName.valueOf(TABLENAME));
401 
402     try {
403       List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
404       for (HRegionInfo regionInfo : onlineRegions) {
405         if (!regionInfo.isMetaTable()) {
406           if (regionInfo.getRegionNameAsString()
407               .contains("TestHBACloseRegion3")) {
408             admin.closeRegionWithEncodedRegionName(regionInfo.getEncodedName(),
409                 null);
410           }
411         }
412       }
413       fail("The test should throw exception if the servername passed is null.");
414     } catch (IllegalArgumentException e) {
415     }
416   }
417 
418 
419   @Test (timeout=300000)
420   public void testCloseRegionWhenServerNameIsEmpty() throws Exception {
421     byte[] TABLENAME = Bytes.toBytes("TestHBACloseRegionWhenServerNameIsEmpty");
422     createTableWithDefaultConf(TABLENAME);
423 
424     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TableName.valueOf(TABLENAME));
425 
426     try {
427       List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
428       for (HRegionInfo regionInfo : onlineRegions) {
429         if (!regionInfo.isMetaTable()) {
430           if (regionInfo.getRegionNameAsString()
431               .contains("TestHBACloseRegionWhenServerNameIsEmpty")) {
432             admin.closeRegionWithEncodedRegionName(regionInfo.getEncodedName(),
433                 " ");
434           }
435         }
436       }
437       fail("The test should throw exception if the servername passed is empty.");
438     } catch (IllegalArgumentException e) {
439     }
440   }
441 
442   @Test (timeout=300000)
443   public void testCloseRegionWhenEncodedRegionNameIsNotGiven() throws Exception {
444     byte[] TABLENAME = Bytes.toBytes("TestHBACloseRegion4");
445     createTableWithDefaultConf(TABLENAME);
446 
447     HRegionInfo info = null;
448     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TableName.valueOf(TABLENAME));
449 
450     List<HRegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
451     for (HRegionInfo regionInfo : onlineRegions) {
452       if (!regionInfo.isMetaTable()) {
453         if (regionInfo.getRegionNameAsString().contains("TestHBACloseRegion4")) {
454           info = regionInfo;
455           try {
456             admin.closeRegionWithEncodedRegionName(regionInfo
457               .getRegionNameAsString(), rs.getServerName().getServerName());
458           } catch (NotServingRegionException nsre) {
459             // expected, ignore it.
460           }
461         }
462       }
463     }
464     onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices());
465     assertTrue("The region should be present in online regions list.",
466         onlineRegions.contains(info));
467   }
468 
469   private HBaseAdmin createTable(byte[] TABLENAME) throws IOException {
470 
471     Configuration config = TEST_UTIL.getConfiguration();
472     HBaseAdmin admin = new HBaseAdmin(config);
473 
474     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(TABLENAME));
475     HColumnDescriptor hcd = new HColumnDescriptor("value");
476 
477     htd.addFamily(hcd);
478     admin.createTable(htd, null);
479     return admin;
480   }
481 
482   private void createTableWithDefaultConf(byte[] TABLENAME) throws IOException {
483     createTableWithDefaultConf(TableName.valueOf(TABLENAME));
484   }
485 
486   private void createTableWithDefaultConf(TableName TABLENAME) throws IOException {
487     HTableDescriptor htd = new HTableDescriptor(TABLENAME);
488     HColumnDescriptor hcd = new HColumnDescriptor("value");
489     htd.addFamily(hcd);
490 
491     admin.createTable(htd, null);
492   }
493 
494   /**
495    * For HBASE-2556
496    * @throws IOException
497    */
498   @Test (timeout=300000)
499   public void testGetTableRegions() throws IOException {
500 
501     final TableName tableName = TableName.valueOf("testGetTableRegions");
502 
503     int expectedRegions = 10;
504 
505     // Use 80 bit numbers to make sure we aren't limited
506     byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
507     byte [] endKey =   { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
508 
509 
510     HTableDescriptor desc = new HTableDescriptor(tableName);
511     desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
512     admin.createTable(desc, startKey, endKey, expectedRegions);
513 
514     List<HRegionInfo> RegionInfos = admin.getTableRegions(tableName);
515 
516     assertEquals("Tried to create " + expectedRegions + " regions " +
517         "but only found " + RegionInfos.size(),
518         expectedRegions, RegionInfos.size());
519 
520  }
521 
522   @Test (timeout=300000)
523   public void testWALRollWriting() throws Exception {
524     setUpforLogRolling();
525     String className = this.getClass().getName();
526     StringBuilder v = new StringBuilder(className);
527     while (v.length() < 1000) {
528       v.append(className);
529     }
530     byte[] value = Bytes.toBytes(v.toString());
531     HRegionServer regionServer = startAndWriteData(TableName.valueOf("TestLogRolling"), value);
532     LOG.info("after writing there are "
533         + DefaultWALProvider.getNumRolledLogFiles(regionServer.getWAL(null)) + " log files");
534 
535     // flush all regions
536 
537     List<HRegion> regions = new ArrayList<HRegion>(regionServer
538         .getOnlineRegionsLocalContext());
539     for (HRegion r : regions) {
540       r.flushcache();
541     }
542     admin.rollWALWriter(regionServer.getServerName());
543     int count = DefaultWALProvider.getNumRolledLogFiles(regionServer.getWAL(null));
544     LOG.info("after flushing all regions and rolling logs there are " +
545         count + " log files");
546     assertTrue(("actual count: " + count), count <= 2);
547   }
548 
549   @Test (timeout=300000)
550   public void testMoveToPreviouslyAssignedRS() throws IOException, InterruptedException {
551     byte[] tableName = Bytes.toBytes("testMoveToPreviouslyAssignedRS");
552     MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster();
553     HMaster master = cluster.getMaster();
554     HBaseAdmin localAdmin = createTable(tableName);
555     List<HRegionInfo> tableRegions = localAdmin.getTableRegions(tableName);
556     HRegionInfo hri = tableRegions.get(0);
557     AssignmentManager am = master.getAssignmentManager();
558     assertTrue("Region " + hri.getRegionNameAsString()
559       + " should be assigned properly", am.waitForAssignment(hri));
560     ServerName server = am.getRegionStates().getRegionServerOfRegion(hri);
561     localAdmin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(server.getServerName()));
562     assertEquals("Current region server and region server before move should be same.", server,
563       am.getRegionStates().getRegionServerOfRegion(hri));
564   }
565 
566 
567   private void setUpforLogRolling() {
568     // Force a region split after every 768KB
569     TEST_UTIL.getConfiguration().setLong(HConstants.HREGION_MAX_FILESIZE,
570         768L * 1024L);
571 
572     // We roll the log after every 32 writes
573     TEST_UTIL.getConfiguration().setInt("hbase.regionserver.maxlogentries", 32);
574 
575     TEST_UTIL.getConfiguration().setInt(
576         "hbase.regionserver.logroll.errors.tolerated", 2);
577     TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000);
578 
579     // For less frequently updated regions flush after every 2 flushes
580     TEST_UTIL.getConfiguration().setInt(
581         "hbase.hregion.memstore.optionalflushcount", 2);
582 
583     // We flush the cache after every 8192 bytes
584     TEST_UTIL.getConfiguration().setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE,
585         8192);
586 
587     // Increase the amount of time between client retries
588     TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 10 * 1000);
589 
590     // Reduce thread wake frequency so that other threads can get
591     // a chance to run.
592     TEST_UTIL.getConfiguration().setInt(HConstants.THREAD_WAKE_FREQUENCY,
593         2 * 1000);
594 
595     /**** configuration for testLogRollOnDatanodeDeath ****/
596     // make sure log.hflush() calls syncFs() to open a pipeline
597     TEST_UTIL.getConfiguration().setBoolean("dfs.support.append", true);
598     // lower the namenode & datanode heartbeat so the namenode
599     // quickly detects datanode failures
600     TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
601     TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
602     // the namenode might still try to choose the recently-dead datanode
603     // for a pipeline, so try to a new pipeline multiple times
604     TEST_UTIL.getConfiguration().setInt("dfs.client.block.write.retries", 30);
605     TEST_UTIL.getConfiguration().setInt(
606         "hbase.regionserver.hlog.tolerable.lowreplication", 2);
607     TEST_UTIL.getConfiguration().setInt(
608         "hbase.regionserver.hlog.lowreplication.rolllimit", 3);
609   }
610 
611   private HRegionServer startAndWriteData(TableName tableName, byte[] value)
612   throws IOException, InterruptedException {
613     // When the hbase:meta table can be opened, the region servers are running
614     new HTable(
615       TEST_UTIL.getConfiguration(), TableName.META_TABLE_NAME).close();
616 
617     // Create the test table and open it
618     HTableDescriptor desc = new HTableDescriptor(tableName);
619     desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
620     admin.createTable(desc);
621     Table table = new HTable(TEST_UTIL.getConfiguration(), tableName);
622 
623     HRegionServer regionServer = TEST_UTIL.getRSForFirstRegionInTable(tableName);
624     for (int i = 1; i <= 256; i++) { // 256 writes should cause 8 log rolls
625       Put put = new Put(Bytes.toBytes("row" + String.format("%1$04d", i)));
626       put.add(HConstants.CATALOG_FAMILY, null, value);
627       table.put(put);
628       if (i % 32 == 0) {
629         // After every 32 writes sleep to let the log roller run
630         try {
631           Thread.sleep(2000);
632         } catch (InterruptedException e) {
633           // continue
634         }
635       }
636     }
637 
638     table.close();
639     return regionServer;
640   }
641 
642   /**
643    * HBASE-4417 checkHBaseAvailable() doesn't close zk connections
644    */
645   @Test (timeout=300000)
646   public void testCheckHBaseAvailableClosesConnection() throws Exception {
647     Configuration conf = TEST_UTIL.getConfiguration();
648 
649     int initialCount = HConnectionTestingUtility.getConnectionCount();
650     HBaseAdmin.checkHBaseAvailable(conf);
651     int finalCount = HConnectionTestingUtility.getConnectionCount();
652 
653     Assert.assertEquals(initialCount, finalCount) ;
654   }
655 
656   /**
657    * Check that we have an exception if the cluster is not there.
658    */
659   @Test (timeout=300000)
660   public void testCheckHBaseAvailableWithoutCluster() {
661     Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
662 
663     // Change the ZK address to go to something not used.
664     conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT,
665       conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, 9999)+10);
666 
667     int initialCount = HConnectionTestingUtility.getConnectionCount();
668 
669     long start = System.currentTimeMillis();
670     try {
671       HBaseAdmin.checkHBaseAvailable(conf);
672       assertTrue(false);
673     } catch (MasterNotRunningException ignored) {
674     } catch (ZooKeeperConnectionException ignored) {
675     } catch (ServiceException ignored) {
676     } catch (IOException ignored) {
677     }
678     long end = System.currentTimeMillis();
679 
680     int finalCount = HConnectionTestingUtility.getConnectionCount();
681 
682     Assert.assertEquals(initialCount, finalCount) ;
683 
684     LOG.info("It took "+(end-start)+" ms to find out that" +
685       " HBase was not available");
686   }
687 
688   @Test (timeout=300000)
689   public void testDisableCatalogTable() throws Exception {
690     try {
691       this.admin.disableTable(TableName.META_TABLE_NAME);
692       fail("Expected to throw ConstraintException");
693     } catch (ConstraintException e) {
694     }
695     // Before the fix for HBASE-6146, the below table creation was failing as the hbase:meta table
696     // actually getting disabled by the disableTable() call.
697     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("testDisableCatalogTable".getBytes()));
698     HColumnDescriptor hcd = new HColumnDescriptor("cf1".getBytes());
699     htd.addFamily(hcd);
700     TEST_UTIL.getHBaseAdmin().createTable(htd);
701   }
702 
703   @Test (timeout=300000)
704   public void testIsEnabledOrDisabledOnUnknownTable() throws Exception {
705     try {
706       admin.isTableEnabled(TableName.valueOf("unkownTable"));
707       fail("Test should fail if isTableEnabled called on unknown table.");
708     } catch (IOException e) {
709     }
710 
711     try {
712       admin.isTableDisabled(TableName.valueOf("unkownTable"));
713       fail("Test should fail if isTableDisabled called on unknown table.");
714     } catch (IOException e) {
715     }
716   }
717 
718   @Test (timeout=300000)
719   public void testGetRegion() throws Exception {
720     // We use actual HBaseAdmin instance instead of going via Admin interface in
721     // here because makes use of an internal HBA method (TODO: Fix.).
722     HBaseAdmin rawAdmin = new HBaseAdmin(TEST_UTIL.getConfiguration());
723 
724     final TableName tableName = TableName.valueOf("testGetRegion");
725     LOG.info("Started " + tableName);
726     HTable t = TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY);
727     TEST_UTIL.createMultiRegions(t, HConstants.CATALOG_FAMILY);
728 
729     HRegionLocation regionLocation = t.getRegionLocation("mmm");
730     HRegionInfo region = regionLocation.getRegionInfo();
731     byte[] regionName = region.getRegionName();
732     Pair<HRegionInfo, ServerName> pair = rawAdmin.getRegion(regionName);
733     assertTrue(Bytes.equals(regionName, pair.getFirst().getRegionName()));
734     pair = rawAdmin.getRegion(region.getEncodedNameAsBytes());
735     assertTrue(Bytes.equals(regionName, pair.getFirst().getRegionName()));
736   }
737 }