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;
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.nio.ByteBuffer;
025import java.util.NavigableMap;
026import java.util.TreeMap;
027import org.apache.commons.io.IOUtils;
028import org.apache.hadoop.conf.Configuration;
029import org.apache.hadoop.fs.FSDataInputStream;
030import org.apache.hadoop.fs.FileStatus;
031import org.apache.hadoop.fs.FileSystem;
032import org.apache.hadoop.fs.Path;
033import org.apache.hadoop.hbase.ByteBufferKeyValue;
034import org.apache.hadoop.hbase.HBaseClassTestRule;
035import org.apache.hadoop.hbase.HBaseTestingUtil;
036import org.apache.hadoop.hbase.HConstants;
037import org.apache.hadoop.hbase.KeyValue;
038import org.apache.hadoop.hbase.ServerName;
039import org.apache.hadoop.hbase.TableName;
040import org.apache.hadoop.hbase.client.RegionInfo;
041import org.apache.hadoop.hbase.client.RegionInfoBuilder;
042import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
043import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
044import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
045import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter;
046import org.apache.hadoop.hbase.regionserver.wal.SecureAsyncProtobufLogWriter;
047import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogReader;
048import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogWriter;
049import org.apache.hadoop.hbase.regionserver.wal.SecureWALCellCodec;
050import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
051import org.apache.hadoop.hbase.testclassification.RegionServerTests;
052import org.apache.hadoop.hbase.testclassification.SmallTests;
053import org.apache.hadoop.hbase.util.Bytes;
054import org.apache.hadoop.hbase.util.CommonFSUtils;
055import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
056import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
057import org.junit.BeforeClass;
058import org.junit.ClassRule;
059import org.junit.Rule;
060import org.junit.Test;
061import org.junit.experimental.categories.Category;
062import org.junit.rules.TestName;
063
064/**
065 * Test that verifies WAL written by SecureProtobufLogWriter is not readable by ProtobufLogReader
066 */
067@Category({RegionServerTests.class, SmallTests.class})
068public class TestWALReaderOnSecureWAL {
069
070  @ClassRule
071  public static final HBaseClassTestRule CLASS_RULE =
072      HBaseClassTestRule.forClass(TestWALReaderOnSecureWAL.class);
073
074  static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
075  final byte[] value = Bytes.toBytes("Test value");
076
077  private static final String WAL_ENCRYPTION = "hbase.regionserver.wal.encryption";
078
079  @Rule
080  public TestName currentTest = new TestName();
081
082  @BeforeClass
083  public static void setUpBeforeClass() throws Exception {
084    Configuration conf = TEST_UTIL.getConfiguration();
085    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
086    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
087    conf.setBoolean(WALSplitter.SPLIT_SKIP_ERRORS_KEY, true);
088    conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
089    CommonFSUtils.setRootDir(conf, TEST_UTIL.getDataTestDir());
090  }
091
092  private Path writeWAL(final WALFactory wals, final String tblName, boolean offheap)
093      throws IOException {
094    Configuration conf = TEST_UTIL.getConfiguration();
095    String clsName = conf.get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
096    conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, SecureWALCellCodec.class,
097      WALCellCodec.class);
098    try {
099      TableName tableName = TableName.valueOf(tblName);
100      NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
101      scopes.put(tableName.getName(), 0);
102      RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build();
103      final int total = 10;
104      final byte[] row = Bytes.toBytes("row");
105      final byte[] family = Bytes.toBytes("family");
106      final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1);
107
108      // Write the WAL
109      WAL wal = wals.getWAL(regionInfo);
110      for (int i = 0; i < total; i++) {
111        WALEdit kvs = new WALEdit();
112        KeyValue kv = new KeyValue(row, family, Bytes.toBytes(i), value);
113        if (offheap) {
114          ByteBuffer bb = ByteBuffer.allocateDirect(kv.getBuffer().length);
115          bb.put(kv.getBuffer());
116          ByteBufferKeyValue offheapKV = new ByteBufferKeyValue(bb, 0, kv.getLength());
117          kvs.add(offheapKV);
118        } else {
119          kvs.add(kv);
120        }
121        wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName,
122          EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs);
123      }
124      wal.sync();
125      final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal);
126      wal.shutdown();
127
128      return walPath;
129    } finally {
130      // restore the cell codec class
131      conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, clsName);
132    }
133  }
134
135  @Test()
136  public void testWALReaderOnSecureWALWithKeyValues() throws Exception {
137    testSecureWALInternal(false);
138  }
139
140  @Test()
141  public void testWALReaderOnSecureWALWithOffheapKeyValues() throws Exception {
142    testSecureWALInternal(true);
143  }
144
145  private void testSecureWALInternal(boolean offheap) throws IOException, FileNotFoundException {
146    Configuration conf = TEST_UTIL.getConfiguration();
147    conf.setClass("hbase.regionserver.hlog.reader.impl", ProtobufLogReader.class,
148      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, ServerName
192      .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 = new Path(ZKSplitLog.getSplitLogDir(rootdir, listStatus[0].getPath().getName()),
218        "corrupt");
219      assertTrue(!fs.exists(file));
220    } catch (IOException ioe) {
221      assertTrue("WAL should have been processed", false);
222    }
223    wals.close();
224  }
225}