001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.regionserver;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertTrue;
022
023import java.io.IOException;
024import java.util.ArrayList;
025import java.util.Collections;
026import java.util.List;
027import org.apache.hadoop.conf.Configuration;
028import org.apache.hadoop.fs.FileSystem;
029import org.apache.hadoop.fs.Path;
030import org.apache.hadoop.hbase.Cell;
031import org.apache.hadoop.hbase.CellComparatorImpl;
032import org.apache.hadoop.hbase.HBaseClassTestRule;
033import org.apache.hadoop.hbase.HBaseTestingUtil;
034import org.apache.hadoop.hbase.HConstants;
035import org.apache.hadoop.hbase.MemoryCompactionPolicy;
036import org.apache.hadoop.hbase.PrivateCellUtil;
037import org.apache.hadoop.hbase.TableName;
038import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
039import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
040import org.apache.hadoop.hbase.client.RegionInfo;
041import org.apache.hadoop.hbase.client.RegionInfoBuilder;
042import org.apache.hadoop.hbase.client.Scan;
043import org.apache.hadoop.hbase.client.TableDescriptor;
044import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
045import org.apache.hadoop.hbase.io.hfile.BlockCache;
046import org.apache.hadoop.hbase.io.hfile.BlockCacheFactory;
047import org.apache.hadoop.hbase.testclassification.MediumTests;
048import org.apache.hadoop.hbase.util.Bytes;
049import org.apache.hadoop.hbase.util.CommonFSUtils;
050import org.apache.hadoop.hbase.util.FSUtils;
051import org.apache.hadoop.hbase.wal.WAL;
052import org.apache.hadoop.hbase.wal.WALEdit;
053import org.apache.hadoop.hbase.wal.WALFactory;
054import org.apache.hadoop.hbase.wal.WALKey;
055import org.apache.hadoop.hbase.wal.WALSplitUtil;
056import org.junit.BeforeClass;
057import org.junit.ClassRule;
058import org.junit.Rule;
059import org.junit.Test;
060import org.junit.experimental.categories.Category;
061import org.junit.rules.TestName;
062import org.slf4j.Logger;
063import org.slf4j.LoggerFactory;
064
065/**
066 * Tests around replay of recovered.edits content.
067 */
068@Category({ MediumTests.class })
069public class TestRecoveredEdits {
070
071  @ClassRule
072  public static final HBaseClassTestRule CLASS_RULE =
073    HBaseClassTestRule.forClass(TestRecoveredEdits.class);
074
075  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
076  private static final Logger LOG = LoggerFactory.getLogger(TestRecoveredEdits.class);
077
078  private static BlockCache blockCache;
079
080  @Rule
081  public TestName testName = new TestName();
082
083  /**
084   * Path to a recovered.edits file in hbase-server test resources folder. This is a little fragile
085   * getting this path to a file of 10M of edits.
086   */
087  @SuppressWarnings("checkstyle:VisibilityModifier")
088  public static final Path RECOVEREDEDITS_PATH = new Path(
089    System.getProperty("test.build.classes", "target/test-classes"), "0000000000000016310");
090
091  /**
092   * Name of table referenced by edits in the recovered.edits file.
093   */
094  public static final String RECOVEREDEDITS_TABLENAME = "IntegrationTestBigLinkedList";
095
096  /**
097   * Column family referenced by edits in the recovered.edits file.
098   */
099  public static final byte[] RECOVEREDEDITS_COLUMNFAMILY = Bytes.toBytes("meta");
100  public static final byte[][] RECOVEREDITS_COLUMNFAMILY_ARRAY =
101    new byte[][] { RECOVEREDEDITS_COLUMNFAMILY };
102  public static final ColumnFamilyDescriptor RECOVEREDEDITS_CFD =
103    ColumnFamilyDescriptorBuilder.newBuilder(RECOVEREDEDITS_COLUMNFAMILY).build();
104
105  /**
106   * Name of table mentioned edits from recovered.edits
107   */
108  @BeforeClass
109  public static void setUpBeforeClass() throws Exception {
110    blockCache = BlockCacheFactory.createBlockCache(TEST_UTIL.getConfiguration());
111  }
112
113  /**
114   * HBASE-12782 ITBLL fails for me if generator does anything but 5M per maptask. Create a region.
115   * Close it. Then copy into place a file to replay, one that is bigger than configured flush size
116   * so we bring on lots of flushes. Then reopen and confirm all edits made it in.
117   */
118  @Test
119  public void testReplayWorksThoughLotsOfFlushing() throws IOException {
120    for (MemoryCompactionPolicy policy : MemoryCompactionPolicy.values()) {
121      testReplayWorksWithMemoryCompactionPolicy(policy);
122    }
123  }
124
125  private void testReplayWorksWithMemoryCompactionPolicy(MemoryCompactionPolicy policy)
126    throws IOException {
127    Configuration conf = new Configuration(TEST_UTIL.getConfiguration());
128    // Set it so we flush every 1M or so. Thats a lot.
129    conf.setInt(HConstants.HREGION_MEMSTORE_FLUSH_SIZE, 1024 * 1024);
130    conf.set(CompactingMemStore.COMPACTING_MEMSTORE_TYPE_KEY, String.valueOf(policy).toLowerCase());
131    TableDescriptor tableDescriptor =
132      TableDescriptorBuilder.newBuilder(TableName.valueOf(testName.getMethodName()))
133        .setColumnFamily(RECOVEREDEDITS_CFD).build();
134    RegionInfo hri = RegionInfoBuilder.newBuilder(tableDescriptor.getTableName()).build();
135    final String encodedRegionName = hri.getEncodedName();
136    Path hbaseRootDir = TEST_UTIL.getDataTestDir();
137    FileSystem fs = FileSystem.get(TEST_UTIL.getConfiguration());
138    Path tableDir = CommonFSUtils.getTableDir(hbaseRootDir, tableDescriptor.getTableName());
139    HRegionFileSystem hrfs = new HRegionFileSystem(TEST_UTIL.getConfiguration(), fs, tableDir, hri);
140    if (fs.exists(hrfs.getRegionDir())) {
141      LOG.info("Region directory already exists. Deleting.");
142      fs.delete(hrfs.getRegionDir(), true);
143    }
144    HRegion region =
145      HBaseTestingUtil.createRegionAndWAL(hri, hbaseRootDir, conf, tableDescriptor, blockCache);
146    assertEquals(encodedRegionName, region.getRegionInfo().getEncodedName());
147    List<String> storeFiles = region.getStoreFileList(RECOVEREDITS_COLUMNFAMILY_ARRAY);
148    // There should be no store files.
149    assertTrue(storeFiles.isEmpty());
150    region.close();
151    Path regionDir = FSUtils.getRegionDirFromRootDir(hbaseRootDir, hri);
152    Path recoveredEditsDir = WALSplitUtil.getRegionDirRecoveredEditsDir(regionDir);
153    // Copy this file under the region's recovered.edits dir so it is replayed on reopen.
154    Path destination = new Path(recoveredEditsDir, RECOVEREDEDITS_PATH.getName());
155    fs.copyToLocalFile(RECOVEREDEDITS_PATH, destination);
156    assertTrue(fs.exists(destination));
157    // Now the file 0000000000000016310 is under recovered.edits, reopen the region to replay.
158    region = HRegion.openHRegion(region, null);
159    assertEquals(encodedRegionName, region.getRegionInfo().getEncodedName());
160    storeFiles = region.getStoreFileList(RECOVEREDITS_COLUMNFAMILY_ARRAY);
161    // Our 0000000000000016310 is 10MB. Most of the edits are for one region. Lets assume that if
162    // we flush at 1MB, that there are at least 3 flushed files that are there because of the
163    // replay of edits.
164    if (policy == MemoryCompactionPolicy.EAGER || policy == MemoryCompactionPolicy.ADAPTIVE) {
165      assertTrue("Files count=" + storeFiles.size(), storeFiles.size() >= 1);
166    } else {
167      assertTrue("Files count=" + storeFiles.size(), storeFiles.size() > 10);
168    }
169    // Now verify all edits made it into the region.
170    int count = verifyAllEditsMadeItIn(fs, conf, RECOVEREDEDITS_PATH, region);
171    assertTrue(count > 0);
172    LOG.info("Checked " + count + " edits made it in");
173  }
174
175  /**
176   * @return Return how many edits seen.
177   */
178  // Used by TestWALPlayer over in hbase-mapreduce too.
179  public static int verifyAllEditsMadeItIn(final FileSystem fs, final Configuration conf,
180    final Path edits, final HRegion region) throws IOException {
181    int count = 0;
182    // Read all cells from recover edits
183    List<Cell> walCells = new ArrayList<>();
184    try (WAL.Reader reader = WALFactory.createReader(fs, edits, conf)) {
185      WAL.Entry entry;
186      while ((entry = reader.next()) != null) {
187        WALKey key = entry.getKey();
188        WALEdit val = entry.getEdit();
189        count++;
190        // Check this edit is for this region.
191        if (
192          !Bytes.equals(key.getEncodedRegionName(), region.getRegionInfo().getEncodedNameAsBytes())
193        ) {
194          continue;
195        }
196        Cell previous = null;
197        for (Cell cell : val.getCells()) {
198          if (WALEdit.isMetaEditFamily(cell)) {
199            continue;
200          }
201          if (previous != null && CellComparatorImpl.COMPARATOR.compareRows(previous, cell) == 0) {
202            continue;
203          }
204          previous = cell;
205          walCells.add(cell);
206        }
207      }
208    }
209
210    // Read all cells from region
211    List<Cell> regionCells = new ArrayList<>();
212    try (RegionScanner scanner = region.getScanner(new Scan())) {
213      List<Cell> tmpCells;
214      do {
215        tmpCells = new ArrayList<>();
216        scanner.nextRaw(tmpCells);
217        regionCells.addAll(tmpCells);
218      } while (!tmpCells.isEmpty());
219    }
220
221    Collections.sort(walCells, CellComparatorImpl.COMPARATOR);
222    int found = 0;
223    for (int i = 0, j = 0; i < walCells.size() && j < regionCells.size();) {
224      int compareResult = PrivateCellUtil.compareKeyIgnoresMvcc(CellComparatorImpl.COMPARATOR,
225        walCells.get(i), regionCells.get(j));
226      if (compareResult == 0) {
227        i++;
228        j++;
229        found++;
230      } else if (compareResult > 0) {
231        j++;
232      } else {
233        i++;
234      }
235    }
236    assertEquals("Only found " + found + " cells in region, but there are " + walCells.size()
237      + " cells in recover edits", found, walCells.size());
238    return count;
239  }
240}