View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.regionserver;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.assertFalse;
23  import static org.junit.Assert.assertTrue;
24  import static org.mockito.Matchers.anyInt;
25  import static org.mockito.Matchers.eq;
26  import static org.mockito.Mockito.*;
27  
28  import org.apache.hadoop.hbase.MockRegionServerServicesWithWALs;
29  import org.apache.hadoop.hbase.ServerName;
30  import org.apache.hadoop.hbase.testclassification.MediumTests;
31  import org.apache.hadoop.hbase.wal.RegionGroupingProvider;
32  import org.junit.runner.RunWith;
33  import org.junit.runners.Parameterized;
34  import org.mockito.Mockito;
35  
36  import java.io.IOException;
37  import java.util.ArrayList;
38  import java.util.Collection;
39  import java.util.List;
40  
41  import org.apache.hadoop.conf.Configuration;
42  import org.apache.hadoop.fs.FileSystem;
43  import org.apache.hadoop.fs.Path;
44  import org.apache.hadoop.hbase.Cell;
45  import org.apache.hadoop.hbase.HBaseTestingUtility;
46  import org.apache.hadoop.hbase.HColumnDescriptor;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.HRegionInfo;
49  import org.apache.hadoop.hbase.HTableDescriptor;
50  import org.apache.hadoop.hbase.Server;
51  import org.apache.hadoop.hbase.TableName;
52  import org.apache.hadoop.hbase.client.Scan;
53  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
54  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
55  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
56  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
57  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
58  import org.apache.hadoop.hbase.io.hfile.LruBlockCache;
59  import org.apache.hadoop.hbase.util.Bytes;
60  import org.apache.hadoop.hbase.util.FSUtils;
61  import org.apache.hadoop.hbase.util.PairOfSameType;
62  import org.apache.hadoop.hbase.wal.WALFactory;
63  import org.apache.zookeeper.KeeperException;
64  import org.junit.After;
65  import org.junit.Before;
66  import org.junit.Test;
67  import org.junit.experimental.categories.Category;
68  
69  import com.google.common.collect.ImmutableList;
70  
71  /**
72   * Test the {@link SplitTransactionImpl} class against an HRegion (as opposed to
73   * running cluster).
74   */
75  @RunWith(Parameterized.class)
76  @Category(MediumTests.class)
77  public class TestSplitTransaction {
78    private final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
79    private final Path testdir =
80      TEST_UTIL.getDataTestDir(this.getClass().getName());
81    private HRegion parent;
82    private WALFactory wals;
83    private FileSystem fs;
84    private static final byte [] STARTROW = new byte [] {'a', 'a', 'a'};
85    // '{' is next ascii after 'z'.
86    private static final byte [] ENDROW = new byte [] {'{', '{', '{'};
87    private static final byte [] GOOD_SPLIT_ROW = new byte [] {'d', 'd', 'd'};
88    private static final byte [] CF = HConstants.CATALOG_FAMILY;
89    
90    private static boolean preRollBackCalled = false;
91    private static boolean postRollBackCalled = false;
92  
93    private String walProvider;
94    private String strategy;
95  
96    @Parameterized.Parameters
97    public static final Collection<Object[]> parameters() {
98      List<Object[]> params = new ArrayList<>(4);
99      params.add(new Object[] { "filesystem", "" });
100     params.add(new Object[] { "multiwal", "identity" });
101     params.add(new Object[] { "multiwal", "bounded" });
102     params.add(new Object[] { "multiwal", "namespace" });
103     return params;
104   }
105 
106   public TestSplitTransaction(String walProvider, String strategy) {
107     this.walProvider = walProvider;
108     this.strategy = strategy;
109   }
110 
111   @Before
112   public void setup() throws IOException {
113     this.fs = FileSystem.get(TEST_UTIL.getConfiguration());
114     TEST_UTIL.getConfiguration().set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, CustomObserver.class.getName());
115     this.fs.delete(this.testdir, true);
116     TEST_UTIL.getConfiguration().set(WALFactory.WAL_PROVIDER, walProvider);
117     if (!strategy.isEmpty()) {
118       TEST_UTIL.getConfiguration().set(RegionGroupingProvider.REGION_GROUPING_STRATEGY, strategy);
119     }
120     final Configuration walConf = new Configuration(TEST_UTIL.getConfiguration());
121     FSUtils.setRootDir(walConf, this.testdir);
122     this.wals = new WALFactory(walConf, null, this.getClass().getName());
123     this.parent = createRegion(this.testdir, this.wals);
124     RegionCoprocessorHost host = new RegionCoprocessorHost(this.parent, null, TEST_UTIL.getConfiguration());
125     this.parent.setCoprocessorHost(host);
126     TEST_UTIL.getConfiguration().setBoolean("hbase.testing.nocluster", true);
127   }
128 
129   @After public void teardown() throws IOException {
130     if (this.parent != null && !this.parent.isClosed()) this.parent.close();
131     Path regionDir = this.parent.getRegionFileSystem().getRegionDir();
132     if (this.fs.exists(regionDir) && !this.fs.delete(regionDir, true)) {
133       throw new IOException("Failed delete of " + regionDir);
134     }
135     if (this.wals != null) {
136       this.wals.close();
137     }
138     this.fs.delete(this.testdir, true);
139   }
140 
141   @Test public void testFailAfterPONR() throws IOException, KeeperException {
142     final int rowcount = TEST_UTIL.loadRegion(this.parent, CF);
143     assertTrue(rowcount > 0);
144     int parentRowCount = countRows(this.parent);
145     assertEquals(rowcount, parentRowCount);
146 
147     // Start transaction.
148     SplitTransactionImpl st = prepareGOOD_SPLIT_ROW();
149     SplitTransactionImpl spiedUponSt = spy(st);
150     Mockito
151         .doThrow(new MockedFailedDaughterOpen())
152         .when(spiedUponSt)
153         .openDaughterRegion((Server) Mockito.anyObject(),
154             (HRegion) Mockito.anyObject());
155 
156     // Run the execute.  Look at what it returns.
157     boolean expectedException = false;
158     Server mockServer = Mockito.mock(Server.class);
159     when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration());
160     try {
161       spiedUponSt.execute(mockServer, null);
162     } catch (IOException e) {
163       if (e.getCause() != null &&
164           e.getCause() instanceof MockedFailedDaughterOpen) {
165         expectedException = true;
166       }
167     }
168     assertTrue(expectedException);
169     // Run rollback returns that we should restart.
170     assertFalse(spiedUponSt.rollback(null, null));
171     // Make sure that region a and region b are still in the filesystem, that
172     // they have not been removed; this is supposed to be the case if we go
173     // past point of no return.
174     Path tableDir =  this.parent.getRegionFileSystem().getTableDir();
175     Path daughterADir = new Path(tableDir, spiedUponSt.getFirstDaughter().getEncodedName());
176     Path daughterBDir = new Path(tableDir, spiedUponSt.getSecondDaughter().getEncodedName());
177     assertTrue(TEST_UTIL.getTestFileSystem().exists(daughterADir));
178     assertTrue(TEST_UTIL.getTestFileSystem().exists(daughterBDir));
179   }
180 
181   /**
182    * Test straight prepare works.  Tries to split on {@link #GOOD_SPLIT_ROW}
183    * @throws IOException
184    */
185   @Test public void testPrepare() throws IOException {
186     prepareGOOD_SPLIT_ROW();
187   }
188 
189   private SplitTransactionImpl prepareGOOD_SPLIT_ROW() throws IOException {
190     return prepareGOOD_SPLIT_ROW(this.parent);
191   }
192 
193   private SplitTransactionImpl prepareGOOD_SPLIT_ROW(final HRegion parentRegion)
194       throws IOException {
195     SplitTransactionImpl st = new SplitTransactionImpl(parentRegion, GOOD_SPLIT_ROW);
196     assertTrue(st.prepare());
197     return st;
198   }
199 
200   /**
201    * Pass a reference store
202    */
203   @Test public void testPrepareWithRegionsWithReference() throws IOException {
204     HStore storeMock = Mockito.mock(HStore.class);
205     when(storeMock.hasReferences()).thenReturn(true);
206     when(storeMock.getFamily()).thenReturn(new HColumnDescriptor("cf"));
207     when(storeMock.close()).thenReturn(ImmutableList.<StoreFile>of());
208     this.parent.stores.put(Bytes.toBytes(""), storeMock);
209 
210     SplitTransactionImpl st = new SplitTransactionImpl(this.parent, GOOD_SPLIT_ROW);
211 
212     assertFalse("a region should not be splittable if it has instances of store file references",
213                 st.prepare());
214   }
215 
216   /**
217    * Test SplitTransactionListener
218    */
219   @Test public void testSplitTransactionListener() throws IOException {
220     SplitTransactionImpl st = new SplitTransactionImpl(this.parent, GOOD_SPLIT_ROW);
221     SplitTransaction.TransactionListener listener =
222             Mockito.mock(SplitTransaction.TransactionListener.class);
223     st.registerTransactionListener(listener);
224     st.prepare();
225     Server mockServer = Mockito.mock(Server.class);
226     when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration());
227     PairOfSameType<Region> daughters = st.execute(mockServer, null);
228     verify(listener).transition(st, SplitTransaction.SplitTransactionPhase.STARTED,
229             SplitTransaction.SplitTransactionPhase.PREPARED);
230     verify(listener, times(15)).transition(any(SplitTransaction.class),
231             any(SplitTransaction.SplitTransactionPhase.class),
232             any(SplitTransaction.SplitTransactionPhase.class));
233     verifyNoMoreInteractions(listener);
234   }
235 
236   /**
237    * Pass an unreasonable split row.
238    */
239   @Test public void testPrepareWithBadSplitRow() throws IOException {
240     // Pass start row as split key.
241     SplitTransactionImpl st = new SplitTransactionImpl(this.parent, STARTROW);
242     assertFalse(st.prepare());
243     st = new SplitTransactionImpl(this.parent, HConstants.EMPTY_BYTE_ARRAY);
244     assertFalse(st.prepare());
245     st = new SplitTransactionImpl(this.parent, new byte [] {'A', 'A', 'A'});
246     assertFalse(st.prepare());
247     st = new SplitTransactionImpl(this.parent, ENDROW);
248     assertFalse(st.prepare());
249   }
250 
251   @Test public void testPrepareWithClosedRegion() throws IOException {
252     this.parent.close();
253     SplitTransactionImpl st = new SplitTransactionImpl(this.parent, GOOD_SPLIT_ROW);
254     assertFalse(st.prepare());
255   }
256 
257   @Test public void testWholesomeSplit() throws IOException {
258     final int rowcount = TEST_UTIL.loadRegion(this.parent, CF, true);
259     assertTrue(rowcount > 0);
260     int parentRowCount = countRows(this.parent);
261     assertEquals(rowcount, parentRowCount);
262 
263     // Pretend region's blocks are not in the cache, used for
264     // testWholesomeSplitWithHFileV1
265     CacheConfig cacheConf = new CacheConfig(TEST_UTIL.getConfiguration());
266     ((LruBlockCache) cacheConf.getBlockCache()).clearCache();
267 
268     // Start transaction.
269     SplitTransactionImpl st = prepareGOOD_SPLIT_ROW();
270 
271     // Run the execute.  Look at what it returns.
272     Server mockServer = Mockito.mock(Server.class);
273     when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration());
274     PairOfSameType<Region> daughters = st.execute(mockServer, null);
275     // Do some assertions about execution.
276     assertTrue(this.fs.exists(this.parent.getRegionFileSystem().getSplitsDir()));
277     // Assert the parent region is closed.
278     assertTrue(this.parent.isClosed());
279 
280     // Assert splitdir is empty -- because its content will have been moved out
281     // to be under the daughter region dirs.
282     assertEquals(0, this.fs.listStatus(this.parent.getRegionFileSystem().getSplitsDir()).length);
283     // Check daughters have correct key span.
284     assertTrue(Bytes.equals(parent.getRegionInfo().getStartKey(),
285       daughters.getFirst().getRegionInfo().getStartKey()));
286     assertTrue(Bytes.equals(GOOD_SPLIT_ROW, daughters.getFirst().getRegionInfo().getEndKey()));
287     assertTrue(Bytes.equals(daughters.getSecond().getRegionInfo().getStartKey(), GOOD_SPLIT_ROW));
288     assertTrue(Bytes.equals(parent.getRegionInfo().getEndKey(),
289       daughters.getSecond().getRegionInfo().getEndKey()));
290     // Count rows. daughters are already open
291     int daughtersRowCount = 0;
292     for (Region openRegion: daughters) {
293       try {
294         int count = countRows(openRegion);
295         assertTrue(count > 0 && count != rowcount);
296         daughtersRowCount += count;
297       } finally {
298         ((HRegion) openRegion).close();
299       }
300     }
301     assertEquals(rowcount, daughtersRowCount);
302     // Assert the write lock is no longer held on parent
303     assertTrue(!this.parent.lock.writeLock().isHeldByCurrentThread());
304   }
305 
306   @Test
307   public void testCountReferencesFailsSplit() throws IOException {
308     final int rowcount = TEST_UTIL.loadRegion(this.parent, CF);
309     assertTrue(rowcount > 0);
310     int parentRowCount = countRows(this.parent);
311     assertEquals(rowcount, parentRowCount);
312 
313     // Start transaction.
314     HRegion spiedRegion = spy(this.parent);
315     SplitTransactionImpl st = prepareGOOD_SPLIT_ROW(spiedRegion);
316     SplitTransactionImpl spiedUponSt = spy(st);
317     doThrow(new IOException("Failing split. Expected reference file count isn't equal."))
318         .when(spiedUponSt).assertReferenceFileCount(anyInt(),
319         eq(new Path(this.parent.getRegionFileSystem().getTableDir(),
320             st.getSecondDaughter().getEncodedName())));
321 
322     // Run the execute.  Look at what it returns.
323     boolean expectedException = false;
324     Server mockServer = Mockito.mock(Server.class);
325     when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration());
326     try {
327       spiedUponSt.execute(mockServer, null);
328     } catch (IOException e) {
329       expectedException = true;
330     }
331     assertTrue(expectedException);
332   }
333 
334 
335   @Test public void testRollback() throws IOException {
336     final int rowcount = TEST_UTIL.loadRegion(this.parent, CF);
337     assertTrue(rowcount > 0);
338     int parentRowCount = countRows(this.parent);
339     assertEquals(rowcount, parentRowCount);
340 
341     // Start transaction.
342     HRegion spiedRegion = spy(this.parent);
343     SplitTransactionImpl st = prepareGOOD_SPLIT_ROW(spiedRegion);
344     SplitTransactionImpl spiedUponSt = spy(st);
345     doNothing().when(spiedUponSt).assertReferenceFileCount(anyInt(),
346         eq(parent.getRegionFileSystem().getSplitsDir(st.getFirstDaughter())));
347     when(spiedRegion.createDaughterRegionFromSplits(spiedUponSt.getSecondDaughter())).
348         thenThrow(new MockedFailedDaughterCreation());
349     // Run the execute.  Look at what it returns.
350     boolean expectedException = false;
351     Server mockServer = Mockito.mock(Server.class);
352     when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration());
353     try {
354       spiedUponSt.execute(mockServer, null);
355     } catch (MockedFailedDaughterCreation e) {
356       expectedException = true;
357     }
358     assertTrue(expectedException);
359     // Run rollback
360     assertTrue(spiedUponSt.rollback(null, null));
361 
362     // Assert I can scan parent.
363     int parentRowCount2 = countRows(this.parent);
364     assertEquals(parentRowCount, parentRowCount2);
365 
366     // Assert rollback cleaned up stuff in fs
367     assertTrue(!this.fs.exists(FSUtils.getRegionDirFromRootDir(this.testdir,
368       st.getFirstDaughter())));
369     assertTrue(!this.fs.exists(FSUtils.getRegionDirFromRootDir(this.testdir,
370       st.getSecondDaughter())));
371     assertTrue(!this.parent.lock.writeLock().isHeldByCurrentThread());
372 
373     // Now retry the split but do not throw an exception this time.
374     assertTrue(st.prepare());
375     PairOfSameType<Region> daughters = st.execute(mockServer, null);
376     // Count rows. daughters are already open
377     int daughtersRowCount = 0;
378     for (Region openRegion: daughters) {
379       try {
380         int count = countRows(openRegion);
381         assertTrue(count > 0 && count != rowcount);
382         daughtersRowCount += count;
383       } finally {
384         ((HRegion) openRegion).close();
385       }
386     }
387     assertEquals(rowcount, daughtersRowCount);
388     // Assert the write lock is no longer held on parent
389     assertTrue(!this.parent.lock.writeLock().isHeldByCurrentThread());
390     assertTrue("Rollback hooks should be called.", wasRollBackHookCalled());
391   }
392   
393   private boolean wasRollBackHookCalled(){
394     return (preRollBackCalled && postRollBackCalled);
395   }
396 
397   /**
398    * Exception used in this class only.
399    */
400   @SuppressWarnings("serial")
401   private class MockedFailedDaughterCreation extends IOException {}
402   private class MockedFailedDaughterOpen extends IOException {}
403 
404   private int countRows(final Region r) throws IOException {
405     int rowcount = 0;
406     InternalScanner scanner = r.getScanner(new Scan());
407     try {
408       List<Cell> kvs = new ArrayList<Cell>();
409       boolean hasNext = true;
410       while (hasNext) {
411         hasNext = scanner.next(kvs);
412         if (!kvs.isEmpty()) rowcount++;
413       }
414     } finally {
415       scanner.close();
416     }
417     return rowcount;
418   }
419 
420   HRegion createRegion(final Path testdir, final WALFactory wals)
421   throws IOException {
422     // Make a region with start and end keys. Use 'aaa', to 'AAA'.  The load
423     // region utility will add rows between 'aaa' and 'zzz'.
424     HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("table"));
425     HColumnDescriptor hcd = new HColumnDescriptor(CF);
426     htd.addFamily(hcd);
427     HRegionInfo hri = new HRegionInfo(htd.getTableName(), STARTROW, ENDROW);
428     Configuration conf = TEST_UTIL.getConfiguration();
429     HRegion r = HRegion.createHRegion(hri, testdir, conf, htd);
430     HRegion.closeHRegion(r);
431     ServerName sn = ServerName.valueOf("testSplitTransaction", 100, 42);
432     final RegionServerServices rss = TEST_UTIL.createMockRegionServerService(sn);
433     MockRegionServerServicesWithWALs rsw =
434       new MockRegionServerServicesWithWALs(rss, wals.getWALProvider());
435     return HRegion.openHRegion(testdir, hri, htd,
436       wals.getWAL(hri.getEncodedNameAsBytes(), hri.getTable().getNamespace()),
437       conf, rsw, null);
438   }
439   
440   public static class CustomObserver extends BaseRegionObserver{
441     @Override
442     public void preRollBackSplit(
443         ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException {
444       preRollBackCalled = true;
445     }
446     
447     @Override
448     public void postRollBackSplit(
449         ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException {
450       postRollBackCalled = true;
451     }
452   }
453 }