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.assertNull;
021import static org.mockito.Mockito.mock;
022import static org.mockito.Mockito.when;
023
024import java.io.IOException;
025import java.io.UncheckedIOException;
026import java.util.List;
027import java.util.NavigableMap;
028import java.util.TreeMap;
029import java.util.concurrent.CompletableFuture;
030import java.util.concurrent.atomic.AtomicInteger;
031import java.util.concurrent.atomic.AtomicReference;
032import org.apache.hadoop.conf.Configuration;
033import org.apache.hadoop.fs.FileSystem;
034import org.apache.hadoop.fs.Path;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.hadoop.hbase.KeyValue;
038import org.apache.hadoop.hbase.TableName;
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.TableDescriptor;
043import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
044import org.apache.hadoop.hbase.regionserver.LogRoller;
045import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
046import org.apache.hadoop.hbase.regionserver.RegionServerServices;
047import org.apache.hadoop.hbase.regionserver.SequenceId;
048import org.apache.hadoop.hbase.testclassification.LargeTests;
049import org.apache.hadoop.hbase.testclassification.RegionServerTests;
050import org.apache.hadoop.hbase.util.Bytes;
051import org.apache.hadoop.hbase.util.CommonFSUtils;
052import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
053import org.apache.hadoop.hbase.util.FutureUtils;
054import org.apache.hadoop.hbase.util.Threads;
055import org.apache.hadoop.hbase.wal.WALEdit;
056import org.apache.hadoop.hbase.wal.WALKey;
057import org.apache.hadoop.hbase.wal.WALKeyImpl;
058import org.apache.hadoop.hbase.wal.WALProvider.AsyncWriter;
059import org.junit.AfterClass;
060import org.junit.BeforeClass;
061import org.junit.ClassRule;
062import org.junit.Test;
063import org.junit.experimental.categories.Category;
064
065import org.apache.hbase.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;
066import org.apache.hbase.thirdparty.io.netty.channel.Channel;
067import org.apache.hbase.thirdparty.io.netty.channel.EventLoopGroup;
068import org.apache.hbase.thirdparty.io.netty.channel.nio.NioEventLoopGroup;
069import org.apache.hbase.thirdparty.io.netty.channel.socket.nio.NioSocketChannel;
070
071/**
072 * Provides AsyncFSWAL test cases.
073 */
074@Category({ RegionServerTests.class, LargeTests.class })
075public class TestAsyncFSWAL extends AbstractTestFSWAL {
076
077  @ClassRule
078  public static final HBaseClassTestRule CLASS_RULE =
079    HBaseClassTestRule.forClass(TestAsyncFSWAL.class);
080
081  private static EventLoopGroup GROUP;
082
083  private static Class<? extends Channel> CHANNEL_CLASS;
084
085  @BeforeClass
086  public static void setUpBeforeClass() throws Exception {
087    GROUP =
088      new NioEventLoopGroup(1, new ThreadFactoryBuilder().setNameFormat("TestAsyncFSWAL-pool-%d")
089        .setDaemon(true).setUncaughtExceptionHandler(Threads.LOGGING_EXCEPTION_HANDLER).build());
090    CHANNEL_CLASS = NioSocketChannel.class;
091    AbstractTestFSWAL.setUpBeforeClass();
092  }
093
094  @AfterClass
095  public static void tearDownAfterClass() throws Exception {
096    AbstractTestFSWAL.tearDownAfterClass();
097    GROUP.shutdownGracefully();
098  }
099
100  @Override
101  protected AbstractFSWAL<?> newWAL(FileSystem fs, Path rootDir, String logDir, String archiveDir,
102    Configuration conf, List<WALActionsListener> listeners, boolean failIfWALExists, String prefix,
103    String suffix) throws IOException {
104    AsyncFSWAL asyncFSWAL = new AsyncFSWAL(fs, rootDir, logDir, archiveDir, conf, listeners,
105      failIfWALExists, prefix, suffix, GROUP, CHANNEL_CLASS);
106    asyncFSWAL.init();
107    return asyncFSWAL;
108  }
109
110  @Override
111  protected AbstractFSWAL<?> newSlowWAL(FileSystem fs, Path rootDir, String logDir,
112    String archiveDir, Configuration conf, List<WALActionsListener> listeners,
113    boolean failIfWALExists, String prefix, String suffix, final Runnable action)
114    throws IOException {
115    AsyncFSWAL asyncFSWAL = new AsyncFSWAL(fs, rootDir, logDir, archiveDir, conf, listeners,
116      failIfWALExists, prefix, suffix, GROUP, CHANNEL_CLASS) {
117      @Override
118      protected void atHeadOfRingBufferEventHandlerAppend() {
119        action.run();
120        super.atHeadOfRingBufferEventHandlerAppend();
121      }
122
123    };
124    asyncFSWAL.init();
125    return asyncFSWAL;
126  }
127
128  @Test
129  public void testBrokenWriter() throws Exception {
130    RegionServerServices services = mock(RegionServerServices.class);
131    when(services.getConfiguration()).thenReturn(CONF);
132    TableDescriptor td = TableDescriptorBuilder.newBuilder(TableName.valueOf("table"))
133      .setColumnFamily(ColumnFamilyDescriptorBuilder.of("row")).build();
134    RegionInfo ri = RegionInfoBuilder.newBuilder(td.getTableName()).build();
135    MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
136    NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
137    for (byte[] fam : td.getColumnFamilyNames()) {
138      scopes.put(fam, 0);
139    }
140    long timestamp = EnvironmentEdgeManager.currentTime();
141    String testName = currentTest.getMethodName();
142    AtomicInteger failedCount = new AtomicInteger(0);
143    try (LogRoller roller = new LogRoller(services);
144      AsyncFSWAL wal = new AsyncFSWAL(FS, CommonFSUtils.getWALRootDir(CONF), DIR.toString(),
145        testName, CONF, null, true, null, null, GROUP, CHANNEL_CLASS) {
146
147        @Override
148        protected AsyncWriter createWriterInstance(Path path) throws IOException {
149          AsyncWriter writer = super.createWriterInstance(path);
150          return new AsyncWriter() {
151
152            @Override
153            public void close() throws IOException {
154              writer.close();
155            }
156
157            @Override
158            public long getLength() {
159              return writer.getLength();
160            }
161
162            @Override
163            public long getSyncedLength() {
164              return writer.getSyncedLength();
165            }
166
167            @Override
168            public CompletableFuture<Long> sync(boolean forceSync) {
169              CompletableFuture<Long> result = writer.sync(forceSync);
170              if (failedCount.incrementAndGet() < 1000) {
171                CompletableFuture<Long> future = new CompletableFuture<>();
172                FutureUtils.addListener(result,
173                  (r, e) -> future.completeExceptionally(new IOException("Inject Error")));
174                return future;
175              } else {
176                return result;
177              }
178            }
179
180            @Override
181            public void append(Entry entry) {
182              writer.append(entry);
183            }
184          };
185        }
186      }) {
187      wal.init();
188      roller.addWAL(wal);
189      roller.start();
190      int numThreads = 10;
191      AtomicReference<Exception> error = new AtomicReference<>();
192      Thread[] threads = new Thread[numThreads];
193      for (int i = 0; i < 10; i++) {
194        final int index = i;
195        threads[index] = new Thread("Write-Thread-" + index) {
196
197          @Override
198          public void run() {
199            byte[] row = Bytes.toBytes("row" + index);
200            WALEdit cols = new WALEdit();
201            cols.add(new KeyValue(row, row, row, timestamp + index, row));
202            WALKeyImpl key = new WALKeyImpl(ri.getEncodedNameAsBytes(), td.getTableName(),
203              SequenceId.NO_SEQUENCE_ID, timestamp, WALKey.EMPTY_UUIDS, HConstants.NO_NONCE,
204              HConstants.NO_NONCE, mvcc, scopes);
205            try {
206              wal.append(ri, key, cols, true);
207            } catch (IOException e) {
208              // should not happen
209              throw new UncheckedIOException(e);
210            }
211            try {
212              wal.sync();
213            } catch (IOException e) {
214              error.set(e);
215            }
216          }
217        };
218      }
219      for (Thread t : threads) {
220        t.start();
221      }
222      for (Thread t : threads) {
223        t.join();
224      }
225      assertNull(error.get());
226    }
227  }
228}