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.assertArrayEquals; 021import static org.junit.Assert.assertEquals; 022import static org.junit.Assert.assertTrue; 023 024import java.io.IOException; 025import java.util.ArrayList; 026import java.util.List; 027import java.util.Random; 028import java.util.Set; 029import java.util.TreeSet; 030import java.util.stream.Collectors; 031import org.apache.commons.io.IOUtils; 032import org.apache.hadoop.conf.Configuration; 033import org.apache.hadoop.hbase.ChoreService; 034import org.apache.hadoop.hbase.HBaseClassTestRule; 035import org.apache.hadoop.hbase.HBaseTestingUtility; 036import org.apache.hadoop.hbase.HConstants; 037import org.apache.hadoop.hbase.HRegionLocation; 038import org.apache.hadoop.hbase.MetaTableAccessor; 039import org.apache.hadoop.hbase.NotServingRegionException; 040import org.apache.hadoop.hbase.ScheduledChore; 041import org.apache.hadoop.hbase.Stoppable; 042import org.apache.hadoop.hbase.TableName; 043import org.apache.hadoop.hbase.client.Admin; 044import org.apache.hadoop.hbase.client.Connection; 045import org.apache.hadoop.hbase.client.ConnectionFactory; 046import org.apache.hadoop.hbase.client.Get; 047import org.apache.hadoop.hbase.client.Put; 048import org.apache.hadoop.hbase.client.RegionInfo; 049import org.apache.hadoop.hbase.client.RegionLocator; 050import org.apache.hadoop.hbase.client.Result; 051import org.apache.hadoop.hbase.client.Table; 052import org.apache.hadoop.hbase.testclassification.LargeTests; 053import org.apache.hadoop.hbase.util.Bytes; 054import org.apache.hadoop.hbase.util.Pair; 055import org.apache.hadoop.hbase.util.PairOfSameType; 056import org.apache.hadoop.hbase.util.StoppableImplementation; 057import org.apache.hadoop.hbase.util.Threads; 058import org.junit.AfterClass; 059import org.junit.BeforeClass; 060import org.junit.ClassRule; 061import org.junit.Rule; 062import org.junit.Test; 063import org.junit.experimental.categories.Category; 064import org.junit.rules.TestName; 065import org.slf4j.Logger; 066import org.slf4j.LoggerFactory; 067 068import org.apache.hbase.thirdparty.com.google.common.collect.Iterators; 069 070@Category(LargeTests.class) 071public class TestEndToEndSplitTransaction { 072 073 @ClassRule 074 public static final HBaseClassTestRule CLASS_RULE = 075 HBaseClassTestRule.forClass(TestEndToEndSplitTransaction.class); 076 077 private static final Logger LOG = LoggerFactory.getLogger(TestEndToEndSplitTransaction.class); 078 private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); 079 private static final Configuration CONF = TEST_UTIL.getConfiguration(); 080 081 @Rule 082 public TestName name = new TestName(); 083 084 @BeforeClass 085 public static void beforeAllTests() throws Exception { 086 TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5); 087 TEST_UTIL.startMiniCluster(); 088 } 089 090 @AfterClass 091 public static void afterAllTests() throws Exception { 092 TEST_UTIL.shutdownMiniCluster(); 093 } 094 095 /** 096 * Tests that the client sees meta table changes as atomic during splits 097 */ 098 @Test 099 public void testFromClientSideWhileSplitting() throws Throwable { 100 LOG.info("Starting testFromClientSideWhileSplitting"); 101 final TableName tableName = TableName.valueOf(name.getMethodName()); 102 final byte[] FAMILY = Bytes.toBytes("family"); 103 104 //SplitTransaction will update the meta table by offlining the parent region, and adding info 105 //for daughters. 106 Table table = TEST_UTIL.createTable(tableName, FAMILY); 107 108 Stoppable stopper = new StoppableImplementation(); 109 RegionSplitter regionSplitter = new RegionSplitter(table); 110 RegionChecker regionChecker = new RegionChecker(CONF, stopper, tableName); 111 final ChoreService choreService = new ChoreService("TEST_SERVER"); 112 113 choreService.scheduleChore(regionChecker); 114 regionSplitter.start(); 115 116 //wait until the splitter is finished 117 regionSplitter.join(); 118 stopper.stop(null); 119 120 if (regionChecker.ex != null) { 121 throw new AssertionError("regionChecker", regionChecker.ex); 122 } 123 124 if (regionSplitter.ex != null) { 125 throw new AssertionError("regionSplitter", regionSplitter.ex); 126 } 127 128 //one final check 129 regionChecker.verify(); 130 } 131 132 static class RegionSplitter extends Thread { 133 final Connection connection; 134 Throwable ex; 135 Table table; 136 TableName tableName; 137 byte[] family; 138 Admin admin; 139 HRegionServer rs; 140 141 RegionSplitter(Table table) throws IOException { 142 this.table = table; 143 this.tableName = table.getName(); 144 this.family = table.getTableDescriptor().getFamiliesKeys().iterator().next(); 145 admin = TEST_UTIL.getAdmin(); 146 rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0); 147 connection = TEST_UTIL.getConnection(); 148 } 149 150 @Override 151 public void run() { 152 try { 153 Random random = new Random(); 154 for (int i= 0; i< 5; i++) { 155 List<RegionInfo> regions = 156 MetaTableAccessor.getTableRegions(connection, tableName, true); 157 if (regions.isEmpty()) { 158 continue; 159 } 160 int regionIndex = random.nextInt(regions.size()); 161 162 //pick a random region and split it into two 163 RegionInfo region = Iterators.get(regions.iterator(), regionIndex); 164 165 //pick the mid split point 166 int start = 0, end = Integer.MAX_VALUE; 167 if (region.getStartKey().length > 0) { 168 start = Bytes.toInt(region.getStartKey()); 169 } 170 if (region.getEndKey().length > 0) { 171 end = Bytes.toInt(region.getEndKey()); 172 } 173 int mid = start + ((end - start) / 2); 174 byte[] splitPoint = Bytes.toBytes(mid); 175 176 //put some rows to the regions 177 addData(start); 178 addData(mid); 179 180 flushAndBlockUntilDone(admin, rs, region.getRegionName()); 181 compactAndBlockUntilDone(admin, rs, region.getRegionName()); 182 183 log("Initiating region split for:" + region.getRegionNameAsString()); 184 try { 185 admin.splitRegion(region.getRegionName(), splitPoint); 186 //wait until the split is complete 187 blockUntilRegionSplit(CONF, 50000, region.getRegionName(), true); 188 189 } catch (NotServingRegionException ex) { 190 //ignore 191 } 192 } 193 } catch (Throwable ex) { 194 this.ex = ex; 195 } 196 } 197 198 void addData(int start) throws IOException { 199 List<Put> puts = new ArrayList<>(); 200 for (int i=start; i< start + 100; i++) { 201 Put put = new Put(Bytes.toBytes(i)); 202 put.addColumn(family, family, Bytes.toBytes(i)); 203 puts.add(put); 204 } 205 table.put(puts); 206 } 207 } 208 209 /** 210 * Checks regions using MetaTableAccessor and HTable methods 211 */ 212 static class RegionChecker extends ScheduledChore { 213 Connection connection; 214 Configuration conf; 215 TableName tableName; 216 Throwable ex; 217 218 RegionChecker(Configuration conf, Stoppable stopper, TableName tableName) throws IOException { 219 super("RegionChecker", stopper, 10); 220 this.conf = conf; 221 this.tableName = tableName; 222 223 this.connection = ConnectionFactory.createConnection(conf); 224 } 225 226 /** verify region boundaries obtained from MetaScanner */ 227 void verifyRegionsUsingMetaTableAccessor() throws Exception { 228 List<RegionInfo> regionList = MetaTableAccessor.getTableRegions(connection, tableName, true); 229 verifyTableRegions(regionList.stream().collect(Collectors.toCollection(() -> new TreeSet<>(RegionInfo.COMPARATOR)))); 230 regionList = MetaTableAccessor.getAllRegions(connection, true); 231 verifyTableRegions(regionList.stream().collect(Collectors.toCollection(() -> new TreeSet<>(RegionInfo.COMPARATOR)))); 232 } 233 234 /** verify region boundaries obtained from HTable.getStartEndKeys() */ 235 void verifyRegionsUsingHTable() throws IOException { 236 Table table = null; 237 try { 238 //HTable.getStartEndKeys() 239 table = connection.getTable(tableName); 240 241 try(RegionLocator rl = connection.getRegionLocator(tableName)) { 242 Pair<byte[][], byte[][]> keys = rl.getStartEndKeys(); 243 verifyStartEndKeys(keys); 244 245 Set<RegionInfo> regions = new TreeSet<>(RegionInfo.COMPARATOR); 246 for (HRegionLocation loc : rl.getAllRegionLocations()) { 247 regions.add(loc.getRegionInfo()); 248 } 249 verifyTableRegions(regions); 250 } 251 252 } finally { 253 IOUtils.closeQuietly(table); 254 } 255 } 256 257 void verify() throws Exception { 258 verifyRegionsUsingMetaTableAccessor(); 259 verifyRegionsUsingHTable(); 260 } 261 262 void verifyTableRegions(Set<RegionInfo> regions) { 263 log("Verifying " + regions.size() + " regions: " + regions); 264 265 byte[][] startKeys = new byte[regions.size()][]; 266 byte[][] endKeys = new byte[regions.size()][]; 267 268 int i=0; 269 for (RegionInfo region : regions) { 270 startKeys[i] = region.getStartKey(); 271 endKeys[i] = region.getEndKey(); 272 i++; 273 } 274 275 Pair<byte[][], byte[][]> keys = new Pair<>(startKeys, endKeys); 276 verifyStartEndKeys(keys); 277 } 278 279 void verifyStartEndKeys(Pair<byte[][], byte[][]> keys) { 280 byte[][] startKeys = keys.getFirst(); 281 byte[][] endKeys = keys.getSecond(); 282 assertEquals(startKeys.length, endKeys.length); 283 assertTrue("Found 0 regions for the table", startKeys.length > 0); 284 285 assertArrayEquals("Start key for the first region is not byte[0]", 286 HConstants.EMPTY_START_ROW, startKeys[0]); 287 byte[] prevEndKey = HConstants.EMPTY_START_ROW; 288 289 // ensure that we do not have any gaps 290 for (int i=0; i<startKeys.length; i++) { 291 assertArrayEquals( 292 "Hole in hbase:meta is detected. prevEndKey=" + Bytes.toStringBinary(prevEndKey) 293 + " ,regionStartKey=" + Bytes.toStringBinary(startKeys[i]), prevEndKey, 294 startKeys[i]); 295 prevEndKey = endKeys[i]; 296 } 297 assertArrayEquals("End key for the last region is not byte[0]", HConstants.EMPTY_END_ROW, 298 endKeys[endKeys.length - 1]); 299 } 300 301 @Override 302 protected void chore() { 303 try { 304 verify(); 305 } catch (Throwable ex) { 306 this.ex = ex; 307 getStopper().stop("caught exception"); 308 } 309 } 310 } 311 312 public static void log(String msg) { 313 LOG.info(msg); 314 } 315 316 /* some utility methods for split tests */ 317 318 public static void flushAndBlockUntilDone(Admin admin, HRegionServer rs, byte[] regionName) 319 throws IOException, InterruptedException { 320 log("flushing region: " + Bytes.toStringBinary(regionName)); 321 admin.flushRegion(regionName); 322 log("blocking until flush is complete: " + Bytes.toStringBinary(regionName)); 323 Threads.sleepWithoutInterrupt(500); 324 while (rs.getOnlineRegion(regionName).getMemStoreDataSize() > 0) { 325 Threads.sleep(50); 326 } 327 } 328 329 public static void compactAndBlockUntilDone(Admin admin, HRegionServer rs, byte[] regionName) 330 throws IOException, InterruptedException { 331 log("Compacting region: " + Bytes.toStringBinary(regionName)); 332 admin.majorCompactRegion(regionName); 333 log("blocking until compaction is complete: " + Bytes.toStringBinary(regionName)); 334 Threads.sleepWithoutInterrupt(500); 335 outer: for (;;) { 336 for (Store store : rs.getOnlineRegion(regionName).getStores()) { 337 if (store.getStorefilesCount() > 1) { 338 Threads.sleep(50); 339 continue outer; 340 } 341 } 342 break; 343 } 344 } 345 346 /** Blocks until the region split is complete in hbase:meta and region server opens the daughters */ 347 public static void blockUntilRegionSplit(Configuration conf, long timeout, 348 final byte[] regionName, boolean waitForDaughters) 349 throws IOException, InterruptedException { 350 long start = System.currentTimeMillis(); 351 log("blocking until region is split:" + Bytes.toStringBinary(regionName)); 352 RegionInfo daughterA = null, daughterB = null; 353 try (Connection conn = ConnectionFactory.createConnection(conf); 354 Table metaTable = conn.getTable(TableName.META_TABLE_NAME)) { 355 Result result = null; 356 RegionInfo region = null; 357 while ((System.currentTimeMillis() - start) < timeout) { 358 result = metaTable.get(new Get(regionName)); 359 if (result == null) { 360 break; 361 } 362 363 region = MetaTableAccessor.getRegionInfo(result); 364 if (region.isSplitParent()) { 365 log("found parent region: " + region.toString()); 366 PairOfSameType<RegionInfo> pair = MetaTableAccessor.getDaughterRegions(result); 367 daughterA = pair.getFirst(); 368 daughterB = pair.getSecond(); 369 break; 370 } 371 Threads.sleep(100); 372 } 373 if (daughterA == null || daughterB == null) { 374 throw new IOException("Failed to get daughters, daughterA=" + daughterA + ", daughterB=" + 375 daughterB + ", timeout=" + timeout + ", result=" + result + ", regionName=" + 376 Bytes.toString(regionName) + ", region=" + region); 377 } 378 379 //if we are here, this means the region split is complete or timed out 380 if (waitForDaughters) { 381 long rem = timeout - (System.currentTimeMillis() - start); 382 blockUntilRegionIsInMeta(conn, rem, daughterA); 383 384 rem = timeout - (System.currentTimeMillis() - start); 385 blockUntilRegionIsInMeta(conn, rem, daughterB); 386 387 rem = timeout - (System.currentTimeMillis() - start); 388 blockUntilRegionIsOpened(conf, rem, daughterA); 389 390 rem = timeout - (System.currentTimeMillis() - start); 391 blockUntilRegionIsOpened(conf, rem, daughterB); 392 } 393 } 394 } 395 396 public static void blockUntilRegionIsInMeta(Connection conn, long timeout, RegionInfo hri) 397 throws IOException, InterruptedException { 398 log("blocking until region is in META: " + hri.getRegionNameAsString()); 399 long start = System.currentTimeMillis(); 400 while (System.currentTimeMillis() - start < timeout) { 401 HRegionLocation loc = MetaTableAccessor.getRegionLocation(conn, hri); 402 if (loc != null && !loc.getRegionInfo().isOffline()) { 403 log("found region in META: " + hri.getRegionNameAsString()); 404 break; 405 } 406 Threads.sleep(10); 407 } 408 } 409 410 public static void blockUntilRegionIsOpened(Configuration conf, long timeout, RegionInfo hri) 411 throws IOException, InterruptedException { 412 log("blocking until region is opened for reading:" + hri.getRegionNameAsString()); 413 long start = System.currentTimeMillis(); 414 try (Connection conn = ConnectionFactory.createConnection(conf); 415 Table table = conn.getTable(hri.getTable())) { 416 byte[] row = hri.getStartKey(); 417 // Check for null/empty row. If we find one, use a key that is likely to be in first region. 418 if (row == null || row.length <= 0) row = new byte[] { '0' }; 419 Get get = new Get(row); 420 while (System.currentTimeMillis() - start < timeout) { 421 try { 422 table.get(get); 423 break; 424 } catch (IOException ex) { 425 // wait some more 426 } 427 Threads.sleep(10); 428 } 429 } 430 } 431}