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.util;
019
020import static org.junit.jupiter.api.Assertions.assertEquals;
021import static org.junit.jupiter.api.Assertions.assertFalse;
022import static org.junit.jupiter.api.Assertions.assertNotEquals;
023import static org.junit.jupiter.api.Assertions.assertNotNull;
024import static org.junit.jupiter.api.Assertions.assertNull;
025import static org.junit.jupiter.api.Assertions.assertSame;
026import static org.junit.jupiter.api.Assertions.assertTrue;
027import static org.junit.jupiter.api.Assertions.fail;
028
029import java.io.File;
030import java.io.IOException;
031import java.io.InterruptedIOException;
032import java.net.URI;
033import java.net.URISyntaxException;
034import java.util.List;
035import java.util.Random;
036import java.util.concurrent.CompletableFuture;
037import java.util.concurrent.atomic.AtomicInteger;
038import org.apache.hadoop.conf.Configuration;
039import org.apache.hadoop.fs.FSDataInputStream;
040import org.apache.hadoop.fs.FSDataOutputStream;
041import org.apache.hadoop.fs.FileStatus;
042import org.apache.hadoop.fs.FileSystem;
043import org.apache.hadoop.fs.FilterFileSystem;
044import org.apache.hadoop.fs.FutureDataInputStreamBuilder;
045import org.apache.hadoop.fs.LocalFileSystem;
046import org.apache.hadoop.fs.Path;
047import org.apache.hadoop.fs.StreamCapabilities;
048import org.apache.hadoop.fs.permission.FsPermission;
049import org.apache.hadoop.hbase.HBaseConfiguration;
050import org.apache.hadoop.hbase.HBaseTestingUtil;
051import org.apache.hadoop.hbase.HConstants;
052import org.apache.hadoop.hbase.HDFSBlocksDistribution;
053import org.apache.hadoop.hbase.client.RegionInfoBuilder;
054import org.apache.hadoop.hbase.exceptions.DeserializationException;
055import org.apache.hadoop.hbase.fs.HFileSystem;
056import org.apache.hadoop.hbase.testclassification.MediumTests;
057import org.apache.hadoop.hbase.testclassification.MiscTests;
058import org.apache.hadoop.hdfs.DFSConfigKeys;
059import org.apache.hadoop.hdfs.DFSHedgedReadMetrics;
060import org.apache.hadoop.hdfs.DFSTestUtil;
061import org.apache.hadoop.hdfs.DistributedFileSystem;
062import org.apache.hadoop.hdfs.MiniDFSCluster;
063import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
064import org.junit.jupiter.api.BeforeEach;
065import org.junit.jupiter.api.Tag;
066import org.junit.jupiter.api.Test;
067import org.slf4j.Logger;
068import org.slf4j.LoggerFactory;
069
070/**
071 * Test {@link FSUtils}.
072 */
073@Tag(MiscTests.TAG)
074@Tag(MediumTests.TAG)
075public class TestFSUtils {
076
077  private static final Logger LOG = LoggerFactory.getLogger(TestFSUtils.class);
078
079  private HBaseTestingUtil htu;
080  private FileSystem fs;
081  private Configuration conf;
082
083  @BeforeEach
084  public void setUp() throws IOException {
085    htu = new HBaseTestingUtil();
086    fs = htu.getTestFileSystem();
087    conf = htu.getConfiguration();
088  }
089
090  @Test
091  public void testIsHDFS() throws Exception {
092    assertFalse(CommonFSUtils.isHDFS(conf));
093    MiniDFSCluster cluster = null;
094    try {
095      cluster = htu.startMiniDFSCluster(1);
096      assertTrue(CommonFSUtils.isHDFS(conf));
097      assertTrue(FSUtils.supportSafeMode(cluster.getFileSystem()));
098      FSUtils.checkDfsSafeMode(conf);
099    } finally {
100      if (cluster != null) {
101        cluster.shutdown();
102      }
103    }
104  }
105
106  @Test
107  public void testLocalFileSystemSafeMode() throws Exception {
108    conf.setClass("fs.file.impl", LocalFileSystem.class, FileSystem.class);
109    assertFalse(CommonFSUtils.isHDFS(conf));
110    assertFalse(FSUtils.supportSafeMode(FileSystem.get(conf)));
111    FSUtils.checkDfsSafeMode(conf);
112  }
113
114  private void WriteDataToHDFS(FileSystem fs, Path file, int dataSize) throws Exception {
115    FSDataOutputStream out = fs.create(file);
116    byte[] data = new byte[dataSize];
117    out.write(data, 0, dataSize);
118    out.close();
119  }
120
121  @Test
122  public void testComputeHDFSBlocksDistributionByInputStream() throws Exception {
123    testComputeHDFSBlocksDistribution((fs, testFile) -> {
124      try (FSDataInputStream open = fs.open(testFile)) {
125        assertTrue(open instanceof HdfsDataInputStream);
126        return FSUtils.computeHDFSBlocksDistribution((HdfsDataInputStream) open);
127      }
128    });
129  }
130
131  @Test
132  public void testComputeHDFSBlockDistribution() throws Exception {
133    testComputeHDFSBlocksDistribution((fs, testFile) -> {
134      FileStatus status = fs.getFileStatus(testFile);
135      return FSUtils.computeHDFSBlocksDistribution(fs, status, 0, status.getLen());
136    });
137  }
138
139  @FunctionalInterface
140  interface HDFSBlockDistributionFunction {
141    HDFSBlocksDistribution getForPath(FileSystem fs, Path path) throws IOException;
142  }
143
144  private void testComputeHDFSBlocksDistribution(
145    HDFSBlockDistributionFunction fileToBlockDistribution) throws Exception {
146    final int DEFAULT_BLOCK_SIZE = 1024;
147    conf.setLong("dfs.blocksize", DEFAULT_BLOCK_SIZE);
148    MiniDFSCluster cluster = null;
149    Path testFile = null;
150
151    try {
152      // set up a cluster with 3 nodes
153      String hosts[] = new String[] { "host1", "host2", "host3" };
154      cluster = htu.startMiniDFSCluster(hosts);
155      cluster.waitActive();
156      FileSystem fs = cluster.getFileSystem();
157
158      // create a file with two blocks
159      testFile = new Path("/test1.txt");
160      WriteDataToHDFS(fs, testFile, 2 * DEFAULT_BLOCK_SIZE);
161
162      // given the default replication factor is 3, the same as the number of
163      // datanodes; the locality index for each host should be 100%,
164      // or getWeight for each host should be the same as getUniqueBlocksWeights
165      final long maxTime = EnvironmentEdgeManager.currentTime() + 2000;
166      boolean ok;
167      do {
168        ok = true;
169
170        HDFSBlocksDistribution blocksDistribution =
171          fileToBlockDistribution.getForPath(fs, testFile);
172
173        long uniqueBlocksTotalWeight = blocksDistribution.getUniqueBlocksTotalWeight();
174        for (String host : hosts) {
175          long weight = blocksDistribution.getWeight(host);
176          ok = (ok && uniqueBlocksTotalWeight == weight);
177        }
178      } while (!ok && EnvironmentEdgeManager.currentTime() < maxTime);
179      assertTrue(ok);
180    } finally {
181      htu.shutdownMiniDFSCluster();
182    }
183
184    try {
185      // set up a cluster with 4 nodes
186      String hosts[] = new String[] { "host1", "host2", "host3", "host4" };
187      cluster = htu.startMiniDFSCluster(hosts);
188      cluster.waitActive();
189      FileSystem fs = cluster.getFileSystem();
190
191      // create a file with three blocks
192      testFile = new Path("/test2.txt");
193      WriteDataToHDFS(fs, testFile, 3 * DEFAULT_BLOCK_SIZE);
194
195      // given the default replication factor is 3, we will have total of 9
196      // replica of blocks; thus the host with the highest weight should have
197      // weight == 3 * DEFAULT_BLOCK_SIZE
198      final long maxTime = EnvironmentEdgeManager.currentTime() + 2000;
199      long weight;
200      long uniqueBlocksTotalWeight;
201      do {
202        HDFSBlocksDistribution blocksDistribution =
203          fileToBlockDistribution.getForPath(fs, testFile);
204        uniqueBlocksTotalWeight = blocksDistribution.getUniqueBlocksTotalWeight();
205
206        String tophost = blocksDistribution.getTopHosts().get(0);
207        weight = blocksDistribution.getWeight(tophost);
208
209        // NameNode is informed asynchronously, so we may have a delay. See HBASE-6175
210      } while (uniqueBlocksTotalWeight != weight && EnvironmentEdgeManager.currentTime() < maxTime);
211      assertTrue(uniqueBlocksTotalWeight == weight);
212
213    } finally {
214      htu.shutdownMiniDFSCluster();
215    }
216
217    try {
218      // set up a cluster with 4 nodes
219      String hosts[] = new String[] { "host1", "host2", "host3", "host4" };
220      cluster = htu.startMiniDFSCluster(hosts);
221      cluster.waitActive();
222      FileSystem fs = cluster.getFileSystem();
223
224      // create a file with one block
225      testFile = new Path("/test3.txt");
226      WriteDataToHDFS(fs, testFile, DEFAULT_BLOCK_SIZE);
227
228      // given the default replication factor is 3, we will have total of 3
229      // replica of blocks; thus there is one host without weight
230      final long maxTime = EnvironmentEdgeManager.currentTime() + 2000;
231      HDFSBlocksDistribution blocksDistribution;
232      do {
233        blocksDistribution = fileToBlockDistribution.getForPath(fs, testFile);
234        // NameNode is informed asynchronously, so we may have a delay. See HBASE-6175
235      } while (
236        blocksDistribution.getTopHosts().size() != 3
237          && EnvironmentEdgeManager.currentTime() < maxTime
238      );
239      assertEquals(3, blocksDistribution.getTopHosts().size(),
240        "Wrong number of hosts distributing blocks.");
241    } finally {
242      htu.shutdownMiniDFSCluster();
243    }
244  }
245
246  private void writeVersionFile(Path versionFile, String version) throws IOException {
247    if (CommonFSUtils.isExists(fs, versionFile)) {
248      assertTrue(CommonFSUtils.delete(fs, versionFile, true));
249    }
250    try (FSDataOutputStream s = fs.create(versionFile)) {
251      s.writeUTF(version);
252    }
253    assertTrue(fs.exists(versionFile));
254  }
255
256  @Test
257  public void testVersion() throws DeserializationException, IOException {
258    final Path rootdir = htu.getDataTestDir();
259    final FileSystem fs = rootdir.getFileSystem(conf);
260    assertNull(FSUtils.getVersion(fs, rootdir));
261    // No meta dir so no complaint from checkVersion.
262    // Presumes it a new install. Will create version file.
263    FSUtils.checkVersion(fs, rootdir, true);
264    // Now remove the version file and create a metadir so checkVersion fails.
265    Path versionFile = new Path(rootdir, HConstants.VERSION_FILE_NAME);
266    assertTrue(CommonFSUtils.isExists(fs, versionFile));
267    assertTrue(CommonFSUtils.delete(fs, versionFile, true));
268    Path metaRegionDir =
269      FSUtils.getRegionDirFromRootDir(rootdir, RegionInfoBuilder.FIRST_META_REGIONINFO);
270    FsPermission defaultPerms =
271      CommonFSUtils.getFilePermissions(fs, this.conf, HConstants.DATA_FILE_UMASK_KEY);
272    CommonFSUtils.create(fs, metaRegionDir, defaultPerms, false);
273    boolean thrown = false;
274    try {
275      FSUtils.checkVersion(fs, rootdir, true);
276    } catch (FileSystemVersionException e) {
277      thrown = true;
278    }
279    assertTrue(thrown, "Expected FileSystemVersionException");
280    // Write out a good version file. See if we can read it in and convert.
281    String version = HConstants.FILE_SYSTEM_VERSION;
282    writeVersionFile(versionFile, version);
283    FileStatus[] status = fs.listStatus(versionFile);
284    assertNotNull(status);
285    assertTrue(status.length > 0);
286    String newVersion = FSUtils.getVersion(fs, rootdir);
287    assertEquals(version.length(), newVersion.length());
288    assertEquals(version, newVersion);
289    // File will have been converted. Exercise the pb format
290    assertEquals(version, FSUtils.getVersion(fs, rootdir));
291    FSUtils.checkVersion(fs, rootdir, true);
292    // Write an old version file.
293    String oldVersion = "1";
294    writeVersionFile(versionFile, oldVersion);
295    newVersion = FSUtils.getVersion(fs, rootdir);
296    assertNotEquals(version, newVersion);
297    thrown = false;
298    try {
299      FSUtils.checkVersion(fs, rootdir, true);
300    } catch (FileSystemVersionException e) {
301      thrown = true;
302    }
303    assertTrue(thrown, "Expected FileSystemVersionException");
304  }
305
306  @Test
307  public void testPermMask() throws Exception {
308    final Path rootdir = htu.getDataTestDir();
309    final FileSystem fs = rootdir.getFileSystem(conf);
310    // default fs permission
311    FsPermission defaultFsPerm =
312      CommonFSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
313    // 'hbase.data.umask.enable' is false. We will get default fs permission.
314    assertEquals(FsPermission.getFileDefault(), defaultFsPerm);
315
316    conf.setBoolean(HConstants.ENABLE_DATA_FILE_UMASK, true);
317    // first check that we don't crash if we don't have perms set
318    FsPermission defaultStartPerm =
319      CommonFSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
320    // default 'hbase.data.umask'is 000, and this umask will be used when
321    // 'hbase.data.umask.enable' is true.
322    // Therefore we will not get the real fs default in this case.
323    // Instead we will get the starting point FULL_RWX_PERMISSIONS
324    assertEquals(new FsPermission(CommonFSUtils.FULL_RWX_PERMISSIONS), defaultStartPerm);
325
326    conf.setStrings(HConstants.DATA_FILE_UMASK_KEY, "077");
327    // now check that we get the right perms
328    FsPermission filePerm =
329      CommonFSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
330    assertEquals(new FsPermission("700"), filePerm);
331
332    // then that the correct file is created
333    Path p = new Path("target" + File.separator + HBaseTestingUtil.getRandomUUID().toString());
334    try {
335      FSDataOutputStream out = FSUtils.create(conf, fs, p, filePerm, null);
336      out.close();
337      FileStatus stat = fs.getFileStatus(p);
338      assertEquals(new FsPermission("700"), stat.getPermission());
339      // and then cleanup
340    } finally {
341      fs.delete(p, true);
342    }
343  }
344
345  @Test
346  public void testDeleteAndExists() throws Exception {
347    final Path rootdir = htu.getDataTestDir();
348    final FileSystem fs = rootdir.getFileSystem(conf);
349    conf.setBoolean(HConstants.ENABLE_DATA_FILE_UMASK, true);
350    FsPermission perms = CommonFSUtils.getFilePermissions(fs, conf, HConstants.DATA_FILE_UMASK_KEY);
351    // then that the correct file is created
352    String file = HBaseTestingUtil.getRandomUUID().toString();
353    Path p = new Path(htu.getDataTestDir(), "temptarget" + File.separator + file);
354    Path p1 = new Path(htu.getDataTestDir(), "temppath" + File.separator + file);
355    try {
356      FSDataOutputStream out = FSUtils.create(conf, fs, p, perms, null);
357      out.close();
358      assertTrue(CommonFSUtils.isExists(fs, p), "The created file should be present");
359      // delete the file with recursion as false. Only the file will be deleted.
360      CommonFSUtils.delete(fs, p, false);
361      // Create another file
362      FSDataOutputStream out1 = FSUtils.create(conf, fs, p1, perms, null);
363      out1.close();
364      // delete the file with recursion as false. Still the file only will be deleted
365      CommonFSUtils.delete(fs, p1, true);
366      assertFalse(CommonFSUtils.isExists(fs, p1), "The created file should be present");
367      // and then cleanup
368    } finally {
369      CommonFSUtils.delete(fs, p, true);
370      CommonFSUtils.delete(fs, p1, true);
371    }
372  }
373
374  @Test
375  public void testFilteredStatusDoesNotThrowOnNotFound() throws Exception {
376    MiniDFSCluster cluster = htu.startMiniDFSCluster(1);
377    try {
378      assertNull(FSUtils.listStatusWithStatusFilter(cluster.getFileSystem(),
379        new Path("definitely/doesn't/exist"), null));
380    } finally {
381      cluster.shutdown();
382    }
383
384  }
385
386  @Test
387  public void testRenameAndSetModifyTime() throws Exception {
388    MiniDFSCluster cluster = htu.startMiniDFSCluster(1);
389    assertTrue(CommonFSUtils.isHDFS(conf));
390
391    FileSystem fs = FileSystem.get(conf);
392    Path testDir = htu.getDataTestDirOnTestFS("testArchiveFile");
393
394    String file = HBaseTestingUtil.getRandomUUID().toString();
395    Path p = new Path(testDir, file);
396
397    FSDataOutputStream out = fs.create(p);
398    out.close();
399    assertTrue(CommonFSUtils.isExists(fs, p), "The created file should be present");
400
401    long expect = EnvironmentEdgeManager.currentTime() + 1000;
402    assertNotEquals(expect, fs.getFileStatus(p).getModificationTime());
403
404    ManualEnvironmentEdge mockEnv = new ManualEnvironmentEdge();
405    mockEnv.setValue(expect);
406    EnvironmentEdgeManager.injectEdge(mockEnv);
407    try {
408      String dstFile = HBaseTestingUtil.getRandomUUID().toString();
409      Path dst = new Path(testDir, dstFile);
410
411      assertTrue(CommonFSUtils.renameAndSetModifyTime(fs, p, dst));
412      assertFalse(CommonFSUtils.isExists(fs, p), "The moved file should not be present");
413      assertTrue(CommonFSUtils.isExists(fs, dst), "The dst file should be present");
414
415      assertEquals(expect, fs.getFileStatus(dst).getModificationTime());
416      cluster.shutdown();
417    } finally {
418      EnvironmentEdgeManager.reset();
419    }
420  }
421
422  @Test
423  public void testSetStoragePolicyDefault() throws Exception {
424    verifyNoHDFSApiInvocationForDefaultPolicy();
425    verifyFileInDirWithStoragePolicy(HConstants.DEFAULT_WAL_STORAGE_POLICY);
426  }
427
428  /**
429   * Note: currently the default policy is set to defer to HDFS and this case is to verify the
430   * logic, will need to remove the check if the default policy is changed
431   */
432  private void verifyNoHDFSApiInvocationForDefaultPolicy() throws URISyntaxException, IOException {
433    FileSystem testFs = new AlwaysFailSetStoragePolicyFileSystem();
434    testFs.initialize(new URI("hdfs://localhost/"), conf);
435    // There should be no exception thrown when setting to default storage policy, which indicates
436    // the HDFS API hasn't been called
437    try {
438      CommonFSUtils.setStoragePolicy(testFs, new Path("non-exist"),
439        HConstants.DEFAULT_WAL_STORAGE_POLICY, true);
440    } catch (IOException e) {
441      fail("Should have bypassed the FS API when setting default storage policy");
442    }
443    // There should be exception thrown when given non-default storage policy, which indicates the
444    // HDFS API has been called
445    try {
446      CommonFSUtils.setStoragePolicy(testFs, new Path("non-exist"), "HOT", true);
447      fail("Should have invoked the FS API but haven't");
448    } catch (IOException e) {
449      // expected given an invalid path
450    }
451  }
452
453  class AlwaysFailSetStoragePolicyFileSystem extends DistributedFileSystem {
454    @Override
455    public void setStoragePolicy(final Path src, final String policyName) throws IOException {
456      throw new IOException("The setStoragePolicy method is invoked");
457    }
458  }
459
460  /* might log a warning, but still work. (always warning on Hadoop < 2.6.0) */
461  @Test
462  public void testSetStoragePolicyValidButMaybeNotPresent() throws Exception {
463    verifyFileInDirWithStoragePolicy("ALL_SSD");
464  }
465
466  final String INVALID_STORAGE_POLICY = "1772";
467
468  /* should log a warning, but still work. (different warning on Hadoop < 2.6.0) */
469  @Test
470  public void testSetStoragePolicyInvalid() throws Exception {
471    verifyFileInDirWithStoragePolicy(INVALID_STORAGE_POLICY);
472  }
473
474  // Here instead of TestCommonFSUtils because we need a minicluster
475  private void verifyFileInDirWithStoragePolicy(final String policy) throws Exception {
476    conf.set(HConstants.WAL_STORAGE_POLICY, policy);
477
478    MiniDFSCluster cluster = htu.startMiniDFSCluster(1);
479    try {
480      assertTrue(CommonFSUtils.isHDFS(conf));
481
482      FileSystem fs = FileSystem.get(conf);
483      Path testDir = htu.getDataTestDirOnTestFS("testArchiveFile");
484      fs.mkdirs(testDir);
485
486      String storagePolicy =
487        conf.get(HConstants.WAL_STORAGE_POLICY, HConstants.DEFAULT_WAL_STORAGE_POLICY);
488      CommonFSUtils.setStoragePolicy(fs, testDir, storagePolicy);
489
490      String file = HBaseTestingUtil.getRandomUUID().toString();
491      Path p = new Path(testDir, file);
492      WriteDataToHDFS(fs, p, 4096);
493      HFileSystem hfs = new HFileSystem(fs);
494      String policySet = hfs.getStoragePolicyName(p);
495      LOG.debug("The storage policy of path " + p + " is " + policySet);
496      if (
497        policy.equals(HConstants.DEFER_TO_HDFS_STORAGE_POLICY)
498          || policy.equals(INVALID_STORAGE_POLICY)
499      ) {
500        String hdfsDefaultPolicy = hfs.getStoragePolicyName(hfs.getHomeDirectory());
501        LOG.debug("The default hdfs storage policy (indicated by home path: "
502          + hfs.getHomeDirectory() + ") is " + hdfsDefaultPolicy);
503        assertEquals(hdfsDefaultPolicy, policySet);
504      } else {
505        assertEquals(policy, policySet);
506      }
507      // will assert existence before deleting.
508      cleanupFile(fs, testDir);
509    } finally {
510      cluster.shutdown();
511    }
512  }
513
514  /**
515   * Ugly test that ensures we can get at the hedged read counters in dfsclient. Does a bit of
516   * preading with hedged reads enabled using code taken from hdfs TestPread.
517   */
518  @Test
519  public void testDFSHedgedReadMetrics() throws Exception {
520    // Enable hedged reads and set it so the threshold is really low.
521    // Most of this test is taken from HDFS, from TestPread.
522    conf.setInt(DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THREADPOOL_SIZE, 5);
523    conf.setLong(DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THRESHOLD_MILLIS, 0);
524    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 4096);
525    conf.setLong(DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY, 4096);
526    // Set short retry timeouts so this test runs faster
527    conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, 0);
528    conf.setBoolean("dfs.datanode.transferTo.allowed", false);
529    // disable metrics logger since it depend on commons-logging internal classes and we do not want
530    // commons-logging on our classpath
531    conf.setInt(DFSConfigKeys.DFS_NAMENODE_METRICS_LOGGER_PERIOD_SECONDS_KEY, 0);
532    conf.setInt(DFSConfigKeys.DFS_DATANODE_METRICS_LOGGER_PERIOD_SECONDS_KEY, 0);
533    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
534    // Get the metrics. Should be empty.
535    DFSHedgedReadMetrics metrics = FSUtils.getDFSHedgedReadMetrics(conf);
536    assertEquals(0, metrics.getHedgedReadOps());
537    FileSystem fileSys = cluster.getFileSystem();
538    try {
539      Path p = new Path("preadtest.dat");
540      // We need > 1 blocks to test out the hedged reads.
541      DFSTestUtil.createFile(fileSys, p, 12 * blockSize, 12 * blockSize, blockSize, (short) 3,
542        seed);
543      pReadFile(fileSys, p);
544      cleanupFile(fileSys, p);
545      assertTrue(metrics.getHedgedReadOps() > 0);
546    } finally {
547      fileSys.close();
548      cluster.shutdown();
549    }
550  }
551
552  @Test
553  public void testCopyFilesParallel() throws Exception {
554    MiniDFSCluster cluster = htu.startMiniDFSCluster(1);
555    cluster.waitActive();
556    FileSystem fs = cluster.getFileSystem();
557    Path src = new Path("/src");
558    fs.mkdirs(src);
559    for (int i = 0; i < 50; i++) {
560      WriteDataToHDFS(fs, new Path(src, String.valueOf(i)), 1024);
561    }
562    Path sub = new Path(src, "sub");
563    fs.mkdirs(sub);
564    for (int i = 0; i < 50; i++) {
565      WriteDataToHDFS(fs, new Path(sub, String.valueOf(i)), 1024);
566    }
567    Path dst = new Path("/dst");
568    List<Path> allFiles = FSUtils.copyFilesParallel(fs, src, fs, dst, conf, 4);
569
570    assertEquals(102, allFiles.size());
571    FileStatus[] list = fs.listStatus(dst);
572    assertEquals(51, list.length);
573    FileStatus[] sublist = fs.listStatus(new Path(dst, "sub"));
574    assertEquals(50, sublist.length);
575  }
576
577  // Below is taken from TestPread over in HDFS.
578  static final int blockSize = 4096;
579  static final long seed = 0xDEADBEEFL;
580  private Random rand = new Random(); // This test depends on Random#setSeed
581
582  private void pReadFile(FileSystem fileSys, Path name) throws IOException {
583    FSDataInputStream stm = fileSys.open(name);
584    byte[] expected = new byte[12 * blockSize];
585    rand.setSeed(seed);
586    rand.nextBytes(expected);
587    // do a sanity check. Read first 4K bytes
588    byte[] actual = new byte[4096];
589    stm.readFully(actual);
590    checkAndEraseData(actual, 0, expected, "Read Sanity Test");
591    // now do a pread for the first 8K bytes
592    actual = new byte[8192];
593    doPread(stm, 0L, actual, 0, 8192);
594    checkAndEraseData(actual, 0, expected, "Pread Test 1");
595    // Now check to see if the normal read returns 4K-8K byte range
596    actual = new byte[4096];
597    stm.readFully(actual);
598    checkAndEraseData(actual, 4096, expected, "Pread Test 2");
599    // Now see if we can cross a single block boundary successfully
600    // read 4K bytes from blockSize - 2K offset
601    stm.readFully(blockSize - 2048, actual, 0, 4096);
602    checkAndEraseData(actual, (blockSize - 2048), expected, "Pread Test 3");
603    // now see if we can cross two block boundaries successfully
604    // read blockSize + 4K bytes from blockSize - 2K offset
605    actual = new byte[blockSize + 4096];
606    stm.readFully(blockSize - 2048, actual);
607    checkAndEraseData(actual, (blockSize - 2048), expected, "Pread Test 4");
608    // now see if we can cross two block boundaries that are not cached
609    // read blockSize + 4K bytes from 10*blockSize - 2K offset
610    actual = new byte[blockSize + 4096];
611    stm.readFully(10 * blockSize - 2048, actual);
612    checkAndEraseData(actual, (10 * blockSize - 2048), expected, "Pread Test 5");
613    // now check that even after all these preads, we can still read
614    // bytes 8K-12K
615    actual = new byte[4096];
616    stm.readFully(actual);
617    checkAndEraseData(actual, 8192, expected, "Pread Test 6");
618    // done
619    stm.close();
620    // check block location caching
621    stm = fileSys.open(name);
622    stm.readFully(1, actual, 0, 4096);
623    stm.readFully(4 * blockSize, actual, 0, 4096);
624    stm.readFully(7 * blockSize, actual, 0, 4096);
625    actual = new byte[3 * 4096];
626    stm.readFully(0 * blockSize, actual, 0, 3 * 4096);
627    checkAndEraseData(actual, 0, expected, "Pread Test 7");
628    actual = new byte[8 * 4096];
629    stm.readFully(3 * blockSize, actual, 0, 8 * 4096);
630    checkAndEraseData(actual, 3 * blockSize, expected, "Pread Test 8");
631    // read the tail
632    stm.readFully(11 * blockSize + blockSize / 2, actual, 0, blockSize / 2);
633    IOException res = null;
634    try { // read beyond the end of the file
635      stm.readFully(11 * blockSize + blockSize / 2, actual, 0, blockSize);
636    } catch (IOException e) {
637      // should throw an exception
638      res = e;
639    }
640    assertTrue(res != null, "Error reading beyond file boundary.");
641
642    stm.close();
643  }
644
645  private void checkAndEraseData(byte[] actual, int from, byte[] expected, String message) {
646    for (int idx = 0; idx < actual.length; idx++) {
647      assertEquals(expected[from + idx], actual[idx], message + " byte " + (from + idx)
648        + " differs. expected " + expected[from + idx] + " actual " + actual[idx]);
649      actual[idx] = 0;
650    }
651  }
652
653  private void doPread(FSDataInputStream stm, long position, byte[] buffer, int offset, int length)
654    throws IOException {
655    int nread = 0;
656    // long totalRead = 0;
657    // DFSInputStream dfstm = null;
658
659    /*
660     * Disable. This counts do not add up. Some issue in original hdfs tests? if
661     * (stm.getWrappedStream() instanceof DFSInputStream) { dfstm = (DFSInputStream)
662     * (stm.getWrappedStream()); totalRead = dfstm.getReadStatistics().getTotalBytesRead(); }
663     */
664
665    while (nread < length) {
666      int nbytes = stm.read(position + nread, buffer, offset + nread, length - nread);
667      assertTrue(nbytes > 0, "Error in pread");
668      nread += nbytes;
669    }
670
671    /*
672     * Disable. This counts do not add up. Some issue in original hdfs tests? if (dfstm != null) {
673     * if (isHedgedRead) { assertTrue("Expected read statistic to be incremented", length <=
674     * dfstm.getReadStatistics().getTotalBytesRead() - totalRead); } else {
675     * assertEquals("Expected read statistic to be incremented", length, dfstm
676     * .getReadStatistics().getTotalBytesRead() - totalRead); } }
677     */
678  }
679
680  private void cleanupFile(FileSystem fileSys, Path name) throws IOException {
681    assertTrue(fileSys.exists(name));
682    assertTrue(fileSys.delete(name, true));
683    assertTrue(!fileSys.exists(name));
684  }
685
686  static {
687    try {
688      Class.forName("org.apache.hadoop.fs.StreamCapabilities");
689      LOG.debug("Test thought StreamCapabilities class was present.");
690    } catch (ClassNotFoundException exception) {
691      LOG.debug("Test didn't think StreamCapabilities class was present.");
692    }
693  }
694
695  // Here instead of TestCommonFSUtils because we need a minicluster
696  @Test
697  public void checkStreamCapabilitiesOnHdfsDataOutputStream() throws Exception {
698    MiniDFSCluster cluster = htu.startMiniDFSCluster(1);
699    try (FileSystem filesystem = cluster.getFileSystem()) {
700      FSDataOutputStream stream = filesystem.create(new Path("/tmp/foobar"));
701      assertTrue(stream.hasCapability(StreamCapabilities.HSYNC));
702      assertTrue(stream.hasCapability(StreamCapabilities.HFLUSH));
703      assertFalse(stream.hasCapability("a capability that hopefully HDFS doesn't add."));
704    } finally {
705      cluster.shutdown();
706    }
707  }
708
709  private void testIsSameHdfs(int nnport) throws IOException {
710    Configuration conf = HBaseConfiguration.create();
711    Path srcPath = new Path("hdfs://localhost:" + nnport + "/");
712    Path desPath = new Path("hdfs://127.0.0.1/");
713    FileSystem srcFs = srcPath.getFileSystem(conf);
714    FileSystem desFs = desPath.getFileSystem(conf);
715
716    assertTrue(FSUtils.isSameHdfs(conf, srcFs, desFs));
717
718    desPath = new Path("hdfs://127.0.0.1:8070/");
719    desFs = desPath.getFileSystem(conf);
720    assertTrue(!FSUtils.isSameHdfs(conf, srcFs, desFs));
721
722    desPath = new Path("hdfs://127.0.1.1:" + nnport + "/");
723    desFs = desPath.getFileSystem(conf);
724    assertTrue(!FSUtils.isSameHdfs(conf, srcFs, desFs));
725
726    conf.set("fs.defaultFS", "hdfs://haosong-hadoop");
727    conf.set("dfs.nameservices", "haosong-hadoop");
728    conf.set("dfs.ha.namenodes.haosong-hadoop", "nn1,nn2");
729    conf.set("dfs.client.failover.proxy.provider.haosong-hadoop",
730      "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");
731
732    conf.set("dfs.namenode.rpc-address.haosong-hadoop.nn1", "127.0.0.1:" + nnport);
733    conf.set("dfs.namenode.rpc-address.haosong-hadoop.nn2", "127.10.2.1:8000");
734    desPath = new Path("/");
735    desFs = desPath.getFileSystem(conf);
736    assertTrue(FSUtils.isSameHdfs(conf, srcFs, desFs));
737
738    conf.set("dfs.namenode.rpc-address.haosong-hadoop.nn1", "127.10.2.1:" + nnport);
739    conf.set("dfs.namenode.rpc-address.haosong-hadoop.nn2", "127.0.0.1:8000");
740    desPath = new Path("/");
741    desFs = desPath.getFileSystem(conf);
742    assertTrue(!FSUtils.isSameHdfs(conf, srcFs, desFs));
743  }
744
745  @Test
746  public void testIsSameHdfs() throws IOException {
747    String hadoopVersion = org.apache.hadoop.util.VersionInfo.getVersion();
748    LOG.info("hadoop version is: " + hadoopVersion);
749    boolean isHadoop3_0_0 = hadoopVersion.startsWith("3.0.0");
750    if (isHadoop3_0_0) {
751      // Hadoop 3.0.0 alpha1+ ~ 3.0.0 GA changed default nn port to 9820.
752      // See HDFS-9427
753      testIsSameHdfs(9820);
754    } else {
755      // pre hadoop 3.0.0 defaults to port 8020
756      // Hadoop 3.0.1 changed it back to port 8020. See HDFS-12990
757      testIsSameHdfs(8020);
758    }
759  }
760
761  @Test
762  public void testOpenForReadUsesOpenFileWithSuppliedStatus() throws IOException {
763    Path testPath = new Path(htu.getDataTestDir("openForReadStatus").toString(), "data");
764    FileSystem rawFs = testPath.getFileSystem(conf);
765    try (FSDataOutputStream out = rawFs.create(testPath)) {
766      out.writeBytes("x");
767    }
768    FileStatus status = rawFs.getFileStatus(testPath);
769
770    OpenForReadTrackingFileSystem trackingFs = new OpenForReadTrackingFileSystem(rawFs);
771    try (FSDataInputStream in = FSUtils.openForRead(trackingFs, testPath, status)) {
772      assertEquals(1, trackingFs.openFileBuildCount.get());
773      assertEquals(0, trackingFs.legacyOpenCount.get());
774      assertSame(status, trackingFs.suppliedFileStatus);
775      assertNotNull(in);
776    }
777  }
778
779  @Test
780  public void testOpenForReadFallsBackWhenOpenFileUnsupported() throws IOException {
781    Path testPath = new Path(htu.getDataTestDir("openForReadFallback").toString(), "data");
782    FileSystem rawFs = testPath.getFileSystem(conf);
783    try (FSDataOutputStream out = rawFs.create(testPath)) {
784      out.writeBytes("x");
785    }
786    FileStatus status = rawFs.getFileStatus(testPath);
787
788    OpenForReadTrackingFileSystem trackingFs = new OpenForReadTrackingFileSystem(rawFs);
789    trackingFs.openFileThrowsUnsupported = true;
790    try (FSDataInputStream in = FSUtils.openForRead(trackingFs, testPath, status)) {
791      assertEquals(0, trackingFs.openFileBuildCount.get());
792      assertEquals(1, trackingFs.legacyOpenCount.get());
793      assertNotNull(in);
794    }
795  }
796
797  @Test
798  public void testOpenForReadPropagatesInterrupt() throws IOException {
799    Path testPath = new Path(htu.getDataTestDir("openForReadInterrupt").toString(), "data");
800    FileSystem rawFs = testPath.getFileSystem(conf);
801    try (FSDataOutputStream out = rawFs.create(testPath)) {
802      out.writeBytes("x");
803    }
804    FileStatus status = rawFs.getFileStatus(testPath);
805
806    OpenForReadTrackingFileSystem trackingFs = new OpenForReadTrackingFileSystem(rawFs);
807    trackingFs.interruptOnBuildGet = true;
808    try {
809      FSUtils.openForRead(trackingFs, testPath, status);
810      fail("expected InterruptedIOException");
811    } catch (InterruptedIOException e) {
812      assertTrue(Thread.currentThread().isInterrupted());
813      assertEquals(0, trackingFs.legacyOpenCount.get());
814    } finally {
815      Thread.interrupted();
816    }
817
818    // The asynchronous open completes after the caller gave up; the abandoned stream must be
819    // closed.
820    AtomicInteger closeCount = new AtomicInteger();
821    FSDataInputStream lateStream = new FSDataInputStream(rawFs.open(testPath)) {
822      @Override
823      public void close() throws IOException {
824        closeCount.incrementAndGet();
825        super.close();
826      }
827    };
828    assertTrue(trackingFs.pendingOpen.complete(lateStream));
829    assertEquals(1, closeCount.get());
830  }
831
832  /**
833   * Counts legacy {@link FileSystem#open(Path, int)} vs {@link FileSystem#openFile(Path)} usage and
834   * records {@code withFileStatus} for {@link FSUtils#openForRead}.
835   */
836  private static final class OpenForReadTrackingFileSystem extends FilterFileSystem {
837
838    final AtomicInteger legacyOpenCount = new AtomicInteger();
839    final AtomicInteger openFileBuildCount = new AtomicInteger();
840    volatile FileStatus suppliedFileStatus;
841    boolean openFileThrowsUnsupported;
842    boolean interruptOnBuildGet;
843    volatile CompletableFuture<FSDataInputStream> pendingOpen;
844
845    OpenForReadTrackingFileSystem(FileSystem fs) {
846      super(fs);
847    }
848
849    @Override
850    public FSDataInputStream open(Path p, int bufferSize) throws IOException {
851      legacyOpenCount.incrementAndGet();
852      return super.open(p, bufferSize);
853    }
854
855    @Override
856    public FutureDataInputStreamBuilder openFile(Path path) throws IOException {
857      if (openFileThrowsUnsupported) {
858        throw new UnsupportedOperationException("openFile not supported");
859      }
860      FutureDataInputStreamBuilder delegate = super.openFile(path);
861      return new TrackingFutureDataInputStreamBuilder(delegate);
862    }
863
864    private final class TrackingFutureDataInputStreamBuilder
865      implements FutureDataInputStreamBuilder {
866
867      private final FutureDataInputStreamBuilder delegate;
868
869      private TrackingFutureDataInputStreamBuilder(FutureDataInputStreamBuilder delegate) {
870        this.delegate = delegate;
871      }
872
873      @Override
874      public FutureDataInputStreamBuilder withFileStatus(FileStatus status) {
875        suppliedFileStatus = status;
876        delegate.withFileStatus(status);
877        return this;
878      }
879
880      @Override
881      public CompletableFuture<FSDataInputStream> build() throws IOException {
882        openFileBuildCount.incrementAndGet();
883        if (interruptOnBuildGet) {
884          // A pending future makes get() observe the interrupt; the test completes it afterwards
885          // to simulate an asynchronous open that finishes after the caller was interrupted.
886          Thread.currentThread().interrupt();
887          pendingOpen = new CompletableFuture<>();
888          return pendingOpen;
889        }
890        return delegate.build();
891      }
892
893      @Override
894      public FutureDataInputStreamBuilder opt(String key, String value) {
895        delegate.opt(key, value);
896        return this;
897      }
898
899      @Override
900      public FutureDataInputStreamBuilder opt(String key, String... values) {
901        delegate.opt(key, values);
902        return this;
903      }
904
905      @Override
906      public FutureDataInputStreamBuilder must(String key, String value) {
907        delegate.must(key, value);
908        return this;
909      }
910
911      @Override
912      public FutureDataInputStreamBuilder must(String key, String... values) {
913        delegate.must(key, values);
914        return this;
915      }
916    }
917  }
918}