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;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertNull;
024import static org.junit.Assert.assertTrue;
025
026import java.io.IOException;
027import java.net.URI;
028import java.util.Collection;
029import java.util.List;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.fs.FSDataInputStream;
032import org.apache.hadoop.fs.FSDataOutputStream;
033import org.apache.hadoop.fs.FileStatus;
034import org.apache.hadoop.fs.FileSystem;
035import org.apache.hadoop.fs.Path;
036import org.apache.hadoop.fs.permission.FsPermission;
037import org.apache.hadoop.hbase.HBaseClassTestRule;
038import org.apache.hadoop.hbase.HBaseTestingUtility;
039import org.apache.hadoop.hbase.HColumnDescriptor;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.Admin;
042import org.apache.hadoop.hbase.client.Connection;
043import org.apache.hadoop.hbase.client.Put;
044import org.apache.hadoop.hbase.client.RegionInfo;
045import org.apache.hadoop.hbase.client.RegionInfoBuilder;
046import org.apache.hadoop.hbase.client.Table;
047import org.apache.hadoop.hbase.fs.HFileSystem;
048import org.apache.hadoop.hbase.testclassification.MediumTests;
049import org.apache.hadoop.hbase.testclassification.RegionServerTests;
050import org.apache.hadoop.hbase.util.Bytes;
051import org.apache.hadoop.hbase.util.FSUtils;
052import org.apache.hadoop.util.Progressable;
053import org.junit.ClassRule;
054import org.junit.Rule;
055import org.junit.Test;
056import org.junit.experimental.categories.Category;
057import org.junit.rules.TestName;
058import org.slf4j.Logger;
059import org.slf4j.LoggerFactory;
060
061@Category({RegionServerTests.class, MediumTests.class})
062public class TestHRegionFileSystem {
063
064  @ClassRule
065  public static final HBaseClassTestRule CLASS_RULE =
066      HBaseClassTestRule.forClass(TestHRegionFileSystem.class);
067
068  private static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
069  private static final Logger LOG = LoggerFactory.getLogger(TestHRegionFileSystem.class);
070
071  public static final byte[] FAMILY_NAME = Bytes.toBytes("info");
072  private static final byte[][] FAMILIES = {
073    Bytes.add(FAMILY_NAME, Bytes.toBytes("-A")),
074    Bytes.add(FAMILY_NAME, Bytes.toBytes("-B")) };
075  private static final TableName TABLE_NAME = TableName.valueOf("TestTable");
076
077  @Rule
078  public TestName name = new TestName();
079
080  @Test
081  public void testBlockStoragePolicy() throws Exception {
082    TEST_UTIL = new HBaseTestingUtility();
083    Configuration conf = TEST_UTIL.getConfiguration();
084    TEST_UTIL.startMiniCluster();
085    Table table = TEST_UTIL.createTable(TABLE_NAME, FAMILIES);
086    assertEquals("Should start with empty table", 0, TEST_UTIL.countRows(table));
087    HRegionFileSystem regionFs = getHRegionFS(TEST_UTIL.getConnection(), table, conf);
088    // the original block storage policy would be HOT
089    String spA = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[0]));
090    String spB = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[1]));
091    LOG.debug("Storage policy of cf 0: [" + spA + "].");
092    LOG.debug("Storage policy of cf 1: [" + spB + "].");
093    assertEquals("HOT", spA);
094    assertEquals("HOT", spB);
095
096    // Recreate table and make sure storage policy could be set through configuration
097    TEST_UTIL.shutdownMiniCluster();
098    TEST_UTIL.getConfiguration().set(HStore.BLOCK_STORAGE_POLICY_KEY, "WARM");
099    TEST_UTIL.startMiniCluster();
100    table = TEST_UTIL.createTable(TABLE_NAME, FAMILIES);
101    regionFs = getHRegionFS(TEST_UTIL.getConnection(), table, conf);
102
103    try (Admin admin = TEST_UTIL.getConnection().getAdmin()) {
104      spA = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[0]));
105      spB = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[1]));
106      LOG.debug("Storage policy of cf 0: [" + spA + "].");
107      LOG.debug("Storage policy of cf 1: [" + spB + "].");
108      assertEquals("WARM", spA);
109      assertEquals("WARM", spB);
110
111      // alter table cf schema to change storage policies
112      // and make sure it could override settings in conf
113      HColumnDescriptor hcdA = new HColumnDescriptor(Bytes.toString(FAMILIES[0]));
114      // alter through setting HStore#BLOCK_STORAGE_POLICY_KEY in HColumnDescriptor
115      hcdA.setValue(HStore.BLOCK_STORAGE_POLICY_KEY, "ONE_SSD");
116      admin.modifyColumnFamily(TABLE_NAME, hcdA);
117      while (TEST_UTIL.getMiniHBaseCluster().getMaster().getAssignmentManager().
118          getRegionStates().hasRegionsInTransition()) {
119        Thread.sleep(200);
120        LOG.debug("Waiting on table to finish schema altering");
121      }
122      // alter through HColumnDescriptor#setStoragePolicy
123      HColumnDescriptor hcdB = new HColumnDescriptor(Bytes.toString(FAMILIES[1]));
124      hcdB.setStoragePolicy("ALL_SSD");
125      admin.modifyColumnFamily(TABLE_NAME, hcdB);
126      while (TEST_UTIL.getMiniHBaseCluster().getMaster().getAssignmentManager().getRegionStates()
127          .hasRegionsInTransition()) {
128        Thread.sleep(200);
129        LOG.debug("Waiting on table to finish schema altering");
130      }
131      spA = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[0]));
132      spB = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[1]));
133      LOG.debug("Storage policy of cf 0: [" + spA + "].");
134      LOG.debug("Storage policy of cf 1: [" + spB + "].");
135      assertNotNull(spA);
136      assertEquals("ONE_SSD", spA);
137      assertNotNull(spB);
138      assertEquals("ALL_SSD", spB);
139
140      // flush memstore snapshot into 3 files
141      for (long i = 0; i < 3; i++) {
142        Put put = new Put(Bytes.toBytes(i));
143        put.addColumn(FAMILIES[0], Bytes.toBytes(i), Bytes.toBytes(i));
144        table.put(put);
145        admin.flush(TABLE_NAME);
146      }
147      // there should be 3 files in store dir
148      FileSystem fs = TEST_UTIL.getDFSCluster().getFileSystem();
149      Path storePath = regionFs.getStoreDir(Bytes.toString(FAMILIES[0]));
150      FileStatus[] storeFiles = FSUtils.listStatus(fs, storePath);
151      assertNotNull(storeFiles);
152      assertEquals(3, storeFiles.length);
153      // store temp dir still exists but empty
154      Path storeTempDir = new Path(regionFs.getTempDir(), Bytes.toString(FAMILIES[0]));
155      assertTrue(fs.exists(storeTempDir));
156      FileStatus[] tempFiles = FSUtils.listStatus(fs, storeTempDir);
157      assertNull(tempFiles);
158      // storage policy of cf temp dir and 3 store files should be ONE_SSD
159      assertEquals("ONE_SSD",
160        ((HFileSystem) regionFs.getFileSystem()).getStoragePolicyName(storeTempDir));
161      for (FileStatus status : storeFiles) {
162        assertEquals("ONE_SSD",
163          ((HFileSystem) regionFs.getFileSystem()).getStoragePolicyName(status.getPath()));
164      }
165
166      // change storage policies by calling raw api directly
167      regionFs.setStoragePolicy(Bytes.toString(FAMILIES[0]), "ALL_SSD");
168      regionFs.setStoragePolicy(Bytes.toString(FAMILIES[1]), "ONE_SSD");
169      spA = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[0]));
170      spB = regionFs.getStoragePolicyName(Bytes.toString(FAMILIES[1]));
171      LOG.debug("Storage policy of cf 0: [" + spA + "].");
172      LOG.debug("Storage policy of cf 1: [" + spB + "].");
173      assertNotNull(spA);
174      assertEquals("ALL_SSD", spA);
175      assertNotNull(spB);
176      assertEquals("ONE_SSD", spB);
177    } finally {
178      table.close();
179      TEST_UTIL.deleteTable(TABLE_NAME);
180      TEST_UTIL.shutdownMiniCluster();
181    }
182  }
183
184  private HRegionFileSystem getHRegionFS(Connection conn, Table table, Configuration conf)
185      throws IOException {
186    FileSystem fs = TEST_UTIL.getDFSCluster().getFileSystem();
187    Path tableDir = FSUtils.getTableDir(TEST_UTIL.getDefaultRootDirPath(), table.getName());
188    List<Path> regionDirs = FSUtils.getRegionDirs(fs, tableDir);
189    assertEquals(1, regionDirs.size());
190    List<Path> familyDirs = FSUtils.getFamilyDirs(fs, regionDirs.get(0));
191    assertEquals(2, familyDirs.size());
192    RegionInfo hri =
193      conn.getRegionLocator(table.getName()).getAllRegionLocations().get(0).getRegion();
194    HRegionFileSystem regionFs = new HRegionFileSystem(conf, new HFileSystem(fs), tableDir, hri);
195    return regionFs;
196  }
197
198  @Test
199  public void testOnDiskRegionCreation() throws IOException {
200    Path rootDir = TEST_UTIL.getDataTestDirOnTestFS(name.getMethodName());
201    FileSystem fs = TEST_UTIL.getTestFileSystem();
202    Configuration conf = TEST_UTIL.getConfiguration();
203
204    // Create a Region
205    RegionInfo hri = RegionInfoBuilder.newBuilder(TableName.valueOf(name.getMethodName())).build();
206    HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(conf, fs,
207        FSUtils.getTableDir(rootDir, hri.getTable()), hri);
208
209    // Verify if the region is on disk
210    Path regionDir = regionFs.getRegionDir();
211    assertTrue("The region folder should be created", fs.exists(regionDir));
212
213    // Verify the .regioninfo
214    RegionInfo hriVerify = HRegionFileSystem.loadRegionInfoFileContent(fs, regionDir);
215    assertEquals(hri, hriVerify);
216
217    // Open the region
218    regionFs = HRegionFileSystem.openRegionFromFileSystem(conf, fs,
219        FSUtils.getTableDir(rootDir, hri.getTable()), hri, false);
220    assertEquals(regionDir, regionFs.getRegionDir());
221
222    // Delete the region
223    HRegionFileSystem.deleteRegionFromFileSystem(conf, fs,
224        FSUtils.getTableDir(rootDir, hri.getTable()), hri);
225    assertFalse("The region folder should be removed", fs.exists(regionDir));
226
227    fs.delete(rootDir, true);
228  }
229
230  @Test
231  public void testNonIdempotentOpsWithRetries() throws IOException {
232    Path rootDir = TEST_UTIL.getDataTestDirOnTestFS(name.getMethodName());
233    FileSystem fs = TEST_UTIL.getTestFileSystem();
234    Configuration conf = TEST_UTIL.getConfiguration();
235
236    // Create a Region
237    RegionInfo hri = RegionInfoBuilder.newBuilder(TableName.valueOf(name.getMethodName())).build();
238    HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(conf, fs, rootDir, hri);
239    assertTrue(fs.exists(regionFs.getRegionDir()));
240
241    regionFs = new HRegionFileSystem(conf, new MockFileSystemForCreate(), rootDir, hri);
242    boolean result = regionFs.createDir(new Path("/foo/bar"));
243    assertTrue("Couldn't create the directory", result);
244
245    regionFs = new HRegionFileSystem(conf, new MockFileSystem(), rootDir, hri);
246    result = regionFs.rename(new Path("/foo/bar"), new Path("/foo/bar2"));
247    assertTrue("Couldn't rename the directory", result);
248
249    regionFs = new HRegionFileSystem(conf, new MockFileSystem(), rootDir, hri);
250    result = regionFs.deleteDir(new Path("/foo/bar"));
251    assertTrue("Couldn't delete the directory", result);
252    fs.delete(rootDir, true);
253  }
254
255  static class MockFileSystemForCreate extends MockFileSystem {
256    @Override
257    public boolean exists(Path path) {
258      return false;
259    }
260  }
261
262  /**
263   * a mock fs which throws exception for first 3 times, and then process the call (returns the
264   * excepted result).
265   */
266  static class MockFileSystem extends FileSystem {
267    int retryCount;
268    final static int successRetryCount = 3;
269
270    public MockFileSystem() {
271      retryCount = 0;
272    }
273
274    @Override
275    public FSDataOutputStream append(Path arg0, int arg1, Progressable arg2) throws IOException {
276      throw new IOException("");
277    }
278
279    @Override
280    public FSDataOutputStream create(Path arg0, FsPermission arg1, boolean arg2, int arg3,
281        short arg4, long arg5, Progressable arg6) throws IOException {
282      LOG.debug("Create, " + retryCount);
283      if (retryCount++ < successRetryCount) throw new IOException("Something bad happen");
284      return null;
285    }
286
287    @Override
288    public boolean delete(Path arg0) throws IOException {
289      if (retryCount++ < successRetryCount) throw new IOException("Something bad happen");
290      return true;
291    }
292
293    @Override
294    public boolean delete(Path arg0, boolean arg1) throws IOException {
295      if (retryCount++ < successRetryCount) throw new IOException("Something bad happen");
296      return true;
297    }
298
299    @Override
300    public FileStatus getFileStatus(Path arg0) throws IOException {
301      FileStatus fs = new FileStatus();
302      return fs;
303    }
304
305    @Override
306    public boolean exists(Path path) {
307      return true;
308    }
309
310    @Override
311    public URI getUri() {
312      throw new RuntimeException("Something bad happen");
313    }
314
315    @Override
316    public Path getWorkingDirectory() {
317      throw new RuntimeException("Something bad happen");
318    }
319
320    @Override
321    public FileStatus[] listStatus(Path arg0) throws IOException {
322      throw new IOException("Something bad happen");
323    }
324
325    @Override
326    public boolean mkdirs(Path arg0, FsPermission arg1) throws IOException {
327      LOG.debug("mkdirs, " + retryCount);
328      if (retryCount++ < successRetryCount) throw new IOException("Something bad happen");
329      return true;
330    }
331
332    @Override
333    public FSDataInputStream open(Path arg0, int arg1) throws IOException {
334      throw new IOException("Something bad happen");
335    }
336
337    @Override
338    public boolean rename(Path arg0, Path arg1) throws IOException {
339      LOG.debug("rename, " + retryCount);
340      if (retryCount++ < successRetryCount) throw new IOException("Something bad happen");
341      return true;
342    }
343
344    @Override
345    public void setWorkingDirectory(Path arg0) {
346      throw new RuntimeException("Something bad happen");
347    }
348  }
349
350  @Test
351  public void testTempAndCommit() throws IOException {
352    Path rootDir = TEST_UTIL.getDataTestDirOnTestFS("testTempAndCommit");
353    FileSystem fs = TEST_UTIL.getTestFileSystem();
354    Configuration conf = TEST_UTIL.getConfiguration();
355
356    // Create a Region
357    String familyName = "cf";
358
359    RegionInfo hri = RegionInfoBuilder.newBuilder(TableName.valueOf(name.getMethodName())).build();
360    HRegionFileSystem regionFs = HRegionFileSystem.createRegionOnFileSystem(conf, fs, rootDir, hri);
361
362    // New region, no store files
363    Collection<StoreFileInfo> storeFiles = regionFs.getStoreFiles(familyName);
364    assertEquals(0, storeFiles != null ? storeFiles.size() : 0);
365
366    // Create a new file in temp (no files in the family)
367    Path buildPath = regionFs.createTempName();
368    fs.createNewFile(buildPath);
369    storeFiles = regionFs.getStoreFiles(familyName);
370    assertEquals(0, storeFiles != null ? storeFiles.size() : 0);
371
372    // commit the file
373    Path dstPath = regionFs.commitStoreFile(familyName, buildPath);
374    storeFiles = regionFs.getStoreFiles(familyName);
375    assertEquals(0, storeFiles != null ? storeFiles.size() : 0);
376    assertFalse(fs.exists(buildPath));
377
378    fs.delete(rootDir, true);
379  }
380}