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.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertTrue;
024
025import java.io.EOFException;
026import java.io.IOException;
027import java.util.ArrayList;
028import java.util.HashSet;
029import java.util.List;
030import java.util.Set;
031import java.util.concurrent.atomic.AtomicBoolean;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.Cell;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.hadoop.hbase.TableName;
038import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
039import org.apache.hadoop.hbase.client.Put;
040import org.apache.hadoop.hbase.client.RegionInfo;
041import org.apache.hadoop.hbase.client.Result;
042import org.apache.hadoop.hbase.client.ResultScanner;
043import org.apache.hadoop.hbase.client.Scan;
044import org.apache.hadoop.hbase.client.Table;
045import org.apache.hadoop.hbase.client.TableDescriptor;
046import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
047import org.apache.hadoop.hbase.fs.HFileSystem;
048import org.apache.hadoop.hbase.regionserver.HRegion;
049import org.apache.hadoop.hbase.testclassification.LargeTests;
050import org.apache.hadoop.hbase.testclassification.VerySlowRegionServerTests;
051import org.apache.hadoop.hbase.util.Bytes;
052import org.apache.hadoop.hbase.util.FSUtils;
053import org.apache.hadoop.hbase.util.JVMClusterUtil;
054import org.apache.hadoop.hbase.wal.AbstractFSWALProvider;
055import org.apache.hadoop.hbase.wal.WAL;
056import org.apache.hadoop.hbase.wal.WALFactory;
057import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
058import org.apache.hadoop.hdfs.server.datanode.DataNode;
059import org.junit.BeforeClass;
060import org.junit.ClassRule;
061import org.junit.Test;
062import org.junit.experimental.categories.Category;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066@Category({ VerySlowRegionServerTests.class, LargeTests.class })
067public class TestLogRolling extends AbstractTestLogRolling {
068
069  @ClassRule
070  public static final HBaseClassTestRule CLASS_RULE =
071      HBaseClassTestRule.forClass(TestLogRolling.class);
072
073  private static final Logger LOG = LoggerFactory.getLogger(TestLogRolling.class);
074
075  @BeforeClass
076  public static void setUpBeforeClass() throws Exception {
077    // TODO: testLogRollOnDatanodeDeath fails if short circuit reads are on under the hadoop2
078    // profile. See HBASE-9337 for related issues.
079    System.setProperty("hbase.tests.use.shortcircuit.reads", "false");
080
081    /**** configuration for testLogRollOnDatanodeDeath ****/
082    // lower the namenode & datanode heartbeat so the namenode
083    // quickly detects datanode failures
084    Configuration conf= TEST_UTIL.getConfiguration();
085    conf.setInt("dfs.namenode.heartbeat.recheck-interval", 5000);
086    conf.setInt("dfs.heartbeat.interval", 1);
087    // the namenode might still try to choose the recently-dead datanode
088    // for a pipeline, so try to a new pipeline multiple times
089    conf.setInt("dfs.client.block.write.retries", 30);
090    conf.setInt("hbase.regionserver.hlog.tolerable.lowreplication", 2);
091    conf.setInt("hbase.regionserver.hlog.lowreplication.rolllimit", 3);
092    conf.set(WALFactory.WAL_PROVIDER, "filesystem");
093    conf.set(WALFactory.META_WAL_PROVIDER, "filesystem");
094    AbstractTestLogRolling.setUpBeforeClass();
095  }
096
097  void batchWriteAndWait(Table table, final FSHLog log, int start, boolean expect, int timeout)
098      throws IOException {
099    for (int i = 0; i < 10; i++) {
100      Put put = new Put(Bytes.toBytes("row" + String.format("%1$04d", (start + i))));
101      put.addColumn(HConstants.CATALOG_FAMILY, null, value);
102      table.put(put);
103    }
104    Put tmpPut = new Put(Bytes.toBytes("tmprow"));
105    tmpPut.addColumn(HConstants.CATALOG_FAMILY, null, value);
106    long startTime = System.currentTimeMillis();
107    long remaining = timeout;
108    while (remaining > 0) {
109      if (log.isLowReplicationRollEnabled() == expect) {
110        break;
111      } else {
112        // Trigger calling FSHlog#checkLowReplication()
113        table.put(tmpPut);
114        try {
115          Thread.sleep(200);
116        } catch (InterruptedException e) {
117          // continue
118        }
119        remaining = timeout - (System.currentTimeMillis() - startTime);
120      }
121    }
122  }
123
124  /**
125   * Tests that logs are rolled upon detecting datanode death Requires an HDFS jar with HDFS-826 &
126   * syncFs() support (HDFS-200)
127   */
128  @Test
129  public void testLogRollOnDatanodeDeath() throws Exception {
130    TEST_UTIL.ensureSomeRegionServersAvailable(2);
131    assertTrue("This test requires WAL file replication set to 2.",
132      fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) == 2);
133    LOG.info("Replication=" + fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
134
135    this.server = cluster.getRegionServer(0);
136
137    // Create the test table and open it
138    TableDescriptor desc = TableDescriptorBuilder.newBuilder(TableName.valueOf(getName()))
139        .setColumnFamily(ColumnFamilyDescriptorBuilder.of(HConstants.CATALOG_FAMILY)).build();
140
141    admin.createTable(desc);
142    Table table = TEST_UTIL.getConnection().getTable(desc.getTableName());
143
144    server = TEST_UTIL.getRSForFirstRegionInTable(desc.getTableName());
145    RegionInfo region = server.getRegions(desc.getTableName()).get(0).getRegionInfo();
146    final FSHLog log = (FSHLog) server.getWAL(region);
147    final AtomicBoolean lowReplicationHookCalled = new AtomicBoolean(false);
148
149    log.registerWALActionsListener(new WALActionsListener() {
150      @Override
151      public void logRollRequested(boolean lowReplication) {
152        if (lowReplication) {
153          lowReplicationHookCalled.lazySet(true);
154        }
155      }
156    });
157
158    // add up the datanode count, to ensure proper replication when we kill 1
159    // This function is synchronous; when it returns, the dfs cluster is active
160    // We start 3 servers and then stop 2 to avoid a directory naming conflict
161    // when we stop/start a namenode later, as mentioned in HBASE-5163
162    List<DataNode> existingNodes = dfsCluster.getDataNodes();
163    int numDataNodes = 3;
164    dfsCluster.startDataNodes(TEST_UTIL.getConfiguration(), numDataNodes, true, null, null);
165    List<DataNode> allNodes = dfsCluster.getDataNodes();
166    for (int i = allNodes.size() - 1; i >= 0; i--) {
167      if (existingNodes.contains(allNodes.get(i))) {
168        dfsCluster.stopDataNode(i);
169      }
170    }
171
172    assertTrue(
173      "DataNodes " + dfsCluster.getDataNodes().size() + " default replication "
174          + fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()),
175      dfsCluster.getDataNodes()
176          .size() >= fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) + 1);
177
178    writeData(table, 2);
179
180    long curTime = System.currentTimeMillis();
181    LOG.info("log.getCurrentFileName(): " + log.getCurrentFileName());
182    long oldFilenum = AbstractFSWALProvider.extractFileNumFromWAL(log);
183    assertTrue("Log should have a timestamp older than now",
184      curTime > oldFilenum && oldFilenum != -1);
185
186    assertTrue("The log shouldn't have rolled yet",
187      oldFilenum == AbstractFSWALProvider.extractFileNumFromWAL(log));
188    final DatanodeInfo[] pipeline = log.getPipeline();
189    assertTrue(pipeline.length == fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
190
191    // kill a datanode in the pipeline to force a log roll on the next sync()
192    // This function is synchronous, when it returns the node is killed.
193    assertTrue(dfsCluster.stopDataNode(pipeline[0].getName()) != null);
194
195    // this write should succeed, but trigger a log roll
196    writeData(table, 2);
197    long newFilenum = AbstractFSWALProvider.extractFileNumFromWAL(log);
198
199    assertTrue("Missing datanode should've triggered a log roll",
200      newFilenum > oldFilenum && newFilenum > curTime);
201
202    assertTrue("The log rolling hook should have been called with the low replication flag",
203      lowReplicationHookCalled.get());
204
205    // write some more log data (this should use a new hdfs_out)
206    writeData(table, 3);
207    assertTrue("The log should not roll again.",
208      AbstractFSWALProvider.extractFileNumFromWAL(log) == newFilenum);
209    // kill another datanode in the pipeline, so the replicas will be lower than
210    // the configured value 2.
211    assertTrue(dfsCluster.stopDataNode(pipeline[1].getName()) != null);
212
213    batchWriteAndWait(table, log, 3, false, 14000);
214    int replication = log.getLogReplication();
215    assertTrue("LowReplication Roller should've been disabled, current replication=" + replication,
216      !log.isLowReplicationRollEnabled());
217
218    dfsCluster.startDataNodes(TEST_UTIL.getConfiguration(), 1, true, null, null);
219
220    // Force roll writer. The new log file will have the default replications,
221    // and the LowReplication Roller will be enabled.
222    log.rollWriter(true);
223    batchWriteAndWait(table, log, 13, true, 10000);
224    replication = log.getLogReplication();
225    assertTrue("New log file should have the default replication instead of " + replication,
226      replication == fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
227    assertTrue("LowReplication Roller should've been enabled", log.isLowReplicationRollEnabled());
228  }
229
230  /**
231   * Test that WAL is rolled when all data nodes in the pipeline have been restarted.
232   * @throws Exception
233   */
234  @Test
235  public void testLogRollOnPipelineRestart() throws Exception {
236    LOG.info("Starting testLogRollOnPipelineRestart");
237    assertTrue("This test requires WAL file replication.",
238      fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()) > 1);
239    LOG.info("Replication=" + fs.getDefaultReplication(TEST_UTIL.getDataTestDirOnTestFS()));
240    // When the hbase:meta table can be opened, the region servers are running
241    Table t = TEST_UTIL.getConnection().getTable(TableName.META_TABLE_NAME);
242    try {
243      this.server = cluster.getRegionServer(0);
244
245      // Create the test table and open it
246      TableDescriptor desc = TableDescriptorBuilder.newBuilder(TableName.valueOf(getName()))
247          .setColumnFamily(ColumnFamilyDescriptorBuilder.of(HConstants.CATALOG_FAMILY)).build();
248
249      admin.createTable(desc);
250      Table table = TEST_UTIL.getConnection().getTable(desc.getTableName());
251
252      server = TEST_UTIL.getRSForFirstRegionInTable(desc.getTableName());
253      RegionInfo region = server.getRegions(desc.getTableName()).get(0).getRegionInfo();
254      final WAL log = server.getWAL(region);
255      final List<Path> paths = new ArrayList<>(1);
256      final List<Integer> preLogRolledCalled = new ArrayList<>();
257
258      paths.add(AbstractFSWALProvider.getCurrentFileName(log));
259      log.registerWALActionsListener(new WALActionsListener() {
260
261        @Override
262        public void preLogRoll(Path oldFile, Path newFile) {
263          LOG.debug("preLogRoll: oldFile=" + oldFile + " newFile=" + newFile);
264          preLogRolledCalled.add(new Integer(1));
265        }
266
267        @Override
268        public void postLogRoll(Path oldFile, Path newFile) {
269          paths.add(newFile);
270        }
271      });
272
273      writeData(table, 1002);
274
275      long curTime = System.currentTimeMillis();
276      LOG.info("log.getCurrentFileName()): " + AbstractFSWALProvider.getCurrentFileName(log));
277      long oldFilenum = AbstractFSWALProvider.extractFileNumFromWAL(log);
278      assertTrue("Log should have a timestamp older than now",
279        curTime > oldFilenum && oldFilenum != -1);
280
281      assertTrue("The log shouldn't have rolled yet",
282        oldFilenum == AbstractFSWALProvider.extractFileNumFromWAL(log));
283
284      // roll all datanodes in the pipeline
285      dfsCluster.restartDataNodes();
286      Thread.sleep(1000);
287      dfsCluster.waitActive();
288      LOG.info("Data Nodes restarted");
289      validateData(table, 1002);
290
291      // this write should succeed, but trigger a log roll
292      writeData(table, 1003);
293      long newFilenum = AbstractFSWALProvider.extractFileNumFromWAL(log);
294
295      assertTrue("Missing datanode should've triggered a log roll",
296        newFilenum > oldFilenum && newFilenum > curTime);
297      validateData(table, 1003);
298
299      writeData(table, 1004);
300
301      // roll all datanode again
302      dfsCluster.restartDataNodes();
303      Thread.sleep(1000);
304      dfsCluster.waitActive();
305      LOG.info("Data Nodes restarted");
306      validateData(table, 1004);
307
308      // this write should succeed, but trigger a log roll
309      writeData(table, 1005);
310
311      // force a log roll to read back and verify previously written logs
312      log.rollWriter(true);
313      assertTrue("preLogRolledCalled has size of " + preLogRolledCalled.size(),
314        preLogRolledCalled.size() >= 1);
315
316      // read back the data written
317      Set<String> loggedRows = new HashSet<>();
318      FSUtils fsUtils = FSUtils.getInstance(fs, TEST_UTIL.getConfiguration());
319      for (Path p : paths) {
320        LOG.debug("recovering lease for " + p);
321        fsUtils.recoverFileLease(((HFileSystem) fs).getBackingFs(), p, TEST_UTIL.getConfiguration(),
322          null);
323
324        LOG.debug("Reading WAL " + FSUtils.getPath(p));
325        WAL.Reader reader = null;
326        try {
327          reader = WALFactory.createReader(fs, p, TEST_UTIL.getConfiguration());
328          WAL.Entry entry;
329          while ((entry = reader.next()) != null) {
330            LOG.debug("#" + entry.getKey().getSequenceId() + ": " + entry.getEdit().getCells());
331            for (Cell cell : entry.getEdit().getCells()) {
332              loggedRows.add(
333                Bytes.toStringBinary(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
334            }
335          }
336        } catch (EOFException e) {
337          LOG.debug("EOF reading file " + FSUtils.getPath(p));
338        } finally {
339          if (reader != null) reader.close();
340        }
341      }
342
343      // verify the written rows are there
344      assertTrue(loggedRows.contains("row1002"));
345      assertTrue(loggedRows.contains("row1003"));
346      assertTrue(loggedRows.contains("row1004"));
347      assertTrue(loggedRows.contains("row1005"));
348
349      // flush all regions
350      for (HRegion r : server.getOnlineRegionsLocalContext()) {
351        try {
352          r.flush(true);
353        } catch (Exception e) {
354          // This try/catch was added by HBASE-14317. It is needed
355          // because this issue tightened up the semantic such that
356          // a failed append could not be followed by a successful
357          // sync. What is coming out here is a failed sync, a sync
358          // that used to 'pass'.
359          LOG.info(e.toString(), e);
360        }
361      }
362
363      ResultScanner scanner = table.getScanner(new Scan());
364      try {
365        for (int i = 2; i <= 5; i++) {
366          Result r = scanner.next();
367          assertNotNull(r);
368          assertFalse(r.isEmpty());
369          assertEquals("row100" + i, Bytes.toString(r.getRow()));
370        }
371      } finally {
372        scanner.close();
373      }
374
375      // verify that no region servers aborted
376      for (JVMClusterUtil.RegionServerThread rsThread : TEST_UTIL.getHBaseCluster()
377          .getRegionServerThreads()) {
378        assertFalse(rsThread.getRegionServer().isAborted());
379      }
380    } finally {
381      if (t != null) t.close();
382    }
383  }
384
385}