View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.regionserver;
19  
20  import static org.junit.Assert.assertArrayEquals;
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  
25  import com.google.common.collect.Iterators;
26  import com.google.common.collect.Sets;
27  import com.google.protobuf.ServiceException;
28  
29  import java.io.IOException;
30  import java.util.ArrayList;
31  import java.util.List;
32  import java.util.NavigableMap;
33  import java.util.Random;
34  import java.util.Set;
35  import java.util.TreeSet;
36  
37  import org.apache.commons.io.IOUtils;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.hadoop.conf.Configuration;
41  import org.apache.hadoop.hbase.ChoreService;
42  import org.apache.hadoop.hbase.HBaseTestingUtility;
43  import org.apache.hadoop.hbase.HConstants;
44  import org.apache.hadoop.hbase.HRegionInfo;
45  import org.apache.hadoop.hbase.HRegionLocation;
46  import org.apache.hadoop.hbase.MetaTableAccessor;
47  import org.apache.hadoop.hbase.NotServingRegionException;
48  import org.apache.hadoop.hbase.ScheduledChore;
49  import org.apache.hadoop.hbase.ServerName;
50  import org.apache.hadoop.hbase.Stoppable;
51  import org.apache.hadoop.hbase.TableName;
52  import org.apache.hadoop.hbase.client.Admin;
53  import org.apache.hadoop.hbase.client.Connection;
54  import org.apache.hadoop.hbase.client.ConnectionFactory;
55  import org.apache.hadoop.hbase.client.Get;
56  import org.apache.hadoop.hbase.client.HTable;
57  import org.apache.hadoop.hbase.client.MetaScanner;
58  import org.apache.hadoop.hbase.client.Put;
59  import org.apache.hadoop.hbase.client.Result;
60  import org.apache.hadoop.hbase.client.Scan;
61  import org.apache.hadoop.hbase.client.Table;
62  import org.apache.hadoop.hbase.coordination.BaseCoordinatedStateManager;
63  import org.apache.hadoop.hbase.ipc.HBaseRpcControllerImpl;
64  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
65  import org.apache.hadoop.hbase.protobuf.RequestConverter;
66  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
67  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
68  import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos;
69  import org.apache.hadoop.hbase.testclassification.LargeTests;
70  import org.apache.hadoop.hbase.util.Bytes;
71  import org.apache.hadoop.hbase.util.Pair;
72  import org.apache.hadoop.hbase.util.PairOfSameType;
73  import org.apache.hadoop.hbase.util.StoppableImplementation;
74  import org.apache.hadoop.hbase.util.Threads;
75  import org.junit.AfterClass;
76  import org.junit.BeforeClass;
77  import org.junit.Test;
78  import org.junit.experimental.categories.Category;
79  
80  @Category(LargeTests.class)
81  public class TestEndToEndSplitTransaction {
82    private static final Log LOG = LogFactory.getLog(TestEndToEndSplitTransaction.class);
83    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
84    private static final Configuration CONF = TEST_UTIL.getConfiguration();
85  
86    @BeforeClass
87    public static void beforeAllTests() throws Exception {
88      TEST_UTIL.getConfiguration().setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
89      TEST_UTIL.startMiniCluster();
90    }
91  
92    @AfterClass
93    public static void afterAllTests() throws Exception {
94      TEST_UTIL.shutdownMiniCluster();
95    }
96  
97    @Test
98    public void testMasterOpsWhileSplitting() throws Exception {
99      TableName tableName = TableName.valueOf("TestSplit");
100     byte[] familyName = Bytes.toBytes("fam");
101     try (HTable ht = TEST_UTIL.createTable(tableName, familyName)) {
102       TEST_UTIL.loadTable(ht, familyName, false);
103     }
104     HRegionServer server = TEST_UTIL.getHBaseCluster().getRegionServer(0);
105     byte[] firstRow = Bytes.toBytes("aaa");
106     byte[] splitRow = Bytes.toBytes("lll");
107     byte[] lastRow = Bytes.toBytes("zzz");
108     try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration())) {
109       // this will also cache the region
110       byte[] regionName = conn.getRegionLocator(tableName).getRegionLocation(splitRow)
111           .getRegionInfo().getRegionName();
112       Region region = server.getRegion(regionName);
113       SplitTransactionImpl split = new SplitTransactionImpl((HRegion) region, splitRow);
114       split.prepare();
115 
116       // 1. phase I
117       PairOfSameType<Region> regions = split.createDaughters(server, server, null);
118       assertFalse(test(conn, tableName, firstRow, server));
119       assertFalse(test(conn, tableName, lastRow, server));
120 
121       // passing null as services prevents final step
122       // 2, most of phase II
123       split.openDaughters(server, null, regions.getFirst(), regions.getSecond());
124       assertFalse(test(conn, tableName, firstRow, server));
125       assertFalse(test(conn, tableName, lastRow, server));
126 
127       // 3. finish phase II
128       // note that this replicates some code from SplitTransaction
129       // 2nd daughter first
130       if (split.useZKForAssignment) {
131         server.postOpenDeployTasks(regions.getSecond());
132       } else {
133       server.reportRegionStateTransition(
134         RegionServerStatusProtos.RegionStateTransition.TransitionCode.SPLIT,
135         region.getRegionInfo(), regions.getFirst().getRegionInfo(),
136         regions.getSecond().getRegionInfo());
137       }
138 
139       // first daughter second
140       if (split.useZKForAssignment) {
141         server.postOpenDeployTasks(regions.getFirst());
142       }
143 
144       // Add to online regions
145       server.addToOnlineRegions(regions.getSecond());
146       // THIS is the crucial point:
147       // the 2nd daughter was added, so querying before the split key should fail.
148       assertFalse(test(conn, tableName, firstRow, server));
149       // past splitkey is ok.
150       assertTrue(test(conn, tableName, lastRow, server));
151 
152       // Add to online regions
153       server.addToOnlineRegions(regions.getFirst());
154       assertTrue(test(conn, tableName, firstRow, server));
155       assertTrue(test(conn, tableName, lastRow, server));
156 
157       if (split.useZKForAssignment) {
158         // 4. phase III
159         ((BaseCoordinatedStateManager) server.getCoordinatedStateManager())
160           .getSplitTransactionCoordination().completeSplitTransaction(server, regions.getFirst(),
161             regions.getSecond(), split.std, region);
162       }
163 
164       assertTrue(test(conn, tableName, firstRow, server));
165       assertTrue(test(conn, tableName, lastRow, server));
166     }
167   }
168 
169   @Test
170   public void testTableAvailableWhileSplitting() throws Exception {
171     TableName tableName = TableName.valueOf("TestTableAvailableWhileSplitting");
172     byte[] familyName = Bytes.toBytes("fam");
173     try (HTable ht = TEST_UTIL.createTable(tableName, familyName)) {
174       TEST_UTIL.loadTable(ht, familyName, false);
175     }
176     Admin admin = TEST_UTIL.getHBaseAdmin();
177     HRegionServer server = TEST_UTIL.getHBaseCluster().getRegionServer(0);
178     byte[] splitRow = Bytes.toBytes("lll");
179     try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration())) {
180       byte[] regionName = conn.getRegionLocator(tableName).getRegionLocation(splitRow)
181           .getRegionInfo().getRegionName();
182       Region region = server.getRegion(regionName);
183       SplitTransactionImpl split = new SplitTransactionImpl((HRegion) region, splitRow);
184       split.prepare();
185       assertTrue(admin.isTableAvailable(tableName));
186 
187       // 1. phase I
188       PairOfSameType<Region> regions = split.createDaughters(server, server, null);
189       // Parent should be offline at this stage and daughters not yet open
190       assertFalse(admin.isTableAvailable(tableName));
191 
192       // passing null as services prevents final step of postOpenDeployTasks
193       // 2, most of phase II
194       split.openDaughters(server, null, regions.getFirst(), regions.getSecond());
195       assertFalse(admin.isTableAvailable(tableName));
196 
197       // Finish openeing daughters
198       // 2nd daughter first
199       if (split.useZKForAssignment) {
200         server.postOpenDeployTasks(regions.getSecond());
201       } else {
202         server.reportRegionStateTransition(
203           RegionServerStatusProtos.RegionStateTransition.TransitionCode.SPLIT,
204           region.getRegionInfo(), regions.getFirst().getRegionInfo(),
205           regions.getSecond().getRegionInfo());
206       }
207 
208       // first daughter second
209       if (split.useZKForAssignment) {
210         server.postOpenDeployTasks(regions.getFirst());
211       }
212 
213       // After postOpenDeploy daughters should have location in meta
214       assertTrue(admin.isTableAvailable(tableName));
215 
216       server.addToOnlineRegions(regions.getSecond());
217       server.addToOnlineRegions(regions.getFirst());
218       assertTrue(admin.isTableAvailable(tableName));
219     } finally {
220       if (admin != null) {
221         admin.close();
222       }
223     }
224   }
225 
226   /**
227    * attempt to locate the region and perform a get and scan
228    * @return True if successful, False otherwise.
229    */
230   private boolean test(Connection conn, TableName tableName, byte[] row,
231       HRegionServer server) {
232     // not using HTable to avoid timeouts and retries
233     try {
234       byte[] regionName = conn.getRegionLocator(tableName).getRegionLocation(row, true)
235           .getRegionInfo().getRegionName();
236       // get and scan should now succeed without exception
237       ClientProtos.GetRequest request =
238           RequestConverter.buildGetRequest(regionName, new Get(row));
239       server.getRSRpcServices().get(null, request);
240       ScanRequest scanRequest = RequestConverter.buildScanRequest(
241         regionName, new Scan(row), 1, true);
242       try {
243         server.getRSRpcServices().scan(
244           new HBaseRpcControllerImpl(), scanRequest);
245       } catch (ServiceException se) {
246         throw ProtobufUtil.getRemoteException(se);
247       }
248     } catch (IOException e) {
249       return false;
250     } catch (ServiceException e) {
251       return false;
252     }
253     return true;
254   }
255 
256   /**
257    * Tests that the client sees meta table changes as atomic during splits
258    */
259   @Test
260   public void testFromClientSideWhileSplitting() throws Throwable {
261     LOG.info("Starting testFromClientSideWhileSplitting");
262     final TableName TABLENAME =
263         TableName.valueOf("testFromClientSideWhileSplitting");
264     final byte[] FAMILY = Bytes.toBytes("family");
265 
266     //SplitTransaction will update the meta table by offlining the parent region, and adding info
267     //for daughters.
268     Table table = TEST_UTIL.createTable(TABLENAME, FAMILY);
269 
270     Stoppable stopper = new StoppableImplementation();
271     RegionSplitter regionSplitter = new RegionSplitter(table);
272     RegionChecker regionChecker = new RegionChecker(CONF, stopper, TABLENAME);
273     final ChoreService choreService = new ChoreService("TEST_SERVER");
274 
275     choreService.scheduleChore(regionChecker);
276     regionSplitter.start();
277 
278     //wait until the splitter is finished
279     regionSplitter.join();
280     stopper.stop(null);
281 
282     if (regionChecker.ex != null) {
283       throw regionChecker.ex;
284     }
285 
286     if (regionSplitter.ex != null) {
287       throw regionSplitter.ex;
288     }
289 
290     //one final check
291     regionChecker.verify();
292   }
293 
294   static class RegionSplitter extends Thread {
295     final Connection connection;
296     Throwable ex;
297     Table table;
298     TableName tableName;
299     byte[] family;
300     Admin admin;
301     HRegionServer rs;
302 
303     RegionSplitter(Table table) throws IOException {
304       this.table = table;
305       this.tableName = table.getName();
306       this.family = table.getTableDescriptor().getFamiliesKeys().iterator().next();
307       admin = TEST_UTIL.getHBaseAdmin();
308       rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0);
309       connection = TEST_UTIL.getConnection();
310     }
311 
312     @Override
313     public void run() {
314       try {
315         Random random = new Random();
316         for (int i= 0; i< 5; i++) {
317           NavigableMap<HRegionInfo, ServerName> regions =
318               MetaScanner.allTableRegions(connection, tableName);
319           if (regions.size() == 0) {
320             continue;
321           }
322           int regionIndex = random.nextInt(regions.size());
323 
324           //pick a random region and split it into two
325           HRegionInfo region = Iterators.get(regions.keySet().iterator(), regionIndex);
326 
327           //pick the mid split point
328           int start = 0, end = Integer.MAX_VALUE;
329           if (region.getStartKey().length > 0) {
330             start = Bytes.toInt(region.getStartKey());
331           }
332           if (region.getEndKey().length > 0) {
333             end = Bytes.toInt(region.getEndKey());
334           }
335           int mid = start + ((end - start) / 2);
336           byte[] splitPoint = Bytes.toBytes(mid);
337 
338           //put some rows to the regions
339           addData(start);
340           addData(mid);
341 
342           flushAndBlockUntilDone(admin, rs, region.getRegionName());
343           compactAndBlockUntilDone(admin, rs, region.getRegionName());
344 
345           log("Initiating region split for:" + region.getRegionNameAsString());
346           try {
347             admin.splitRegion(region.getRegionName(), splitPoint);
348             //wait until the split is complete
349             blockUntilRegionSplit(CONF, 50000, region.getRegionName(), true);
350 
351           } catch (NotServingRegionException ex) {
352             //ignore
353           }
354         }
355       } catch (Throwable ex) {
356         this.ex = ex;
357       }
358     }
359 
360     void addData(int start) throws IOException {
361       List<Put> puts = new ArrayList<>();
362       for (int i=start; i< start + 100; i++) {
363         Put put = new Put(Bytes.toBytes(i));
364         put.addColumn(family, family, Bytes.toBytes(i));
365         puts.add(put);
366       }
367       table.put(puts);
368     }
369   }
370 
371   /**
372    * Checks regions using MetaScanner, MetaTableAccessor and HTable methods
373    */
374   static class RegionChecker extends ScheduledChore {
375     Connection connection;
376     Configuration conf;
377     TableName tableName;
378     Throwable ex;
379 
380     RegionChecker(Configuration conf, Stoppable stopper, TableName tableName) throws IOException {
381       super("RegionChecker", stopper, 10);
382       this.conf = conf;
383       this.tableName = tableName;
384 
385       this.connection = ConnectionFactory.createConnection(conf);
386     }
387 
388     /** verify region boundaries obtained from MetaScanner */
389     void verifyRegionsUsingMetaScanner() throws Exception {
390 
391       //MetaScanner.allTableRegions()
392       NavigableMap<HRegionInfo, ServerName> regions = MetaScanner.allTableRegions(connection,
393           tableName);
394       verifyTableRegions(regions.keySet());
395 
396       //MetaScanner.listAllRegions()
397       List<HRegionInfo> regionList = MetaScanner.listAllRegions(conf, connection, false);
398       verifyTableRegions(Sets.newTreeSet(regionList));
399     }
400 
401     /** verify region boundaries obtained from HTable.getStartEndKeys() */
402     void verifyRegionsUsingHTable() throws IOException {
403       HTable table = null;
404       try {
405         table = (HTable) connection.getTable(tableName);
406         Pair<byte[][], byte[][]> keys = table.getRegionLocator().getStartEndKeys();
407         verifyStartEndKeys(keys);
408 
409         //HTable.getRegionsInfo()
410         Set<HRegionInfo> regions = new TreeSet<HRegionInfo>();
411         for (HRegionLocation loc : table.getRegionLocator().getAllRegionLocations()) {
412           regions.add(loc.getRegionInfo());
413         }
414         verifyTableRegions(regions);
415       } finally {
416         IOUtils.closeQuietly(table);
417       }
418     }
419 
420     void verify() throws Exception {
421       verifyRegionsUsingMetaScanner();
422       verifyRegionsUsingHTable();
423     }
424 
425     void verifyTableRegions(Set<HRegionInfo> regions) {
426       log("Verifying " + regions.size() + " regions: " + regions);
427 
428       byte[][] startKeys = new byte[regions.size()][];
429       byte[][] endKeys = new byte[regions.size()][];
430 
431       int i=0;
432       for (HRegionInfo region : regions) {
433         startKeys[i] = region.getStartKey();
434         endKeys[i] = region.getEndKey();
435         i++;
436       }
437 
438       Pair<byte[][], byte[][]> keys = new Pair<byte[][], byte[][]>(startKeys, endKeys);
439       verifyStartEndKeys(keys);
440     }
441 
442     void verifyStartEndKeys(Pair<byte[][], byte[][]> keys) {
443       byte[][] startKeys = keys.getFirst();
444       byte[][] endKeys = keys.getSecond();
445       assertEquals(startKeys.length, endKeys.length);
446       assertTrue("Found 0 regions for the table", startKeys.length > 0);
447 
448       assertArrayEquals("Start key for the first region is not byte[0]",
449           HConstants.EMPTY_START_ROW, startKeys[0]);
450       byte[] prevEndKey = HConstants.EMPTY_START_ROW;
451 
452       // ensure that we do not have any gaps
453       for (int i=0; i<startKeys.length; i++) {
454         assertArrayEquals(
455             "Hole in hbase:meta is detected. prevEndKey=" + Bytes.toStringBinary(prevEndKey)
456                 + " ,regionStartKey=" + Bytes.toStringBinary(startKeys[i]), prevEndKey,
457             startKeys[i]);
458         prevEndKey = endKeys[i];
459       }
460       assertArrayEquals("End key for the last region is not byte[0]", HConstants.EMPTY_END_ROW,
461           endKeys[endKeys.length - 1]);
462     }
463 
464     @Override
465     protected void chore() {
466       try {
467         verify();
468       } catch (Throwable ex) {
469         this.ex = ex;
470         getStopper().stop("caught exception");
471       }
472     }
473   }
474 
475   public static void log(String msg) {
476     LOG.info(msg);
477   }
478 
479   /* some utility methods for split tests */
480 
481   public static void flushAndBlockUntilDone(Admin admin, HRegionServer rs, byte[] regionName)
482       throws IOException, InterruptedException {
483     log("flushing region: " + Bytes.toStringBinary(regionName));
484     admin.flushRegion(regionName);
485     log("blocking until flush is complete: " + Bytes.toStringBinary(regionName));
486     Threads.sleepWithoutInterrupt(500);
487     while (rs.getOnlineRegion(regionName).getMemstoreSize() > 0) {
488       Threads.sleep(50);
489     }
490   }
491 
492   public static void compactAndBlockUntilDone(Admin admin, HRegionServer rs, byte[] regionName)
493       throws IOException, InterruptedException {
494     log("Compacting region: " + Bytes.toStringBinary(regionName));
495     admin.majorCompactRegion(regionName);
496     log("blocking until compaction is complete: " + Bytes.toStringBinary(regionName));
497     Threads.sleepWithoutInterrupt(500);
498     outer: for (;;) {
499       for (Store store : rs.getOnlineRegion(regionName).getStores()) {
500         if (store.getStorefilesCount() > 1) {
501           Threads.sleep(50);
502           continue outer;
503         }
504       }
505       break;
506     }
507   }
508 
509   /** Blocks until the region split is complete in hbase:meta and region server opens the daughters */
510   public static void blockUntilRegionSplit(Configuration conf, long timeout,
511       final byte[] regionName, boolean waitForDaughters)
512       throws IOException, InterruptedException {
513     long start = System.currentTimeMillis();
514     log("blocking until region is split:" +  Bytes.toStringBinary(regionName));
515     HRegionInfo daughterA = null, daughterB = null;
516     try (Connection conn = ConnectionFactory.createConnection(conf);
517         Table metaTable = conn.getTable(TableName.META_TABLE_NAME)) {
518       Result result = null;
519       HRegionInfo region = null;
520       while ((System.currentTimeMillis() - start) < timeout) {
521         result = metaTable.get(new Get(regionName));
522         if (result == null) {
523           break;
524         }
525 
526         region = MetaTableAccessor.getHRegionInfo(result);
527         if (region.isSplitParent()) {
528           log("found parent region: " + region.toString());
529           PairOfSameType<HRegionInfo> pair = MetaTableAccessor.getDaughterRegions(result);
530           daughterA = pair.getFirst();
531           daughterB = pair.getSecond();
532           break;
533         }
534         Threads.sleep(100);
535       }
536       if (daughterA == null || daughterB == null) {
537         throw new IOException("Failed to get daughters, daughterA=" + daughterA + ", daughterB=" +
538           daughterB + ", timeout=" + timeout + ", result=" + result + ", regionName=" +
539           Bytes.toString(regionName) + ", region=" + region);
540       }
541 
542       //if we are here, this means the region split is complete or timed out
543       if (waitForDaughters) {
544         long rem = timeout - (System.currentTimeMillis() - start);
545         blockUntilRegionIsInMeta(conn, rem, daughterA);
546 
547         rem = timeout - (System.currentTimeMillis() - start);
548         blockUntilRegionIsInMeta(conn, rem, daughterB);
549 
550         rem = timeout - (System.currentTimeMillis() - start);
551         blockUntilRegionIsOpened(conf, rem, daughterA);
552 
553         rem = timeout - (System.currentTimeMillis() - start);
554         blockUntilRegionIsOpened(conf, rem, daughterB);
555       }
556     }
557   }
558 
559   public static void blockUntilRegionIsInMeta(Connection conn, long timeout, HRegionInfo hri)
560       throws IOException, InterruptedException {
561     log("blocking until region is in META: " + hri.getRegionNameAsString());
562     long start = System.currentTimeMillis();
563     while (System.currentTimeMillis() - start < timeout) {
564       HRegionLocation loc = MetaTableAccessor.getRegionLocation(conn, hri);
565       if (loc != null && !loc.getRegionInfo().isOffline()) {
566         log("found region in META: " + hri.getRegionNameAsString());
567         break;
568       }
569       Threads.sleep(10);
570     }
571   }
572 
573   public static void blockUntilRegionIsOpened(Configuration conf, long timeout, HRegionInfo hri)
574       throws IOException, InterruptedException {
575     log("blocking until region is opened for reading:" + hri.getRegionNameAsString());
576     long start = System.currentTimeMillis();
577     try (Connection conn = ConnectionFactory.createConnection(conf);
578         Table table = conn.getTable(hri.getTable())) {
579       byte[] row = hri.getStartKey();
580       // Check for null/empty row. If we find one, use a key that is likely to be in first region.
581       if (row == null || row.length <= 0) row = new byte[] { '0' };
582       Get get = new Get(row);
583       while (System.currentTimeMillis() - start < timeout) {
584         try {
585           table.get(get);
586           break;
587         } catch (IOException ex) {
588           // wait some more
589         }
590         Threads.sleep(10);
591       }
592     }
593   }
594 }
595