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 java.io.IOException;
021import org.apache.hadoop.conf.Configuration;
022import org.apache.hadoop.fs.FileSystem;
023import org.apache.hadoop.fs.Path;
024import org.apache.hadoop.hbase.HBaseClassTestRule;
025import org.apache.hadoop.hbase.HBaseTestingUtil;
026import org.apache.hadoop.hbase.HConstants;
027import org.apache.hadoop.hbase.KeyValue;
028import org.apache.hadoop.hbase.ServerName;
029import org.apache.hadoop.hbase.TableName;
030import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
031import org.apache.hadoop.hbase.client.RegionInfo;
032import org.apache.hadoop.hbase.client.RegionInfoBuilder;
033import org.apache.hadoop.hbase.client.TableDescriptor;
034import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
035import org.apache.hadoop.hbase.monitoring.TaskMonitor;
036import org.apache.hadoop.hbase.testclassification.RegionServerTests;
037import org.apache.hadoop.hbase.testclassification.SmallTests;
038import org.apache.hadoop.hbase.util.Bytes;
039import org.apache.hadoop.hbase.util.CancelableProgressable;
040import org.apache.hadoop.hbase.util.CommonFSUtils;
041import org.apache.hadoop.hbase.wal.WAL;
042import org.apache.hadoop.hbase.wal.WALEdit;
043import org.apache.hadoop.hbase.wal.WALEditInternalHelper;
044import org.apache.hadoop.hbase.wal.WALFactory;
045import org.apache.hadoop.hbase.wal.WALKeyImpl;
046import org.apache.hadoop.hbase.wal.WALProvider;
047import org.apache.hadoop.hbase.wal.WALSplitUtil;
048import org.junit.After;
049import org.junit.Assert;
050import org.junit.Before;
051import org.junit.ClassRule;
052import org.junit.Rule;
053import org.junit.Test;
054import org.junit.experimental.categories.Category;
055import org.junit.rules.TestName;
056import org.mockito.Mockito;
057import org.slf4j.Logger;
058import org.slf4j.LoggerFactory;
059
060/**
061 * HBASE-21031 If replay edits fails, we need to make sure memstore is rollbacked And if MSLAB is
062 * used, all chunk is released too.
063 */
064@Category({ RegionServerTests.class, SmallTests.class })
065public class TestRecoveredEditsReplayAndAbort {
066  @ClassRule
067  public static final HBaseClassTestRule CLASS_RULE =
068    HBaseClassTestRule.forClass(TestRecoveredEditsReplayAndAbort.class);
069
070  private static final Logger LOG = LoggerFactory.getLogger(TestRecoveredEditsReplayAndAbort.class);
071
072  protected final byte[] row = Bytes.toBytes("rowA");
073
074  protected final static byte[] fam1 = Bytes.toBytes("colfamily11");
075
076  @Rule
077  public TestName name = new TestName();
078
079  // Test names
080  protected TableName tableName;
081  protected String method;
082
083  protected static HBaseTestingUtil TEST_UTIL;
084  public static Configuration CONF;
085  private HRegion region = null;
086
087  @Before
088  public void setup() throws IOException {
089    TEST_UTIL = new HBaseTestingUtil();
090    CONF = TEST_UTIL.getConfiguration();
091    method = name.getMethodName();
092    tableName = TableName.valueOf(method);
093  }
094
095  @After
096  public void tearDown() throws Exception {
097    LOG.info("Cleaning test directory: " + TEST_UTIL.getDataTestDir());
098    TEST_UTIL.cleanupTestDir();
099  }
100
101  @Test
102  public void test() throws Exception {
103    // set flush size to 10MB
104    CONF.setInt("hbase.hregion.memstore.flush.size", 1024 * 1024 * 10);
105    // set the report interval to a very small value
106    CONF.setInt("hbase.hstore.report.interval.edits", 1);
107    CONF.setInt("hbase.hstore.report.period", 0);
108    // mock a RegionServerServices
109    final RegionServerAccounting rsAccounting = new RegionServerAccounting(CONF);
110    RegionServerServices rs = Mockito.mock(RegionServerServices.class);
111    ChunkCreator.initialize(MemStoreLAB.CHUNK_SIZE_DEFAULT, false, 0, 0, 0, null,
112      MemStoreLAB.INDEX_CHUNK_SIZE_PERCENTAGE_DEFAULT);
113    Mockito.when(rs.getRegionServerAccounting()).thenReturn(rsAccounting);
114    Mockito.when(rs.isAborted()).thenReturn(false);
115    Mockito.when(rs.getNonceManager()).thenReturn(null);
116    Mockito.when(rs.getServerName()).thenReturn(ServerName.valueOf("test", 0, 111));
117    Mockito.when(rs.getConfiguration()).thenReturn(CONF);
118    // create a region
119    TableName testTable = TableName.valueOf("testRecoveredEidtsReplayAndAbort");
120    TableDescriptor htd = TableDescriptorBuilder.newBuilder(testTable)
121      .setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(fam1).build()).build();
122    RegionInfo info = RegionInfoBuilder.newBuilder(htd.getTableName()).build();
123    Path logDir = TEST_UTIL.getDataTestDirOnTestFS("TestRecoveredEidtsReplayAndAbort.log");
124    final WAL wal = HBaseTestingUtil.createWal(CONF, logDir, info);
125    Path rootDir = TEST_UTIL.getDataTestDir();
126    Path tableDir = CommonFSUtils.getTableDir(rootDir, info.getTable());
127    HRegionFileSystem.createRegionOnFileSystem(CONF, TEST_UTIL.getTestFileSystem(), tableDir, info);
128    region = HRegion.newHRegion(tableDir, wal, TEST_UTIL.getTestFileSystem(), CONF, info, htd, rs,
129      rs.getKeyManagementService());
130    // create some recovered.edits
131    final WALFactory wals = new WALFactory(CONF, method);
132    try {
133      Path regiondir = region.getRegionFileSystem().getRegionDir();
134      FileSystem fs = region.getRegionFileSystem().getFileSystem();
135      byte[] regionName = region.getRegionInfo().getEncodedNameAsBytes();
136
137      Path recoveredEditsDir = WALSplitUtil.getRegionDirRecoveredEditsDir(regiondir);
138      long maxSeqId = 1200;
139      long minSeqId = 1000;
140      long totalEdits = maxSeqId - minSeqId;
141      for (long i = minSeqId; i <= maxSeqId; i += 100) {
142        Path recoveredEdits = new Path(recoveredEditsDir, String.format("%019d", i));
143        LOG.info("Begin to write recovered.edits : " + recoveredEdits);
144        fs.create(recoveredEdits);
145        WALProvider.Writer writer = wals.createRecoveredEditsWriter(fs, recoveredEdits);
146        for (long j = i; j < i + 100; j++) {
147          long time = System.nanoTime();
148          WALEdit edit = new WALEdit();
149          // 200KB kv
150          byte[] value = new byte[200 * 1024];
151          Bytes.random(value);
152          WALEditInternalHelper.addExtendedCell(edit,
153            new KeyValue(row, fam1, Bytes.toBytes(j), time, KeyValue.Type.Put, value));
154          writer.append(new WAL.Entry(
155            new WALKeyImpl(regionName, tableName, j, time, HConstants.DEFAULT_CLUSTER_ID), edit));
156        }
157        writer.close();
158      }
159      TaskMonitor.get().createStatus(method);
160      // try to replay the edits
161      try {
162        region.initialize(new CancelableProgressable() {
163          private long replayedEdits = 0;
164
165          @Override
166          public boolean progress() {
167            replayedEdits++;
168            // during replay, rsAccounting should align with global memstore, because
169            // there is only one memstore here
170            Assert.assertEquals(rsAccounting.getGlobalMemStoreDataSize(),
171              region.getMemStoreDataSize());
172            Assert.assertEquals(rsAccounting.getGlobalMemStoreHeapSize(),
173              region.getMemStoreHeapSize());
174            Assert.assertEquals(rsAccounting.getGlobalMemStoreOffHeapSize(),
175              region.getMemStoreOffHeapSize());
176            // abort the replay before finishing, leaving some edits in the memory
177            return replayedEdits < totalEdits - 10;
178          }
179        });
180        Assert.fail("Should not reach here");
181      } catch (IOException t) {
182        LOG.info("Current memstore: " + region.getMemStoreDataSize() + ", "
183          + region.getMemStoreHeapSize() + ", " + region.getMemStoreOffHeapSize());
184      }
185      // After aborting replay, there should be no data in the memory
186      Assert.assertEquals(0, rsAccounting.getGlobalMemStoreDataSize());
187      Assert.assertEquals(0, region.getMemStoreDataSize());
188      // All the chunk in the MSLAB should be recycled, otherwise, there might be
189      // a memory leak.
190      Assert.assertEquals(0, ChunkCreator.getInstance().numberOfMappedChunks());
191    } finally {
192      HBaseTestingUtil.closeRegionAndWAL(this.region);
193      this.region = null;
194      wals.close();
195    }
196  }
197}