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.wal;
019
020import static org.junit.Assert.assertFalse;
021import static org.junit.Assert.assertTrue;
022
023import java.io.FileNotFoundException;
024import java.io.IOException;
025import java.nio.ByteBuffer;
026import java.util.NavigableMap;
027import java.util.TreeMap;
028import org.apache.commons.io.IOUtils;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.fs.FSDataInputStream;
031import org.apache.hadoop.fs.FileStatus;
032import org.apache.hadoop.fs.FileSystem;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.ByteBufferKeyValue;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HBaseTestingUtility;
037import org.apache.hadoop.hbase.HConstants;
038import org.apache.hadoop.hbase.KeyValue;
039import org.apache.hadoop.hbase.ServerName;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.RegionInfo;
042import org.apache.hadoop.hbase.client.RegionInfoBuilder;
043import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
044import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
045import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
046import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter;
047import org.apache.hadoop.hbase.regionserver.wal.SecureAsyncProtobufLogWriter;
048import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogReader;
049import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogWriter;
050import org.apache.hadoop.hbase.regionserver.wal.SecureWALCellCodec;
051import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
052import org.apache.hadoop.hbase.testclassification.RegionServerTests;
053import org.apache.hadoop.hbase.testclassification.SmallTests;
054import org.apache.hadoop.hbase.util.Bytes;
055import org.apache.hadoop.hbase.util.CommonFSUtils;
056import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
057import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
058import org.junit.BeforeClass;
059import org.junit.ClassRule;
060import org.junit.Rule;
061import org.junit.Test;
062import org.junit.experimental.categories.Category;
063import org.junit.rules.TestName;
064
065/**
066 * Test that verifies WAL written by SecureProtobufLogWriter is not readable by ProtobufLogReader
067 */
068@Category({ RegionServerTests.class, SmallTests.class })
069public class TestWALReaderOnSecureWAL {
070
071  @ClassRule
072  public static final HBaseClassTestRule CLASS_RULE =
073    HBaseClassTestRule.forClass(TestWALReaderOnSecureWAL.class);
074
075  static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
076  final byte[] value = Bytes.toBytes("Test value");
077
078  private static final String WAL_ENCRYPTION = "hbase.regionserver.wal.encryption";
079
080  @Rule
081  public TestName currentTest = new TestName();
082
083  @BeforeClass
084  public static void setUpBeforeClass() throws Exception {
085    Configuration conf = TEST_UTIL.getConfiguration();
086    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
087    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
088    conf.setBoolean(WALSplitter.SPLIT_SKIP_ERRORS_KEY, true);
089    conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
090    CommonFSUtils.setRootDir(conf, TEST_UTIL.getDataTestDir());
091  }
092
093  private Path writeWAL(final WALFactory wals, final String tblName, boolean offheap)
094    throws IOException {
095    Configuration conf = TEST_UTIL.getConfiguration();
096    String clsName = conf.get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
097    conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, SecureWALCellCodec.class,
098      WALCellCodec.class);
099    try {
100      TableName tableName = TableName.valueOf(tblName);
101      NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
102      scopes.put(tableName.getName(), 0);
103      RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build();
104      final int total = 10;
105      final byte[] row = Bytes.toBytes("row");
106      final byte[] family = Bytes.toBytes("family");
107      final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1);
108
109      // Write the WAL
110      WAL wal = wals.getWAL(regionInfo);
111      for (int i = 0; i < total; i++) {
112        WALEdit kvs = new WALEdit();
113        KeyValue kv = new KeyValue(row, family, Bytes.toBytes(i), value);
114        if (offheap) {
115          ByteBuffer bb = ByteBuffer.allocateDirect(kv.getBuffer().length);
116          bb.put(kv.getBuffer());
117          ByteBufferKeyValue offheapKV = new ByteBufferKeyValue(bb, 0, kv.getLength());
118          kvs.add(offheapKV);
119        } else {
120          kvs.add(kv);
121        }
122        wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName,
123          EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs);
124      }
125      wal.sync();
126      final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal);
127      wal.shutdown();
128
129      return walPath;
130    } finally {
131      // restore the cell codec class
132      conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, clsName);
133    }
134  }
135
136  @Test()
137  public void testWALReaderOnSecureWALWithKeyValues() throws Exception {
138    testSecureWALInternal(false);
139  }
140
141  @Test()
142  public void testWALReaderOnSecureWALWithOffheapKeyValues() throws Exception {
143    testSecureWALInternal(true);
144  }
145
146  private void testSecureWALInternal(boolean offheap) throws IOException, FileNotFoundException {
147    Configuration conf = TEST_UTIL.getConfiguration();
148    conf.setClass("hbase.regionserver.hlog.reader.impl", ProtobufLogReader.class, WAL.Reader.class);
149    conf.setClass("hbase.regionserver.hlog.writer.impl", SecureProtobufLogWriter.class,
150      WALProvider.Writer.class);
151    conf.setClass("hbase.regionserver.hlog.async.writer.impl", SecureAsyncProtobufLogWriter.class,
152      WALProvider.AsyncWriter.class);
153    conf.setBoolean(WAL_ENCRYPTION, true);
154    FileSystem fs = TEST_UTIL.getTestFileSystem();
155    final WALFactory wals = new WALFactory(conf, currentTest.getMethodName());
156    Path walPath = writeWAL(wals, currentTest.getMethodName(), offheap);
157
158    // Insure edits are not plaintext
159    long length = fs.getFileStatus(walPath).getLen();
160    FSDataInputStream in = fs.open(walPath);
161    byte[] fileData = new byte[(int) length];
162    IOUtils.readFully(in, fileData);
163    in.close();
164    assertFalse("Cells appear to be plaintext", Bytes.contains(fileData, value));
165
166    // Confirm the WAL cannot be read back by ProtobufLogReader
167    try {
168      wals.createReader(TEST_UTIL.getTestFileSystem(), walPath);
169      assertFalse(true);
170    } catch (IOException ioe) {
171      System.out.println("Expected ioe " + ioe.getMessage());
172    }
173
174    FileStatus[] listStatus = fs.listStatus(walPath.getParent());
175    Path rootdir = CommonFSUtils.getRootDir(conf);
176    WALSplitter s = new WALSplitter(wals, conf, rootdir, fs, rootdir, fs, null, null, null);
177    WALSplitter.SplitWALResult swr = s.splitWAL(listStatus[0], null);
178    assertTrue(swr.isCorrupt());
179    wals.close();
180  }
181
182  @Test()
183  public void testSecureWALReaderOnWAL() throws Exception {
184    Configuration conf = TEST_UTIL.getConfiguration();
185    conf.setClass("hbase.regionserver.hlog.reader.impl", SecureProtobufLogReader.class,
186      WAL.Reader.class);
187    conf.setClass("hbase.regionserver.hlog.writer.impl", ProtobufLogWriter.class,
188      WALProvider.Writer.class);
189    conf.setBoolean(WAL_ENCRYPTION, false);
190    FileSystem fs = TEST_UTIL.getTestFileSystem();
191    final WALFactory wals = new WALFactory(conf,
192      ServerName.valueOf(currentTest.getMethodName(), 16010, EnvironmentEdgeManager.currentTime())
193        .toString());
194    Path walPath = writeWAL(wals, currentTest.getMethodName(), false);
195
196    // Ensure edits are plaintext
197    long length = fs.getFileStatus(walPath).getLen();
198    FSDataInputStream in = fs.open(walPath);
199    byte[] fileData = new byte[(int) length];
200    IOUtils.readFully(in, fileData);
201    in.close();
202    assertTrue("Cells should be plaintext", Bytes.contains(fileData, value));
203
204    // Confirm the WAL can be read back by SecureProtobufLogReader
205    try {
206      WAL.Reader reader = wals.createReader(TEST_UTIL.getTestFileSystem(), walPath);
207      reader.close();
208    } catch (IOException ioe) {
209      assertFalse(true);
210    }
211
212    FileStatus[] listStatus = fs.listStatus(walPath.getParent());
213    Path rootdir = CommonFSUtils.getRootDir(conf);
214    try {
215      WALSplitter s = new WALSplitter(wals, conf, rootdir, fs, rootdir, fs, null, null, null);
216      s.splitWAL(listStatus[0], null);
217      Path file =
218        new Path(ZKSplitLog.getSplitLogDir(rootdir, listStatus[0].getPath().getName()), "corrupt");
219      assertTrue(!fs.exists(file));
220    } catch (IOException ioe) {
221      assertTrue("WAL should have been processed", false);
222    }
223    wals.close();
224  }
225}