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.regionserver; 019 020import static org.junit.Assert.assertEquals; 021import static org.junit.Assert.assertFalse; 022import static org.junit.Assert.assertNotNull; 023import static org.junit.Assert.assertNotSame; 024import static org.junit.Assert.assertNull; 025import static org.junit.Assert.assertTrue; 026import static org.junit.Assert.fail; 027 028import java.io.IOException; 029import java.util.Collection; 030import java.util.List; 031import java.util.Map; 032import java.util.Optional; 033import java.util.concurrent.CountDownLatch; 034import java.util.concurrent.atomic.AtomicBoolean; 035import org.apache.hadoop.conf.Configuration; 036import org.apache.hadoop.fs.FileSystem; 037import org.apache.hadoop.fs.Path; 038import org.apache.hadoop.hbase.Coprocessor; 039import org.apache.hadoop.hbase.CoprocessorEnvironment; 040import org.apache.hadoop.hbase.HBaseClassTestRule; 041import org.apache.hadoop.hbase.HBaseTestingUtility; 042import org.apache.hadoop.hbase.HColumnDescriptor; 043import org.apache.hadoop.hbase.HConstants; 044import org.apache.hadoop.hbase.HTableDescriptor; 045import org.apache.hadoop.hbase.MasterNotRunningException; 046import org.apache.hadoop.hbase.MetaTableAccessor; 047import org.apache.hadoop.hbase.MiniHBaseCluster; 048import org.apache.hadoop.hbase.ServerName; 049import org.apache.hadoop.hbase.TableName; 050import org.apache.hadoop.hbase.UnknownRegionException; 051import org.apache.hadoop.hbase.ZooKeeperConnectionException; 052import org.apache.hadoop.hbase.client.Admin; 053import org.apache.hadoop.hbase.client.Consistency; 054import org.apache.hadoop.hbase.client.Delete; 055import org.apache.hadoop.hbase.client.DoNotRetryRegionException; 056import org.apache.hadoop.hbase.client.Get; 057import org.apache.hadoop.hbase.client.Mutation; 058import org.apache.hadoop.hbase.client.Put; 059import org.apache.hadoop.hbase.client.RegionInfo; 060import org.apache.hadoop.hbase.client.Result; 061import org.apache.hadoop.hbase.client.ResultScanner; 062import org.apache.hadoop.hbase.client.Scan; 063import org.apache.hadoop.hbase.client.Table; 064import org.apache.hadoop.hbase.client.TestReplicasClient.SlowMeCopro; 065import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; 066import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; 067import org.apache.hadoop.hbase.coprocessor.MasterObserver; 068import org.apache.hadoop.hbase.coprocessor.ObserverContext; 069import org.apache.hadoop.hbase.exceptions.UnexpectedStateException; 070import org.apache.hadoop.hbase.master.HMaster; 071import org.apache.hadoop.hbase.master.LoadBalancer; 072import org.apache.hadoop.hbase.master.MasterRpcServices; 073import org.apache.hadoop.hbase.master.NoSuchProcedureException; 074import org.apache.hadoop.hbase.master.RegionState; 075import org.apache.hadoop.hbase.master.RegionState.State; 076import org.apache.hadoop.hbase.master.assignment.AssignmentManager; 077import org.apache.hadoop.hbase.master.assignment.RegionStates; 078import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility; 079import org.apache.hadoop.hbase.regionserver.compactions.CompactionContext; 080import org.apache.hadoop.hbase.regionserver.throttle.NoLimitThroughputController; 081import org.apache.hadoop.hbase.testclassification.LargeTests; 082import org.apache.hadoop.hbase.testclassification.RegionServerTests; 083import org.apache.hadoop.hbase.util.Bytes; 084import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 085import org.apache.hadoop.hbase.util.FSUtils; 086import org.apache.hadoop.hbase.util.HBaseFsck; 087import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread; 088import org.apache.hadoop.hbase.util.Threads; 089import org.apache.zookeeper.KeeperException; 090import org.apache.zookeeper.KeeperException.NodeExistsException; 091import org.junit.After; 092import org.junit.AfterClass; 093import org.junit.Assert; 094import org.junit.Before; 095import org.junit.BeforeClass; 096import org.junit.ClassRule; 097import org.junit.Rule; 098import org.junit.Test; 099import org.junit.experimental.categories.Category; 100import org.junit.rules.TestName; 101import org.slf4j.Logger; 102import org.slf4j.LoggerFactory; 103 104import org.apache.hbase.thirdparty.com.google.protobuf.RpcController; 105import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException; 106 107import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 108import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionStateTransition.TransitionCode; 109import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionRequest; 110import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.ReportRegionStateTransitionResponse; 111 112/** 113 * The below tests are testing split region against a running cluster 114 */ 115@Category({RegionServerTests.class, LargeTests.class}) 116@SuppressWarnings("deprecation") 117public class TestSplitTransactionOnCluster { 118 119 @ClassRule 120 public static final HBaseClassTestRule CLASS_RULE = 121 HBaseClassTestRule.forClass(TestSplitTransactionOnCluster.class); 122 123 private static final Logger LOG = LoggerFactory.getLogger(TestSplitTransactionOnCluster.class); 124 private Admin admin = null; 125 private MiniHBaseCluster cluster = null; 126 private static final int NB_SERVERS = 3; 127 128 static final HBaseTestingUtility TESTING_UTIL = 129 new HBaseTestingUtility(); 130 131 @Rule 132 public TestName name = new TestName(); 133 134 @BeforeClass public static void before() throws Exception { 135 TESTING_UTIL.getConfiguration().setInt(HConstants.HBASE_BALANCER_PERIOD, 60000); 136 TESTING_UTIL.startMiniCluster(1, NB_SERVERS, null, MyMaster.class, null); 137 } 138 139 @AfterClass public static void after() throws Exception { 140 TESTING_UTIL.shutdownMiniCluster(); 141 } 142 143 @Before public void setup() throws IOException { 144 TESTING_UTIL.ensureSomeNonStoppedRegionServersAvailable(NB_SERVERS); 145 this.admin = TESTING_UTIL.getAdmin(); 146 this.cluster = TESTING_UTIL.getMiniHBaseCluster(); 147 } 148 149 @After 150 public void tearDown() throws Exception { 151 this.admin.close(); 152 for (HTableDescriptor htd: this.admin.listTables()) { 153 LOG.info("Tear down, remove table=" + htd.getTableName()); 154 TESTING_UTIL.deleteTable(htd.getTableName()); 155 } 156 } 157 158 private RegionInfo getAndCheckSingleTableRegion(final List<HRegion> regions) 159 throws IOException, InterruptedException { 160 assertEquals(1, regions.size()); 161 RegionInfo hri = regions.get(0).getRegionInfo(); 162 try { 163 cluster.getMaster().getAssignmentManager().waitForAssignment(hri, 600000); 164 } catch (NoSuchProcedureException e) { 165 LOG.info("Presume the procedure has been cleaned up so just proceed: " + e.toString()); 166 } 167 return hri; 168 } 169 170 private void requestSplitRegion( 171 final HRegionServer rsServer, 172 final Region region, 173 final byte[] midKey) throws IOException { 174 long procId = cluster.getMaster().splitRegion(region.getRegionInfo(), midKey, 0, 0); 175 // wait for the split to complete or get interrupted. If the split completes successfully, 176 // the procedure will return true; if the split fails, the procedure would throw exception. 177 ProcedureTestingUtility.waitProcedure(cluster.getMaster().getMasterProcedureExecutor(), procId); 178 } 179 180 @Test 181 public void testRITStateForRollback() throws Exception { 182 final TableName tableName = TableName.valueOf(name.getMethodName()); 183 final HMaster master = cluster.getMaster(); 184 try { 185 // Create table then get the single region for our new table. 186 Table t = createTableAndWait(tableName, Bytes.toBytes("cf")); 187 final List<HRegion> regions = cluster.getRegions(tableName); 188 final RegionInfo hri = getAndCheckSingleTableRegion(regions); 189 insertData(tableName, admin, t); 190 t.close(); 191 192 // Turn off balancer so it doesn't cut in and mess up our placements. 193 this.admin.setBalancerRunning(false, true); 194 // Turn off the meta scanner so it don't remove parent on us. 195 master.setCatalogJanitorEnabled(false); 196 197 // find a splittable region 198 final HRegion region = findSplittableRegion(regions); 199 assertTrue("not able to find a splittable region", region != null); 200 201 // install master co-processor to fail splits 202 master.getMasterCoprocessorHost().load( 203 FailingSplitMasterObserver.class, 204 Coprocessor.PRIORITY_USER, 205 master.getConfiguration()); 206 207 // split async 208 this.admin.splitRegion(region.getRegionInfo().getRegionName(), new byte[] {42}); 209 210 // we have to wait until the SPLITTING state is seen by the master 211 FailingSplitMasterObserver observer = 212 master.getMasterCoprocessorHost().findCoprocessor(FailingSplitMasterObserver.class); 213 assertNotNull(observer); 214 observer.latch.await(); 215 216 LOG.info("Waiting for region to come out of RIT"); 217 while (!cluster.getMaster().getAssignmentManager().getRegionStates().isRegionOnline(hri)) { 218 Threads.sleep(100); 219 } 220 assertTrue(cluster.getMaster().getAssignmentManager().getRegionStates().isRegionOnline(hri)); 221 } finally { 222 admin.setBalancerRunning(true, false); 223 master.setCatalogJanitorEnabled(true); 224 abortAndWaitForMaster(); 225 TESTING_UTIL.deleteTable(tableName); 226 } 227 } 228 229 @Test 230 public void testSplitFailedCompactionAndSplit() throws Exception { 231 final TableName tableName = TableName.valueOf(name.getMethodName()); 232 // Create table then get the single region for our new table. 233 HTableDescriptor htd = new HTableDescriptor(tableName); 234 byte[] cf = Bytes.toBytes("cf"); 235 htd.addFamily(new HColumnDescriptor(cf)); 236 admin.createTable(htd); 237 238 for (int i = 0; cluster.getRegions(tableName).isEmpty() && i < 100; i++) { 239 Thread.sleep(100); 240 } 241 assertEquals(1, cluster.getRegions(tableName).size()); 242 243 HRegion region = cluster.getRegions(tableName).get(0); 244 HStore store = region.getStore(cf); 245 int regionServerIndex = cluster.getServerWith(region.getRegionInfo().getRegionName()); 246 HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); 247 248 Table t = TESTING_UTIL.getConnection().getTable(tableName); 249 // insert data 250 insertData(tableName, admin, t); 251 insertData(tableName, admin, t); 252 253 int fileNum = store.getStorefiles().size(); 254 // 0, Compaction Request 255 store.triggerMajorCompaction(); 256 Optional<CompactionContext> cc = store.requestCompaction(); 257 assertTrue(cc.isPresent()); 258 // 1, A timeout split 259 // 1.1 close region 260 assertEquals(2, region.close(false).get(cf).size()); 261 // 1.2 rollback and Region initialize again 262 region.initialize(); 263 264 // 2, Run Compaction cc 265 assertFalse(region.compact(cc.get(), store, NoLimitThroughputController.INSTANCE)); 266 assertTrue(fileNum > store.getStorefiles().size()); 267 268 // 3, Split 269 requestSplitRegion(regionServer, region, Bytes.toBytes("row3")); 270 assertEquals(2, cluster.getRegions(tableName).size()); 271 } 272 273 public static class FailingSplitMasterObserver implements MasterCoprocessor, MasterObserver { 274 volatile CountDownLatch latch; 275 276 @Override 277 public void start(CoprocessorEnvironment e) throws IOException { 278 latch = new CountDownLatch(1); 279 } 280 281 @Override 282 public Optional<MasterObserver> getMasterObserver() { 283 return Optional.of(this); 284 } 285 286 @Override 287 public void preSplitRegionBeforeMETAAction( 288 final ObserverContext<MasterCoprocessorEnvironment> ctx, 289 final byte[] splitKey, 290 final List<Mutation> metaEntries) throws IOException { 291 latch.countDown(); 292 throw new IOException("Causing rollback of region split"); 293 } 294 } 295 296 @Test 297 public void testSplitRollbackOnRegionClosing() throws IOException, InterruptedException { 298 final TableName tableName = TableName.valueOf(name.getMethodName()); 299 300 // Create table then get the single region for our new table. 301 Table t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); 302 List<HRegion> regions = cluster.getRegions(tableName); 303 RegionInfo hri = getAndCheckSingleTableRegion(regions); 304 305 int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); 306 307 RegionStates regionStates = cluster.getMaster().getAssignmentManager().getRegionStates(); 308 309 // Turn off balancer so it doesn't cut in and mess up our placements. 310 this.admin.setBalancerRunning(false, true); 311 // Turn off the meta scanner so it don't remove parent on us. 312 cluster.getMaster().setCatalogJanitorEnabled(false); 313 try { 314 // Add a bit of load up into the table so splittable. 315 TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false); 316 // Get region pre-split. 317 HRegionServer server = cluster.getRegionServer(tableRegionIndex); 318 printOutRegions(server, "Initial regions: "); 319 int regionCount = cluster.getRegions(hri.getTable()).size(); 320 regionStates.updateRegionState(hri, RegionState.State.CLOSING); 321 322 // Now try splitting.... should fail. And each should successfully 323 // rollback. 324 // We don't roll back here anymore. Instead we fail-fast on construction of the 325 // split transaction. Catch the exception instead. 326 try { 327 this.admin.splitRegion(hri.getRegionName()); 328 fail(); 329 } catch (DoNotRetryRegionException e) { 330 // Expected 331 } 332 // Wait around a while and assert count of regions remains constant. 333 for (int i = 0; i < 10; i++) { 334 Thread.sleep(100); 335 assertEquals(regionCount, cluster.getRegions(hri.getTable()).size()); 336 } 337 regionStates.updateRegionState(hri, State.OPEN); 338 // Now try splitting and it should work. 339 split(hri, server, regionCount); 340 // Get daughters 341 checkAndGetDaughters(tableName); 342 // OK, so split happened after we cleared the blocking node. 343 } finally { 344 admin.setBalancerRunning(true, false); 345 cluster.getMaster().setCatalogJanitorEnabled(true); 346 t.close(); 347 } 348 } 349 350 /** 351 * Test that if daughter split on us, we won't do the shutdown handler fixup 352 * just because we can't find the immediate daughter of an offlined parent. 353 * @throws IOException 354 * @throws InterruptedException 355 */ 356 @Test 357 public void testShutdownFixupWhenDaughterHasSplit()throws IOException, InterruptedException { 358 final TableName tableName = TableName.valueOf(name.getMethodName()); 359 360 // Create table then get the single region for our new table. 361 Table t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); 362 List<HRegion> regions = cluster.getRegions(tableName); 363 RegionInfo hri = getAndCheckSingleTableRegion(regions); 364 365 int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); 366 367 // Turn off balancer so it doesn't cut in and mess up our placements. 368 this.admin.setBalancerRunning(false, true); 369 // Turn off the meta scanner so it don't remove parent on us. 370 cluster.getMaster().setCatalogJanitorEnabled(false); 371 try { 372 // Add a bit of load up into the table so splittable. 373 TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY); 374 // Get region pre-split. 375 HRegionServer server = cluster.getRegionServer(tableRegionIndex); 376 printOutRegions(server, "Initial regions: "); 377 int regionCount = cluster.getRegions(hri.getTable()).size(); 378 // Now split. 379 split(hri, server, regionCount); 380 // Get daughters 381 List<HRegion> daughters = checkAndGetDaughters(tableName); 382 // Now split one of the daughters. 383 regionCount = cluster.getRegions(hri.getTable()).size(); 384 RegionInfo daughter = daughters.get(0).getRegionInfo(); 385 LOG.info("Daughter we are going to split: " + daughter); 386 // Compact first to ensure we have cleaned up references -- else the split 387 // will fail. 388 this.admin.compactRegion(daughter.getRegionName()); 389 daughters = cluster.getRegions(tableName); 390 HRegion daughterRegion = null; 391 for (HRegion r: daughters) { 392 if (RegionInfo.COMPARATOR.compare(r.getRegionInfo(), daughter) == 0) { 393 daughterRegion = r; 394 LOG.info("Found matching HRI: " + daughterRegion); 395 break; 396 } 397 } 398 assertTrue(daughterRegion != null); 399 for (int i=0; i<100; i++) { 400 if (!daughterRegion.hasReferences()) break; 401 Threads.sleep(100); 402 } 403 assertFalse("Waiting for reference to be compacted", daughterRegion.hasReferences()); 404 LOG.info("Daughter hri before split (has been compacted): " + daughter); 405 split(daughter, server, regionCount); 406 // Get list of daughters 407 daughters = cluster.getRegions(tableName); 408 for (HRegion d: daughters) { 409 LOG.info("Regions before crash: " + d); 410 } 411 // Now crash the server 412 cluster.abortRegionServer(tableRegionIndex); 413 waitUntilRegionServerDead(); 414 awaitDaughters(tableName, daughters.size()); 415 // Assert daughters are online and ONLY the original daughters -- that 416 // fixup didn't insert one during server shutdown recover. 417 regions = cluster.getRegions(tableName); 418 for (HRegion d: daughters) { 419 LOG.info("Regions after crash: " + d); 420 } 421 if (daughters.size() != regions.size()) { 422 LOG.info("Daughters=" + daughters.size() + ", regions=" + regions.size()); 423 } 424 assertEquals(daughters.size(), regions.size()); 425 for (HRegion r: regions) { 426 LOG.info("Regions post crash " + r + ", contains=" + daughters.contains(r)); 427 assertTrue("Missing region post crash " + r, daughters.contains(r)); 428 } 429 } finally { 430 LOG.info("EXITING"); 431 admin.setBalancerRunning(true, false); 432 cluster.getMaster().setCatalogJanitorEnabled(true); 433 t.close(); 434 } 435 } 436 437 @Test 438 public void testSplitShouldNotThrowNPEEvenARegionHasEmptySplitFiles() throws Exception { 439 TableName userTableName = TableName.valueOf(name.getMethodName()); 440 HTableDescriptor htd = new HTableDescriptor(userTableName); 441 HColumnDescriptor hcd = new HColumnDescriptor("col"); 442 htd.addFamily(hcd); 443 admin.createTable(htd); 444 Table table = TESTING_UTIL.getConnection().getTable(userTableName); 445 try { 446 for (int i = 0; i <= 5; i++) { 447 String row = "row" + i; 448 Put p = new Put(row.getBytes()); 449 String val = "Val" + i; 450 p.addColumn("col".getBytes(), "ql".getBytes(), val.getBytes()); 451 table.put(p); 452 admin.flush(userTableName); 453 Delete d = new Delete(row.getBytes()); 454 // Do a normal delete 455 table.delete(d); 456 admin.flush(userTableName); 457 } 458 admin.majorCompact(userTableName); 459 List<RegionInfo> regionsOfTable = 460 cluster.getMaster().getAssignmentManager().getRegionStates() 461 .getRegionsOfTable(userTableName); 462 assertEquals(1, regionsOfTable.size()); 463 RegionInfo hRegionInfo = regionsOfTable.get(0); 464 Put p = new Put("row6".getBytes()); 465 p.addColumn("col".getBytes(), "ql".getBytes(), "val".getBytes()); 466 table.put(p); 467 p = new Put("row7".getBytes()); 468 p.addColumn("col".getBytes(), "ql".getBytes(), "val".getBytes()); 469 table.put(p); 470 p = new Put("row8".getBytes()); 471 p.addColumn("col".getBytes(), "ql".getBytes(), "val".getBytes()); 472 table.put(p); 473 admin.flush(userTableName); 474 admin.splitRegion(hRegionInfo.getRegionName(), "row7".getBytes()); 475 regionsOfTable = cluster.getMaster() 476 .getAssignmentManager().getRegionStates() 477 .getRegionsOfTable(userTableName); 478 479 while (regionsOfTable.size() != 2) { 480 Thread.sleep(1000); 481 regionsOfTable = cluster.getMaster() 482 .getAssignmentManager().getRegionStates() 483 .getRegionsOfTable(userTableName); 484 LOG.debug("waiting 2 regions to be available, got " + regionsOfTable.size() + 485 ": " + regionsOfTable); 486 487 } 488 Assert.assertEquals(2, regionsOfTable.size()); 489 490 Scan s = new Scan(); 491 ResultScanner scanner = table.getScanner(s); 492 int mainTableCount = 0; 493 for (Result rr = scanner.next(); rr != null; rr = scanner.next()) { 494 mainTableCount++; 495 } 496 Assert.assertEquals(3, mainTableCount); 497 } finally { 498 table.close(); 499 } 500 } 501 502 /** 503 * Verifies HBASE-5806. Here the case is that splitting is completed but before the 504 * CJ could remove the parent region the master is killed and restarted. 505 * @throws IOException 506 * @throws InterruptedException 507 * @throws NodeExistsException 508 * @throws KeeperException 509 */ 510 @Test 511 public void testMasterRestartAtRegionSplitPendingCatalogJanitor() 512 throws IOException, InterruptedException, NodeExistsException, 513 KeeperException, ServiceException { 514 final TableName tableName = TableName.valueOf(name.getMethodName()); 515 516 // Create table then get the single region for our new table. 517 Table t = createTableAndWait(tableName, HConstants.CATALOG_FAMILY); 518 List<HRegion> regions = cluster.getRegions(tableName); 519 RegionInfo hri = getAndCheckSingleTableRegion(regions); 520 521 int tableRegionIndex = ensureTableRegionNotOnSameServerAsMeta(admin, hri); 522 523 // Turn off balancer so it doesn't cut in and mess up our placements. 524 this.admin.setBalancerRunning(false, true); 525 // Turn off the meta scanner so it don't remove parent on us. 526 cluster.getMaster().setCatalogJanitorEnabled(false); 527 try { 528 // Add a bit of load up into the table so splittable. 529 TESTING_UTIL.loadTable(t, HConstants.CATALOG_FAMILY, false); 530 // Get region pre-split. 531 HRegionServer server = cluster.getRegionServer(tableRegionIndex); 532 printOutRegions(server, "Initial regions: "); 533 // Call split. 534 this.admin.splitRegion(hri.getRegionName()); 535 List<HRegion> daughters = checkAndGetDaughters(tableName); 536 // Before cleanup, get a new master. 537 HMaster master = abortAndWaitForMaster(); 538 // Now call compact on the daughters and clean up any references. 539 for (HRegion daughter: daughters) { 540 daughter.compact(true); 541 assertFalse(daughter.hasReferences()); 542 } 543 // BUT calling compact on the daughters is not enough. The CatalogJanitor looks 544 // in the filesystem, and the filesystem content is not same as what the Region 545 // is reading from. Compacted-away files are picked up later by the compacted 546 // file discharger process. It runs infrequently. Make it run so CatalogJanitor 547 // doens't find any references. 548 for (RegionServerThread rst: cluster.getRegionServerThreads()) { 549 boolean oldSetting = rst.getRegionServer().compactedFileDischarger.setUseExecutor(false); 550 rst.getRegionServer().compactedFileDischarger.run(); 551 rst.getRegionServer().compactedFileDischarger.setUseExecutor(oldSetting); 552 } 553 cluster.getMaster().setCatalogJanitorEnabled(true); 554 LOG.info("Starting run of CatalogJanitor"); 555 cluster.getMaster().getCatalogJanitor().run(); 556 ProcedureTestingUtility.waitAllProcedures(cluster.getMaster().getMasterProcedureExecutor()); 557 RegionStates regionStates = master.getAssignmentManager().getRegionStates(); 558 ServerName regionServerOfRegion = regionStates.getRegionServerOfRegion(hri); 559 assertEquals(null, regionServerOfRegion); 560 } finally { 561 TESTING_UTIL.getAdmin().setBalancerRunning(true, false); 562 cluster.getMaster().setCatalogJanitorEnabled(true); 563 t.close(); 564 } 565 } 566 567 @Test 568 public void testSplitWithRegionReplicas() throws Exception { 569 final TableName tableName = TableName.valueOf(name.getMethodName()); 570 HTableDescriptor htd = TESTING_UTIL.createTableDescriptor(name.getMethodName()); 571 htd.setRegionReplication(2); 572 htd.addCoprocessor(SlowMeCopro.class.getName()); 573 // Create table then get the single region for our new table. 574 Table t = TESTING_UTIL.createTable(htd, new byte[][]{Bytes.toBytes("cf")}, null); 575 List<HRegion> oldRegions; 576 do { 577 oldRegions = cluster.getRegions(tableName); 578 Thread.sleep(10); 579 } while (oldRegions.size() != 2); 580 for (HRegion h : oldRegions) LOG.debug("OLDREGION " + h.getRegionInfo()); 581 try { 582 int regionServerIndex = cluster.getServerWith(oldRegions.get(0).getRegionInfo() 583 .getRegionName()); 584 HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); 585 insertData(tableName, admin, t); 586 // Turn off balancer so it doesn't cut in and mess up our placements. 587 admin.setBalancerRunning(false, true); 588 // Turn off the meta scanner so it don't remove parent on us. 589 cluster.getMaster().setCatalogJanitorEnabled(false); 590 boolean tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(), 591 tableName); 592 assertEquals("The specified table should be present.", true, tableExists); 593 final HRegion region = findSplittableRegion(oldRegions); 594 regionServerIndex = cluster.getServerWith(region.getRegionInfo().getRegionName()); 595 regionServer = cluster.getRegionServer(regionServerIndex); 596 assertTrue("not able to find a splittable region", region != null); 597 try { 598 requestSplitRegion(regionServer, region, Bytes.toBytes("row2")); 599 } catch (IOException e) { 600 e.printStackTrace(); 601 fail("Split execution should have succeeded with no exceptions thrown " + e); 602 } 603 //TESTING_UTIL.waitUntilAllRegionsAssigned(tableName); 604 List<HRegion> newRegions; 605 do { 606 newRegions = cluster.getRegions(tableName); 607 for (HRegion h : newRegions) LOG.debug("NEWREGION " + h.getRegionInfo()); 608 Thread.sleep(1000); 609 } while ((newRegions.contains(oldRegions.get(0)) || newRegions.contains(oldRegions.get(1))) 610 || newRegions.size() != 4); 611 tableExists = MetaTableAccessor.tableExists(regionServer.getConnection(), 612 tableName); 613 assertEquals("The specified table should be present.", true, tableExists); 614 // exists works on stale and we see the put after the flush 615 byte[] b1 = "row1".getBytes(); 616 Get g = new Get(b1); 617 g.setConsistency(Consistency.STRONG); 618 // The following GET will make a trip to the meta to get the new location of the 1st daughter 619 // In the process it will also get the location of the replica of the daughter (initially 620 // pointing to the parent's replica) 621 Result r = t.get(g); 622 Assert.assertFalse(r.isStale()); 623 LOG.info("exists stale after flush done"); 624 625 SlowMeCopro.getPrimaryCdl().set(new CountDownLatch(1)); 626 g = new Get(b1); 627 g.setConsistency(Consistency.TIMELINE); 628 // This will succeed because in the previous GET we get the location of the replica 629 r = t.get(g); 630 Assert.assertTrue(r.isStale()); 631 SlowMeCopro.getPrimaryCdl().get().countDown(); 632 } finally { 633 SlowMeCopro.getPrimaryCdl().get().countDown(); 634 admin.setBalancerRunning(true, false); 635 cluster.getMaster().setCatalogJanitorEnabled(true); 636 t.close(); 637 } 638 } 639 640 private void insertData(final TableName tableName, Admin admin, Table t) throws IOException, 641 InterruptedException { 642 Put p = new Put(Bytes.toBytes("row1")); 643 p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("1")); 644 t.put(p); 645 p = new Put(Bytes.toBytes("row2")); 646 p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("2")); 647 t.put(p); 648 p = new Put(Bytes.toBytes("row3")); 649 p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("3")); 650 t.put(p); 651 p = new Put(Bytes.toBytes("row4")); 652 p.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q1"), Bytes.toBytes("4")); 653 t.put(p); 654 admin.flush(tableName); 655 } 656 657 /** 658 * If a table has regions that have no store files in a region, they should split successfully 659 * into two regions with no store files. 660 */ 661 @Test 662 public void testSplitRegionWithNoStoreFiles() 663 throws Exception { 664 final TableName tableName = TableName.valueOf(name.getMethodName()); 665 // Create table then get the single region for our new table. 666 createTableAndWait(tableName, HConstants.CATALOG_FAMILY); 667 List<HRegion> regions = cluster.getRegions(tableName); 668 RegionInfo hri = getAndCheckSingleTableRegion(regions); 669 ensureTableRegionNotOnSameServerAsMeta(admin, hri); 670 int regionServerIndex = cluster.getServerWith(regions.get(0).getRegionInfo() 671 .getRegionName()); 672 HRegionServer regionServer = cluster.getRegionServer(regionServerIndex); 673 // Turn off balancer so it doesn't cut in and mess up our placements. 674 this.admin.setBalancerRunning(false, true); 675 // Turn off the meta scanner so it don't remove parent on us. 676 cluster.getMaster().setCatalogJanitorEnabled(false); 677 try { 678 // Precondition: we created a table with no data, no store files. 679 printOutRegions(regionServer, "Initial regions: "); 680 Configuration conf = cluster.getConfiguration(); 681 HBaseFsck.debugLsr(conf, new Path("/")); 682 Path rootDir = FSUtils.getRootDir(conf); 683 FileSystem fs = TESTING_UTIL.getDFSCluster().getFileSystem(); 684 Map<String, Path> storefiles = 685 FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName); 686 assertEquals("Expected nothing but found " + storefiles.toString(), 0, storefiles.size()); 687 688 // find a splittable region. Refresh the regions list 689 regions = cluster.getRegions(tableName); 690 final HRegion region = findSplittableRegion(regions); 691 assertTrue("not able to find a splittable region", region != null); 692 693 // Now split. 694 try { 695 requestSplitRegion(regionServer, region, Bytes.toBytes("row2")); 696 } catch (IOException e) { 697 fail("Split execution should have succeeded with no exceptions thrown"); 698 } 699 700 // Postcondition: split the table with no store files into two regions, but still have no 701 // store files 702 List<HRegion> daughters = cluster.getRegions(tableName); 703 assertEquals(2, daughters.size()); 704 705 // check dirs 706 HBaseFsck.debugLsr(conf, new Path("/")); 707 Map<String, Path> storefilesAfter = 708 FSUtils.getTableStoreFilePathMap(null, fs, rootDir, tableName); 709 assertEquals("Expected nothing but found " + storefilesAfter.toString(), 0, 710 storefilesAfter.size()); 711 712 hri = region.getRegionInfo(); // split parent 713 AssignmentManager am = cluster.getMaster().getAssignmentManager(); 714 RegionStates regionStates = am.getRegionStates(); 715 long start = EnvironmentEdgeManager.currentTime(); 716 while (!regionStates.isRegionInState(hri, State.SPLIT)) { 717 LOG.debug("Waiting for SPLIT state on: " + hri); 718 assertFalse("Timed out in waiting split parent to be in state SPLIT", 719 EnvironmentEdgeManager.currentTime() - start > 60000); 720 Thread.sleep(500); 721 } 722 assertTrue(regionStates.isRegionInState(daughters.get(0).getRegionInfo(), State.OPEN)); 723 assertTrue(regionStates.isRegionInState(daughters.get(1).getRegionInfo(), State.OPEN)); 724 725 // We should not be able to assign it again 726 am.assign(hri); 727 assertFalse("Split region can't be assigned", 728 regionStates.isRegionInTransition(hri)); 729 assertTrue(regionStates.isRegionInState(hri, State.SPLIT)); 730 731 // We should not be able to unassign it either 732 try { 733 am.unassign(hri); 734 fail("Should have thrown exception"); 735 } catch (UnexpectedStateException e) { 736 // Expected 737 } 738 assertFalse("Split region can't be unassigned", 739 regionStates.isRegionInTransition(hri)); 740 assertTrue(regionStates.isRegionInState(hri, State.SPLIT)); 741 } finally { 742 admin.setBalancerRunning(true, false); 743 cluster.getMaster().setCatalogJanitorEnabled(true); 744 } 745 } 746 747 @Test 748 public void testStoreFileReferenceCreationWhenSplitPolicySaysToSkipRangeCheck() 749 throws Exception { 750 final TableName tableName = TableName.valueOf(name.getMethodName()); 751 try { 752 HTableDescriptor htd = new HTableDescriptor(tableName); 753 htd.addFamily(new HColumnDescriptor("f")); 754 htd.addFamily(new HColumnDescriptor("i_f")); 755 htd.setRegionSplitPolicyClassName(CustomSplitPolicy.class.getName()); 756 admin.createTable(htd); 757 List<HRegion> regions = awaitTableRegions(tableName); 758 HRegion region = regions.get(0); 759 for(int i = 3;i<9;i++) { 760 Put p = new Put(Bytes.toBytes("row"+i)); 761 p.addColumn(Bytes.toBytes("f"), Bytes.toBytes("q"), Bytes.toBytes("value" + i)); 762 p.addColumn(Bytes.toBytes("i_f"), Bytes.toBytes("q"), Bytes.toBytes("value" + i)); 763 region.put(p); 764 } 765 region.flush(true); 766 HStore store = region.getStore(Bytes.toBytes("f")); 767 Collection<HStoreFile> storefiles = store.getStorefiles(); 768 assertEquals(1, storefiles.size()); 769 assertFalse(region.hasReferences()); 770 Path referencePath = 771 region.getRegionFileSystem().splitStoreFile(region.getRegionInfo(), "f", 772 storefiles.iterator().next(), Bytes.toBytes("row1"), false, region.getSplitPolicy()); 773 assertNull(referencePath); 774 referencePath = 775 region.getRegionFileSystem().splitStoreFile(region.getRegionInfo(), "i_f", 776 storefiles.iterator().next(), Bytes.toBytes("row1"), false, region.getSplitPolicy()); 777 assertNotNull(referencePath); 778 } finally { 779 TESTING_UTIL.deleteTable(tableName); 780 } 781 } 782 783 private HRegion findSplittableRegion(final List<HRegion> regions) throws InterruptedException { 784 for (int i = 0; i < 5; ++i) { 785 for (HRegion r: regions) { 786 if (r.isSplittable() && r.getRegionInfo().getReplicaId() == 0) { 787 return(r); 788 } 789 } 790 Thread.sleep(100); 791 } 792 return(null); 793 } 794 795 private List<HRegion> checkAndGetDaughters(TableName tableName) 796 throws InterruptedException { 797 List<HRegion> daughters = null; 798 // try up to 10s 799 for (int i=0; i<100; i++) { 800 daughters = cluster.getRegions(tableName); 801 if (daughters.size() >= 2) break; 802 Thread.sleep(100); 803 } 804 assertTrue(daughters.size() >= 2); 805 return daughters; 806 } 807 808 private HMaster abortAndWaitForMaster() 809 throws IOException, InterruptedException { 810 cluster.abortMaster(0); 811 cluster.waitOnMaster(0); 812 HMaster master = cluster.startMaster().getMaster(); 813 cluster.waitForActiveAndReadyMaster(); 814 return master; 815 } 816 817 private void split(final RegionInfo hri, final HRegionServer server, final int regionCount) 818 throws IOException, InterruptedException { 819 admin.splitRegion(hri.getRegionName()); 820 for (int i = 0; cluster.getRegions(hri.getTable()).size() <= regionCount && i < 60; i++) { 821 LOG.debug("Waiting on region " + hri.getRegionNameAsString() + " to split"); 822 Thread.sleep(2000); 823 } 824 assertFalse("Waited too long for split", 825 cluster.getRegions(hri.getTable()).size() <= regionCount); 826 } 827 828 /** 829 * Ensure single table region is not on same server as the single hbase:meta table 830 * region. 831 * @param admin 832 * @param hri 833 * @return Index of the server hosting the single table region 834 * @throws UnknownRegionException 835 * @throws MasterNotRunningException 836 * @throws org.apache.hadoop.hbase.ZooKeeperConnectionException 837 * @throws InterruptedException 838 */ 839 private int ensureTableRegionNotOnSameServerAsMeta(final Admin admin, 840 final RegionInfo hri) 841 throws IOException, MasterNotRunningException, 842 ZooKeeperConnectionException, InterruptedException { 843 // Now make sure that the table region is not on same server as that hosting 844 // hbase:meta We don't want hbase:meta replay polluting our test when we later crash 845 // the table region serving server. 846 int metaServerIndex = cluster.getServerWithMeta(); 847 boolean tablesOnMaster = LoadBalancer.isTablesOnMaster(TESTING_UTIL.getConfiguration()); 848 if (tablesOnMaster) { 849 // Need to check master is supposed to host meta... perhaps it is not. 850 throw new UnsupportedOperationException(); 851 // TODO: assertTrue(metaServerIndex == -1); // meta is on master now 852 } 853 HRegionServer metaRegionServer = tablesOnMaster? 854 cluster.getMaster(): cluster.getRegionServer(metaServerIndex); 855 int tableRegionIndex = cluster.getServerWith(hri.getRegionName()); 856 assertTrue(tableRegionIndex != -1); 857 HRegionServer tableRegionServer = cluster.getRegionServer(tableRegionIndex); 858 LOG.info("MetaRegionServer=" + metaRegionServer.getServerName() + 859 ", other=" + tableRegionServer.getServerName()); 860 if (metaRegionServer.getServerName().equals(tableRegionServer.getServerName())) { 861 HRegionServer hrs = getOtherRegionServer(cluster, metaRegionServer); 862 assertNotNull(hrs); 863 assertNotNull(hri); 864 LOG.info("Moving " + hri.getRegionNameAsString() + " from " + 865 metaRegionServer.getServerName() + " to " + 866 hrs.getServerName() + "; metaServerIndex=" + metaServerIndex); 867 admin.move(hri.getEncodedNameAsBytes(), Bytes.toBytes(hrs.getServerName().toString())); 868 } 869 // Wait till table region is up on the server that is NOT carrying hbase:meta. 870 for (int i = 0; i < 100; i++) { 871 tableRegionIndex = cluster.getServerWith(hri.getRegionName()); 872 if (tableRegionIndex != -1 && tableRegionIndex != metaServerIndex) break; 873 LOG.debug("Waiting on region move off the hbase:meta server; current index " + 874 tableRegionIndex + " and metaServerIndex=" + metaServerIndex); 875 Thread.sleep(100); 876 } 877 assertTrue("Region not moved off hbase:meta server, tableRegionIndex=" + tableRegionIndex, 878 tableRegionIndex != -1 && tableRegionIndex != metaServerIndex); 879 // Verify for sure table region is not on same server as hbase:meta 880 tableRegionIndex = cluster.getServerWith(hri.getRegionName()); 881 assertTrue(tableRegionIndex != -1); 882 assertNotSame(metaServerIndex, tableRegionIndex); 883 return tableRegionIndex; 884 } 885 886 /** 887 * Find regionserver other than the one passed. 888 * Can't rely on indexes into list of regionservers since crashed servers 889 * occupy an index. 890 * @param cluster 891 * @param notThisOne 892 * @return A regionserver that is not <code>notThisOne</code> or null if none 893 * found 894 */ 895 private HRegionServer getOtherRegionServer(final MiniHBaseCluster cluster, 896 final HRegionServer notThisOne) { 897 for (RegionServerThread rst: cluster.getRegionServerThreads()) { 898 HRegionServer hrs = rst.getRegionServer(); 899 if (hrs.getServerName().equals(notThisOne.getServerName())) continue; 900 if (hrs.isStopping() || hrs.isStopped()) continue; 901 return hrs; 902 } 903 return null; 904 } 905 906 private void printOutRegions(final HRegionServer hrs, final String prefix) 907 throws IOException { 908 List<RegionInfo> regions = ProtobufUtil.getOnlineRegions(hrs.getRSRpcServices()); 909 for (RegionInfo region: regions) { 910 LOG.info(prefix + region.getRegionNameAsString()); 911 } 912 } 913 914 private void waitUntilRegionServerDead() throws InterruptedException, IOException { 915 // Wait until the master processes the RS shutdown 916 for (int i=0; (cluster.getMaster().getClusterMetrics() 917 .getLiveServerMetrics().size() > NB_SERVERS 918 || cluster.getLiveRegionServerThreads().size() > NB_SERVERS) && i<100; i++) { 919 LOG.info("Waiting on server to go down"); 920 Thread.sleep(100); 921 } 922 assertFalse("Waited too long for RS to die", 923 cluster.getMaster().getClusterMetrics(). getLiveServerMetrics().size() > NB_SERVERS 924 || cluster.getLiveRegionServerThreads().size() > NB_SERVERS); 925 } 926 927 private void awaitDaughters(TableName tableName, int numDaughters) throws InterruptedException { 928 // Wait till regions are back on line again. 929 for (int i = 0; cluster.getRegions(tableName).size() < numDaughters && i < 60; i++) { 930 LOG.info("Waiting for repair to happen"); 931 Thread.sleep(1000); 932 } 933 if (cluster.getRegions(tableName).size() < numDaughters) { 934 fail("Waiting too long for daughter regions"); 935 } 936 } 937 938 private List<HRegion> awaitTableRegions(final TableName tableName) throws InterruptedException { 939 List<HRegion> regions = null; 940 for (int i = 0; i < 100; i++) { 941 regions = cluster.getRegions(tableName); 942 if (regions.size() > 0) break; 943 Thread.sleep(100); 944 } 945 return regions; 946 } 947 948 private Table createTableAndWait(TableName tableName, byte[] cf) throws IOException, 949 InterruptedException { 950 Table t = TESTING_UTIL.createTable(tableName, cf); 951 awaitTableRegions(tableName); 952 assertTrue("Table not online: " + tableName, 953 cluster.getRegions(tableName).size() != 0); 954 return t; 955 } 956 957 // Make it public so that JVMClusterUtil can access it. 958 public static class MyMaster extends HMaster { 959 public MyMaster(Configuration conf) throws IOException, KeeperException, InterruptedException { 960 super(conf); 961 } 962 963 @Override 964 protected RSRpcServices createRpcServices() throws IOException { 965 return new MyMasterRpcServices(this); 966 } 967 } 968 969 static class MyMasterRpcServices extends MasterRpcServices { 970 static AtomicBoolean enabled = new AtomicBoolean(false); 971 972 private HMaster myMaster; 973 public MyMasterRpcServices(HMaster master) throws IOException { 974 super(master); 975 myMaster = master; 976 } 977 978 @Override 979 public ReportRegionStateTransitionResponse reportRegionStateTransition(RpcController c, 980 ReportRegionStateTransitionRequest req) throws ServiceException { 981 ReportRegionStateTransitionResponse resp = super.reportRegionStateTransition(c, req); 982 if (enabled.get() && req.getTransition(0).getTransitionCode().equals( 983 TransitionCode.READY_TO_SPLIT) && !resp.hasErrorMessage()) { 984 RegionStates regionStates = myMaster.getAssignmentManager().getRegionStates(); 985 for (RegionStates.RegionStateNode regionState: 986 regionStates.getRegionsInTransition()) { 987 /* TODO!!!! 988 // Find the merging_new region and remove it 989 if (regionState.isSplittingNew()) { 990 regionStates.deleteRegion(regionState.getRegion()); 991 } 992 */ 993 } 994 } 995 return resp; 996 } 997 } 998 999 static class CustomSplitPolicy extends IncreasingToUpperBoundRegionSplitPolicy { 1000 1001 @Override 1002 protected boolean shouldSplit() { 1003 return true; 1004 } 1005 1006 @Override 1007 public boolean skipStoreFileRangeCheck(String familyName) { 1008 if(familyName.startsWith("i_")) { 1009 return true; 1010 } else { 1011 return false; 1012 } 1013 } 1014 } 1015} 1016