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.wal;
019
020import static org.hamcrest.CoreMatchers.containsString;
021import static org.hamcrest.MatcherAssert.assertThat;
022import static org.junit.Assert.assertEquals;
023import static org.junit.Assert.assertNotEquals;
024import static org.junit.Assert.assertNotNull;
025import static org.junit.Assert.assertNull;
026import static org.junit.Assert.assertTrue;
027import static org.junit.Assert.fail;
028import static org.mockito.Mockito.mock;
029import static org.mockito.Mockito.when;
030
031import java.io.IOException;
032import java.util.ArrayList;
033import java.util.Collection;
034import java.util.Collections;
035import java.util.Comparator;
036import java.util.HashSet;
037import java.util.List;
038import java.util.Map;
039import java.util.NavigableMap;
040import java.util.Set;
041import java.util.TreeMap;
042import java.util.UUID;
043import java.util.concurrent.ConcurrentSkipListMap;
044import java.util.concurrent.CountDownLatch;
045import java.util.concurrent.ExecutorService;
046import java.util.concurrent.Executors;
047import java.util.concurrent.atomic.AtomicBoolean;
048import java.util.stream.Collectors;
049import org.apache.hadoop.conf.Configuration;
050import org.apache.hadoop.fs.FileStatus;
051import org.apache.hadoop.fs.FileSystem;
052import org.apache.hadoop.fs.Path;
053import org.apache.hadoop.hbase.CellScanner;
054import org.apache.hadoop.hbase.Coprocessor;
055import org.apache.hadoop.hbase.HBaseConfiguration;
056import org.apache.hadoop.hbase.HBaseTestingUtil;
057import org.apache.hadoop.hbase.HConstants;
058import org.apache.hadoop.hbase.KeyValue;
059import org.apache.hadoop.hbase.ServerName;
060import org.apache.hadoop.hbase.TableName;
061import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
062import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
063import org.apache.hadoop.hbase.client.Durability;
064import org.apache.hadoop.hbase.client.Get;
065import org.apache.hadoop.hbase.client.Put;
066import org.apache.hadoop.hbase.client.RegionInfo;
067import org.apache.hadoop.hbase.client.RegionInfoBuilder;
068import org.apache.hadoop.hbase.client.Result;
069import org.apache.hadoop.hbase.client.TableDescriptor;
070import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
071import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
072import org.apache.hadoop.hbase.coprocessor.SampleRegionWALCoprocessor;
073import org.apache.hadoop.hbase.regionserver.ChunkCreator;
074import org.apache.hadoop.hbase.regionserver.FlushPolicy;
075import org.apache.hadoop.hbase.regionserver.FlushPolicyFactory;
076import org.apache.hadoop.hbase.regionserver.HRegion;
077import org.apache.hadoop.hbase.regionserver.HStore;
078import org.apache.hadoop.hbase.regionserver.MemStoreLAB;
079import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
080import org.apache.hadoop.hbase.regionserver.RegionServerServices;
081import org.apache.hadoop.hbase.regionserver.SequenceId;
082import org.apache.hadoop.hbase.util.Bytes;
083import org.apache.hadoop.hbase.util.CommonFSUtils;
084import org.apache.hadoop.hbase.util.EnvironmentEdge;
085import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
086import org.apache.hadoop.hbase.util.Threads;
087import org.apache.hadoop.hbase.wal.AbstractFSWALProvider;
088import org.apache.hadoop.hbase.wal.WAL;
089import org.apache.hadoop.hbase.wal.WALEdit;
090import org.apache.hadoop.hbase.wal.WALKey;
091import org.apache.hadoop.hbase.wal.WALKeyImpl;
092import org.junit.AfterClass;
093import org.junit.Before;
094import org.junit.BeforeClass;
095import org.junit.Rule;
096import org.junit.Test;
097import org.junit.rules.TestName;
098import org.slf4j.Logger;
099import org.slf4j.LoggerFactory;
100
101public abstract class AbstractTestFSWAL {
102
103  protected static final Logger LOG = LoggerFactory.getLogger(AbstractTestFSWAL.class);
104
105  protected static Configuration CONF;
106  protected static FileSystem FS;
107  protected static Path DIR;
108  protected final static HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
109
110  @Rule
111  public final TestName currentTest = new TestName();
112
113  @Before
114  public void setUp() throws Exception {
115    FileStatus[] entries = FS.listStatus(new Path("/"));
116    for (FileStatus dir : entries) {
117      FS.delete(dir.getPath(), true);
118    }
119    final Path hbaseDir = TEST_UTIL.createRootDir();
120    final Path hbaseWALDir = TEST_UTIL.createWALRootDir();
121    DIR = new Path(hbaseWALDir, currentTest.getMethodName());
122    assertNotEquals(hbaseDir, hbaseWALDir);
123  }
124
125  @BeforeClass
126  public static void setUpBeforeClass() throws Exception {
127    // Make block sizes small.
128    TEST_UTIL.getConfiguration().setInt("dfs.blocksize", 1024 * 1024);
129    // quicker heartbeat interval for faster DN death notification
130    TEST_UTIL.getConfiguration().setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
131    TEST_UTIL.getConfiguration().setInt("dfs.heartbeat.interval", 1);
132    TEST_UTIL.getConfiguration().setInt("dfs.client.socket-timeout", 5000);
133
134    // faster failover with cluster.shutdown();fs.close() idiom
135    TEST_UTIL.getConfiguration().setInt("hbase.ipc.client.connect.max.retries", 1);
136    TEST_UTIL.getConfiguration().setInt("dfs.client.block.recovery.retries", 1);
137    TEST_UTIL.getConfiguration().setInt("hbase.ipc.client.connection.maxidletime", 500);
138    TEST_UTIL.getConfiguration().set(CoprocessorHost.WAL_COPROCESSOR_CONF_KEY,
139      SampleRegionWALCoprocessor.class.getName());
140    TEST_UTIL.startMiniDFSCluster(3);
141
142    CONF = TEST_UTIL.getConfiguration();
143    FS = TEST_UTIL.getDFSCluster().getFileSystem();
144  }
145
146  @AfterClass
147  public static void tearDownAfterClass() throws Exception {
148    TEST_UTIL.shutdownMiniCluster();
149  }
150
151  protected abstract AbstractFSWAL<?> newWAL(FileSystem fs, Path rootDir, String WALDir,
152    String archiveDir, Configuration conf, List<WALActionsListener> listeners,
153    boolean failIfWALExists, String prefix, String suffix) throws IOException;
154
155  protected abstract AbstractFSWAL<?> newSlowWAL(FileSystem fs, Path rootDir, String WALDir,
156    String archiveDir, Configuration conf, List<WALActionsListener> listeners,
157    boolean failIfWALExists, String prefix, String suffix, Runnable action) throws IOException;
158
159  /**
160   * A loaded WAL coprocessor won't break existing WAL test cases.
161   */
162  @Test
163  public void testWALCoprocessorLoaded() throws Exception {
164    // test to see whether the coprocessor is loaded or not.
165    AbstractFSWAL<?> wal = null;
166    try {
167      wal = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(),
168        HConstants.HREGION_OLDLOGDIR_NAME, CONF, null, true, null, null);
169      WALCoprocessorHost host = wal.getCoprocessorHost();
170      Coprocessor c = host.findCoprocessor(SampleRegionWALCoprocessor.class);
171      assertNotNull(c);
172    } finally {
173      if (wal != null) {
174        wal.close();
175      }
176    }
177  }
178
179  protected void addEdits(WAL log, RegionInfo hri, TableDescriptor htd, int times,
180    MultiVersionConcurrencyControl mvcc, NavigableMap<byte[], Integer> scopes, String cf)
181    throws IOException {
182    final byte[] row = Bytes.toBytes(cf);
183    for (int i = 0; i < times; i++) {
184      long timestamp = EnvironmentEdgeManager.currentTime();
185      WALEdit cols = new WALEdit();
186      cols.add(new KeyValue(row, row, row, timestamp, row));
187      WALKeyImpl key =
188        new WALKeyImpl(hri.getEncodedNameAsBytes(), htd.getTableName(), SequenceId.NO_SEQUENCE_ID,
189          timestamp, WALKey.EMPTY_UUIDS, HConstants.NO_NONCE, HConstants.NO_NONCE, mvcc, scopes);
190      log.appendData(hri, key, cols);
191    }
192    log.sync();
193  }
194
195  /**
196   * helper method to simulate region flush for a WAL.
197   */
198  protected void flushRegion(WAL wal, byte[] regionEncodedName, Set<byte[]> flushedFamilyNames) {
199    wal.startCacheFlush(regionEncodedName, flushedFamilyNames);
200    wal.completeCacheFlush(regionEncodedName, HConstants.NO_SEQNUM);
201  }
202
203  /**
204   * tests the log comparator. Ensure that we are not mixing meta logs with non-meta logs (throws
205   * exception if we do). Comparison is based on the timestamp present in the wal name.
206   */
207  @Test
208  public void testWALComparator() throws Exception {
209    AbstractFSWAL<?> wal1 = null;
210    AbstractFSWAL<?> walMeta = null;
211    try {
212      wal1 = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(),
213        HConstants.HREGION_OLDLOGDIR_NAME, CONF, null, true, null, null);
214      LOG.debug("Log obtained is: " + wal1);
215      Comparator<Path> comp = wal1.LOG_NAME_COMPARATOR;
216      Path p1 = wal1.computeFilename(11);
217      Path p2 = wal1.computeFilename(12);
218      // comparing with itself returns 0
219      assertTrue(comp.compare(p1, p1) == 0);
220      // comparing with different filenum.
221      assertTrue(comp.compare(p1, p2) < 0);
222      walMeta = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(),
223        HConstants.HREGION_OLDLOGDIR_NAME, CONF, null, true, null,
224        AbstractFSWALProvider.META_WAL_PROVIDER_ID);
225      Comparator<Path> compMeta = walMeta.LOG_NAME_COMPARATOR;
226
227      Path p1WithMeta = walMeta.computeFilename(11);
228      Path p2WithMeta = walMeta.computeFilename(12);
229      assertTrue(compMeta.compare(p1WithMeta, p1WithMeta) == 0);
230      assertTrue(compMeta.compare(p1WithMeta, p2WithMeta) < 0);
231      // mixing meta and non-meta logs gives error
232      boolean ex = false;
233      try {
234        comp.compare(p1WithMeta, p2);
235      } catch (IllegalArgumentException e) {
236        ex = true;
237      }
238      assertTrue("Comparator doesn't complain while checking meta log files", ex);
239      boolean exMeta = false;
240      try {
241        compMeta.compare(p1WithMeta, p2);
242      } catch (IllegalArgumentException e) {
243        exMeta = true;
244      }
245      assertTrue("Meta comparator doesn't complain while checking log files", exMeta);
246    } finally {
247      if (wal1 != null) {
248        wal1.close();
249      }
250      if (walMeta != null) {
251        walMeta.close();
252      }
253    }
254  }
255
256  // now we will close asynchronously and will not archive a wal file unless it is fully closed, so
257  // sometimes we need to wait a bit before asserting, especially when you want to test the removal
258  // of numRolledLogFiles
259  private void waitNumRolledLogFiles(AbstractFSWAL<?> wal, int expected) {
260    TEST_UTIL.waitFor(5000, () -> wal.getNumRolledLogFiles() == expected);
261  }
262
263  private void testFindMemStoresEligibleForFlush(AbstractFSWAL<?> wal) throws IOException {
264    String cf1 = "cf1";
265    String cf2 = "cf2";
266    String cf3 = "cf3";
267    TableDescriptor t1 = TableDescriptorBuilder.newBuilder(TableName.valueOf("t1"))
268      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(cf1)).build();
269    TableDescriptor t2 = TableDescriptorBuilder.newBuilder(TableName.valueOf("t2"))
270      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(cf1)).build();
271    RegionInfo hri1 = RegionInfoBuilder.newBuilder(t1.getTableName()).build();
272    RegionInfo hri2 = RegionInfoBuilder.newBuilder(t2.getTableName()).build();
273
274    List<ColumnFamilyDescriptor> cfs = new ArrayList<>();
275    cfs.add(ColumnFamilyDescriptorBuilder.of(cf1));
276    cfs.add(ColumnFamilyDescriptorBuilder.of(cf2));
277    TableDescriptor t3 =
278      TableDescriptorBuilder.newBuilder(TableName.valueOf("t3")).setColumnFamilies(cfs).build();
279    RegionInfo hri3 = RegionInfoBuilder.newBuilder(t3.getTableName()).build();
280
281    // add edits and roll the wal
282    MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
283    NavigableMap<byte[], Integer> scopes1 = new TreeMap<>(Bytes.BYTES_COMPARATOR);
284    for (byte[] fam : t1.getColumnFamilyNames()) {
285      scopes1.put(fam, 0);
286    }
287    NavigableMap<byte[], Integer> scopes2 = new TreeMap<>(Bytes.BYTES_COMPARATOR);
288    for (byte[] fam : t2.getColumnFamilyNames()) {
289      scopes2.put(fam, 0);
290    }
291    NavigableMap<byte[], Integer> scopes3 = new TreeMap<>(Bytes.BYTES_COMPARATOR);
292    for (byte[] fam : t3.getColumnFamilyNames()) {
293      scopes3.put(fam, 0);
294    }
295    addEdits(wal, hri1, t1, 2, mvcc, scopes1, cf1);
296    wal.rollWriter();
297    // add some more edits and roll the wal. This would reach the log number threshold
298    addEdits(wal, hri1, t1, 2, mvcc, scopes1, cf1);
299    wal.rollWriter();
300    // with above rollWriter call, the max logs limit is reached.
301    waitNumRolledLogFiles(wal, 2);
302
303    // get the regions to flush; since there is only one region in the oldest wal, it should
304    // return only one region.
305    Map<byte[], List<byte[]>> regionsToFlush = wal.findRegionsToForceFlush();
306    assertEquals(1, regionsToFlush.size());
307    assertEquals(hri1.getEncodedNameAsBytes(), (byte[]) regionsToFlush.keySet().toArray()[0]);
308    // insert edits in second region
309    addEdits(wal, hri2, t2, 2, mvcc, scopes2, cf1);
310    // get the regions to flush, it should still read region1.
311    regionsToFlush = wal.findRegionsToForceFlush();
312    assertEquals(1, regionsToFlush.size());
313    assertEquals(hri1.getEncodedNameAsBytes(), (byte[]) regionsToFlush.keySet().toArray()[0]);
314    // flush region 1, and roll the wal file. Only last wal which has entries for region1 should
315    // remain.
316    flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getColumnFamilyNames());
317    wal.rollWriter();
318    // only one wal should remain now (that is for the second region).
319    waitNumRolledLogFiles(wal, 1);
320    // flush the second region
321    flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getColumnFamilyNames());
322    wal.rollWriter(true);
323    // no wal should remain now.
324    waitNumRolledLogFiles(wal, 0);
325    // add edits both to region 1 and region 2, and roll.
326    addEdits(wal, hri1, t1, 2, mvcc, scopes1, cf1);
327    addEdits(wal, hri2, t2, 2, mvcc, scopes2, cf1);
328    wal.rollWriter();
329    // add edits and roll the writer, to reach the max logs limit.
330    waitNumRolledLogFiles(wal, 1);
331    addEdits(wal, hri1, t1, 2, mvcc, scopes1, cf1);
332    wal.rollWriter();
333    // it should return two regions to flush, as the oldest wal file has entries
334    // for both regions.
335    regionsToFlush = wal.findRegionsToForceFlush();
336    assertEquals(2, regionsToFlush.size());
337    // flush both regions
338    flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getColumnFamilyNames());
339    flushRegion(wal, hri2.getEncodedNameAsBytes(), t2.getColumnFamilyNames());
340    wal.rollWriter(true);
341    waitNumRolledLogFiles(wal, 0);
342    // Add an edit to region1, and roll the wal.
343    addEdits(wal, hri1, t1, 2, mvcc, scopes1, cf1);
344    // tests partial flush: roll on a partial flush, and ensure that wal is not archived.
345    wal.startCacheFlush(hri1.getEncodedNameAsBytes(), t1.getColumnFamilyNames());
346    wal.rollWriter();
347    wal.completeCacheFlush(hri1.getEncodedNameAsBytes(), HConstants.NO_SEQNUM);
348    waitNumRolledLogFiles(wal, 1);
349
350    // clear test data
351    flushRegion(wal, hri1.getEncodedNameAsBytes(), t1.getColumnFamilyNames());
352    wal.rollWriter(true);
353    // add edits for three familes
354    addEdits(wal, hri3, t3, 2, mvcc, scopes3, cf1);
355    addEdits(wal, hri3, t3, 2, mvcc, scopes3, cf2);
356    addEdits(wal, hri3, t3, 2, mvcc, scopes3, cf3);
357    wal.rollWriter();
358    addEdits(wal, hri3, t3, 2, mvcc, scopes3, cf1);
359    wal.rollWriter();
360    waitNumRolledLogFiles(wal, 2);
361    // flush one family before archive oldest wal
362    Set<byte[]> flushedFamilyNames = new HashSet<>();
363    flushedFamilyNames.add(Bytes.toBytes(cf1));
364    flushRegion(wal, hri3.getEncodedNameAsBytes(), flushedFamilyNames);
365    regionsToFlush = wal.findRegionsToForceFlush();
366    // then only two family need to be flushed when archive oldest wal
367    assertEquals(1, regionsToFlush.size());
368    assertEquals(hri3.getEncodedNameAsBytes(), (byte[]) regionsToFlush.keySet().toArray()[0]);
369    assertEquals(2, regionsToFlush.get(hri3.getEncodedNameAsBytes()).size());
370  }
371
372  /**
373   * On rolling a wal after reaching the threshold, {@link WAL#rollWriter()} returns the list of
374   * regions which should be flushed in order to archive the oldest wal file.
375   * <p>
376   * This method tests this behavior by inserting edits and rolling the wal enough times to reach
377   * the max number of logs threshold. It checks whether we get the "right regions and stores" for
378   * flush on rolling the wal.
379   */
380  @Test
381  public void testFindMemStoresEligibleForFlush() throws Exception {
382    LOG.debug("testFindMemStoresEligibleForFlush");
383    Configuration conf1 = HBaseConfiguration.create(CONF);
384    conf1.setInt("hbase.regionserver.maxlogs", 1);
385    try (AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getWALRootDir(conf1), DIR.toString(),
386      HConstants.HREGION_OLDLOGDIR_NAME, conf1, null, true, null, null)) {
387      testFindMemStoresEligibleForFlush(wal);
388    }
389
390  }
391
392  @Test(expected = IOException.class)
393  public void testFailedToCreateWALIfParentRenamed()
394    throws IOException, CommonFSUtils.StreamLacksCapabilityException {
395    final String name = "testFailedToCreateWALIfParentRenamed";
396    AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), name,
397      HConstants.HREGION_OLDLOGDIR_NAME, CONF, null, true, null, null);
398    long filenum = EnvironmentEdgeManager.currentTime();
399    Path path = wal.computeFilename(filenum);
400    wal.createWriterInstance(FS, path);
401    Path parent = path.getParent();
402    path = wal.computeFilename(filenum + 1);
403    Path newPath = new Path(parent.getParent(), parent.getName() + "-splitting");
404    FS.rename(parent, newPath);
405    wal.createWriterInstance(FS, path);
406    fail("It should fail to create the new WAL");
407  }
408
409  /**
410   * Test flush for sure has a sequence id that is beyond the last edit appended. We do this by
411   * slowing appends in the background ring buffer thread while in foreground we call flush. The
412   * addition of the sync over HRegion in flush should fix an issue where flush was returning before
413   * all of its appends had made it out to the WAL (HBASE-11109).
414   * @see <a href="https://issues.apache.org/jira/browse/HBASE-11109">HBASE-11109</a>
415   */
416  @Test
417  public void testFlushSequenceIdIsGreaterThanAllEditsInHFile() throws IOException {
418    String testName = currentTest.getMethodName();
419    final TableName tableName = TableName.valueOf(testName);
420    final RegionInfo hri = RegionInfoBuilder.newBuilder(tableName).build();
421    final byte[] rowName = tableName.getName();
422    final TableDescriptor htd = TableDescriptorBuilder.newBuilder(tableName)
423      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("f")).build();
424    HRegion r = HBaseTestingUtil.createRegionAndWAL(hri, TEST_UTIL.getDefaultRootDirPath(),
425      TEST_UTIL.getConfiguration(), htd);
426    HBaseTestingUtil.closeRegionAndWAL(r);
427    final int countPerFamily = 10;
428    final AtomicBoolean goslow = new AtomicBoolean(false);
429    NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
430    for (byte[] fam : htd.getColumnFamilyNames()) {
431      scopes.put(fam, 0);
432    }
433    // subclass and doctor a method.
434    AbstractFSWAL<?> wal = newSlowWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(),
435      testName, CONF, null, true, null, null, new Runnable() {
436
437        @Override
438        public void run() {
439          if (goslow.get()) {
440            Threads.sleep(100);
441            LOG.debug("Sleeping before appending 100ms");
442          }
443        }
444      });
445    HRegion region = HRegion.openHRegion(TEST_UTIL.getConfiguration(),
446      TEST_UTIL.getTestFileSystem(), TEST_UTIL.getDefaultRootDirPath(), hri, htd, wal);
447    EnvironmentEdge ee = EnvironmentEdgeManager.getDelegate();
448    try {
449      List<Put> puts = null;
450      for (byte[] fam : htd.getColumnFamilyNames()) {
451        puts = TestWALReplay.addRegionEdits(rowName, fam, countPerFamily, ee, region, "x");
452      }
453
454      // Now assert edits made it in.
455      final Get g = new Get(rowName);
456      Result result = region.get(g);
457      assertEquals(countPerFamily * htd.getColumnFamilyNames().size(), result.size());
458
459      // Construct a WALEdit and add it a few times to the WAL.
460      WALEdit edits = new WALEdit();
461      for (Put p : puts) {
462        CellScanner cs = p.cellScanner();
463        while (cs.advance()) {
464          edits.add(cs.current());
465        }
466      }
467      // Add any old cluster id.
468      List<UUID> clusterIds = new ArrayList<>(1);
469      clusterIds.add(TEST_UTIL.getRandomUUID());
470      // Now make appends run slow.
471      goslow.set(true);
472      for (int i = 0; i < countPerFamily; i++) {
473        final RegionInfo info = region.getRegionInfo();
474        final WALKeyImpl logkey = new WALKeyImpl(info.getEncodedNameAsBytes(), tableName,
475          EnvironmentEdgeManager.currentTime(), clusterIds, -1, -1, region.getMVCC(), scopes);
476        wal.append(info, logkey, edits, true);
477        region.getMVCC().completeAndWait(logkey.getWriteEntry());
478      }
479      region.flush(true);
480      // FlushResult.flushSequenceId is not visible here so go get the current sequence id.
481      long currentSequenceId = region.getReadPoint(null);
482      // Now release the appends
483      goslow.set(false);
484      assertTrue(currentSequenceId >= region.getReadPoint(null));
485    } finally {
486      region.close(true);
487      wal.close();
488    }
489  }
490
491  @Test
492  public void testSyncNoAppend() throws IOException {
493    String testName = currentTest.getMethodName();
494    AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(), testName,
495      CONF, null, true, null, null);
496    try {
497      wal.sync();
498    } finally {
499      wal.close();
500    }
501  }
502
503  @Test
504  public void testWriteEntryCanBeNull() throws IOException {
505    String testName = currentTest.getMethodName();
506    AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(), testName,
507      CONF, null, true, null, null);
508    wal.close();
509    TableDescriptor td = TableDescriptorBuilder.newBuilder(TableName.valueOf("table"))
510      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("row")).build();
511    RegionInfo ri = RegionInfoBuilder.newBuilder(td.getTableName()).build();
512    MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
513    NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
514    for (byte[] fam : td.getColumnFamilyNames()) {
515      scopes.put(fam, 0);
516    }
517    long timestamp = EnvironmentEdgeManager.currentTime();
518    byte[] row = Bytes.toBytes("row");
519    WALEdit cols = new WALEdit();
520    cols.add(new KeyValue(row, row, row, timestamp, row));
521    WALKeyImpl key =
522      new WALKeyImpl(ri.getEncodedNameAsBytes(), td.getTableName(), SequenceId.NO_SEQUENCE_ID,
523        timestamp, WALKey.EMPTY_UUIDS, HConstants.NO_NONCE, HConstants.NO_NONCE, mvcc, scopes);
524    try {
525      wal.append(ri, key, cols, true);
526      fail("Should fail since the wal has already been closed");
527    } catch (IOException e) {
528      // expected
529      assertThat(e.getMessage(), containsString("log is closed"));
530      // the WriteEntry should be null since we fail before setting it.
531      assertNull(key.getWriteEntry());
532    }
533  }
534
535  @Test(expected = WALClosedException.class)
536  public void testRollWriterForClosedWAL() throws IOException {
537    String testName = currentTest.getMethodName();
538    AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(), testName,
539      CONF, null, true, null, null);
540    wal.close();
541    wal.rollWriter();
542  }
543
544  private AbstractFSWAL<?> createHoldingWAL(String testName, AtomicBoolean startHoldingForAppend,
545    CountDownLatch holdAppend) throws IOException {
546    AbstractFSWAL<?> wal = newWAL(FS, CommonFSUtils.getRootDir(CONF), testName,
547      HConstants.HREGION_OLDLOGDIR_NAME, CONF, null, true, null, null);
548    // newWAL has already called wal.init()
549    wal.registerWALActionsListener(new WALActionsListener() {
550      @Override
551      public void visitLogEntryBeforeWrite(RegionInfo info, WALKey logKey, WALEdit logEdit) {
552        if (startHoldingForAppend.get()) {
553          try {
554            holdAppend.await();
555          } catch (InterruptedException e) {
556            LOG.error(e.toString(), e);
557          }
558        }
559      }
560    });
561    return wal;
562  }
563
564  private HRegion createHoldingHRegion(Configuration conf, TableDescriptor htd, WAL wal)
565    throws IOException {
566    RegionInfo hri = RegionInfoBuilder.newBuilder(htd.getTableName()).build();
567    ChunkCreator.initialize(MemStoreLAB.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null,
568      MemStoreLAB.INDEX_CHUNK_SIZE_PERCENTAGE_DEFAULT);
569    TEST_UTIL.createLocalHRegion(hri, CONF, htd, wal).close();
570    RegionServerServices rsServices = mock(RegionServerServices.class);
571    when(rsServices.getServerName()).thenReturn(ServerName.valueOf("localhost:12345", 123456));
572    when(rsServices.getConfiguration()).thenReturn(conf);
573    return HRegion.openHRegion(TEST_UTIL.getDataTestDir(), hri, htd, wal, conf, rsServices, null);
574  }
575
576  private void doPutWithAsyncWAL(ExecutorService exec, HRegion region, Put put,
577    Runnable flushOrCloseRegion, AtomicBoolean startHoldingForAppend,
578    CountDownLatch flushOrCloseFinished, CountDownLatch holdAppend)
579    throws InterruptedException, IOException {
580    // do a regular write first because of memstore size calculation.
581    region.put(put);
582
583    startHoldingForAppend.set(true);
584    region.put(new Put(put).setDurability(Durability.ASYNC_WAL));
585
586    // give the put a chance to start
587    Threads.sleep(3000);
588
589    exec.submit(flushOrCloseRegion);
590
591    // give the flush a chance to start. Flush should have got the region lock, and
592    // should have been waiting on the mvcc complete after this.
593    Threads.sleep(3000);
594
595    // let the append to WAL go through now that the flush already started
596    holdAppend.countDown();
597    flushOrCloseFinished.await();
598  }
599
600  // Testcase for HBASE-23181
601  @Test
602  public void testUnflushedSeqIdTrackingWithAsyncWal() throws IOException, InterruptedException {
603    String testName = currentTest.getMethodName();
604    byte[] b = Bytes.toBytes("b");
605    TableDescriptor htd = TableDescriptorBuilder.newBuilder(TableName.valueOf("table"))
606      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(b)).build();
607
608    AtomicBoolean startHoldingForAppend = new AtomicBoolean(false);
609    CountDownLatch holdAppend = new CountDownLatch(1);
610    CountDownLatch closeFinished = new CountDownLatch(1);
611    ExecutorService exec = Executors.newFixedThreadPool(1);
612    AbstractFSWAL<?> wal = createHoldingWAL(testName, startHoldingForAppend, holdAppend);
613    // open a new region which uses this WAL
614    HRegion region = createHoldingHRegion(TEST_UTIL.getConfiguration(), htd, wal);
615    try {
616      doPutWithAsyncWAL(exec, region, new Put(b).addColumn(b, b, b), () -> {
617        try {
618          Map<?, ?> closeResult = region.close();
619          LOG.info("Close result:" + closeResult);
620          closeFinished.countDown();
621        } catch (IOException e) {
622          LOG.error(e.toString(), e);
623        }
624      }, startHoldingForAppend, closeFinished, holdAppend);
625
626      // now check the region's unflushed seqIds.
627      long seqId = wal.getEarliestMemStoreSeqNum(region.getRegionInfo().getEncodedNameAsBytes());
628      assertEquals("Found seqId for the region which is already closed", HConstants.NO_SEQNUM,
629        seqId);
630    } finally {
631      exec.shutdownNow();
632      region.close();
633      wal.close();
634    }
635  }
636
637  private static final Set<byte[]> STORES_TO_FLUSH =
638    Collections.newSetFromMap(new ConcurrentSkipListMap<byte[], Boolean>(Bytes.BYTES_COMPARATOR));
639
640  // Testcase for HBASE-23157
641  @Test
642  public void testMaxFlushedSequenceIdGoBackwards() throws IOException, InterruptedException {
643    String testName = currentTest.getMethodName();
644    byte[] a = Bytes.toBytes("a");
645    byte[] b = Bytes.toBytes("b");
646    TableDescriptor htd = TableDescriptorBuilder.newBuilder(TableName.valueOf("table"))
647      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(a))
648      .setColumnFamily(ColumnFamilyDescriptorBuilder.of(b)).build();
649
650    AtomicBoolean startHoldingForAppend = new AtomicBoolean(false);
651    CountDownLatch holdAppend = new CountDownLatch(1);
652    CountDownLatch flushFinished = new CountDownLatch(1);
653    ExecutorService exec = Executors.newFixedThreadPool(2);
654    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
655    conf.setClass(FlushPolicyFactory.HBASE_FLUSH_POLICY_KEY, FlushSpecificStoresPolicy.class,
656      FlushPolicy.class);
657    AbstractFSWAL<?> wal = createHoldingWAL(testName, startHoldingForAppend, holdAppend);
658    // open a new region which uses this WAL
659    HRegion region = createHoldingHRegion(conf, htd, wal);
660    try {
661      Put put = new Put(a).addColumn(a, a, a).addColumn(b, b, b);
662      doPutWithAsyncWAL(exec, region, put, () -> {
663        try {
664          HRegion.FlushResult flushResult = region.flush(true);
665          LOG.info("Flush result:" + flushResult.getResult());
666          LOG.info("Flush succeeded:" + flushResult.isFlushSucceeded());
667          flushFinished.countDown();
668        } catch (IOException e) {
669          LOG.error(e.toString(), e);
670        }
671      }, startHoldingForAppend, flushFinished, holdAppend);
672
673      // get the max flushed sequence id after the first flush
674      long maxFlushedSeqId1 = region.getMaxFlushedSeqId();
675
676      region.put(put);
677      // this time we only flush family a
678      STORES_TO_FLUSH.add(a);
679      region.flush(false);
680
681      // get the max flushed sequence id after the second flush
682      long maxFlushedSeqId2 = region.getMaxFlushedSeqId();
683      // make sure that the maxFlushedSequenceId does not go backwards
684      assertTrue(
685        "maxFlushedSeqId1(" + maxFlushedSeqId1
686          + ") is not greater than or equal to maxFlushedSeqId2(" + maxFlushedSeqId2 + ")",
687        maxFlushedSeqId1 <= maxFlushedSeqId2);
688    } finally {
689      exec.shutdownNow();
690      region.close();
691      wal.close();
692    }
693  }
694
695  public static final class FlushSpecificStoresPolicy extends FlushPolicy {
696
697    @Override
698    public Collection<HStore> selectStoresToFlush() {
699      if (STORES_TO_FLUSH.isEmpty()) {
700        return region.getStores();
701      } else {
702        return STORES_TO_FLUSH.stream().map(region::getStore).collect(Collectors.toList());
703      }
704    }
705  }
706}