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.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertTrue;
023
024import java.util.Arrays;
025import java.util.List;
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.FileSystem;
032import org.apache.hadoop.fs.Path;
033import org.apache.hadoop.hbase.Cell;
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.TableName;
039import org.apache.hadoop.hbase.client.RegionInfo;
040import org.apache.hadoop.hbase.client.RegionInfoBuilder;
041import org.apache.hadoop.hbase.io.crypto.MockAesKeyProvider;
042import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
043import org.apache.hadoop.hbase.testclassification.MediumTests;
044import org.apache.hadoop.hbase.testclassification.RegionServerTests;
045import org.apache.hadoop.hbase.util.Bytes;
046import org.apache.hadoop.hbase.util.CommonFSUtils;
047import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
048import org.junit.AfterClass;
049import org.junit.Before;
050import org.junit.BeforeClass;
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.junit.runner.RunWith;
057import org.junit.runners.Parameterized;
058import org.junit.runners.Parameterized.Parameter;
059import org.junit.runners.Parameterized.Parameters;
060
061@RunWith(Parameterized.class)
062@Category({ RegionServerTests.class, MediumTests.class })
063public class TestSecureWAL {
064
065  @ClassRule
066  public static final HBaseClassTestRule CLASS_RULE =
067    HBaseClassTestRule.forClass(TestSecureWAL.class);
068
069  static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
070
071  @Rule
072  public TestName name = new TestName();
073
074  @Parameter
075  public String walProvider;
076
077  @Parameters(name = "{index}: provider={0}")
078  public static Iterable<Object[]> data() {
079    return Arrays.asList(new Object[] { "defaultProvider" }, new Object[] { "asyncfs" });
080  }
081
082  @BeforeClass
083  public static void setUpBeforeClass() throws Exception {
084    Configuration conf = TEST_UTIL.getConfiguration();
085    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, MockAesKeyProvider.class.getName());
086    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
087    conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
088    CommonFSUtils.setRootDir(conf, TEST_UTIL.getDataTestDirOnTestFS());
089    TEST_UTIL.startMiniDFSCluster(3);
090  }
091
092  @AfterClass
093  public static void tearDownAfterClass() throws Exception {
094    TEST_UTIL.shutdownMiniCluster();
095  }
096
097  @Before
098  public void setUp() {
099    TEST_UTIL.getConfiguration().set(WALFactory.WAL_PROVIDER, walProvider);
100  }
101
102  @Test
103  public void testSecureWAL() throws Exception {
104    TableName tableName = TableName.valueOf(name.getMethodName().replaceAll("[^a-zA-Z0-9]", "_"));
105    NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
106    scopes.put(tableName.getName(), 0);
107    RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build();
108    final int total = 10;
109    final byte[] row = Bytes.toBytes("row");
110    final byte[] family = Bytes.toBytes("family");
111    final byte[] value = Bytes.toBytes("Test value");
112    FileSystem fs = TEST_UTIL.getDFSCluster().getFileSystem();
113    final WALFactory wals =
114      new WALFactory(TEST_UTIL.getConfiguration(), tableName.getNameAsString());
115
116    // Write the WAL
117    final WAL wal = wals.getWAL(regionInfo);
118
119    MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl();
120
121    for (int i = 0; i < total; i++) {
122      WALEdit kvs = new WALEdit();
123      kvs.add(new KeyValue(row, family, Bytes.toBytes(i), value));
124      wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName,
125        EnvironmentEdgeManager.currentTime(), mvcc, scopes), kvs);
126    }
127    wal.sync();
128    final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal);
129    wals.shutdown();
130
131    // Insure edits are not plaintext
132    long length = fs.getFileStatus(walPath).getLen();
133    FSDataInputStream in = fs.open(walPath);
134    byte[] fileData = new byte[(int) length];
135    IOUtils.readFully(in, fileData);
136    in.close();
137    assertFalse("Cells appear to be plaintext", Bytes.contains(fileData, value));
138
139    // Confirm the WAL can be read back
140    int count = 0;
141    try (WALStreamReader reader = wals.createStreamReader(TEST_UTIL.getTestFileSystem(), walPath)) {
142      WAL.Entry entry = new WAL.Entry();
143      while (reader.next(entry) != null) {
144        count++;
145        List<Cell> cells = entry.getEdit().getCells();
146        assertTrue("Should be one KV per WALEdit", cells.size() == 1);
147        for (Cell cell : cells) {
148          assertTrue("Incorrect row", Bytes.equals(cell.getRowArray(), cell.getRowOffset(),
149            cell.getRowLength(), row, 0, row.length));
150          assertTrue("Incorrect family", Bytes.equals(cell.getFamilyArray(), cell.getFamilyOffset(),
151            cell.getFamilyLength(), family, 0, family.length));
152          assertTrue("Incorrect value", Bytes.equals(cell.getValueArray(), cell.getValueOffset(),
153            cell.getValueLength(), value, 0, value.length));
154        }
155      }
156      assertEquals("Should have read back as many KVs as written", total, count);
157    }
158  }
159}