001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.client; 019 020import static org.junit.Assert.assertEquals; 021import static org.junit.Assert.assertFalse; 022import static org.junit.Assert.assertTrue; 023import static org.junit.Assert.fail; 024 025import java.io.IOException; 026import java.util.ArrayList; 027import java.util.EnumSet; 028import java.util.HashMap; 029import java.util.List; 030import java.util.Random; 031import java.util.concurrent.atomic.AtomicInteger; 032import java.util.stream.Collectors; 033import org.apache.hadoop.conf.Configuration; 034import org.apache.hadoop.hbase.ClusterMetrics.Option; 035import org.apache.hadoop.hbase.HBaseClassTestRule; 036import org.apache.hadoop.hbase.HBaseTestingUtility; 037import org.apache.hadoop.hbase.HColumnDescriptor; 038import org.apache.hadoop.hbase.HConstants; 039import org.apache.hadoop.hbase.HRegionLocation; 040import org.apache.hadoop.hbase.HTableDescriptor; 041import org.apache.hadoop.hbase.MiniHBaseCluster; 042import org.apache.hadoop.hbase.ServerName; 043import org.apache.hadoop.hbase.TableExistsException; 044import org.apache.hadoop.hbase.TableName; 045import org.apache.hadoop.hbase.TableNotDisabledException; 046import org.apache.hadoop.hbase.TableNotEnabledException; 047import org.apache.hadoop.hbase.TableNotFoundException; 048import org.apache.hadoop.hbase.UnknownRegionException; 049import org.apache.hadoop.hbase.ZooKeeperConnectionException; 050import org.apache.hadoop.hbase.constraint.ConstraintException; 051import org.apache.hadoop.hbase.master.HMaster; 052import org.apache.hadoop.hbase.master.assignment.AssignmentManager; 053import org.apache.hadoop.hbase.regionserver.HRegion; 054import org.apache.hadoop.hbase.regionserver.HRegionServer; 055import org.apache.hadoop.hbase.testclassification.ClientTests; 056import org.apache.hadoop.hbase.testclassification.LargeTests; 057import org.apache.hadoop.hbase.util.Bytes; 058import org.apache.hadoop.hbase.util.Pair; 059import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; 060import org.junit.After; 061import org.junit.AfterClass; 062import org.junit.Before; 063import org.junit.BeforeClass; 064import org.junit.ClassRule; 065import org.junit.Rule; 066import org.junit.Test; 067import org.junit.experimental.categories.Category; 068import org.junit.rules.TestName; 069import org.slf4j.Logger; 070import org.slf4j.LoggerFactory; 071 072import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 073 074/** 075 * Class to test HBaseAdmin. 076 * Spins up the minicluster once at test start and then takes it down afterward. 077 * Add any testing of HBaseAdmin functionality here. 078 */ 079@Category({LargeTests.class, ClientTests.class}) 080public class TestAdmin2 { 081 082 @ClassRule 083 public static final HBaseClassTestRule CLASS_RULE = 084 HBaseClassTestRule.forClass(TestAdmin2.class); 085 086 private static final Logger LOG = LoggerFactory.getLogger(TestAdmin2.class); 087 private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); 088 private Admin admin; 089 090 @Rule 091 public TestName name = new TestName(); 092 093 @BeforeClass 094 public static void setUpBeforeClass() throws Exception { 095 TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100); 096 TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250); 097 TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6); 098 TEST_UTIL.getConfiguration().setInt("hbase.regionserver.metahandler.count", 30); 099 TEST_UTIL.getConfiguration().setBoolean( 100 "hbase.master.enabletable.roundrobin", true); 101 TEST_UTIL.startMiniCluster(3); 102 } 103 104 @AfterClass 105 public static void tearDownAfterClass() throws Exception { 106 TEST_UTIL.shutdownMiniCluster(); 107 } 108 109 @Before 110 public void setUp() throws Exception { 111 this.admin = TEST_UTIL.getHBaseAdmin(); 112 } 113 114 @After 115 public void tearDown() throws Exception { 116 for (HTableDescriptor htd : this.admin.listTables()) { 117 TEST_UTIL.deleteTable(htd.getTableName()); 118 } 119 } 120 121 @Test 122 public void testCreateBadTables() throws IOException { 123 String msg = null; 124 try { 125 this.admin.createTable(new HTableDescriptor(TableName.META_TABLE_NAME)); 126 } catch(TableExistsException e) { 127 msg = e.toString(); 128 } 129 assertTrue("Unexcepted exception message " + msg, msg != null && 130 msg.startsWith(TableExistsException.class.getName()) && 131 msg.contains(TableName.META_TABLE_NAME.getNameAsString())); 132 133 // Now try and do concurrent creation with a bunch of threads. 134 final HTableDescriptor threadDesc = new HTableDescriptor(TableName.valueOf(name.getMethodName())); 135 threadDesc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 136 int count = 10; 137 Thread [] threads = new Thread [count]; 138 final AtomicInteger successes = new AtomicInteger(0); 139 final AtomicInteger failures = new AtomicInteger(0); 140 final Admin localAdmin = this.admin; 141 for (int i = 0; i < count; i++) { 142 threads[i] = new Thread(Integer.toString(i)) { 143 @Override 144 public void run() { 145 try { 146 localAdmin.createTable(threadDesc); 147 successes.incrementAndGet(); 148 } catch (TableExistsException e) { 149 failures.incrementAndGet(); 150 } catch (IOException e) { 151 throw new RuntimeException("Failed threaded create" + getName(), e); 152 } 153 } 154 }; 155 } 156 for (int i = 0; i < count; i++) { 157 threads[i].start(); 158 } 159 for (int i = 0; i < count; i++) { 160 while(threads[i].isAlive()) { 161 try { 162 Thread.sleep(100); 163 } catch (InterruptedException e) { 164 // continue 165 } 166 } 167 } 168 // All threads are now dead. Count up how many tables were created and 169 // how many failed w/ appropriate exception. 170 assertEquals(1, successes.get()); 171 assertEquals(count - 1, failures.get()); 172 } 173 174 /** 175 * Test for hadoop-1581 'HBASE: Unopenable tablename bug'. 176 * @throws Exception 177 */ 178 @Test 179 public void testTableNameClash() throws Exception { 180 final String name = this.name.getMethodName(); 181 HTableDescriptor htd1 = new HTableDescriptor(TableName.valueOf(name + "SOMEUPPERCASE")); 182 HTableDescriptor htd2 = new HTableDescriptor(TableName.valueOf(name)); 183 htd1.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 184 htd2.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 185 admin.createTable(htd1); 186 admin.createTable(htd2); 187 // Before fix, below would fail throwing a NoServerForRegionException. 188 TEST_UTIL.getConnection().getTable(htd2.getTableName()).close(); 189 } 190 191 /*** 192 * HMaster.createTable used to be kind of synchronous call 193 * Thus creating of table with lots of regions can cause RPC timeout 194 * After the fix to make createTable truly async, RPC timeout shouldn't be an 195 * issue anymore 196 * @throws Exception 197 */ 198 @Test 199 public void testCreateTableRPCTimeOut() throws Exception { 200 final String name = this.name.getMethodName(); 201 int oldTimeout = TEST_UTIL.getConfiguration(). 202 getInt(HConstants.HBASE_RPC_TIMEOUT_KEY, HConstants.DEFAULT_HBASE_RPC_TIMEOUT); 203 TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, 1500); 204 try { 205 int expectedRegions = 100; 206 // Use 80 bit numbers to make sure we aren't limited 207 byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; 208 byte [] endKey = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; 209 Admin hbaseadmin = TEST_UTIL.getHBaseAdmin(); 210 HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name)); 211 htd.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 212 hbaseadmin.createTable(htd, startKey, endKey, expectedRegions); 213 } finally { 214 TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_RPC_TIMEOUT_KEY, oldTimeout); 215 } 216 } 217 218 /** 219 * Test read only tables 220 * @throws Exception 221 */ 222 @Test 223 public void testReadOnlyTable() throws Exception { 224 final TableName name = TableName.valueOf(this.name.getMethodName()); 225 Table table = TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY); 226 byte[] value = Bytes.toBytes("somedata"); 227 // This used to use an empty row... That must have been a bug 228 Put put = new Put(value); 229 put.addColumn(HConstants.CATALOG_FAMILY, HConstants.CATALOG_FAMILY, value); 230 table.put(put); 231 table.close(); 232 } 233 234 /** 235 * Test that user table names can contain '-' and '.' so long as they do not 236 * start with same. HBASE-771 237 * @throws IOException 238 */ 239 @Test 240 public void testTableNames() throws IOException { 241 byte[][] illegalNames = new byte[][] { 242 Bytes.toBytes("-bad"), 243 Bytes.toBytes(".bad") 244 }; 245 for (byte[] illegalName : illegalNames) { 246 try { 247 new HTableDescriptor(TableName.valueOf(illegalName)); 248 throw new IOException("Did not detect '" + 249 Bytes.toString(illegalName) + "' as an illegal user table name"); 250 } catch (IllegalArgumentException e) { 251 // expected 252 } 253 } 254 byte[] legalName = Bytes.toBytes("g-oo.d"); 255 try { 256 new HTableDescriptor(TableName.valueOf(legalName)); 257 } catch (IllegalArgumentException e) { 258 throw new IOException("Legal user table name: '" + 259 Bytes.toString(legalName) + "' caused IllegalArgumentException: " + 260 e.getMessage()); 261 } 262 } 263 264 /** 265 * For HADOOP-2579 266 * @throws IOException 267 */ 268 @Test (expected=TableExistsException.class) 269 public void testTableExistsExceptionWithATable() throws IOException { 270 final TableName name = TableName.valueOf(this.name.getMethodName()); 271 TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY).close(); 272 TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY); 273 } 274 275 /** 276 * Can't disable a table if the table isn't in enabled state 277 * @throws IOException 278 */ 279 @Test (expected=TableNotEnabledException.class) 280 public void testTableNotEnabledExceptionWithATable() throws IOException { 281 final TableName name = TableName.valueOf(this.name.getMethodName()); 282 TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY).close(); 283 this.admin.disableTable(name); 284 this.admin.disableTable(name); 285 } 286 287 /** 288 * Can't enable a table if the table isn't in disabled state 289 * @throws IOException 290 */ 291 @Test (expected=TableNotDisabledException.class) 292 public void testTableNotDisabledExceptionWithATable() throws IOException { 293 final TableName name = TableName.valueOf(this.name.getMethodName()); 294 Table t = TEST_UTIL.createTable(name, HConstants.CATALOG_FAMILY); 295 try { 296 this.admin.enableTable(name); 297 }finally { 298 t.close(); 299 } 300 } 301 302 /** 303 * For HADOOP-2579 304 * @throws IOException 305 */ 306 @Test (expected=TableNotFoundException.class) 307 public void testTableNotFoundExceptionWithoutAnyTables() throws IOException { 308 TableName tableName = TableName 309 .valueOf("testTableNotFoundExceptionWithoutAnyTables"); 310 Table ht = TEST_UTIL.getConnection().getTable(tableName); 311 ht.get(new Get(Bytes.toBytes("e"))); 312 } 313 314 @Test 315 public void testShouldUnassignTheRegion() throws Exception { 316 final TableName tableName = TableName.valueOf(name.getMethodName()); 317 createTableWithDefaultConf(tableName); 318 319 RegionInfo info = null; 320 HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(tableName); 321 List<RegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices()); 322 for (RegionInfo regionInfo : onlineRegions) { 323 if (!regionInfo.getTable().isSystemTable()) { 324 info = regionInfo; 325 admin.unassign(regionInfo.getRegionName(), true); 326 } 327 } 328 boolean isInList = ProtobufUtil.getOnlineRegions( 329 rs.getRSRpcServices()).contains(info); 330 long timeout = System.currentTimeMillis() + 10000; 331 while ((System.currentTimeMillis() < timeout) && (isInList)) { 332 Thread.sleep(100); 333 isInList = ProtobufUtil.getOnlineRegions( 334 rs.getRSRpcServices()).contains(info); 335 } 336 337 assertFalse("The region should not be present in online regions list.", 338 isInList); 339 } 340 341 @Test 342 public void testCloseRegionIfInvalidRegionNameIsPassed() throws Exception { 343 final String name = this.name.getMethodName(); 344 byte[] tableName = Bytes.toBytes(name); 345 createTableWithDefaultConf(tableName); 346 347 RegionInfo info = null; 348 HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(TableName.valueOf(tableName)); 349 List<RegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices()); 350 for (RegionInfo regionInfo : onlineRegions) { 351 if (!regionInfo.isMetaRegion()) { 352 if (regionInfo.getRegionNameAsString().contains(name)) { 353 info = regionInfo; 354 try { 355 admin.unassign(Bytes.toBytes("sample"), true); 356 } catch (UnknownRegionException nsre) { 357 // expected, ignore it 358 } 359 } 360 } 361 } 362 onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices()); 363 assertTrue("The region should be present in online regions list.", 364 onlineRegions.contains(info)); 365 } 366 367 @Test 368 public void testCloseRegionThatFetchesTheHRIFromMeta() throws Exception { 369 final TableName tableName = TableName.valueOf(name.getMethodName()); 370 createTableWithDefaultConf(tableName); 371 372 RegionInfo info = null; 373 HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(tableName); 374 List<RegionInfo> onlineRegions = ProtobufUtil.getOnlineRegions(rs.getRSRpcServices()); 375 for (RegionInfo regionInfo : onlineRegions) { 376 if (!regionInfo.isMetaRegion()) { 377 if (regionInfo.getRegionNameAsString().contains("TestHBACloseRegion2")) { 378 info = regionInfo; 379 admin.unassign(regionInfo.getRegionName(), true); 380 } 381 } 382 } 383 384 boolean isInList = ProtobufUtil.getOnlineRegions( 385 rs.getRSRpcServices()).contains(info); 386 long timeout = System.currentTimeMillis() + 10000; 387 while ((System.currentTimeMillis() < timeout) && (isInList)) { 388 Thread.sleep(100); 389 isInList = ProtobufUtil.getOnlineRegions( 390 rs.getRSRpcServices()).contains(info); 391 } 392 393 assertFalse("The region should not be present in online regions list.", 394 isInList); 395 } 396 397 private HBaseAdmin createTable(TableName tableName) throws IOException { 398 HBaseAdmin admin = TEST_UTIL.getHBaseAdmin(); 399 400 HTableDescriptor htd = new HTableDescriptor(tableName); 401 HColumnDescriptor hcd = new HColumnDescriptor("value"); 402 403 htd.addFamily(hcd); 404 admin.createTable(htd, null); 405 return admin; 406 } 407 408 private void createTableWithDefaultConf(byte[] TABLENAME) throws IOException { 409 createTableWithDefaultConf(TableName.valueOf(TABLENAME)); 410 } 411 412 private void createTableWithDefaultConf(TableName TABLENAME) throws IOException { 413 HTableDescriptor htd = new HTableDescriptor(TABLENAME); 414 HColumnDescriptor hcd = new HColumnDescriptor("value"); 415 htd.addFamily(hcd); 416 417 admin.createTable(htd, null); 418 } 419 420 /** 421 * For HBASE-2556 422 * @throws IOException 423 */ 424 @Test 425 public void testGetTableRegions() throws IOException { 426 final TableName tableName = TableName.valueOf(name.getMethodName()); 427 428 int expectedRegions = 10; 429 430 // Use 80 bit numbers to make sure we aren't limited 431 byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; 432 byte [] endKey = { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }; 433 434 435 HTableDescriptor desc = new HTableDescriptor(tableName); 436 desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 437 admin.createTable(desc, startKey, endKey, expectedRegions); 438 439 List<RegionInfo> RegionInfos = admin.getRegions(tableName); 440 441 assertEquals("Tried to create " + expectedRegions + " regions " + 442 "but only found " + RegionInfos.size(), 443 expectedRegions, RegionInfos.size()); 444 } 445 446 @Test 447 public void testMoveToPreviouslyAssignedRS() throws IOException, InterruptedException { 448 MiniHBaseCluster cluster = TEST_UTIL.getHBaseCluster(); 449 HMaster master = cluster.getMaster(); 450 final TableName tableName = TableName.valueOf(name.getMethodName()); 451 Admin localAdmin = createTable(tableName); 452 List<RegionInfo> tableRegions = localAdmin.getRegions(tableName); 453 RegionInfo hri = tableRegions.get(0); 454 AssignmentManager am = master.getAssignmentManager(); 455 ServerName server = am.getRegionStates().getRegionServerOfRegion(hri); 456 localAdmin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(server.getServerName())); 457 assertEquals("Current region server and region server before move should be same.", server, 458 am.getRegionStates().getRegionServerOfRegion(hri)); 459 } 460 461 @Test 462 public void testWALRollWriting() throws Exception { 463 setUpforLogRolling(); 464 String className = this.getClass().getName(); 465 StringBuilder v = new StringBuilder(className); 466 while (v.length() < 1000) { 467 v.append(className); 468 } 469 byte[] value = Bytes.toBytes(v.toString()); 470 HRegionServer regionServer = startAndWriteData(TableName.valueOf(name.getMethodName()), value); 471 LOG.info("after writing there are " 472 + AbstractFSWALProvider.getNumRolledLogFiles(regionServer.getWAL(null)) + " log files"); 473 474 // flush all regions 475 for (HRegion r : regionServer.getOnlineRegionsLocalContext()) { 476 r.flush(true); 477 } 478 admin.rollWALWriter(regionServer.getServerName()); 479 int count = AbstractFSWALProvider.getNumRolledLogFiles(regionServer.getWAL(null)); 480 LOG.info("after flushing all regions and rolling logs there are " + 481 count + " log files"); 482 assertTrue(("actual count: " + count), count <= 2); 483 } 484 485 private void setUpforLogRolling() { 486 // Force a region split after every 768KB 487 TEST_UTIL.getConfiguration().setLong(HConstants.HREGION_MAX_FILESIZE, 488 768L * 1024L); 489 490 // We roll the log after every 32 writes 491 TEST_UTIL.getConfiguration().setInt("hbase.regionserver.maxlogentries", 32); 492 493 TEST_UTIL.getConfiguration().setInt( 494 "hbase.regionserver.logroll.errors.tolerated", 2); 495 TEST_UTIL.getConfiguration().setInt("hbase.rpc.timeout", 10 * 1000); 496 497 // For less frequently updated regions flush after every 2 flushes 498 TEST_UTIL.getConfiguration().setInt( 499 "hbase.hregion.memstore.optionalflushcount", 2); 500 501 // We flush the cache after every 8192 bytes 502 TEST_UTIL.getConfiguration().setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 503 8192); 504 505 // Increase the amount of time between client retries 506 TEST_UTIL.getConfiguration().setLong("hbase.client.pause", 10 * 1000); 507 508 // Reduce thread wake frequency so that other threads can get 509 // a chance to run. 510 TEST_UTIL.getConfiguration().setInt(HConstants.THREAD_WAKE_FREQUENCY, 511 2 * 1000); 512 513 /**** configuration for testLogRollOnDatanodeDeath ****/ 514 // lower the namenode & datanode heartbeat so the namenode 515 // quickly detects datanode failures 516 TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000); 517 TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1); 518 // the namenode might still try to choose the recently-dead datanode 519 // for a pipeline, so try to a new pipeline multiple times 520 TEST_UTIL.getConfiguration().setInt("dfs.client.block.write.retries", 30); 521 TEST_UTIL.getConfiguration().setInt( 522 "hbase.regionserver.hlog.tolerable.lowreplication", 2); 523 TEST_UTIL.getConfiguration().setInt( 524 "hbase.regionserver.hlog.lowreplication.rolllimit", 3); 525 } 526 527 private HRegionServer startAndWriteData(TableName tableName, byte[] value) 528 throws IOException, InterruptedException { 529 // When the hbase:meta table can be opened, the region servers are running 530 TEST_UTIL.getConnection().getTable(TableName.META_TABLE_NAME).close(); 531 532 // Create the test table and open it 533 HTableDescriptor desc = new HTableDescriptor(tableName); 534 desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY)); 535 admin.createTable(desc); 536 Table table = TEST_UTIL.getConnection().getTable(tableName); 537 538 HRegionServer regionServer = TEST_UTIL.getRSForFirstRegionInTable(tableName); 539 for (int i = 1; i <= 256; i++) { // 256 writes should cause 8 log rolls 540 Put put = new Put(Bytes.toBytes("row" + String.format("%1$04d", i))); 541 put.addColumn(HConstants.CATALOG_FAMILY, null, value); 542 table.put(put); 543 if (i % 32 == 0) { 544 // After every 32 writes sleep to let the log roller run 545 try { 546 Thread.sleep(2000); 547 } catch (InterruptedException e) { 548 // continue 549 } 550 } 551 } 552 553 table.close(); 554 return regionServer; 555 } 556 557 /** 558 * Check that we have an exception if the cluster is not there. 559 */ 560 @Test 561 public void testCheckHBaseAvailableWithoutCluster() { 562 Configuration conf = new Configuration(TEST_UTIL.getConfiguration()); 563 564 // Change the ZK address to go to something not used. 565 conf.setInt(HConstants.ZOOKEEPER_CLIENT_PORT, 566 conf.getInt(HConstants.ZOOKEEPER_CLIENT_PORT, 9999)+10); 567 568 long start = System.currentTimeMillis(); 569 try { 570 HBaseAdmin.available(conf); 571 assertTrue(false); 572 } catch (ZooKeeperConnectionException ignored) { 573 } catch (IOException ignored) { 574 } 575 long end = System.currentTimeMillis(); 576 577 LOG.info("It took "+(end-start)+" ms to find out that" + 578 " HBase was not available"); 579 } 580 581 @Test 582 public void testDisableCatalogTable() throws Exception { 583 try { 584 this.admin.disableTable(TableName.META_TABLE_NAME); 585 fail("Expected to throw ConstraintException"); 586 } catch (ConstraintException e) { 587 } 588 // Before the fix for HBASE-6146, the below table creation was failing as the hbase:meta table 589 // actually getting disabled by the disableTable() call. 590 HTableDescriptor htd = 591 new HTableDescriptor(TableName.valueOf(Bytes.toBytes(name.getMethodName()))); 592 HColumnDescriptor hcd = new HColumnDescriptor(Bytes.toBytes("cf1")); 593 htd.addFamily(hcd); 594 TEST_UTIL.getHBaseAdmin().createTable(htd); 595 } 596 597 @Test 598 public void testIsEnabledOrDisabledOnUnknownTable() throws Exception { 599 try { 600 admin.isTableEnabled(TableName.valueOf(name.getMethodName())); 601 fail("Test should fail if isTableEnabled called on unknown table."); 602 } catch (IOException e) { 603 } 604 605 try { 606 admin.isTableDisabled(TableName.valueOf(name.getMethodName())); 607 fail("Test should fail if isTableDisabled called on unknown table."); 608 } catch (IOException e) { 609 } 610 } 611 612 @Test 613 public void testGetRegion() throws Exception { 614 // We use actual HBaseAdmin instance instead of going via Admin interface in 615 // here because makes use of an internal HBA method (TODO: Fix.). 616 HBaseAdmin rawAdmin = TEST_UTIL.getHBaseAdmin(); 617 618 final TableName tableName = TableName.valueOf(name.getMethodName()); 619 LOG.info("Started " + tableName); 620 Table t = TEST_UTIL.createMultiRegionTable(tableName, HConstants.CATALOG_FAMILY); 621 622 try (RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName)) { 623 HRegionLocation regionLocation = locator.getRegionLocation(Bytes.toBytes("mmm")); 624 RegionInfo region = regionLocation.getRegionInfo(); 625 byte[] regionName = region.getRegionName(); 626 Pair<RegionInfo, ServerName> pair = rawAdmin.getRegion(regionName); 627 assertTrue(Bytes.equals(regionName, pair.getFirst().getRegionName())); 628 pair = rawAdmin.getRegion(region.getEncodedNameAsBytes()); 629 assertTrue(Bytes.equals(regionName, pair.getFirst().getRegionName())); 630 } 631 } 632 633 @Test 634 public void testBalancer() throws Exception { 635 boolean initialState = admin.isBalancerEnabled(); 636 637 // Start the balancer, wait for it. 638 boolean prevState = admin.setBalancerRunning(!initialState, true); 639 640 // The previous state should be the original state we observed 641 assertEquals(initialState, prevState); 642 643 // Current state should be opposite of the original 644 assertEquals(!initialState, admin.isBalancerEnabled()); 645 646 // Reset it back to what it was 647 prevState = admin.setBalancerRunning(initialState, true); 648 649 // The previous state should be the opposite of the initial state 650 assertEquals(!initialState, prevState); 651 // Current state should be the original state again 652 assertEquals(initialState, admin.isBalancerEnabled()); 653 } 654 655 @Test 656 public void testRegionNormalizer() throws Exception { 657 boolean initialState = admin.isNormalizerEnabled(); 658 659 // flip state 660 boolean prevState = admin.setNormalizerRunning(!initialState); 661 662 // The previous state should be the original state we observed 663 assertEquals(initialState, prevState); 664 665 // Current state should be opposite of the original 666 assertEquals(!initialState, admin.isNormalizerEnabled()); 667 668 // Reset it back to what it was 669 prevState = admin.setNormalizerRunning(initialState); 670 671 // The previous state should be the opposite of the initial state 672 assertEquals(!initialState, prevState); 673 // Current state should be the original state again 674 assertEquals(initialState, admin.isNormalizerEnabled()); 675 } 676 677 @Test 678 public void testAbortProcedureFail() throws Exception { 679 Random randomGenerator = new Random(); 680 long procId = randomGenerator.nextLong(); 681 682 boolean abortResult = admin.abortProcedure(procId, true); 683 assertFalse(abortResult); 684 } 685 686 @Test 687 public void testGetProcedures() throws Exception { 688 String procList = admin.getProcedures(); 689 assertTrue(procList.startsWith("[")); 690 } 691 692 @Test 693 public void testGetLocks() throws Exception { 694 String lockList = admin.getLocks(); 695 assertTrue(lockList.startsWith("[")); 696 } 697 698 @Test 699 public void testDecommissionRegionServers() throws Exception { 700 List<ServerName> decommissionedRegionServers = admin.listDecommissionedRegionServers(); 701 assertTrue(decommissionedRegionServers.isEmpty()); 702 703 final TableName tableName = TableName.valueOf(name.getMethodName()); 704 TEST_UTIL.createMultiRegionTable(tableName, Bytes.toBytes("f"), 6); 705 706 ArrayList<ServerName> clusterRegionServers = 707 new ArrayList<>(admin.getClusterMetrics(EnumSet.of(Option.LIVE_SERVERS)) 708 .getLiveServerMetrics().keySet()); 709 710 assertEquals(3, clusterRegionServers.size()); 711 712 HashMap<ServerName, List<RegionInfo>> serversToDecommssion = new HashMap<>(); 713 // Get a server that has regions. We will decommission two of the servers, 714 // leaving one online. 715 int i; 716 for (i = 0; i < clusterRegionServers.size(); i++) { 717 List<RegionInfo> regionsOnServer = admin.getRegions(clusterRegionServers.get(i)); 718 if (regionsOnServer.size() > 0) { 719 serversToDecommssion.put(clusterRegionServers.get(i), regionsOnServer); 720 break; 721 } 722 } 723 724 clusterRegionServers.remove(i); 725 // Get another server to decommission. 726 serversToDecommssion.put(clusterRegionServers.get(0), 727 admin.getRegions(clusterRegionServers.get(0))); 728 729 ServerName remainingServer = clusterRegionServers.get(1); 730 731 // Decommission 732 admin.decommissionRegionServers(new ArrayList<ServerName>(serversToDecommssion.keySet()), true); 733 assertEquals(2, admin.listDecommissionedRegionServers().size()); 734 735 // Verify the regions have been off the decommissioned servers, all on the one 736 // remaining server. 737 for (ServerName server : serversToDecommssion.keySet()) { 738 for (RegionInfo region : serversToDecommssion.get(server)) { 739 TEST_UTIL.assertRegionOnServer(region, remainingServer, 10000); 740 } 741 } 742 743 // Recommission and load the regions. 744 for (ServerName server : serversToDecommssion.keySet()) { 745 List<byte[]> encodedRegionNames = serversToDecommssion.get(server).stream() 746 .map(region -> region.getEncodedNameAsBytes()).collect(Collectors.toList()); 747 admin.recommissionRegionServer(server, encodedRegionNames); 748 } 749 assertTrue(admin.listDecommissionedRegionServers().isEmpty()); 750 // Verify the regions have been moved to the recommissioned servers 751 for (ServerName server : serversToDecommssion.keySet()) { 752 for (RegionInfo region : serversToDecommssion.get(server)) { 753 TEST_UTIL.assertRegionOnServer(region, server, 10000); 754 } 755 } 756 } 757}