method2testcases
stringlengths
118
6.63k
### Question: FSVisitor { public static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor) throws IOException { FileStatus[] regions = FSUtils.listStatus(fs, tableDir, new FSUtils.RegionDirFilter(fs)); if (regions == null) { LOG.info("No regions under directory:" + tableDir); return; } for (FileStatus region: regions) { visitRegionRecoveredEdits(fs, region.getPath(), visitor); } } private FSVisitor(); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitRecoveredEdits() throws IOException { final Set<String> regions = new HashSet<String>(); final Set<String> edits = new HashSet<String>(); FSVisitor.visitTableRecoveredEdits(fs, tableDir, new FSVisitor.RecoveredEditsVisitor() { public void recoveredEdits (final String region, final String logfile) throws IOException { regions.add(region); edits.add(logfile); } }); assertEquals(tableRegions, regions); assertEquals(recoveredEdits, edits); }
### Question: NativeIO { static native void posix_fadvise( FileDescriptor fd, long offset, long len, int flags) throws NativeIOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testPosixFadvise() throws Exception { FileInputStream fis = new FileInputStream("/dev/zero"); try { NativeIO.posix_fadvise(fis.getFD(), 0, 0, NativeIO.POSIX_FADV_SEQUENTIAL); } catch (UnsupportedOperationException uoe) { assumeTrue(false); } finally { fis.close(); } try { NativeIO.posix_fadvise(fis.getFD(), 0, 1024, NativeIO.POSIX_FADV_SEQUENTIAL); fail("Did not throw on bad file"); } catch (NativeIOException nioe) { assertEquals(Errno.EBADF, nioe.getErrno()); } try { NativeIO.posix_fadvise(null, 0, 1024, NativeIO.POSIX_FADV_SEQUENTIAL); fail("Did not throw on null file"); } catch (NullPointerException npe) { } }
### Question: NativeIO { static native void sync_file_range( FileDescriptor fd, long offset, long nbytes, int flags) throws NativeIOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testSyncFileRange() throws Exception { FileOutputStream fos = new FileOutputStream( new File(TEST_DIR, "testSyncFileRange")); try { fos.write("foo".getBytes()); NativeIO.sync_file_range(fos.getFD(), 0, 1024, NativeIO.SYNC_FILE_RANGE_WRITE); } catch (UnsupportedOperationException uoe) { assumeTrue(false); } finally { fos.close(); } try { NativeIO.sync_file_range(fos.getFD(), 0, 1024, NativeIO.SYNC_FILE_RANGE_WRITE); fail("Did not throw on bad file"); } catch (NativeIOException nioe) { assertEquals(Errno.EBADF, nioe.getErrno()); } }
### Question: NativeIO { static native String getUserName(int uid) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testGetUserName() throws IOException { assertFalse(NativeIO.getUserName(0).isEmpty()); }
### Question: NativeIO { static native String getGroupName(int uid) throws IOException; static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testGetGroupName() throws IOException { assertFalse(NativeIO.getGroupName(0).isEmpty()); }
### Question: NativeIO { public static void renameTo(File src, File dst) throws IOException { if (!nativeLoaded) { if (!src.renameTo(dst)) { throw new IOException("renameTo(src=" + src + ", dst=" + dst + ") failed."); } } else { renameTo0(src.getAbsolutePath(), dst.getAbsolutePath()); } } static boolean isAvailable(); static native FileDescriptor open(String path, int flags, int mode); static native void chmod(String path, int mode); static void posixFadviseIfPossible( FileDescriptor fd, long offset, long len, int flags); static void syncFileRangeIfPossible( FileDescriptor fd, long offset, long nbytes, int flags); static Stat getFstat(FileDescriptor fd); static void renameTo(File src, File dst); static final int O_RDONLY; static final int O_WRONLY; static final int O_RDWR; static final int O_CREAT; static final int O_EXCL; static final int O_NOCTTY; static final int O_TRUNC; static final int O_APPEND; static final int O_NONBLOCK; static final int O_SYNC; static final int O_ASYNC; static final int O_FSYNC; static final int O_NDELAY; static final int POSIX_FADV_NORMAL; static final int POSIX_FADV_RANDOM; static final int POSIX_FADV_SEQUENTIAL; static final int POSIX_FADV_WILLNEED; static final int POSIX_FADV_DONTNEED; static final int POSIX_FADV_NOREUSE; static final int SYNC_FILE_RANGE_WAIT_BEFORE; static final int SYNC_FILE_RANGE_WRITE; static final int SYNC_FILE_RANGE_WAIT_AFTER; }### Answer: @Test public void testRenameTo() throws Exception { final File TEST_DIR = new File(new File( System.getProperty("test.build.data","build/test/data")), "renameTest"); assumeTrue(TEST_DIR.mkdirs()); File nonExistentFile = new File(TEST_DIR, "nonexistent"); File targetFile = new File(TEST_DIR, "target"); try { NativeIO.renameTo(nonExistentFile, targetFile); Assert.fail(); } catch (NativeIOException e) { Assert.assertEquals(e.getErrno(), Errno.ENOENT); } File sourceFile = new File(TEST_DIR, "source"); Assert.assertTrue(sourceFile.createNewFile()); NativeIO.renameTo(sourceFile, sourceFile); NativeIO.renameTo(sourceFile, targetFile); sourceFile = new File(TEST_DIR, "source"); Assert.assertTrue(sourceFile.createNewFile()); File badTarget = new File(targetFile, "subdir"); try { NativeIO.renameTo(sourceFile, badTarget); Assert.fail(); } catch (NativeIOException e) { Assert.assertEquals(e.getErrno(), Errno.ENOTDIR); } FileUtils.deleteQuietly(TEST_DIR); }
### Question: SampleQuantiles { synchronized public void clear() { count = 0; bufferCount = 0; samples.clear(); } SampleQuantiles(Quantile[] quantiles); synchronized void insert(long v); synchronized Map<Quantile, Long> snapshot(); synchronized long getCount(); @VisibleForTesting synchronized int getSampleCount(); synchronized void clear(); }### Answer: @Test public void testClear() throws IOException { for (int i = 0; i < 1000; i++) { estimator.insert(i); } estimator.clear(); assertEquals(estimator.getCount(), 0); assertEquals(estimator.getSampleCount(), 0); try { estimator.snapshot(); fail("Expected IOException for an empty window."); } catch (IOException e) { GenericTestUtils.assertExceptionContains("No samples", e); } }
### Question: FSVisitor { public static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor) throws IOException { Path logsDir = new Path(rootDir, HConstants.HREGION_LOGDIR_NAME); FileStatus[] logServerDirs = FSUtils.listStatus(fs, logsDir); if (logServerDirs == null) { LOG.info("No logs under directory:" + logsDir); return; } for (FileStatus serverLogs: logServerDirs) { String serverName = serverLogs.getPath().getName(); FileStatus[] hlogs = FSUtils.listStatus(fs, serverLogs.getPath()); if (hlogs == null) { LOG.debug("No hfiles found for server: " + serverName + ", skipping."); continue; } for (FileStatus hlogRef: hlogs) { visitor.logFile(serverName, hlogRef.getPath().getName()); } } } private FSVisitor(); static void visitTableStoreFiles(final FileSystem fs, final Path tableDir, final StoreFileVisitor visitor); static void visitRegionStoreFiles(final FileSystem fs, final Path regionDir, final StoreFileVisitor visitor); static void visitTableRecoveredEdits(final FileSystem fs, final Path tableDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitRegionRecoveredEdits(final FileSystem fs, final Path regionDir, final FSVisitor.RecoveredEditsVisitor visitor); static void visitLogFiles(final FileSystem fs, final Path rootDir, final LogFileVisitor visitor); }### Answer: @Test public void testVisitLogFiles() throws IOException { final Set<String> servers = new HashSet<String>(); final Set<String> logs = new HashSet<String>(); FSVisitor.visitLogFiles(fs, rootDir, new FSVisitor.LogFileVisitor() { public void logFile (final String server, final String logfile) throws IOException { servers.add(server); logs.add(logfile); } }); assertEquals(regionServers, servers); assertEquals(serverLogs, logs); }
### Question: PathData implements Comparable<PathData> { public PathData[] getDirectoryContents() throws IOException { checkIfExists(FileTypeRequirement.SHOULD_BE_DIRECTORY); FileStatus[] stats = fs.listStatus(path); PathData[] items = new PathData[stats.length]; for (int i=0; i < stats.length; i++) { String child = getStringForChildPath(stats[i].getPath()); items[i] = new PathData(fs, child, stats[i]); } Arrays.sort(items); return items; } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testUnqualifiedUriContents() throws Exception { String dirString = "d1"; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1/f1", "d1/f1.1", "d1/f2"), sortedString(items) ); } @Test public void testCwdContents() throws Exception { String dirString = Path.CUR_DIR; PathData item = new PathData(dirString, conf); PathData[] items = item.getDirectoryContents(); assertEquals( sortedString("d1", "d2"), sortedString(items) ); }
### Question: PathData implements Comparable<PathData> { public File toFile() { if (!(fs instanceof LocalFileSystem)) { throw new IllegalArgumentException("Not a local path: " + path); } return ((LocalFileSystem)fs).pathToFile(path); } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testToFile() throws Exception { PathData item = new PathData(".", conf); assertEquals(new File(testDir.toString()), item.toFile()); item = new PathData("d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); item = new PathData(testDir + "/d1/f1", conf); assertEquals(new File(testDir + "/d1/f1"), item.toFile()); }
### Question: PathData implements Comparable<PathData> { public static PathData[] expandAsGlob(String pattern, Configuration conf) throws IOException { Path globPath = new Path(pattern); FileSystem fs = globPath.getFileSystem(conf); FileStatus[] stats = fs.globStatus(globPath); PathData[] items = null; if (stats == null) { pattern = pattern.replaceAll("\\\\(.)", "$1"); items = new PathData[]{ new PathData(fs, pattern, null) }; } else { PathType globType; URI globUri = globPath.toUri(); if (globUri.getScheme() != null) { globType = PathType.HAS_SCHEME; } else if (new File(globUri.getPath()).isAbsolute()) { globType = PathType.SCHEMELESS_ABSOLUTE; } else { globType = PathType.RELATIVE; } items = new PathData[stats.length]; int i=0; for (FileStatus stat : stats) { URI matchUri = stat.getPath().toUri(); String globMatch = null; switch (globType) { case HAS_SCHEME: if (globUri.getAuthority() == null) { matchUri = removeAuthority(matchUri); } globMatch = matchUri.toString(); break; case SCHEMELESS_ABSOLUTE: globMatch = matchUri.getPath(); break; case RELATIVE: URI cwdUri = fs.getWorkingDirectory().toUri(); globMatch = relativize(cwdUri, matchUri, stat.isDirectory()); break; } items[i++] = new PathData(fs, globMatch, stat); } } Arrays.sort(items); return items; } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testAbsoluteGlob() throws Exception { PathData[] items = PathData.expandAsGlob(testDir+"/d1/f1*", conf); assertEquals( sortedString(testDir+"/d1/f1", testDir+"/d1/f1.1"), sortedString(items) ); } @Test public void testRelativeGlob() throws Exception { PathData[] items = PathData.expandAsGlob("d1/f1*", conf); assertEquals( sortedString("d1/f1", "d1/f1.1"), sortedString(items) ); } @Test public void testRelativeGlobBack() throws Exception { fs.setWorkingDirectory(new Path("d1")); PathData[] items = PathData.expandAsGlob("../d2/*", conf); assertEquals( sortedString("../d2/f3"), sortedString(items) ); }
### Question: PathData implements Comparable<PathData> { public String toString() { String scheme = uri.getScheme(); String decodedRemainder = uri.getSchemeSpecificPart(); if (scheme == null) { return decodedRemainder; } else { StringBuilder buffer = new StringBuilder(); buffer.append(scheme); buffer.append(":"); buffer.append(decodedRemainder); return buffer.toString(); } } PathData(String pathString, Configuration conf); PathData(File localPath, Configuration conf); private PathData(FileSystem fs, String pathString); private PathData(FileSystem fs, String pathString, FileStatus stat); FileStatus refreshStatus(); PathData suffix(String extension); boolean parentExists(); boolean representsDirectory(); PathData[] getDirectoryContents(); PathData getPathDataForChild(PathData child); static PathData[] expandAsGlob(String pattern, Configuration conf); String toString(); File toFile(); @Override int compareTo(PathData o); @Override boolean equals(Object o); @Override int hashCode(); final FileSystem fs; final Path path; public FileStatus stat; public boolean exists; }### Answer: @Test public void testWithStringAndConfForBuggyPath() throws Exception { String dirString = "file: Path tmpDir = new Path(dirString); PathData item = new PathData(dirString, conf); assertEquals("file:/tmp", tmpDir.toString()); checkPathData(dirString, item); }
### Question: ChRootedFs extends AbstractFileSystem { @Override public boolean delete(final Path f, final boolean recursive) throws IOException, UnresolvedLinkException { return myFs.delete(fullPath(f), recursive); } ChRootedFs(final AbstractFileSystem fs, final Path theRoot); @Override URI getUri(); String stripOutRoot(final Path p); @Override Path getHomeDirectory(); @Override Path getInitialWorkingDirectory(); Path getResolvedQualifiedPath(final Path f); @Override FSDataOutputStream createInternal(final Path f, final EnumSet<CreateFlag> flag, final FsPermission absolutePermission, final int bufferSize, final short replication, final long blockSize, final Progressable progress, final ChecksumOpt checksumOpt, final boolean createParent); @Override boolean delete(final Path f, final boolean recursive); @Override BlockLocation[] getFileBlockLocations(final Path f, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FileStatus getFileLinkStatus(final Path f); @Override FsStatus getFsStatus(); @Override FsServerDefaults getServerDefaults(); @Override int getUriDefaultPort(); @Override FileStatus[] listStatus(final Path f); @Override void mkdir(final Path dir, final FsPermission permission, final boolean createParent); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override void renameInternal(final Path src, final Path dst); @Override void renameInternal(final Path src, final Path dst, final boolean overwrite); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override void setVerifyChecksum(final boolean verifyChecksum); @Override boolean supportsSymlinks(); @Override void createSymlink(final Path target, final Path link, final boolean createParent); @Override Path getLinkTarget(final Path f); @Override List<Token<?>> getDelegationTokens(String renewer); }### Answer: @Test public void testCreateDelete() throws IOException { FileContextTestHelper.createFileNonRecursive(fc, "/foo"); Assert.assertTrue(isFile(fc, new Path("/foo"))); Assert.assertTrue(isFile(fcTarget, new Path(chrootedTo, "foo"))); FileContextTestHelper.createFile(fc, "/newDir/foo"); Assert.assertTrue(isFile(fc, new Path("/newDir/foo"))); Assert.assertTrue(isFile(fcTarget, new Path(chrootedTo,"newDir/foo"))); Assert.assertTrue(fc.delete(new Path("/newDir/foo"), false)); Assert.assertFalse(exists(fc, new Path("/newDir/foo"))); Assert.assertFalse(exists(fcTarget, new Path(chrootedTo,"newDir/foo"))); FileContextTestHelper.createFile(fc, "/newDir/newDir2/foo"); Assert.assertTrue(isFile(fc, new Path("/newDir/newDir2/foo"))); Assert.assertTrue(isFile(fcTarget, new Path(chrootedTo,"newDir/newDir2/foo"))); Assert.assertTrue(fc.delete(new Path("/newDir/newDir2/foo"), false)); Assert.assertFalse(exists(fc, new Path("/newDir/newDir2/foo"))); Assert.assertFalse(exists(fcTarget, new Path(chrootedTo,"newDir/newDir2/foo"))); }
### Question: ChRootedFs extends AbstractFileSystem { @Override public void mkdir(final Path dir, final FsPermission permission, final boolean createParent) throws IOException, UnresolvedLinkException { myFs.mkdir(fullPath(dir), permission, createParent); } ChRootedFs(final AbstractFileSystem fs, final Path theRoot); @Override URI getUri(); String stripOutRoot(final Path p); @Override Path getHomeDirectory(); @Override Path getInitialWorkingDirectory(); Path getResolvedQualifiedPath(final Path f); @Override FSDataOutputStream createInternal(final Path f, final EnumSet<CreateFlag> flag, final FsPermission absolutePermission, final int bufferSize, final short replication, final long blockSize, final Progressable progress, final ChecksumOpt checksumOpt, final boolean createParent); @Override boolean delete(final Path f, final boolean recursive); @Override BlockLocation[] getFileBlockLocations(final Path f, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FileStatus getFileLinkStatus(final Path f); @Override FsStatus getFsStatus(); @Override FsServerDefaults getServerDefaults(); @Override int getUriDefaultPort(); @Override FileStatus[] listStatus(final Path f); @Override void mkdir(final Path dir, final FsPermission permission, final boolean createParent); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override void renameInternal(final Path src, final Path dst); @Override void renameInternal(final Path src, final Path dst, final boolean overwrite); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override void setVerifyChecksum(final boolean verifyChecksum); @Override boolean supportsSymlinks(); @Override void createSymlink(final Path target, final Path link, final boolean createParent); @Override Path getLinkTarget(final Path f); @Override List<Token<?>> getDelegationTokens(String renewer); }### Answer: @Test public void testRename() throws IOException { FileContextTestHelper.createFile(fc, "/newDir/foo"); fc.rename(new Path("/newDir/foo"), new Path("/newDir/fooBar")); Assert.assertFalse(exists(fc, new Path("/newDir/foo"))); Assert.assertFalse(exists(fcTarget, new Path(chrootedTo,"newDir/foo"))); Assert.assertTrue(isFile(fc, FileContextTestHelper.getTestRootPath(fc,"/newDir/fooBar"))); Assert.assertTrue(isFile(fcTarget, new Path(chrootedTo,"newDir/fooBar"))); fc.mkdir(new Path("/newDir/dirFoo"), FileContext.DEFAULT_PERM, false); fc.rename(new Path("/newDir/dirFoo"), new Path("/newDir/dirFooBar")); Assert.assertFalse(exists(fc, new Path("/newDir/dirFoo"))); Assert.assertFalse(exists(fcTarget, new Path(chrootedTo,"newDir/dirFoo"))); Assert.assertTrue(isDir(fc, FileContextTestHelper.getTestRootPath(fc,"/newDir/dirFooBar"))); Assert.assertTrue(isDir(fcTarget, new Path(chrootedTo,"newDir/dirFooBar"))); } @Test public void testRenameAcrossFs() throws IOException { fc.mkdir(new Path("/newDir/dirFoo"), FileContext.DEFAULT_PERM, true); fc.rename(new Path("/newDir/dirFoo"), new Path("file: FileContextTestHelper.isDir(fc, new Path("/dirFooBar")); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public URI getUri() { return myUri; } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testURI() { URI uri = fSys.getUri(); Assert.assertEquals(chrootedTo.toUri(), uri); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public boolean delete(final Path f, final boolean recursive) throws IOException { return super.delete(fullPath(f), recursive); } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testCreateDelete() throws IOException { FileSystemTestHelper.createFile(fSys, "/foo"); Assert.assertTrue(fSys.isFile(new Path("/foo"))); Assert.assertTrue(fSysTarget.isFile(new Path(chrootedTo, "foo"))); FileSystemTestHelper.createFile(fSys, "/newDir/foo"); Assert.assertTrue(fSys.isFile(new Path("/newDir/foo"))); Assert.assertTrue(fSysTarget.isFile(new Path(chrootedTo,"newDir/foo"))); Assert.assertTrue(fSys.delete(new Path("/newDir/foo"), false)); Assert.assertFalse(fSys.exists(new Path("/newDir/foo"))); Assert.assertFalse(fSysTarget.exists(new Path(chrootedTo, "newDir/foo"))); FileSystemTestHelper.createFile(fSys, "/newDir/newDir2/foo"); Assert.assertTrue(fSys.isFile(new Path("/newDir/newDir2/foo"))); Assert.assertTrue(fSysTarget.isFile(new Path(chrootedTo,"newDir/newDir2/foo"))); Assert.assertTrue(fSys.delete(new Path("/newDir/newDir2/foo"), false)); Assert.assertFalse(fSys.exists(new Path("/newDir/newDir2/foo"))); Assert.assertFalse(fSysTarget.exists(new Path(chrootedTo,"newDir/newDir2/foo"))); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public boolean rename(final Path src, final Path dst) throws IOException { return super.rename(fullPath(src), fullPath(dst)); } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testRename() throws IOException { FileSystemTestHelper.createFile(fSys, "/newDir/foo"); fSys.rename(new Path("/newDir/foo"), new Path("/newDir/fooBar")); Assert.assertFalse(fSys.exists(new Path("/newDir/foo"))); Assert.assertFalse(fSysTarget.exists(new Path(chrootedTo,"newDir/foo"))); Assert.assertTrue(fSys.isFile(FileSystemTestHelper.getTestRootPath(fSys,"/newDir/fooBar"))); Assert.assertTrue(fSysTarget.isFile(new Path(chrootedTo,"newDir/fooBar"))); fSys.mkdirs(new Path("/newDir/dirFoo")); fSys.rename(new Path("/newDir/dirFoo"), new Path("/newDir/dirFooBar")); Assert.assertFalse(fSys.exists(new Path("/newDir/dirFoo"))); Assert.assertFalse(fSysTarget.exists(new Path(chrootedTo,"newDir/dirFoo"))); Assert.assertTrue(fSys.isDirectory(FileSystemTestHelper.getTestRootPath(fSys,"/newDir/dirFooBar"))); Assert.assertTrue(fSysTarget.isDirectory(new Path(chrootedTo,"newDir/dirFooBar"))); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public ContentSummary getContentSummary(Path f) throws IOException { return super.getContentSummary(fullPath(f)); } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testGetContentSummary() throws IOException { fSys.mkdirs(new Path("/newDir/dirFoo")); ContentSummary cs = fSys.getContentSummary(new Path("/newDir/dirFoo")); Assert.assertEquals(-1L, cs.getQuota()); Assert.assertEquals(-1L, cs.getSpaceQuota()); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public Path resolvePath(final Path p) throws IOException { return super.resolvePath(fullPath(p)); } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testResolvePath() throws IOException { Assert.assertEquals(chrootedTo, fSys.resolvePath(new Path("/"))); FileSystemTestHelper.createFile(fSys, "/foo"); Assert.assertEquals(new Path(chrootedTo, "foo"), fSys.resolvePath(new Path("/foo"))); } @Test(expected=FileNotFoundException.class) public void testResolvePathNonExisting() throws IOException { fSys.resolvePath(new Path("/nonExisting")); }
### Question: ChRootedFileSystem extends FilterFileSystem { @Override public FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress) throws IOException { return super.create(fullPath(f), permission, overwrite, bufferSize, replication, blockSize, progress); } ChRootedFileSystem(final URI uri, Configuration conf); void initialize(final URI name, final Configuration conf); @Override URI getUri(); Path getResolvedQualifiedPath(final Path f); @Override Path getWorkingDirectory(); @Override void setWorkingDirectory(final Path new_dir); @Override FSDataOutputStream create(final Path f, final FsPermission permission, final boolean overwrite, final int bufferSize, final short replication, final long blockSize, final Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); @Override boolean delete(final Path f, final boolean recursive); @Override @SuppressWarnings("deprecation") boolean delete(Path f); @Override BlockLocation[] getFileBlockLocations(final FileStatus fs, final long start, final long len); @Override FileChecksum getFileChecksum(final Path f); @Override FileStatus getFileStatus(final Path f); @Override FsStatus getStatus(Path p); @Override FileStatus[] listStatus(final Path f); @Override boolean mkdirs(final Path f, final FsPermission permission); @Override FSDataInputStream open(final Path f, final int bufferSize); @Override FSDataOutputStream append(final Path f, final int bufferSize, final Progressable progress); @Override boolean rename(final Path src, final Path dst); @Override void setOwner(final Path f, final String username, final String groupname); @Override void setPermission(final Path f, final FsPermission permission); @Override boolean setReplication(final Path f, final short replication); @Override void setTimes(final Path f, final long mtime, final long atime); @Override Path resolvePath(final Path p); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(); @Override FsServerDefaults getServerDefaults(Path f); }### Answer: @Test public void testURIEmptyPath() throws IOException { Configuration conf = new Configuration(); conf.setClass("fs.mockfs.impl", MockFileSystem.class, FileSystem.class); URI chrootUri = URI.create("mockfs: new ChRootedFileSystem(chrootUri, conf); }
### Question: HarFileSystem extends FilterFileSystem { public FileChecksum getFileChecksum(Path f) { return null; } HarFileSystem(); HarFileSystem(FileSystem fs); @Override String getScheme(); void initialize(URI name, Configuration conf); int getHarVersion(); Path getWorkingDirectory(); @Override URI getUri(); @Override Path makeQualified(Path path); @Override BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); static int getHarHash(Path p); @Override FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); @Override FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream create(Path f, int bufferSize); FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override void close(); @Override boolean setReplication(Path src, short replication); @Override boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); void setOwner(Path p, String username, String groupname); void setPermission(Path p, FsPermission permisssion); static final int VERSION; }### Answer: @Test public void testFileChecksum() { final Path p = new Path("har: final HarFileSystem harfs = new HarFileSystem(); Assert.assertEquals(null, harfs.getFileChecksum(p)); }
### Question: FilterFileSystem extends FileSystem { public FilterFileSystem() { } FilterFileSystem(); FilterFileSystem(FileSystem fs); FileSystem getRawFileSystem(); void initialize(URI name, Configuration conf); URI getUri(); Path makeQualified(Path path); BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path resolvePath(final Path p); FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override void concat(Path f, Path[] psrcs); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); FileStatus[] listStatus(Path f); @Override RemoteIterator<Path> listCorruptFileBlocks(Path path); RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); Path getWorkingDirectory(); @Override FsStatus getStatus(Path p); @Override boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); long getUsed(); @Override long getDefaultBlockSize(); @Override short getDefaultReplication(); @Override FsServerDefaults getServerDefaults(); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(Path f); FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); @Override Configuration getConf(); @Override void close(); @Override void setOwner(Path p, String username, String groupname ); @Override void setTimes(Path p, long mtime, long atime ); @Override void setPermission(Path p, FsPermission permission ); @Override // FileSystem FileSystem[] getChildFileSystems(); }### Answer: @Test public void testFilterFileSystem() throws Exception { for (Method m : FileSystem.class.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers())) continue; if (Modifier.isPrivate(m.getModifiers())) continue; try { DontCheck.class.getMethod(m.getName(), m.getParameterTypes()); LOG.info("Skipping " + m); } catch (NoSuchMethodException exc) { LOG.info("Testing " + m); try{ FilterFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes()); } catch(NoSuchMethodException exc2){ LOG.error("FilterFileSystem doesn't implement " + m); throw exc2; } } } }
### Question: BlockCacheColumnFamilySummary implements Writable, Comparable<BlockCacheColumnFamilySummary> { @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BlockCacheColumnFamilySummary other = (BlockCacheColumnFamilySummary) obj; if (columnFamily == null) { if (other.columnFamily != null) return false; } else if (!columnFamily.equals(other.columnFamily)) return false; if (table == null) { if (other.table != null) return false; } else if (!table.equals(other.table)) return false; return true; } BlockCacheColumnFamilySummary(); BlockCacheColumnFamilySummary(String table, String columnFamily); String getTable(); void setTable(String table); String getColumnFamily(); void setColumnFamily(String columnFamily); int getBlocks(); void setBlocks(int blocks); long getHeapSize(); void incrementBlocks(); void incrementHeapSize(long heapSize); void setHeapSize(long heapSize); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); static BlockCacheColumnFamilySummary createFromStoreFilePath(Path path); @Override int compareTo(BlockCacheColumnFamilySummary o); static BlockCacheColumnFamilySummary create(BlockCacheColumnFamilySummary e); }### Answer: @Test public void testEquals() { BlockCacheColumnFamilySummary e1 = new BlockCacheColumnFamilySummary(); e1.setTable("table1"); e1.setColumnFamily("cf1"); BlockCacheColumnFamilySummary e2 = new BlockCacheColumnFamilySummary(); e2.setTable("table1"); e2.setColumnFamily("cf1"); assertEquals("bcse", e1, e2); }
### Question: FilterFileSystem extends FileSystem { @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return fs.create(f, permission, overwrite, bufferSize, replication, blockSize, progress); } FilterFileSystem(); FilterFileSystem(FileSystem fs); FileSystem getRawFileSystem(); void initialize(URI name, Configuration conf); URI getUri(); Path makeQualified(Path path); BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path resolvePath(final Path p); FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override void concat(Path f, Path[] psrcs); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); FileStatus[] listStatus(Path f); @Override RemoteIterator<Path> listCorruptFileBlocks(Path path); RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); Path getWorkingDirectory(); @Override FsStatus getStatus(Path p); @Override boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); long getUsed(); @Override long getDefaultBlockSize(); @Override short getDefaultReplication(); @Override FsServerDefaults getServerDefaults(); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(Path f); FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); @Override Configuration getConf(); @Override void close(); @Override void setOwner(Path p, String username, String groupname ); @Override void setTimes(Path p, long mtime, long atime ); @Override void setPermission(Path p, FsPermission permission ); @Override // FileSystem FileSystem[] getChildFileSystems(); }### Answer: @Test public void testGetFilterLocalFsSetsConfs() throws Exception { FilterFileSystem flfs = (FilterFileSystem) FileSystem.get(URI.create("flfs:/"), conf); checkFsConf(flfs, conf, 3); }
### Question: FilterFileSystem extends FileSystem { public void setVerifyChecksum(boolean verifyChecksum) { fs.setVerifyChecksum(verifyChecksum); } FilterFileSystem(); FilterFileSystem(FileSystem fs); FileSystem getRawFileSystem(); void initialize(URI name, Configuration conf); URI getUri(); Path makeQualified(Path path); BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path resolvePath(final Path p); FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override void concat(Path f, Path[] psrcs); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); FileStatus[] listStatus(Path f); @Override RemoteIterator<Path> listCorruptFileBlocks(Path path); RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); Path getWorkingDirectory(); @Override FsStatus getStatus(Path p); @Override boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); long getUsed(); @Override long getDefaultBlockSize(); @Override short getDefaultReplication(); @Override FsServerDefaults getServerDefaults(); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(Path f); FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); @Override Configuration getConf(); @Override void close(); @Override void setOwner(Path p, String username, String groupname ); @Override void setTimes(Path p, long mtime, long atime ); @Override void setPermission(Path p, FsPermission permission ); @Override // FileSystem FileSystem[] getChildFileSystems(); }### Answer: @Test public void testVerifyChecksumPassthru() { FileSystem mockFs = mock(FileSystem.class); FileSystem fs = new FilterFileSystem(mockFs); fs.setVerifyChecksum(false); verify(mockFs).setVerifyChecksum(eq(false)); reset(mockFs); fs.setVerifyChecksum(true); verify(mockFs).setVerifyChecksum(eq(true)); }
### Question: FilterFileSystem extends FileSystem { @Override public void setWriteChecksum(boolean writeChecksum) { fs.setWriteChecksum(writeChecksum); } FilterFileSystem(); FilterFileSystem(FileSystem fs); FileSystem getRawFileSystem(); void initialize(URI name, Configuration conf); URI getUri(); Path makeQualified(Path path); BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len); @Override Path resolvePath(final Path p); FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); @Override void concat(Path f, Path[] psrcs); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override @Deprecated FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); FileStatus[] listStatus(Path f); @Override RemoteIterator<Path> listCorruptFileBlocks(Path path); RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); Path getHomeDirectory(); void setWorkingDirectory(Path newDir); Path getWorkingDirectory(); @Override FsStatus getStatus(Path p); @Override boolean mkdirs(Path f, FsPermission permission); void copyFromLocalFile(boolean delSrc, Path src, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path[] srcs, Path dst); void copyFromLocalFile(boolean delSrc, boolean overwrite, Path src, Path dst); void copyToLocalFile(boolean delSrc, Path src, Path dst); Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); long getUsed(); @Override long getDefaultBlockSize(); @Override short getDefaultReplication(); @Override FsServerDefaults getServerDefaults(); @Override ContentSummary getContentSummary(Path f); @Override long getDefaultBlockSize(Path f); @Override short getDefaultReplication(Path f); @Override FsServerDefaults getServerDefaults(Path f); FileStatus getFileStatus(Path f); FileChecksum getFileChecksum(Path f); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); @Override Configuration getConf(); @Override void close(); @Override void setOwner(Path p, String username, String groupname ); @Override void setTimes(Path p, long mtime, long atime ); @Override void setPermission(Path p, FsPermission permission ); @Override // FileSystem FileSystem[] getChildFileSystems(); }### Answer: @Test public void testWriteChecksumPassthru() { FileSystem mockFs = mock(FileSystem.class); FileSystem fs = new FilterFileSystem(mockFs); fs.setWriteChecksum(false); verify(mockFs).setWriteChecksum(eq(false)); reset(mockFs); fs.setWriteChecksum(true); verify(mockFs).setWriteChecksum(eq(true)); }
### Question: LocalFileSystem extends ChecksumFileSystem { @Override public String getScheme() { return "file"; } LocalFileSystem(); LocalFileSystem(FileSystem rawLocalFileSystem); @Override void initialize(URI name, Configuration conf); @Override String getScheme(); FileSystem getRaw(); File pathToFile(Path path); @Override void copyFromLocalFile(boolean delSrc, Path src, Path dst); @Override void copyToLocalFile(boolean delSrc, Path src, Path dst); boolean reportChecksumFailure(Path p, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos); }### Answer: @Test public void testStatistics() throws Exception { FileSystem.getLocal(new Configuration()); int fileSchemeCount = 0; for (Statistics stats : FileSystem.getAllStatistics()) { if (stats.getScheme().equals("file")) { fileSchemeCount++; } } assertEquals(1, fileSchemeCount); }
### Question: LocalDirAllocator { int getCurrentDirectoryIndex() { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.getCurrentDirectoryIndex(); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testDirsNotExist() throws Exception { if (isWindows) return; String dir2 = buildBufferDir(ROOT, 2); String dir3 = buildBufferDir(ROOT, 3); try { conf.set(CONTEXT, dir2 + "," + dir3); createTempFile(SMALL_FILE_SIZE); int firstDirIdx = (dirAllocator.getCurrentDirectoryIndex() == 0) ? 2 : 3; int secondDirIdx = (firstDirIdx == 2) ? 3 : 2; validateTempDirCreation(buildBufferDir(ROOT, firstDirIdx)); validateTempDirCreation(buildBufferDir(ROOT, secondDirIdx)); validateTempDirCreation(buildBufferDir(ROOT, firstDirIdx)); } finally { rmBufferDirs(); } } @Test public void testRWBufferDirBecomesRO() throws Exception { if (isWindows) return; String dir3 = buildBufferDir(ROOT, 3); String dir4 = buildBufferDir(ROOT, 4); try { conf.set(CONTEXT, dir3 + "," + dir4); assertTrue(localFs.mkdirs(new Path(dir3))); assertTrue(localFs.mkdirs(new Path(dir4))); createTempFile(SMALL_FILE_SIZE); int nextDirIdx = (dirAllocator.getCurrentDirectoryIndex() == 0) ? 3 : 4; validateTempDirCreation(buildBufferDir(ROOT, nextDirIdx)); new File(new Path(dir4).toUri().getPath()).setReadOnly(); validateTempDirCreation(dir3); validateTempDirCreation(dir3); } finally { rmBufferDirs(); } }
### Question: LocalDirAllocator { public Path getLocalPathForWrite(String pathStr, Configuration conf) throws IOException { return getLocalPathForWrite(pathStr, SIZE_UNKNOWN, conf); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testLocalPathForWriteDirCreation() throws IOException { String dir0 = buildBufferDir(ROOT, 0); String dir1 = buildBufferDir(ROOT, 1); try { conf.set(CONTEXT, dir0 + "," + dir1); assertTrue(localFs.mkdirs(new Path(dir1))); BUFFER_ROOT.setReadOnly(); Path p1 = dirAllocator.getLocalPathForWrite("p1/x", SMALL_FILE_SIZE, conf); assertTrue(localFs.getFileStatus(p1.getParent()).isDirectory()); Path p2 = dirAllocator.getLocalPathForWrite("p2/x", SMALL_FILE_SIZE, conf, false); try { localFs.getFileStatus(p2.getParent()); } catch (Exception e) { assertEquals(e.getClass(), FileNotFoundException.class); } } finally { Shell.execCommand(new String[] { "chmod", "u+w", BUFFER_DIR_ROOT }); rmBufferDirs(); } } @Test(timeout = 30000) public void testGetLocalPathForWriteForInvalidPaths() throws Exception { conf.set(CONTEXT, " "); try { dirAllocator.getLocalPathForWrite("/test", conf); fail("not throwing the exception"); } catch (IOException e) { assertEquals("Incorrect exception message", "No space available in any of the local directories.", e.getMessage()); } }
### Question: LocalDirAllocator { public File createTmpFileForWrite(String pathStr, long size, Configuration conf) throws IOException { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.createTmpFileForWrite(pathStr, size, conf); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testNoSideEffects() throws IOException { if (isWindows) return; String dir = buildBufferDir(ROOT, 0); try { conf.set(CONTEXT, dir); File result = dirAllocator.createTmpFileForWrite(FILENAME, -1, conf); assertTrue(result.delete()); assertTrue(result.getParentFile().delete()); assertFalse(new File(dir).exists()); } finally { Shell.execCommand(new String[]{"chmod", "u+w", BUFFER_DIR_ROOT}); rmBufferDirs(); } }
### Question: LocalDirAllocator { public Path getLocalPathToRead(String pathStr, Configuration conf) throws IOException { AllocatorPerContext context = obtainContext(contextCfgItemName); return context.getLocalPathToRead(pathStr, conf); } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testGetLocalPathToRead() throws IOException { if (isWindows) return; String dir = buildBufferDir(ROOT, 0); try { conf.set(CONTEXT, dir); assertTrue(localFs.mkdirs(new Path(dir))); File f1 = dirAllocator.createTmpFileForWrite(FILENAME, SMALL_FILE_SIZE, conf); Path p1 = dirAllocator.getLocalPathToRead(f1.getName(), conf); assertEquals(f1.getName(), p1.getName()); assertEquals("file", p1.getFileSystem(conf).getUri().getScheme()); } finally { Shell.execCommand(new String[] { "chmod", "u+w", BUFFER_DIR_ROOT }); rmBufferDirs(); } }
### Question: SlabCache implements SlabItemActionWatcher, BlockCache, HeapSize { Entry<Integer, SingleSizeCache> getHigherBlock(int size) { return sizer.higherEntry(size - 1); } SlabCache(long size, long avgBlockSize); void addSlabByConf(Configuration conf); void cacheBlock(BlockCacheKey cacheKey, Cacheable cachedItem); void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory); CacheStats getStats(); Cacheable getBlock(BlockCacheKey key, boolean caching, boolean repeat); boolean evictBlock(BlockCacheKey cacheKey); @Override void onEviction(BlockCacheKey key, SingleSizeCache notifier); @Override void onInsertion(BlockCacheKey key, SingleSizeCache notifier); void shutdown(); long heapSize(); long size(); long getFreeSize(); @Override long getBlockCount(); long getCurrentSize(); long getEvictedCount(); int evictBlocksByHfileName(String hfileName); @Override List<BlockCacheColumnFamilySummary> getBlockCacheColumnFamilySummaries( Configuration conf); }### Answer: @Test public void testElementPlacement() { assertEquals(cache.getHigherBlock(BLOCK_SIZE).getKey().intValue(), (BLOCK_SIZE * 11 / 10)); assertEquals(cache.getHigherBlock((BLOCK_SIZE * 2)).getKey() .intValue(), (BLOCK_SIZE * 21 / 10)); }
### Question: LocalDirAllocator { @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) public static void removeContext(String contextCfgItemName) { synchronized (contexts) { contexts.remove(contextCfgItemName); } } LocalDirAllocator(String contextCfgItemName); Path getLocalPathForWrite(String pathStr, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf); Path getLocalPathForWrite(String pathStr, long size, Configuration conf, boolean checkWrite); Path getLocalPathToRead(String pathStr, Configuration conf); Iterable<Path> getAllLocalPathsToRead(String pathStr, Configuration conf ); File createTmpFileForWrite(String pathStr, long size, Configuration conf); static boolean isContextValid(String contextCfgItemName); @Deprecated @InterfaceAudience.LimitedPrivate({"MapReduce"}) static void removeContext(String contextCfgItemName); boolean ifExists(String pathStr,Configuration conf); static final int SIZE_UNKNOWN; }### Answer: @Test public void testRemoveContext() throws IOException { String dir = buildBufferDir(ROOT, 0); try { String contextCfgItemName = "application_1340842292563_0004.app.cache.dirs"; conf.set(contextCfgItemName, dir); LocalDirAllocator localDirAllocator = new LocalDirAllocator( contextCfgItemName); localDirAllocator.getLocalPathForWrite("p1/x", SMALL_FILE_SIZE, conf); assertTrue(LocalDirAllocator.isContextValid(contextCfgItemName)); LocalDirAllocator.removeContext(contextCfgItemName); assertFalse(LocalDirAllocator.isContextValid(contextCfgItemName)); } finally { rmBufferDirs(); } }
### Question: ChecksumFileSystem extends FilterFileSystem { public static long getChecksumLength(long size, int bytesPerSum) { return ((size + bytesPerSum - 1) / bytesPerSum) * 4 + CHECKSUM_VERSION.length + 4; } ChecksumFileSystem(FileSystem fs); static double getApproxChkSumLength(long size); void setConf(Configuration conf); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); FileSystem getRawFileSystem(); Path getChecksumFile(Path file); static boolean isChecksumFile(Path file); long getChecksumFileLength(Path file, long fileSize); int getBytesPerSum(); @Override FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); static long getChecksumLength(long size, int bytesPerSum); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream createNonRecursive(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); @Override boolean mkdirs(Path f); @Override void copyFromLocalFile(boolean delSrc, Path src, Path dst); @Override void copyToLocalFile(boolean delSrc, Path src, Path dst); void copyToLocalFile(Path src, Path dst, boolean copyCrc); @Override Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); @Override void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); boolean reportChecksumFailure(Path f, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos); }### Answer: @Test public void testgetChecksumLength() throws Exception { assertEquals(8, ChecksumFileSystem.getChecksumLength(0L, 512)); assertEquals(12, ChecksumFileSystem.getChecksumLength(1L, 512)); assertEquals(12, ChecksumFileSystem.getChecksumLength(512L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(513L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(1023L, 512)); assertEquals(16, ChecksumFileSystem.getChecksumLength(1024L, 512)); assertEquals(408, ChecksumFileSystem.getChecksumLength(100L, 1)); assertEquals(4000000000008L, ChecksumFileSystem.getChecksumLength(10000000000000L, 10)); }
### Question: ChecksumFileSystem extends FilterFileSystem { @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { return create(f, permission, overwrite, true, bufferSize, replication, blockSize, progress); } ChecksumFileSystem(FileSystem fs); static double getApproxChkSumLength(long size); void setConf(Configuration conf); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); FileSystem getRawFileSystem(); Path getChecksumFile(Path file); static boolean isChecksumFile(Path file); long getChecksumFileLength(Path file, long fileSize); int getBytesPerSum(); @Override FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); static long getChecksumLength(long size, int bytesPerSum); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream createNonRecursive(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); @Override boolean mkdirs(Path f); @Override void copyFromLocalFile(boolean delSrc, Path src, Path dst); @Override void copyToLocalFile(boolean delSrc, Path src, Path dst); void copyToLocalFile(Path src, Path dst, boolean copyCrc); @Override Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); @Override void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); boolean reportChecksumFailure(Path f, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos); }### Answer: @Test public void testMultiChunkFile() throws Exception { Path testPath = new Path(TEST_ROOT_DIR, "testMultiChunk"); FSDataOutputStream fout = localFs.create(testPath); for (int i = 0; i < 1000; i++) { fout.write(("testing" + i).getBytes()); } fout.close(); readFile(localFs, testPath, 128); readFile(localFs, testPath, 511); readFile(localFs, testPath, 512); readFile(localFs, testPath, 513); readFile(localFs, testPath, 1023); readFile(localFs, testPath, 1024); readFile(localFs, testPath, 1025); }
### Question: ChecksumFileSystem extends FilterFileSystem { @Override public boolean mkdirs(Path f) throws IOException { return fs.mkdirs(f); } ChecksumFileSystem(FileSystem fs); static double getApproxChkSumLength(long size); void setConf(Configuration conf); void setVerifyChecksum(boolean verifyChecksum); @Override void setWriteChecksum(boolean writeChecksum); FileSystem getRawFileSystem(); Path getChecksumFile(Path file); static boolean isChecksumFile(Path file); long getChecksumFileLength(Path file, long fileSize); int getBytesPerSum(); @Override FSDataInputStream open(Path f, int bufferSize); FSDataOutputStream append(Path f, int bufferSize, Progressable progress); static long getChecksumLength(long size, int bytesPerSum); @Override FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); @Override FSDataOutputStream createNonRecursive(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress); boolean setReplication(Path src, short replication); boolean rename(Path src, Path dst); boolean delete(Path f, boolean recursive); @Override FileStatus[] listStatus(Path f); @Override RemoteIterator<LocatedFileStatus> listLocatedStatus(Path f); @Override boolean mkdirs(Path f); @Override void copyFromLocalFile(boolean delSrc, Path src, Path dst); @Override void copyToLocalFile(boolean delSrc, Path src, Path dst); void copyToLocalFile(Path src, Path dst, boolean copyCrc); @Override Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile); @Override void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile); boolean reportChecksumFailure(Path f, FSDataInputStream in, long inPos, FSDataInputStream sums, long sumsPos); }### Answer: @Test public void testRenameFileIntoDir() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDir"); localFs.mkdirs(dstPath); verifyRename(srcPath, dstPath, true); } @Test public void testRenameFileIntoDirFile() throws Exception { Path srcPath = new Path(TEST_ROOT_DIR, "testRenameSrc"); Path dstPath = new Path(TEST_ROOT_DIR, "testRenameDir/testRenameDst"); assertTrue(localFs.mkdirs(dstPath)); verifyRename(srcPath, dstPath, false); }
### Question: HFileBlock extends SchemaConfigured implements Cacheable { public int getUncompressedSizeWithoutHeader() { return uncompressedSizeWithoutHeader; } HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader, long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset, boolean includesMemstoreTS, int minorVersion, int bytesPerChecksum, byte checksumType, int onDiskDataSizeWithHeader); HFileBlock(ByteBuffer b, int minorVersion); BlockType getBlockType(); short getDataBlockEncodingId(); int getOnDiskSizeWithHeader(); int getUncompressedSizeWithoutHeader(); long getPrevBlockOffset(); ByteBuffer getBufferReadOnly(); @Override String toString(); void assumeUncompressed(); void expectType(BlockType expectedType); long getOffset(); DataInputStream getByteStream(); @Override long heapSize(); static boolean readWithExtra(InputStream in, byte buf[], int bufOffset, int necessaryLen, int extraLen); int getNextBlockOnDiskSizeWithHeader(); @Override int getSerializedLength(); @Override void serialize(ByteBuffer destination); @Override CacheableDeserializer<Cacheable> getDeserializer(); @Override boolean equals(Object comparison); boolean doesIncludeMemstoreTS(); DataBlockEncoding getDataBlockEncoding(); int headerSize(); byte[] getDummyHeaderForVersion(); static final boolean FILL_HEADER; static final boolean DONT_FILL_HEADER; static final int ENCODED_HEADER_SIZE; static final int BYTE_BUFFER_HEAP_SIZE; }### Answer: @Test public void testNoCompression() throws IOException { assertEquals(4000, createTestV2Block(NONE, includesMemstoreTS). getBlockForCaching().getUncompressedSizeWithoutHeader()); }
### Question: FileUtil { public static long getDU(File dir) { long size = 0; if (!dir.exists()) return 0; if (!dir.isDirectory()) { return dir.length(); } else { File[] allFiles = dir.listFiles(); if(allFiles != null) { for (int i = 0; i < allFiles.length; i++) { boolean isSymLink; try { isSymLink = org.apache.commons.io.FileUtils.isSymlink(allFiles[i]); } catch(IOException ioe) { isSymLink = true; } if(!isSymLink) { size += getDU(allFiles[i]); } } } return size; } } static Path[] stat2Paths(FileStatus[] stats); static Path[] stat2Paths(FileStatus[] stats, Path path); static boolean fullyDelete(File dir); static boolean fullyDeleteContents(File dir); @Deprecated static void fullyDelete(FileSystem fs, Path dir); static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf); static boolean copy(FileSystem srcFS, Path[] srcs, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf); static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf); static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString); static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf); static boolean copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf); static String makeShellPath(String filename); static String makeShellPath(File file); static String makeShellPath(File file, boolean makeCanonicalPath); static long getDU(File dir); static void unZip(File inFile, File unzipDir); static void unTar(File inFile, File untarDir); static int symLink(String target, String linkname); static int chmod(String filename, String perm ); static int chmod(String filename, String perm, boolean recursive); static final File createLocalTempFile(final File basefile, final String prefix, final boolean isDeleteOnExit); static void replaceFile(File src, File target); static File[] listFiles(File dir); static String[] list(File dir); }### Answer: @Test public void testGetDU() throws IOException { setupDirs(); long du = FileUtil.getDU(TEST_DIR); Assert.assertEquals(du, 8); }
### Question: HFileBlock extends SchemaConfigured implements Cacheable { void sanityCheck() throws IOException { buf.rewind(); { BlockType blockTypeFromBuf = BlockType.read(buf); if (blockTypeFromBuf != blockType) { throw new IOException("Block type stored in the buffer: " + blockTypeFromBuf + ", block type field: " + blockType); } } sanityCheckAssertion(buf.getInt(), onDiskSizeWithoutHeader, "onDiskSizeWithoutHeader"); sanityCheckAssertion(buf.getInt(), uncompressedSizeWithoutHeader, "uncompressedSizeWithoutHeader"); sanityCheckAssertion(buf.getLong(), prevBlockOffset, "prevBlocKOffset"); if (minorVersion >= MINOR_VERSION_WITH_CHECKSUM) { sanityCheckAssertion(buf.get(), checksumType, "checksumType"); sanityCheckAssertion(buf.getInt(), bytesPerChecksum, "bytesPerChecksum"); sanityCheckAssertion(buf.getInt(), onDiskDataSizeWithHeader, "onDiskDataSizeWithHeader"); } int cksumBytes = totalChecksumBytes(); int hdrSize = headerSize(); int expectedBufLimit = uncompressedSizeWithoutHeader + headerSize() + cksumBytes; if (buf.limit() != expectedBufLimit) { throw new AssertionError("Expected buffer limit " + expectedBufLimit + ", got " + buf.limit()); } int size = uncompressedSizeWithoutHeader + hdrSize + cksumBytes; if (buf.capacity() != size && buf.capacity() != size + hdrSize) { throw new AssertionError("Invalid buffer capacity: " + buf.capacity() + ", expected " + size + " or " + (size + hdrSize)); } } HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader, long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset, boolean includesMemstoreTS, int minorVersion, int bytesPerChecksum, byte checksumType, int onDiskDataSizeWithHeader); HFileBlock(ByteBuffer b, int minorVersion); BlockType getBlockType(); short getDataBlockEncodingId(); int getOnDiskSizeWithHeader(); int getUncompressedSizeWithoutHeader(); long getPrevBlockOffset(); ByteBuffer getBufferReadOnly(); @Override String toString(); void assumeUncompressed(); void expectType(BlockType expectedType); long getOffset(); DataInputStream getByteStream(); @Override long heapSize(); static boolean readWithExtra(InputStream in, byte buf[], int bufOffset, int necessaryLen, int extraLen); int getNextBlockOnDiskSizeWithHeader(); @Override int getSerializedLength(); @Override void serialize(ByteBuffer destination); @Override CacheableDeserializer<Cacheable> getDeserializer(); @Override boolean equals(Object comparison); boolean doesIncludeMemstoreTS(); DataBlockEncoding getDataBlockEncoding(); int headerSize(); byte[] getDummyHeaderForVersion(); static final boolean FILL_HEADER; static final boolean DONT_FILL_HEADER; static final int ENCODED_HEADER_SIZE; static final int BYTE_BUFFER_HEAP_SIZE; }### Answer: @Test public void testReaderV1() throws IOException { for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) { for (boolean pread : new boolean[] { false, true }) { byte[] block = createTestV1Block(algo); Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v1_"+ algo); LOG.info("Creating temporary file at " + path); FSDataOutputStream os = fs.create(path); int totalSize = 0; int numBlocks = 50; for (int i = 0; i < numBlocks; ++i) { os.write(block); totalSize += block.length; } os.close(); FSDataInputStream is = fs.open(path); HFileBlock.FSReader hbr = new HFileBlock.FSReaderV1(is, algo, totalSize); HFileBlock b; int numBlocksRead = 0; long pos = 0; while (pos < totalSize) { b = hbr.readBlockData(pos, block.length, uncompressedSizeV1, pread); b.sanityCheck(); pos += block.length; numBlocksRead++; } assertEquals(numBlocks, numBlocksRead); is.close(); } } }
### Question: UserGroupInformation { @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o == null || getClass() != o.getClass()) { return false; } else { return subject == ((UserGroupInformation) o).subject; } } UserGroupInformation(Subject subject); @InterfaceAudience.Public @InterfaceStability.Evolving static void setConfiguration(Configuration conf); static boolean isSecurityEnabled(); boolean hasKerberosCredentials(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static UserGroupInformation getCurrentUser(); static UserGroupInformation getBestUGI( String ticketCachePath, String user); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation getUGIFromTicketCache( String ticketCache, String user); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static UserGroupInformation getLoginUser(); boolean isFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static void loginUserFromKeytab(String user, String path ); synchronized void checkTGTAndReloginFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized void reloginFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized void reloginFromTicketCache(); synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path ); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static boolean isLoginKeytabBased(); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createRemoteUser(String user); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser); @InterfaceAudience.Public @InterfaceStability.Evolving UserGroupInformation getRealUser(); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createUserForTesting(String user, String[] userGroups); static UserGroupInformation createProxyUserForTesting(String user, UserGroupInformation realUser, String[] userGroups); String getShortUserName(); @InterfaceAudience.Public @InterfaceStability.Evolving String getUserName(); synchronized boolean addTokenIdentifier(TokenIdentifier tokenId); synchronized Set<TokenIdentifier> getTokenIdentifiers(); synchronized boolean addToken(Token<? extends TokenIdentifier> token); synchronized boolean addToken(Text alias, Token<? extends TokenIdentifier> token); synchronized Collection<Token<? extends TokenIdentifier>> getTokens(); synchronized Credentials getCredentials(); synchronized void addCredentials(Credentials credentials); synchronized String[] getGroupNames(); @Override String toString(); synchronized void setAuthenticationMethod(AuthenticationMethod authMethod); synchronized AuthenticationMethod getAuthenticationMethod(); static AuthenticationMethod getRealAuthenticationMethod( UserGroupInformation ugi); @Override boolean equals(Object o); @Override int hashCode(); @InterfaceAudience.Public @InterfaceStability.Evolving T doAs(PrivilegedAction<T> action); @InterfaceAudience.Public @InterfaceStability.Evolving T doAs(PrivilegedExceptionAction<T> action ); static void main(String [] args); static final String HADOOP_TOKEN_FILE_LOCATION; }### Answer: @Test public void testEquals() throws Exception { UserGroupInformation uugi = UserGroupInformation.createUserForTesting(USER_NAME, GROUP_NAMES); assertEquals(uugi, uugi); UserGroupInformation ugi2 = UserGroupInformation.createUserForTesting(USER_NAME, GROUP_NAMES); assertFalse(uugi.equals(ugi2)); assertFalse(uugi.hashCode() == ugi2.hashCode()); UserGroupInformation ugi3 = new UserGroupInformation(uugi.getSubject()); assertEquals(uugi, ugi3); assertEquals(uugi.hashCode(), ugi3.hashCode()); }
### Question: UserGroupInformation { public synchronized boolean addToken(Token<? extends TokenIdentifier> token) { return (token != null) ? addToken(token.getService(), token) : false; } UserGroupInformation(Subject subject); @InterfaceAudience.Public @InterfaceStability.Evolving static void setConfiguration(Configuration conf); static boolean isSecurityEnabled(); boolean hasKerberosCredentials(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static UserGroupInformation getCurrentUser(); static UserGroupInformation getBestUGI( String ticketCachePath, String user); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation getUGIFromTicketCache( String ticketCache, String user); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static UserGroupInformation getLoginUser(); boolean isFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static void loginUserFromKeytab(String user, String path ); synchronized void checkTGTAndReloginFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized void reloginFromKeytab(); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized void reloginFromTicketCache(); synchronized static UserGroupInformation loginUserFromKeytabAndReturnUGI(String user, String path ); @InterfaceAudience.Public @InterfaceStability.Evolving synchronized static boolean isLoginKeytabBased(); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createRemoteUser(String user); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createProxyUser(String user, UserGroupInformation realUser); @InterfaceAudience.Public @InterfaceStability.Evolving UserGroupInformation getRealUser(); @InterfaceAudience.Public @InterfaceStability.Evolving static UserGroupInformation createUserForTesting(String user, String[] userGroups); static UserGroupInformation createProxyUserForTesting(String user, UserGroupInformation realUser, String[] userGroups); String getShortUserName(); @InterfaceAudience.Public @InterfaceStability.Evolving String getUserName(); synchronized boolean addTokenIdentifier(TokenIdentifier tokenId); synchronized Set<TokenIdentifier> getTokenIdentifiers(); synchronized boolean addToken(Token<? extends TokenIdentifier> token); synchronized boolean addToken(Text alias, Token<? extends TokenIdentifier> token); synchronized Collection<Token<? extends TokenIdentifier>> getTokens(); synchronized Credentials getCredentials(); synchronized void addCredentials(Credentials credentials); synchronized String[] getGroupNames(); @Override String toString(); synchronized void setAuthenticationMethod(AuthenticationMethod authMethod); synchronized AuthenticationMethod getAuthenticationMethod(); static AuthenticationMethod getRealAuthenticationMethod( UserGroupInformation ugi); @Override boolean equals(Object o); @Override int hashCode(); @InterfaceAudience.Public @InterfaceStability.Evolving T doAs(PrivilegedAction<T> action); @InterfaceAudience.Public @InterfaceStability.Evolving T doAs(PrivilegedExceptionAction<T> action ); static void main(String [] args); static final String HADOOP_TOKEN_FILE_LOCATION; }### Answer: @SuppressWarnings("unchecked") @Test public <T extends TokenIdentifier> void testAddToken() throws Exception { UserGroupInformation ugi = UserGroupInformation.createRemoteUser("someone"); Token<T> t1 = mock(Token.class); Token<T> t2 = mock(Token.class); Token<T> t3 = mock(Token.class); ugi.addToken(t1); checkTokens(ugi, t1); ugi.addToken(t2); checkTokens(ugi, t2); when(t1.getService()).thenReturn(new Text("t1")); ugi.addToken(t1); checkTokens(ugi, t1, t2); when(t3.getService()).thenReturn(new Text("t1")); ugi.addToken(t3); checkTokens(ugi, t2, t3); when(t1.getService()).thenReturn(new Text("t1.1")); ugi.addToken(t1); checkTokens(ugi, t1, t2, t3); ugi.addToken(t1); checkTokens(ugi, t1, t2, t3); }
### Question: LdapGroupsMapping implements GroupMappingServiceProvider, Configurable { String extractPassword(String pwFile) { if (pwFile.isEmpty()) { return ""; } try { StringBuilder password = new StringBuilder(); Reader reader = new FileReader(pwFile); int c = reader.read(); while (c > -1) { password.append((char)c); c = reader.read(); } reader.close(); return password.toString(); } catch (IOException ioe) { throw new RuntimeException("Could not read password file: " + pwFile, ioe); } } @Override synchronized List<String> getGroups(String user); @Override void cacheGroupsRefresh(); @Override void cacheGroupsAdd(List<String> groups); @Override synchronized Configuration getConf(); @Override synchronized void setConf(Configuration conf); static final String LDAP_CONFIG_PREFIX; static final String LDAP_URL_KEY; static final String LDAP_URL_DEFAULT; static final String LDAP_USE_SSL_KEY; static final Boolean LDAP_USE_SSL_DEFAULT; static final String LDAP_KEYSTORE_KEY; static final String LDAP_KEYSTORE_DEFAULT; static final String LDAP_KEYSTORE_PASSWORD_KEY; static final String LDAP_KEYSTORE_PASSWORD_DEFAULT; static final String LDAP_KEYSTORE_PASSWORD_FILE_KEY; static final String LDAP_KEYSTORE_PASSWORD_FILE_DEFAULT; static final String BIND_USER_KEY; static final String BIND_USER_DEFAULT; static final String BIND_PASSWORD_KEY; static final String BIND_PASSWORD_DEFAULT; static final String BIND_PASSWORD_FILE_KEY; static final String BIND_PASSWORD_FILE_DEFAULT; static final String BASE_DN_KEY; static final String BASE_DN_DEFAULT; static final String USER_SEARCH_FILTER_KEY; static final String USER_SEARCH_FILTER_DEFAULT; static final String GROUP_SEARCH_FILTER_KEY; static final String GROUP_SEARCH_FILTER_DEFAULT; static final String GROUP_MEMBERSHIP_ATTR_KEY; static final String GROUP_MEMBERSHIP_ATTR_DEFAULT; static final String GROUP_NAME_ATTR_KEY; static final String GROUP_NAME_ATTR_DEFAULT; static final String DIRECTORY_SEARCH_TIMEOUT; static final int DIRECTORY_SEARCH_TIMEOUT_DEFAULT; static int RECONNECT_RETRY_COUNT; }### Answer: @Test public void testExtractPassword() throws IOException { File testDir = new File(System.getProperty("test.build.data", "target/test-dir")); testDir.mkdirs(); File secretFile = new File(testDir, "secret.txt"); Writer writer = new FileWriter(secretFile); writer.write("hadoop"); writer.close(); LdapGroupsMapping mapping = new LdapGroupsMapping(); Assert.assertEquals("hadoop", mapping.extractPassword(secretFile.getPath())); }
### Question: Credentials implements Writable { public void addAll(Credentials other) { addAll(other, true); } Credentials(); Credentials(Credentials credentials); byte[] getSecretKey(Text alias); Token<? extends TokenIdentifier> getToken(Text alias); void addToken(Text alias, Token<? extends TokenIdentifier> t); Collection<Token<? extends TokenIdentifier>> getAllTokens(); int numberOfTokens(); int numberOfSecretKeys(); void addSecretKey(Text alias, byte[] key); static Credentials readTokenStorageFile(Path filename, Configuration conf); static Credentials readTokenStorageFile(File filename, Configuration conf); void readTokenStorageStream(DataInputStream in); void writeTokenStorageToStream(DataOutputStream os); void writeTokenStorageFile(Path filename, Configuration conf); @Override void write(DataOutput out); @Override void readFields(DataInput in); void addAll(Credentials other); void mergeAll(Credentials other); }### Answer: @Test public void addAll() { Credentials creds = new Credentials(); creds.addToken(service[0], token[0]); creds.addToken(service[1], token[1]); creds.addSecretKey(secret[0], secret[0].getBytes()); creds.addSecretKey(secret[1], secret[1].getBytes()); Credentials credsToAdd = new Credentials(); credsToAdd.addToken(service[0], token[3]); credsToAdd.addToken(service[2], token[2]); credsToAdd.addSecretKey(secret[0], secret[3].getBytes()); credsToAdd.addSecretKey(secret[2], secret[2].getBytes()); creds.addAll(credsToAdd); assertEquals(3, creds.numberOfTokens()); assertEquals(3, creds.numberOfSecretKeys()); assertEquals(token[3], creds.getToken(service[0])); assertEquals(secret[3], new Text(creds.getSecretKey(secret[0]))); assertEquals(token[1], creds.getToken(service[1])); assertEquals(secret[1], new Text(creds.getSecretKey(secret[1]))); assertEquals(token[2], creds.getToken(service[2])); assertEquals(secret[2], new Text(creds.getSecretKey(secret[2]))); }
### Question: Credentials implements Writable { public void mergeAll(Credentials other) { addAll(other, false); } Credentials(); Credentials(Credentials credentials); byte[] getSecretKey(Text alias); Token<? extends TokenIdentifier> getToken(Text alias); void addToken(Text alias, Token<? extends TokenIdentifier> t); Collection<Token<? extends TokenIdentifier>> getAllTokens(); int numberOfTokens(); int numberOfSecretKeys(); void addSecretKey(Text alias, byte[] key); static Credentials readTokenStorageFile(Path filename, Configuration conf); static Credentials readTokenStorageFile(File filename, Configuration conf); void readTokenStorageStream(DataInputStream in); void writeTokenStorageToStream(DataOutputStream os); void writeTokenStorageFile(Path filename, Configuration conf); @Override void write(DataOutput out); @Override void readFields(DataInput in); void addAll(Credentials other); void mergeAll(Credentials other); }### Answer: @Test public void mergeAll() { Credentials creds = new Credentials(); creds.addToken(service[0], token[0]); creds.addToken(service[1], token[1]); creds.addSecretKey(secret[0], secret[0].getBytes()); creds.addSecretKey(secret[1], secret[1].getBytes()); Credentials credsToAdd = new Credentials(); credsToAdd.addToken(service[0], token[3]); credsToAdd.addToken(service[2], token[2]); credsToAdd.addSecretKey(secret[0], secret[3].getBytes()); credsToAdd.addSecretKey(secret[2], secret[2].getBytes()); creds.mergeAll(credsToAdd); assertEquals(3, creds.numberOfTokens()); assertEquals(3, creds.numberOfSecretKeys()); assertEquals(token[0], creds.getToken(service[0])); assertEquals(secret[0], new Text(creds.getSecretKey(secret[0]))); assertEquals(token[1], creds.getToken(service[1])); assertEquals(secret[1], new Text(creds.getSecretKey(secret[1]))); assertEquals(token[2], creds.getToken(service[2])); assertEquals(secret[2], new Text(creds.getSecretKey(secret[2]))); }
### Question: SecurityUtil { static boolean isTGSPrincipal(KerberosPrincipal principal) { if (principal == null) return false; if (principal.getName().equals("krbtgt/" + principal.getRealm() + "@" + principal.getRealm())) { return true; } return false; } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void isOriginalTGTReturnsCorrectValues() { assertTrue(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/foo@foo"))); assertTrue(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/[email protected]"))); assertFalse(SecurityUtil.isTGSPrincipal (null)); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("blah"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal(""))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/hello"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("/@"))); assertFalse(SecurityUtil.isTGSPrincipal (new KerberosPrincipal("krbtgt/foo@FOO"))); }
### Question: SecurityUtil { @InterfaceAudience.Public @InterfaceStability.Evolving public static String getServerPrincipal(String principalConfig, String hostname) throws IOException { String[] components = getComponents(principalConfig); if (components == null || components.length != 3 || !components[1].equals(HOSTNAME_PATTERN)) { return principalConfig; } else { return replacePattern(components, hostname); } } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void testGetServerPrincipal() throws IOException { String service = "hdfs/"; String realm = "@REALM"; String hostname = "foohost"; String userPrincipal = "foo@FOOREALM"; String shouldReplace = service + SecurityUtil.HOSTNAME_PATTERN + realm; String replaced = service + hostname + realm; verify(shouldReplace, hostname, replaced); String shouldNotReplace = service + SecurityUtil.HOSTNAME_PATTERN + "NAME" + realm; verify(shouldNotReplace, hostname, shouldNotReplace); verify(userPrincipal, hostname, userPrincipal); InetAddress notUsed = Mockito.mock(InetAddress.class); assertEquals(shouldNotReplace, SecurityUtil.getServerPrincipal(shouldNotReplace, notUsed)); Mockito.verify(notUsed, Mockito.never()).getCanonicalHostName(); }
### Question: SecurityUtil { @InterfaceAudience.Public @InterfaceStability.Evolving public static void login(final Configuration conf, final String keytabFileKey, final String userNameKey) throws IOException { login(conf, keytabFileKey, userNameKey, getLocalHostName()); } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void testStartsWithIncorrectSettings() throws IOException { Configuration conf = new Configuration(); conf.set( org.apache.hadoop.fs.CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); String keyTabKey="key"; conf.set(keyTabKey, ""); UserGroupInformation.setConfiguration(conf); boolean gotException = false; try { SecurityUtil.login(conf, keyTabKey, "", ""); } catch (IOException e) { gotException=true; } assertTrue("Exception for empty keytabfile name was expected", gotException); }
### Question: HFileBlock extends SchemaConfigured implements Cacheable { @Override public long heapSize() { long size = ClassSize.align( SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE + 2 * ClassSize.REFERENCE + 6 * Bytes.SIZEOF_INT + 1 * Bytes.SIZEOF_BYTE + 2 * Bytes.SIZEOF_LONG + Bytes.SIZEOF_BOOLEAN ); if (buf != null) { size += ClassSize.align(buf.capacity() + BYTE_BUFFER_HEAP_SIZE); } return ClassSize.align(size); } HFileBlock(BlockType blockType, int onDiskSizeWithoutHeader, int uncompressedSizeWithoutHeader, long prevBlockOffset, ByteBuffer buf, boolean fillHeader, long offset, boolean includesMemstoreTS, int minorVersion, int bytesPerChecksum, byte checksumType, int onDiskDataSizeWithHeader); HFileBlock(ByteBuffer b, int minorVersion); BlockType getBlockType(); short getDataBlockEncodingId(); int getOnDiskSizeWithHeader(); int getUncompressedSizeWithoutHeader(); long getPrevBlockOffset(); ByteBuffer getBufferReadOnly(); @Override String toString(); void assumeUncompressed(); void expectType(BlockType expectedType); long getOffset(); DataInputStream getByteStream(); @Override long heapSize(); static boolean readWithExtra(InputStream in, byte buf[], int bufOffset, int necessaryLen, int extraLen); int getNextBlockOnDiskSizeWithHeader(); @Override int getSerializedLength(); @Override void serialize(ByteBuffer destination); @Override CacheableDeserializer<Cacheable> getDeserializer(); @Override boolean equals(Object comparison); boolean doesIncludeMemstoreTS(); DataBlockEncoding getDataBlockEncoding(); int headerSize(); byte[] getDummyHeaderForVersion(); static final boolean FILL_HEADER; static final boolean DONT_FILL_HEADER; static final int ENCODED_HEADER_SIZE; static final int BYTE_BUFFER_HEAP_SIZE; }### Answer: @Test public void testBlockHeapSize() { if (ClassSize.is32BitJVM()) { assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 64); } else { assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 80); } for (int size : new int[] { 100, 256, 12345 }) { byte[] byteArr = new byte[HFileBlock.HEADER_SIZE_WITH_CHECKSUMS + size]; ByteBuffer buf = ByteBuffer.wrap(byteArr, 0, size); HFileBlock block = new HFileBlock(BlockType.DATA, size, size, -1, buf, HFileBlock.FILL_HEADER, -1, includesMemstoreTS, HFileBlock.MINOR_VERSION_NO_CHECKSUM, 0, ChecksumType.NULL.getCode(), 0); long byteBufferExpectedSize = ClassSize.align(ClassSize.estimateBase(buf.getClass(), true) + HFileBlock.HEADER_SIZE_WITH_CHECKSUMS + size); long hfileBlockExpectedSize = ClassSize.align(ClassSize.estimateBase(HFileBlock.class, true)); long expected = hfileBlockExpectedSize + byteBufferExpectedSize; assertEquals("Block data size: " + size + ", byte buffer expected " + "size: " + byteBufferExpectedSize + ", HFileBlock class expected " + "size: " + hfileBlockExpectedSize + ";", expected, block.heapSize()); } }
### Question: SecurityUtil { public static String getHostFromPrincipal(String principalName) { return new HadoopKerberosName(principalName).getHostName(); } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void testGetHostFromPrincipal() { assertEquals("host", SecurityUtil.getHostFromPrincipal("service/host@realm")); assertEquals(null, SecurityUtil.getHostFromPrincipal("service@realm")); }
### Question: SecurityUtil { public static String buildDTServiceName(URI uri, int defPort) { String authority = uri.getAuthority(); if (authority == null) { return null; } InetSocketAddress addr = NetUtils.createSocketAddr(authority, defPort); return buildTokenService(addr).toString(); } @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, String hostname); @InterfaceAudience.Public @InterfaceStability.Evolving static String getServerPrincipal(String principalConfig, InetAddress addr); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey); @InterfaceAudience.Public @InterfaceStability.Evolving static void login(final Configuration conf, final String keytabFileKey, final String userNameKey, String hostname); static String buildDTServiceName(URI uri, int defPort); static String getHostFromPrincipal(String principalName); @InterfaceAudience.Private static void setSecurityInfoProviders(SecurityInfo... providers); static KerberosInfo getKerberosInfo(Class<?> protocol, Configuration conf); static TokenInfo getTokenInfo(Class<?> protocol, Configuration conf); static InetSocketAddress getTokenServiceAddr(Token<?> token); static void setTokenService(Token<?> token, InetSocketAddress addr); static Text buildTokenService(InetSocketAddress addr); static Text buildTokenService(URI uri); static T doAsLoginUserOrFatal(PrivilegedAction<T> action); static T doAsLoginUser(PrivilegedExceptionAction<T> action); static T doAsCurrentUser(PrivilegedExceptionAction<T> action); static URLConnection openSecureHttpConnection(URL url); @InterfaceAudience.Private static InetAddress getByName(String hostname); static final Log LOG; static final String HOSTNAME_PATTERN; }### Answer: @Test public void testBuildDTServiceName() { SecurityUtil.setTokenServiceUseIp(true); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test: ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test: ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test: ); assertEquals("127.0.0.1:123", SecurityUtil.buildDTServiceName(URI.create("test: ); }
### Question: DomainSocket implements Closeable { public static String getEffectivePath(String path, int port) { return path.replace("_PORT", String.valueOf(port)); } private DomainSocket(String path, int fd); static String getLoadingFailureReason(); @VisibleForTesting static void disableBindPathValidation(); static String getEffectivePath(String path, int port); static DomainSocket bindAndListen(String path); DomainSocket accept(); static DomainSocket connect(String path); boolean isOpen(); String getPath(); DomainInputStream getInputStream(); DomainOutputStream getOutputStream(); DomainChannel getChannel(); void setAttribute(int type, int size); int getAttribute(int type); @Override void close(); void sendFileDescriptors(FileDescriptor jfds[], byte jbuf[], int offset, int length); int receiveFileDescriptors(FileDescriptor[] jfds, byte jbuf[], int offset, int length); int recvFileInputStreams(FileInputStream[] fis, byte buf[], int offset, int length); @Override String toString(); static final int SND_BUF_SIZE; static final int RCV_BUF_SIZE; static final int SND_TIMEO; static final int RCV_TIMEO; }### Answer: @Test(timeout=180000) public void testSocketPathSetGet() throws IOException { Assert.assertEquals("/var/run/hdfs/sock.100", DomainSocket.getEffectivePath("/var/run/hdfs/sock._PORT", 100)); }
### Question: DomainSocket implements Closeable { public static DomainSocket connect(String path) throws IOException { if (loadingFailureReason != null) { throw new UnsupportedOperationException(loadingFailureReason); } int fd = connect0(path); return new DomainSocket(path, fd); } private DomainSocket(String path, int fd); static String getLoadingFailureReason(); @VisibleForTesting static void disableBindPathValidation(); static String getEffectivePath(String path, int port); static DomainSocket bindAndListen(String path); DomainSocket accept(); static DomainSocket connect(String path); boolean isOpen(); String getPath(); DomainInputStream getInputStream(); DomainOutputStream getOutputStream(); DomainChannel getChannel(); void setAttribute(int type, int size); int getAttribute(int type); @Override void close(); void sendFileDescriptors(FileDescriptor jfds[], byte jbuf[], int offset, int length); int receiveFileDescriptors(FileDescriptor[] jfds, byte jbuf[], int offset, int length); int recvFileInputStreams(FileInputStream[] fis, byte buf[], int offset, int length); @Override String toString(); static final int SND_BUF_SIZE; static final int RCV_BUF_SIZE; static final int SND_TIMEO; static final int RCV_TIMEO; }### Answer: @Test(timeout=180000) public void testInvalidOperations() throws IOException { try { DomainSocket.connect( new File(sockDir.getDir(), "test_sock_invalid_operation"). getAbsolutePath()); } catch (IOException e) { GenericTestUtils.assertExceptionContains("connect(2) error: ", e); } }
### Question: SocketIOWithTimeout { SocketIOWithTimeout(SelectableChannel channel, long timeout) throws IOException { checkChannelValidity(channel); this.channel = channel; this.timeout = timeout; channel.configureBlocking(false); } SocketIOWithTimeout(SelectableChannel channel, long timeout); void setTimeout(long timeoutMs); }### Answer: @Test public void testSocketIOWithTimeout() throws Exception { Pipe pipe = Pipe.open(); Pipe.SourceChannel source = pipe.source(); Pipe.SinkChannel sink = pipe.sink(); try { final InputStream in = new SocketInputStream(source, TIMEOUT); OutputStream out = new SocketOutputStream(sink, TIMEOUT); byte[] writeBytes = TEST_STRING.getBytes(); byte[] readBytes = new byte[writeBytes.length]; byte byteWithHighBit = (byte)0x80; out.write(writeBytes); out.write(byteWithHighBit); doIO(null, out, TIMEOUT); in.read(readBytes); assertTrue(Arrays.equals(writeBytes, readBytes)); assertEquals(byteWithHighBit & 0xff, in.read()); doIO(in, null, TIMEOUT); ((SocketInputStream)in).setTimeout(TIMEOUT * 2); doIO(in, null, TIMEOUT * 2); ((SocketInputStream)in).setTimeout(0); TestingThread thread = new TestingThread(ctx) { @Override public void doWork() throws Exception { try { in.read(); fail("Did not fail with interrupt"); } catch (InterruptedIOException ste) { LOG.info("Got expection while reading as expected : " + ste.getMessage()); } } }; ctx.addThread(thread); ctx.startThreads(); Thread.sleep(1000); thread.interrupt(); ctx.stop(); assertTrue(source.isOpen()); assertTrue(sink.isOpen()); try { out.write(1); fail("Did not throw"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "stream is closed", ioe); } out.close(); assertFalse(sink.isOpen()); assertEquals(-1, in.read()); in.close(); assertFalse(source.isOpen()); } finally { if (source != null) { source.close(); } if (sink != null) { sink.close(); } } } @Test public void testSocketIOWithTimeout() throws Exception { Pipe pipe = Pipe.open(); Pipe.SourceChannel source = pipe.source(); Pipe.SinkChannel sink = pipe.sink(); try { final InputStream in = new SocketInputStream(source, TIMEOUT); OutputStream out = new SocketOutputStream(sink, TIMEOUT); byte[] writeBytes = TEST_STRING.getBytes(); byte[] readBytes = new byte[writeBytes.length]; byte byteWithHighBit = (byte)0x80; out.write(writeBytes); out.write(byteWithHighBit); doIO(null, out, TIMEOUT); in.read(readBytes); assertTrue(Arrays.equals(writeBytes, readBytes)); assertEquals(byteWithHighBit & 0xff, in.read()); doIO(in, null, TIMEOUT); ((SocketInputStream)in).setTimeout(TIMEOUT * 2); doIO(in, null, TIMEOUT * 2); ((SocketInputStream)in).setTimeout(0); TestingThread thread = new TestingThread(ctx) { @Override public void doWork() throws Exception { try { in.read(); fail("Did not fail with interrupt"); } catch (InterruptedIOException ste) { LOG.info("Got expection while reading as expected : " + ste.getMessage()); } } }; ctx.addThread(thread); ctx.startThreads(); Thread.sleep(1000); thread.interrupt(); ctx.stop(); assertTrue(source.isOpen()); assertTrue(sink.isOpen()); if (!Shell.WINDOWS && !Shell.PPC_64) { try { out.write(1); fail("Did not throw"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "stream is closed", ioe); } } out.close(); assertFalse(sink.isOpen()); assertEquals(-1, in.read()); in.close(); assertFalse(source.isOpen()); } finally { if (source != null) { source.close(); } if (sink != null) { sink.close(); } } }
### Question: ScriptBasedMapping extends CachedDNSToSwitchMapping { @Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); } ScriptBasedMapping(); ScriptBasedMapping(Configuration conf); @Override Configuration getConf(); @Override String toString(); @Override void setConf(Configuration conf); static final String NO_SCRIPT; }### Answer: @Test public void testFilenameMeansMultiSwitch() throws Throwable { Configuration conf = new Configuration(); conf.set(ScriptBasedMapping.SCRIPT_FILENAME_KEY, "any-filename"); ScriptBasedMapping mapping = createMapping(conf); assertFalse("Expected to be multi switch", mapping.isSingleSwitch()); mapping.setConf(new Configuration()); assertTrue("Expected to be single switch", mapping.isSingleSwitch()); }
### Question: NetUtils { public static InetAddress getLocalInetAddress(String host) throws SocketException { if (host == null) { return null; } InetAddress addr = null; try { addr = SecurityUtil.getByName(host); if (NetworkInterface.getByInetAddress(addr) == null) { addr = null; } } catch (UnknownHostException ignore) { } return addr; } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testGetLocalInetAddress() throws Exception { assertNotNull(NetUtils.getLocalInetAddress("127.0.0.1")); assertNull(NetUtils.getLocalInetAddress("invalid-address-for-test")); assertNull(NetUtils.getLocalInetAddress(null)); }
### Question: NetUtils { public static void verifyHostnames(String[] names) throws UnknownHostException { for (String name: names) { if (name == null) { throw new UnknownHostException("null hostname found"); } URI uri = null; try { uri = new URI(name); if (uri.getHost() == null) { uri = new URI("http: } } catch (URISyntaxException e) { uri = null; } if (uri == null || uri.getHost() == null) { throw new UnknownHostException(name + " is not a valid Inet address"); } } } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test(expected=UnknownHostException.class) public void testVerifyHostnamesException() throws UnknownHostException { String[] names = {"valid.host.com", "1.com", "invalid host here"}; NetUtils.verifyHostnames(names); } @Test public void testVerifyHostnamesNoException() { String[] names = {"valid.host.com", "1.com"}; try { NetUtils.verifyHostnames(names); } catch (UnknownHostException e) { fail("NetUtils.verifyHostnames threw unexpected UnknownHostException"); } }
### Question: NetUtils { public static boolean isLocalAddress(InetAddress addr) { boolean local = addr.isAnyLocalAddress() || addr.isLoopbackAddress(); if (!local) { try { local = NetworkInterface.getByInetAddress(addr) != null; } catch (SocketException e) { local = false; } } return local; } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testIsLocalAddress() throws Exception { assertTrue(NetUtils.isLocalAddress(InetAddress.getLocalHost())); Enumeration<NetworkInterface> interfaces = NetworkInterface .getNetworkInterfaces(); if (interfaces != null) { while (interfaces.hasMoreElements()) { NetworkInterface i = interfaces.nextElement(); Enumeration<InetAddress> addrs = i.getInetAddresses(); if (addrs == null) { continue; } while (addrs.hasMoreElements()) { InetAddress addr = addrs.nextElement(); assertTrue(NetUtils.isLocalAddress(addr)); } } } assertFalse(NetUtils.isLocalAddress(InetAddress.getByName("8.8.8.8"))); }
### Question: NetUtils { public static InetSocketAddress getConnectAddress(Server server) { return getConnectAddress(server.getListenerAddress()); } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testGetConnectAddress() throws IOException { NetUtils.addStaticResolution("host", "127.0.0.1"); InetSocketAddress addr = NetUtils.createSocketAddrForHost("host", 1); InetSocketAddress connectAddr = NetUtils.getConnectAddress(addr); assertEquals(addr.getHostName(), connectAddr.getHostName()); addr = new InetSocketAddress(1); connectAddr = NetUtils.getConnectAddress(addr); assertEquals(InetAddress.getLocalHost().getHostName(), connectAddr.getHostName()); }
### Question: NetUtils { public static InetSocketAddress createSocketAddr(String target) { return createSocketAddr(target, -1); } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testCreateSocketAddress() throws Throwable { InetSocketAddress addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig"); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1", 1000, "myconfig"); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(1000, addr.getPort()); try { addr = NetUtils.createSocketAddr( "127.0.0.1:blahblah", 1000, "myconfig"); fail("Should have failed to parse bad port"); } catch (IllegalArgumentException iae) { assertInException(iae, "myconfig"); } }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public int hashCode() { int result = address == null? 0: address.hashCode(); result ^= toString().hashCode(); return result; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHashCode() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress("localhost", 1234); assertEquals(hsa1.hashCode(), hsa2.hashCode()); HServerAddress hsa3 = new HServerAddress("localhost", 1235); assertNotSame(hsa1.hashCode(), hsa3.hashCode()); }
### Question: NetUtils { public static String normalizeHostName(String name) { try { return InetAddress.getByName(name).getHostAddress(); } catch (UnknownHostException e) { return name; } } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testNormalizeHostName() { List<String> hosts = Arrays.asList(new String[] {"127.0.0.1", "localhost", "3w.org", "UnknownHost"}); List<String> normalizedHosts = NetUtils.normalizeHostNames(hosts); assertEquals(normalizedHosts.get(0), hosts.get(0)); assertFalse(normalizedHosts.get(1).equals(hosts.get(1))); assertEquals(normalizedHosts.get(1), hosts.get(0)); assertFalse(normalizedHosts.get(2).equals(hosts.get(2))); assertEquals(normalizedHosts.get(3), hosts.get(3)); }
### Question: NetUtils { public static String getHostNameOfIP(String ipPort) { if (null == ipPort || !ipPortPattern.matcher(ipPort).matches()) { return null; } try { int colonIdx = ipPort.indexOf(':'); String ip = (-1 == colonIdx) ? ipPort : ipPort.substring(0, ipPort.indexOf(':')); return InetAddress.getByName(ip).getHostName(); } catch (UnknownHostException e) { return null; } } static SocketFactory getSocketFactory(Configuration conf, Class<?> clazz); static SocketFactory getDefaultSocketFactory(Configuration conf); static SocketFactory getSocketFactoryFromProperty( Configuration conf, String propValue); static InetSocketAddress createSocketAddr(String target); static InetSocketAddress createSocketAddr(String target, int defaultPort); static InetSocketAddress createSocketAddr(String target, int defaultPort, String configName); static InetSocketAddress createSocketAddrForHost(String host, int port); static URI getCanonicalUri(URI uri, int defaultPort); static void addStaticResolution(String host, String resolvedName); static String getStaticResolution(String host); static List <String[]> getAllStaticResolutions(); static InetSocketAddress getConnectAddress(Server server); static InetSocketAddress getConnectAddress(InetSocketAddress addr); static SocketInputWrapper getInputStream(Socket socket); static SocketInputWrapper getInputStream(Socket socket, long timeout); static OutputStream getOutputStream(Socket socket); static OutputStream getOutputStream(Socket socket, long timeout); static void connect(Socket socket, SocketAddress address, int timeout); static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout); static String normalizeHostName(String name); static List<String> normalizeHostNames(Collection<String> names); static void verifyHostnames(String[] names); static String getHostNameOfIP(String ipPort); static String getHostname(); static String getHostPortString(InetSocketAddress addr); static InetAddress getLocalInetAddress(String host); static boolean isLocalAddress(InetAddress addr); static IOException wrapException(final String destHost, final int destPort, final String localHost, final int localPort, final IOException exception); static boolean isValidSubnet(String subnet); static List<InetAddress> getIPs(String subnet, boolean returnSubinterfaces); static final String UNKNOWN_HOST; static final String HADOOP_WIKI; }### Answer: @Test public void testGetHostNameOfIP() { assertNull(NetUtils.getHostNameOfIP(null)); assertNull(NetUtils.getHostNameOfIP("")); assertNull(NetUtils.getHostNameOfIP("crazytown")); assertNull(NetUtils.getHostNameOfIP("127.0.0.1:")); assertNull(NetUtils.getHostNameOfIP("127.0.0.1:-1")); assertNull(NetUtils.getHostNameOfIP("127.0.0.1:A")); assertNotNull(NetUtils.getHostNameOfIP("127.0.0.1")); assertNotNull(NetUtils.getHostNameOfIP("127.0.0.1:1")); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { public HServerAddress() { super(); } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddress() { new HServerAddress(); }
### Question: DFSUtil { public static String getNamenodeNameServiceId(Configuration conf) { return getNameServiceId(conf, DFS_NAMENODE_RPC_ADDRESS_KEY); } private DFSUtil(); static Random getRandom(); static SecureRandom getSecureRandom(); static boolean isValidName(String src); static String bytes2String(byte[] bytes); static byte[] string2Bytes(String str); static String byteArray2String(byte[][] pathComponents); static byte[][] bytes2byteArray(byte[] bytes, byte separator); static byte[][] bytes2byteArray(byte[] bytes, int len, byte separator); static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks); static BlockLocation[] locatedBlocks2Locations(List<LocatedBlock> blocks); static Collection<String> getNameServiceIds(Configuration conf); static Collection<String> getNameNodeIds(Configuration conf, String nsId); static String addKeySuffixes(String key, String... suffixes); static Set<String> getAllNnPrincipals(Configuration conf); static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getBackupNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getSecondaryNameNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses( Configuration conf); static List<ConfiguredNNAddress> flattenAddressMap( Map<String, Map<String, InetSocketAddress>> map); static String addressMapToString( Map<String, Map<String, InetSocketAddress>> map); static String nnAddressesAsString(Configuration conf); static Collection<URI> getNsServiceRpcUris(Configuration conf); static Collection<URI> getNameServiceUris(Configuration conf, String... keys); static String getNameServiceIdFromAddress(final Configuration conf, final InetSocketAddress address, String... keys); static String getInfoServer(InetSocketAddress namenodeAddr, Configuration conf, boolean httpsAddress); static String substituteForWildcardAddress(String configuredAddress, String defaultHost); static void setGenericConf(Configuration conf, String nameserviceId, String nnId, String... keys); static float getPercentUsed(long used, long capacity); static float getPercentRemaining(long remaining, long capacity); static String percent2String(double percentage); static int roundBytesToGB(long bytes); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( DatanodeID datanodeid, Configuration conf, int socketTimeout, boolean connectToDnViaHostname, LocatedBlock locatedBlock); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory); static String getNamenodeNameServiceId(Configuration conf); static String getBackupNameServiceId(Configuration conf); static String getSecondaryNameServiceId(Configuration conf); static URI createUri(String scheme, InetSocketAddress address); static void addPBProtocol(Configuration conf, Class<?> protocol, BlockingService service, RPC.Server server); static String getNamenodeServiceAddr(final Configuration conf, String nsId, String nnId); static String getOnlyNameServiceIdOrNull(Configuration conf); static boolean parseHelpArgument(String[] args, String helpDescription, PrintStream out, boolean printGenericCommandUsage); static float getInvalidateWorkPctPerIteration(Configuration conf); static int getReplWorkMultiplier(Configuration conf); static String getSpnegoKeytabKey(Configuration conf, String defaultKey); static final Log LOG; static final Comparator<DatanodeInfo> DECOM_COMPARATOR; static Options helpOptions; static Option helpOpt; }### Answer: @Test public void getNameNodeNameServiceId() { Configuration conf = setupAddress(DFS_NAMENODE_RPC_ADDRESS_KEY); assertEquals("nn1", DFSUtil.getNamenodeNameServiceId(conf)); }
### Question: DFSUtil { public static String getBackupNameServiceId(Configuration conf) { return getNameServiceId(conf, DFS_NAMENODE_BACKUP_ADDRESS_KEY); } private DFSUtil(); static Random getRandom(); static SecureRandom getSecureRandom(); static boolean isValidName(String src); static String bytes2String(byte[] bytes); static byte[] string2Bytes(String str); static String byteArray2String(byte[][] pathComponents); static byte[][] bytes2byteArray(byte[] bytes, byte separator); static byte[][] bytes2byteArray(byte[] bytes, int len, byte separator); static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks); static BlockLocation[] locatedBlocks2Locations(List<LocatedBlock> blocks); static Collection<String> getNameServiceIds(Configuration conf); static Collection<String> getNameNodeIds(Configuration conf, String nsId); static String addKeySuffixes(String key, String... suffixes); static Set<String> getAllNnPrincipals(Configuration conf); static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getBackupNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getSecondaryNameNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses( Configuration conf); static List<ConfiguredNNAddress> flattenAddressMap( Map<String, Map<String, InetSocketAddress>> map); static String addressMapToString( Map<String, Map<String, InetSocketAddress>> map); static String nnAddressesAsString(Configuration conf); static Collection<URI> getNsServiceRpcUris(Configuration conf); static Collection<URI> getNameServiceUris(Configuration conf, String... keys); static String getNameServiceIdFromAddress(final Configuration conf, final InetSocketAddress address, String... keys); static String getInfoServer(InetSocketAddress namenodeAddr, Configuration conf, boolean httpsAddress); static String substituteForWildcardAddress(String configuredAddress, String defaultHost); static void setGenericConf(Configuration conf, String nameserviceId, String nnId, String... keys); static float getPercentUsed(long used, long capacity); static float getPercentRemaining(long remaining, long capacity); static String percent2String(double percentage); static int roundBytesToGB(long bytes); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( DatanodeID datanodeid, Configuration conf, int socketTimeout, boolean connectToDnViaHostname, LocatedBlock locatedBlock); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory); static String getNamenodeNameServiceId(Configuration conf); static String getBackupNameServiceId(Configuration conf); static String getSecondaryNameServiceId(Configuration conf); static URI createUri(String scheme, InetSocketAddress address); static void addPBProtocol(Configuration conf, Class<?> protocol, BlockingService service, RPC.Server server); static String getNamenodeServiceAddr(final Configuration conf, String nsId, String nnId); static String getOnlyNameServiceIdOrNull(Configuration conf); static boolean parseHelpArgument(String[] args, String helpDescription, PrintStream out, boolean printGenericCommandUsage); static float getInvalidateWorkPctPerIteration(Configuration conf); static int getReplWorkMultiplier(Configuration conf); static String getSpnegoKeytabKey(Configuration conf, String defaultKey); static final Log LOG; static final Comparator<DatanodeInfo> DECOM_COMPARATOR; static Options helpOptions; static Option helpOpt; }### Answer: @Test public void getBackupNameServiceId() { Configuration conf = setupAddress(DFS_NAMENODE_BACKUP_ADDRESS_KEY); assertEquals("nn1", DFSUtil.getBackupNameServiceId(conf)); }
### Question: DFSUtil { public static String getSecondaryNameServiceId(Configuration conf) { return getNameServiceId(conf, DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY); } private DFSUtil(); static Random getRandom(); static SecureRandom getSecureRandom(); static boolean isValidName(String src); static String bytes2String(byte[] bytes); static byte[] string2Bytes(String str); static String byteArray2String(byte[][] pathComponents); static byte[][] bytes2byteArray(byte[] bytes, byte separator); static byte[][] bytes2byteArray(byte[] bytes, int len, byte separator); static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks); static BlockLocation[] locatedBlocks2Locations(List<LocatedBlock> blocks); static Collection<String> getNameServiceIds(Configuration conf); static Collection<String> getNameNodeIds(Configuration conf, String nsId); static String addKeySuffixes(String key, String... suffixes); static Set<String> getAllNnPrincipals(Configuration conf); static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getBackupNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getSecondaryNameNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses( Configuration conf); static List<ConfiguredNNAddress> flattenAddressMap( Map<String, Map<String, InetSocketAddress>> map); static String addressMapToString( Map<String, Map<String, InetSocketAddress>> map); static String nnAddressesAsString(Configuration conf); static Collection<URI> getNsServiceRpcUris(Configuration conf); static Collection<URI> getNameServiceUris(Configuration conf, String... keys); static String getNameServiceIdFromAddress(final Configuration conf, final InetSocketAddress address, String... keys); static String getInfoServer(InetSocketAddress namenodeAddr, Configuration conf, boolean httpsAddress); static String substituteForWildcardAddress(String configuredAddress, String defaultHost); static void setGenericConf(Configuration conf, String nameserviceId, String nnId, String... keys); static float getPercentUsed(long used, long capacity); static float getPercentRemaining(long remaining, long capacity); static String percent2String(double percentage); static int roundBytesToGB(long bytes); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( DatanodeID datanodeid, Configuration conf, int socketTimeout, boolean connectToDnViaHostname, LocatedBlock locatedBlock); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory); static String getNamenodeNameServiceId(Configuration conf); static String getBackupNameServiceId(Configuration conf); static String getSecondaryNameServiceId(Configuration conf); static URI createUri(String scheme, InetSocketAddress address); static void addPBProtocol(Configuration conf, Class<?> protocol, BlockingService service, RPC.Server server); static String getNamenodeServiceAddr(final Configuration conf, String nsId, String nnId); static String getOnlyNameServiceIdOrNull(Configuration conf); static boolean parseHelpArgument(String[] args, String helpDescription, PrintStream out, boolean printGenericCommandUsage); static float getInvalidateWorkPctPerIteration(Configuration conf); static int getReplWorkMultiplier(Configuration conf); static String getSpnegoKeytabKey(Configuration conf, String defaultKey); static final Log LOG; static final Comparator<DatanodeInfo> DECOM_COMPARATOR; static Options helpOptions; static Option helpOpt; }### Answer: @Test public void getSecondaryNameServiceId() { Configuration conf = setupAddress(DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY); assertEquals("nn1", DFSUtil.getSecondaryNameServiceId(conf)); }
### Question: DFSUtil { public static Collection<String> getNameServiceIds(Configuration conf) { return conf.getTrimmedStringCollection(DFS_NAMESERVICES); } private DFSUtil(); static Random getRandom(); static SecureRandom getSecureRandom(); static boolean isValidName(String src); static String bytes2String(byte[] bytes); static byte[] string2Bytes(String str); static String byteArray2String(byte[][] pathComponents); static byte[][] bytes2byteArray(byte[] bytes, byte separator); static byte[][] bytes2byteArray(byte[] bytes, int len, byte separator); static BlockLocation[] locatedBlocks2Locations(LocatedBlocks blocks); static BlockLocation[] locatedBlocks2Locations(List<LocatedBlock> blocks); static Collection<String> getNameServiceIds(Configuration conf); static Collection<String> getNameNodeIds(Configuration conf, String nsId); static String addKeySuffixes(String key, String... suffixes); static Set<String> getAllNnPrincipals(Configuration conf); static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getBackupNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getSecondaryNameNodeAddresses( Configuration conf); static Map<String, Map<String, InetSocketAddress>> getNNServiceRpcAddresses( Configuration conf); static List<ConfiguredNNAddress> flattenAddressMap( Map<String, Map<String, InetSocketAddress>> map); static String addressMapToString( Map<String, Map<String, InetSocketAddress>> map); static String nnAddressesAsString(Configuration conf); static Collection<URI> getNsServiceRpcUris(Configuration conf); static Collection<URI> getNameServiceUris(Configuration conf, String... keys); static String getNameServiceIdFromAddress(final Configuration conf, final InetSocketAddress address, String... keys); static String getInfoServer(InetSocketAddress namenodeAddr, Configuration conf, boolean httpsAddress); static String substituteForWildcardAddress(String configuredAddress, String defaultHost); static void setGenericConf(Configuration conf, String nameserviceId, String nnId, String... keys); static float getPercentUsed(long used, long capacity); static float getPercentRemaining(long remaining, long capacity); static String percent2String(double percentage); static int roundBytesToGB(long bytes); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( DatanodeID datanodeid, Configuration conf, int socketTimeout, boolean connectToDnViaHostname, LocatedBlock locatedBlock); static ClientDatanodeProtocol createClientDatanodeProtocolProxy( InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory); static String getNamenodeNameServiceId(Configuration conf); static String getBackupNameServiceId(Configuration conf); static String getSecondaryNameServiceId(Configuration conf); static URI createUri(String scheme, InetSocketAddress address); static void addPBProtocol(Configuration conf, Class<?> protocol, BlockingService service, RPC.Server server); static String getNamenodeServiceAddr(final Configuration conf, String nsId, String nnId); static String getOnlyNameServiceIdOrNull(Configuration conf); static boolean parseHelpArgument(String[] args, String helpDescription, PrintStream out, boolean printGenericCommandUsage); static float getInvalidateWorkPctPerIteration(Configuration conf); static int getReplWorkMultiplier(Configuration conf); static String getSpnegoKeytabKey(Configuration conf, String defaultKey); static final Log LOG; static final Comparator<DatanodeInfo> DECOM_COMPARATOR; static Options helpOptions; static Option helpOpt; }### Answer: @Test public void testGetNameServiceIds() { HdfsConfiguration conf = new HdfsConfiguration(); conf.set(DFS_NAMESERVICES, "nn1,nn2"); Collection<String> nameserviceIds = DFSUtil.getNameServiceIds(conf); Iterator<String> it = nameserviceIds.iterator(); assertEquals(2, nameserviceIds.size()); assertEquals("nn1", it.next().toString()); assertEquals("nn2", it.next().toString()); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public String toString() { return this.cachedToString; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddressInetSocketAddress() { HServerAddress hsa1 = new HServerAddress(new InetSocketAddress("localhost", 1234)); System.out.println(hsa1.toString()); }
### Question: FileInputStreamCache { public synchronized void close() { if (closed) return; closed = true; IOUtils.cleanup(LOG, cacheCleaner); for (Iterator<Entry<Key, Value>> iter = map.entries().iterator(); iter.hasNext();) { Entry<Key, Value> entry = iter.next(); entry.getValue().close(); iter.remove(); } } FileInputStreamCache(int maxCacheSize, long expiryTimeMs); void put(DatanodeID datanodeID, ExtendedBlock block, FileInputStream fis[]); synchronized FileInputStream[] get(DatanodeID datanodeID, ExtendedBlock block); synchronized void close(); synchronized String toString(); long getExpiryTimeMs(); int getMaxCacheSize(); }### Answer: @Test public void testCreateAndDestroy() throws Exception { FileInputStreamCache cache = new FileInputStreamCache(10, 1000); cache.close(); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (getClass() != o.getClass()) return false; return compareTo((HServerAddress)o) == 0; } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testHServerAddressString() { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress(new InetSocketAddress("localhost", 1234)); assertTrue(hsa1.equals(hsa2)); }
### Question: HServerAddress implements WritableComparable<HServerAddress> { public void readFields(DataInput in) throws IOException { String hostname = in.readUTF(); int port = in.readInt(); if (hostname != null && hostname.length() > 0) { this.address = getResolvedAddress(new InetSocketAddress(hostname, port)); checkBindAddressCanBeResolved(); createCachedToString(); } } HServerAddress(); HServerAddress(InetSocketAddress address); HServerAddress(final String hostname, final int port); HServerAddress(HServerAddress other); String getBindAddress(); int getPort(); String getHostname(); String getHostnameAndPort(); InetSocketAddress getInetSocketAddress(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); void readFields(DataInput in); void write(DataOutput out); int compareTo(HServerAddress o); }### Answer: @Test public void testReadFields() throws IOException { HServerAddress hsa1 = new HServerAddress("localhost", 1234); HServerAddress hsa2 = new HServerAddress("localhost", 1235); byte [] bytes = Writables.getBytes(hsa1); HServerAddress deserialized = (HServerAddress)Writables.getWritable(bytes, new HServerAddress()); assertEquals(hsa1, deserialized); bytes = Writables.getBytes(hsa2); deserialized = (HServerAddress)Writables.getWritable(bytes, new HServerAddress()); assertNotSame(hsa1, deserialized); }
### Question: LayoutVersion { public static boolean supports(final Feature f, final int lv) { final EnumSet<Feature> set = map.get(lv); return set != null && set.contains(f); } static String getString(); static boolean supports(final Feature f, final int lv); static int getCurrentLayoutVersion(); static final int BUGFIX_HDFS_2991_VERSION; }### Answer: @Test public void testRelease203() { assertTrue(LayoutVersion.supports(Feature.DELEGATION_TOKEN, Feature.RESERVED_REL20_203.lv)); } @Test public void testRelease204() { assertTrue(LayoutVersion.supports(Feature.DELEGATION_TOKEN, Feature.RESERVED_REL20_204.lv)); }
### Question: MD5FileUtils { public static MD5Hash computeMd5ForFile(File dataFile) throws IOException { InputStream in = new FileInputStream(dataFile); try { MessageDigest digester = MD5Hash.getDigester(); DigestInputStream dis = new DigestInputStream(in, digester); IOUtils.copyBytes(dis, new IOUtils.NullOutputStream(), 128*1024); return new MD5Hash(digester.digest()); } finally { IOUtils.closeStream(in); } } static void verifySavedMD5(File dataFile, MD5Hash expectedMD5); static MD5Hash readStoredMd5ForFile(File dataFile); static MD5Hash computeMd5ForFile(File dataFile); static void saveMD5File(File dataFile, MD5Hash digest); static File getDigestFileForFile(File file); static final String MD5_SUFFIX; }### Answer: @Test public void testComputeMd5ForFile() throws Exception { MD5Hash computedDigest = MD5FileUtils.computeMd5ForFile(TEST_FILE); assertEquals(TEST_MD5, computedDigest); }
### Question: MD5FileUtils { public static void verifySavedMD5(File dataFile, MD5Hash expectedMD5) throws IOException { MD5Hash storedHash = readStoredMd5ForFile(dataFile); if (!expectedMD5.equals(storedHash)) { throw new IOException( "File " + dataFile + " did not match stored MD5 checksum " + " (stored: " + storedHash + ", computed: " + expectedMD5); } } static void verifySavedMD5(File dataFile, MD5Hash expectedMD5); static MD5Hash readStoredMd5ForFile(File dataFile); static MD5Hash computeMd5ForFile(File dataFile); static void saveMD5File(File dataFile, MD5Hash digest); static File getDigestFileForFile(File file); static final String MD5_SUFFIX; }### Answer: @Test(expected=IOException.class) public void testVerifyMD5FileMissing() throws Exception { MD5FileUtils.verifySavedMD5(TEST_FILE, TEST_MD5); }
### Question: ServerName implements Comparable<ServerName> { public static ServerName parseServerName(final String str) { return SERVERNAME_PATTERN.matcher(str).matches()? new ServerName(str): new ServerName(str, NON_STARTCODE); } ServerName(final String hostname, final int port, final long startcode); ServerName(final String serverName); ServerName(final String hostAndPort, final long startCode); static String parseHostname(final String serverName); static int parsePort(final String serverName); static long parseStartcode(final String serverName); @Override String toString(); synchronized byte [] getVersionedBytes(); String getServerName(); String getHostname(); int getPort(); long getStartcode(); static String getServerName(String hostName, int port, long startcode); static String getServerName(final String hostAndPort, final long startcode); String getHostAndPort(); static long getServerStartcodeFromServerName(final String serverName); static String getServerNameLessStartCode(String inServerName); @Override int compareTo(ServerName other); @Override int hashCode(); @Override boolean equals(Object o); static ServerName findServerWithSameHostnamePort(final Collection<ServerName> names, final ServerName serverName); static boolean isSameHostnameAndPort(final ServerName left, final ServerName right); static ServerName parseVersionedServerName(final byte [] versionedBytes); static ServerName parseServerName(final String str); static final int NON_STARTCODE; static final String SERVERNAME_SEPARATOR; static Pattern SERVERNAME_PATTERN; static final String UNKNOWN_SERVERNAME; }### Answer: @Test public void testRegexPatterns() { assertTrue(Pattern.matches(Addressing.VALID_PORT_REGEX, "123")); assertFalse(Pattern.matches(Addressing.VALID_PORT_REGEX, "")); assertTrue(ServerName.SERVERNAME_PATTERN.matcher("www1.example.org,1234,567").matches()); ServerName.parseServerName("a.b.c,58102,1319771740322"); ServerName.parseServerName("192.168.1.199,58102,1319771740322"); ServerName.parseServerName("a.b.c:58102"); ServerName.parseServerName("192.168.1.199:58102"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public Iterator<T> iterator() { return new LinkedSetIterator(); } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testOneElementBasic() { LOG.info("Test one element basic"); set.add(list.get(0)); assertEquals(1, set.size()); assertFalse(set.isEmpty()); Iterator<Integer> iter = set.iterator(); assertTrue(iter.hasNext()); assertEquals(list.get(0), iter.next()); assertFalse(iter.hasNext()); LOG.info("Test one element basic - DONE"); } @Test public void testMultiBasic() { LOG.info("Test multi element basic"); for (Integer i : list) { assertTrue(set.add(i)); } assertEquals(list.size(), set.size()); for (Integer i : list) { assertTrue(set.contains(i)); } for (Integer i : list) { assertFalse(set.add(i)); } for (Integer i : list) { assertTrue(set.contains(i)); } Iterator<Integer> iter = set.iterator(); int num = 0; while (iter.hasNext()) { assertEquals(list.get(num++), iter.next()); } assertEquals(list.size(), num); LOG.info("Test multi element basic - DONE"); } @Test public void testRemoveMulti() { LOG.info("Test remove multi"); for (Integer i : list) { assertTrue(set.add(i)); } for (int i = 0; i < NUM / 2; i++) { assertTrue(set.remove(list.get(i))); } for (int i = 0; i < NUM / 2; i++) { assertFalse(set.contains(list.get(i))); } for (int i = NUM / 2; i < NUM; i++) { assertTrue(set.contains(list.get(i))); } Iterator<Integer> iter = set.iterator(); int num = NUM / 2; while (iter.hasNext()) { assertEquals(list.get(num++), iter.next()); } assertEquals(num, NUM); LOG.info("Test remove multi - DONE"); } @Test public void testRemoveAll() { LOG.info("Test remove all"); for (Integer i : list) { assertTrue(set.add(i)); } for (int i = 0; i < NUM; i++) { assertTrue(set.remove(list.get(i))); } for (int i = 0; i < NUM; i++) { assertFalse(set.contains(list.get(i))); } Iterator<Integer> iter = set.iterator(); assertFalse(iter.hasNext()); assertTrue(set.isEmpty()); LOG.info("Test remove all - DONE"); }
### Question: ServerName implements Comparable<ServerName> { public ServerName(final String hostname, final int port, final long startcode) { this.hostname = hostname; this.port = port; this.startcode = startcode; this.servername = getServerName(hostname, port, startcode); } ServerName(final String hostname, final int port, final long startcode); ServerName(final String serverName); ServerName(final String hostAndPort, final long startCode); static String parseHostname(final String serverName); static int parsePort(final String serverName); static long parseStartcode(final String serverName); @Override String toString(); synchronized byte [] getVersionedBytes(); String getServerName(); String getHostname(); int getPort(); long getStartcode(); static String getServerName(String hostName, int port, long startcode); static String getServerName(final String hostAndPort, final long startcode); String getHostAndPort(); static long getServerStartcodeFromServerName(final String serverName); static String getServerNameLessStartCode(String inServerName); @Override int compareTo(ServerName other); @Override int hashCode(); @Override boolean equals(Object o); static ServerName findServerWithSameHostnamePort(final Collection<ServerName> names, final ServerName serverName); static boolean isSameHostnameAndPort(final ServerName left, final ServerName right); static ServerName parseVersionedServerName(final byte [] versionedBytes); static ServerName parseServerName(final String str); static final int NON_STARTCODE; static final String SERVERNAME_SEPARATOR; static Pattern SERVERNAME_PATTERN; static final String UNKNOWN_SERVERNAME; }### Answer: @Test public void testServerName() { ServerName sn = new ServerName("www.example.org", 1234, 5678); ServerName sn2 = new ServerName("www.example.org", 1234, 5678); ServerName sn3 = new ServerName("www.example.org", 1234, 56789); assertTrue(sn.equals(sn2)); assertFalse(sn.equals(sn3)); assertEquals(sn.hashCode(), sn2.hashCode()); assertNotSame(sn.hashCode(), sn3.hashCode()); assertEquals(sn.toString(), ServerName.getServerName("www.example.org", 1234, 5678)); assertEquals(sn.toString(), ServerName.getServerName("www.example.org:1234", 5678)); assertEquals(sn.toString(), "www.example.org" + ServerName.SERVERNAME_SEPARATOR + "1234" + ServerName.SERVERNAME_SEPARATOR + "5678"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { public T pollFirst() { if (head == null) { return null; } T first = head.element; this.remove(first); return first; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollOneElement() { LOG.info("Test poll one element"); set.add(list.get(0)); assertEquals(list.get(0), set.pollFirst()); assertNull(set.pollFirst()); LOG.info("Test poll one element - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public List<T> pollAll() { List<T> retList = new ArrayList<T>(size); while (head != null) { retList.add(head.element); head = head.after; } this.clear(); return retList; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollAll() { LOG.info("Test poll all"); for (Integer i : list) { assertTrue(set.add(i)); } while (set.pollFirst() != null); assertEquals(0, set.size()); assertTrue(set.isEmpty()); for (int i = 0; i < NUM; i++) { assertFalse(set.contains(list.get(i))); } Iterator<Integer> iter = set.iterator(); assertFalse(iter.hasNext()); LOG.info("Test poll all - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public List<T> pollN(int n) { if (n >= size) { return pollAll(); } List<T> retList = new ArrayList<T>(n); while (n-- > 0 && head != null) { T curr = head.element; this.removeElem(curr); retList.add(curr); } shrinkIfNecessary(); return retList; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testPollNOne() { LOG.info("Test pollN one"); set.add(list.get(0)); List<Integer> l = set.pollN(10); assertEquals(1, l.size()); assertEquals(list.get(0), l.get(0)); LOG.info("Test pollN one - DONE"); } @Test public void testPollNMulti() { LOG.info("Test pollN multi"); set.addAll(list); List<Integer> l = set.pollN(10); assertEquals(10, l.size()); for (int i = 0; i < 10; i++) { assertEquals(list.get(i), l.get(i)); } l = set.pollN(1000); assertEquals(NUM - 10, l.size()); for (int i = 10; i < NUM; i++) { assertEquals(list.get(i), l.get(i - 10)); } assertTrue(set.isEmpty()); assertEquals(0, set.size()); LOG.info("Test pollN multi - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override public void clear() { super.clear(); this.head = null; this.tail = null; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testClear() { LOG.info("Test clear"); set.addAll(list); assertEquals(NUM, set.size()); assertFalse(set.isEmpty()); set.clear(); assertEquals(0, set.size()); assertTrue(set.isEmpty()); assertEquals(0, set.pollAll().size()); assertEquals(0, set.pollN(10).size()); assertNull(set.pollFirst()); Iterator<Integer> iter = set.iterator(); assertFalse(iter.hasNext()); LOG.info("Test clear - DONE"); }
### Question: LightWeightLinkedSet extends LightWeightHashSet<T> { @Override @SuppressWarnings("unchecked") public <U> U[] toArray(U[] a) { if (a == null) { throw new NullPointerException("Input array can not be null"); } if (a.length < size) { a = (U[]) java.lang.reflect.Array.newInstance(a.getClass() .getComponentType(), size); } int currentIndex = 0; DoubleLinkedElement<T> current = head; while (current != null) { T curr = current.element; a[currentIndex++] = (U) curr; current = current.after; } return a; } LightWeightLinkedSet(int initCapacity, float maxLoadFactor, float minLoadFactor); LightWeightLinkedSet(); T pollFirst(); @Override List<T> pollN(int n); @Override List<T> pollAll(); @Override @SuppressWarnings("unchecked") U[] toArray(U[] a); @Override Iterator<T> iterator(); @Override void clear(); }### Answer: @Test public void testOther() { LOG.info("Test other"); assertTrue(set.addAll(list)); Integer[] array = set.toArray(new Integer[0]); assertEquals(NUM, array.length); for (int i = 0; i < array.length; i++) { assertTrue(list.contains(array[i])); } assertEquals(NUM, set.size()); Object[] array2 = set.toArray(); assertEquals(NUM, array2.length); for (int i = 0; i < array2.length; i++) { assertTrue(list.contains((Integer) array2[i])); } LOG.info("Test capacity - DONE"); } @Test public void testOther() { LOG.info("Test other"); assertTrue(set.addAll(list)); Integer[] array = set.toArray(new Integer[0]); assertEquals(NUM, array.length); for (int i = 0; i < array.length; i++) { assertTrue(list.contains(array[i])); } assertEquals(NUM, set.size()); Object[] array2 = set.toArray(); assertEquals(NUM, array2.length); for (int i = 0; i < array2.length; i++) { assertTrue(list.contains(array2[i])); } LOG.info("Test capacity - DONE"); }
### Question: ServerName implements Comparable<ServerName> { public static long getServerStartcodeFromServerName(final String serverName) { int index = serverName.lastIndexOf(SERVERNAME_SEPARATOR); return Long.parseLong(serverName.substring(index + 1)); } ServerName(final String hostname, final int port, final long startcode); ServerName(final String serverName); ServerName(final String hostAndPort, final long startCode); static String parseHostname(final String serverName); static int parsePort(final String serverName); static long parseStartcode(final String serverName); @Override String toString(); synchronized byte [] getVersionedBytes(); String getServerName(); String getHostname(); int getPort(); long getStartcode(); static String getServerName(String hostName, int port, long startcode); static String getServerName(final String hostAndPort, final long startcode); String getHostAndPort(); static long getServerStartcodeFromServerName(final String serverName); static String getServerNameLessStartCode(String inServerName); @Override int compareTo(ServerName other); @Override int hashCode(); @Override boolean equals(Object o); static ServerName findServerWithSameHostnamePort(final Collection<ServerName> names, final ServerName serverName); static boolean isSameHostnameAndPort(final ServerName left, final ServerName right); static ServerName parseVersionedServerName(final byte [] versionedBytes); static ServerName parseServerName(final String str); static final int NON_STARTCODE; static final String SERVERNAME_SEPARATOR; static Pattern SERVERNAME_PATTERN; static final String UNKNOWN_SERVERNAME; }### Answer: @Test public void getServerStartcodeFromServerName() { ServerName sn = new ServerName("www.example.org", 1234, 5678); assertEquals(5678, ServerName.getServerStartcodeFromServerName(sn.toString())); assertNotSame(5677, ServerName.getServerStartcodeFromServerName(sn.toString())); }
### Question: HDFSBlocksDistribution { public void addHostsAndBlockWeight(String[] hosts, long weight) { if (hosts == null || hosts.length == 0) { return; } addUniqueWeight(weight); for (String hostname : hosts) { addHostAndBlockWeight(hostname, weight); } } HDFSBlocksDistribution(); @Override synchronized String toString(); void addHostsAndBlockWeight(String[] hosts, long weight); Map<String,HostAndWeight> getHostAndWeights(); long getWeight(String host); long getUniqueBlocksTotalWeight(); float getBlockLocalityIndex(String host); void add(HDFSBlocksDistribution otherBlocksDistribution); List<String> getTopHosts(); }### Answer: @Test public void testAddHostsAndBlockWeight() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.addHostsAndBlockWeight(null, 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[0], 100); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 101); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[] {"test"}, 202); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("test host should have weight 303", 303, distribution.getHostAndWeights().get("test").getWeight()); distribution.addHostsAndBlockWeight(new String[] {"testTwo"}, 222); assertEquals("Should be two hosts", 2, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 525", 525, distribution.getUniqueBlocksTotalWeight()); }
### Question: HDFSBlocksDistribution { public void add(HDFSBlocksDistribution otherBlocksDistribution) { Map<String,HostAndWeight> otherHostAndWeights = otherBlocksDistribution.getHostAndWeights(); for (Map.Entry<String, HostAndWeight> otherHostAndWeight: otherHostAndWeights.entrySet()) { addHostAndBlockWeight(otherHostAndWeight.getValue().host, otherHostAndWeight.getValue().weight); } addUniqueWeight(otherBlocksDistribution.getUniqueBlocksTotalWeight()); } HDFSBlocksDistribution(); @Override synchronized String toString(); void addHostsAndBlockWeight(String[] hosts, long weight); Map<String,HostAndWeight> getHostAndWeights(); long getWeight(String host); long getUniqueBlocksTotalWeight(); float getBlockLocalityIndex(String host); void add(HDFSBlocksDistribution otherBlocksDistribution); List<String> getTopHosts(); }### Answer: @Test public void testAdd() throws Exception { HDFSBlocksDistribution distribution = new HDFSBlocksDistribution(); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Expecting no hosts weights", 0, distribution.getHostAndWeights().size()); distribution.addHostsAndBlockWeight(new String[]{"test"}, 10); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); distribution.add(new MockHDFSBlocksDistribution()); assertEquals("Should be one host", 1, distribution.getHostAndWeights().size()); assertEquals("Total weight should be 10", 10, distribution.getUniqueBlocksTotalWeight()); }
### Question: BlockMissingException extends IOException { public BlockMissingException(String filename, String description, long offset) { super(description); this.filename = filename; this.offset = offset; } BlockMissingException(String filename, String description, long offset); String getFile(); long getOffset(); }### Answer: @Test public void testBlockMissingException() throws Exception { LOG.info("Test testBlockMissingException started."); long blockSize = 1024L; int numBlocks = 4; conf = new HdfsConfiguration(); try { dfs = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATANODES).build(); dfs.waitActive(); fileSys = (DistributedFileSystem)dfs.getFileSystem(); Path file1 = new Path("/user/dhruba/raidtest/file1"); createOldFile(fileSys, file1, 1, numBlocks, blockSize); LocatedBlocks locations = null; locations = fileSys.dfs.getNamenode().getBlockLocations(file1.toString(), 0, numBlocks * blockSize); LOG.info("Remove first block of file"); corruptBlock(file1, locations.get(0).getBlock()); validateFile(fileSys, file1); } finally { if (fileSys != null) fileSys.close(); if (dfs != null) dfs.shutdown(); } LOG.info("Test testBlockMissingException completed."); } @Test public void testBlockMissingException() throws Exception { LOG.info("Test testBlockMissingException started."); long blockSize = 1024L; int numBlocks = 4; conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE, 10); try { dfs = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATANODES).build(); dfs.waitActive(); fileSys = dfs.getFileSystem(); Path file1 = new Path("/user/dhruba/raidtest/file1"); createOldFile(fileSys, file1, 1, numBlocks, blockSize); LocatedBlocks locations = null; locations = fileSys.dfs.getNamenode().getBlockLocations(file1.toString(), 0, numBlocks * blockSize); LOG.info("Remove first block of file"); corruptBlock(file1, locations.get(0).getBlock()); validateFile(fileSys, file1); } finally { if (fileSys != null) fileSys.close(); if (dfs != null) dfs.shutdown(); } LOG.info("Test testBlockMissingException completed."); }
### Question: QuorumJournalManager implements JournalManager { @Override public void format(NamespaceInfo nsInfo) throws IOException { QuorumCall<AsyncLogger,Void> call = loggers.format(nsInfo); try { call.waitFor(loggers.size(), loggers.size(), 0, FORMAT_TIMEOUT_MS, "format"); } catch (InterruptedException e) { throw new IOException("Interrupted waiting for format() response"); } catch (TimeoutException e) { throw new IOException("Timed out waiting for format() response"); } if (call.countExceptions() > 0) { call.rethrowException("Could not format one or more JournalNodes"); } } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testFormat() throws Exception { QuorumJournalManager qjm = closeLater(new QuorumJournalManager( conf, cluster.getQuorumJournalURI("testFormat-jid"), FAKE_NSINFO)); assertFalse(qjm.hasSomeData()); qjm.format(FAKE_NSINFO); assertTrue(qjm.hasSomeData()); }
### Question: QuorumJournalManager implements JournalManager { @Override public void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk) throws IOException { QuorumCall<AsyncLogger, RemoteEditLogManifest> q = loggers.getEditLogManifest(fromTxnId); Map<AsyncLogger, RemoteEditLogManifest> resps = loggers.waitForWriteQuorum(q, selectInputStreamsTimeoutMs, "selectInputStreams"); LOG.debug("selectInputStream manifests:\n" + Joiner.on("\n").withKeyValueSeparator(": ").join(resps)); final PriorityQueue<EditLogInputStream> allStreams = new PriorityQueue<EditLogInputStream>(64, JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR); for (Map.Entry<AsyncLogger, RemoteEditLogManifest> e : resps.entrySet()) { AsyncLogger logger = e.getKey(); RemoteEditLogManifest manifest = e.getValue(); for (RemoteEditLog remoteLog : manifest.getLogs()) { URL url = logger.buildURLToFetchLogs(remoteLog.getStartTxId()); EditLogInputStream elis = EditLogFileInputStream.fromUrl( url, remoteLog.getStartTxId(), remoteLog.getEndTxId(), remoteLog.isInProgress()); allStreams.add(elis); } } JournalSet.chainAndMakeRedundantStreams( streams, allStreams, fromTxnId, inProgressOk); } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testSelectInputStreamsMajorityDown() throws Exception { cluster.shutdown(); List<EditLogInputStream> streams = Lists.newArrayList(); try { qjm.selectInputStreams(streams, 0, false); fail("Did not throw IOE"); } catch (QuorumException ioe) { GenericTestUtils.assertExceptionContains( "Got too many exceptions", ioe); assertTrue(streams.isEmpty()); } }
### Question: QuorumJournalManager implements JournalManager { @Override public void recoverUnfinalizedSegments() throws IOException { Preconditions.checkState(!isActiveWriter, "already active writer"); LOG.info("Starting recovery process for unclosed journal segments..."); Map<AsyncLogger, NewEpochResponseProto> resps = createNewUniqueEpoch(); LOG.info("Successfully started new epoch " + loggers.getEpoch()); if (LOG.isDebugEnabled()) { LOG.debug("newEpoch(" + loggers.getEpoch() + ") responses:\n" + QuorumCall.mapToString(resps)); } long mostRecentSegmentTxId = Long.MIN_VALUE; for (NewEpochResponseProto r : resps.values()) { if (r.hasLastSegmentTxId()) { mostRecentSegmentTxId = Math.max(mostRecentSegmentTxId, r.getLastSegmentTxId()); } } if (mostRecentSegmentTxId != Long.MIN_VALUE) { recoverUnclosedSegment(mostRecentSegmentTxId); } isActiveWriter = true; } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testChangeWritersLogsInSync() throws Exception { writeSegment(cluster, qjm, 1, 3, false); QJMTestUtil.assertExistsInQuorum(cluster, NNStorage.getInProgressEditsFileName(1)); qjm = closeLater(new QuorumJournalManager( conf, cluster.getQuorumJournalURI(JID), FAKE_NSINFO)); qjm.recoverUnfinalizedSegments(); checkRecovery(cluster, 1, 3); }
### Question: QuorumJournalManager implements JournalManager { @Override public void close() throws IOException { loggers.close(); } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testNewerVersionOfSegmentWins() throws Exception { setupEdgeCaseOneJnHasSegmentWithAcceptedRecovery(); cluster.getJournalNode(0).stopAndJoin(0); qjm = createSpyingQJM(); try { assertEquals(100, QJMTestUtil.recoverAndReturnLastTxn(qjm)); writeSegment(cluster, qjm, 101, 50, false); } finally { qjm.close(); } cluster.restartJournalNode(0); qjm = createSpyingQJM(); try { assertEquals(150, QJMTestUtil.recoverAndReturnLastTxn(qjm)); } finally { qjm.close(); } } @Test public void testNewerVersionOfSegmentWins2() throws Exception { setupEdgeCaseOneJnHasSegmentWithAcceptedRecovery(); cluster.getJournalNode(0).stopAndJoin(0); qjm = createSpyingQJM(); try { assertEquals(100, QJMTestUtil.recoverAndReturnLastTxn(qjm)); cluster.restartJournalNode(0); cluster.getJournalNode(1).stopAndJoin(0); writeSegment(cluster, qjm, 101, 50, false); } finally { qjm.close(); } cluster.restartJournalNode(1); cluster.getJournalNode(2).stopAndJoin(0); qjm = createSpyingQJM(); try { assertEquals(150, QJMTestUtil.recoverAndReturnLastTxn(qjm)); } finally { qjm.close(); } }
### Question: FuzzyRowFilter extends FilterBase { static SatisfiesCode satisfies(byte[] row, byte[] fuzzyKeyBytes, byte[] fuzzyKeyMeta) { return satisfies(row, 0, row.length, fuzzyKeyBytes, fuzzyKeyMeta); } FuzzyRowFilter(); FuzzyRowFilter(List<Pair<byte[], byte[]>> fuzzyKeysData); @Override ReturnCode filterKeyValue(KeyValue kv); @Override KeyValue getNextKeyHint(KeyValue currentKV); @Override boolean filterAllRemaining(); @Override void write(DataOutput dataOutput); @Override void readFields(DataInput dataInput); @Override String toString(); }### Answer: @Test public void testSatisfies() { Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NEXT_EXISTS, FuzzyRowFilter.satisfies(new byte[]{1, (byte) -128, 0, 0, 1}, new byte[]{1, 0, 1}, new byte[]{0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.YES, FuzzyRowFilter.satisfies(new byte[]{1, (byte) -128, 1, 0, 1}, new byte[]{1, 0, 1}, new byte[]{0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NEXT_EXISTS, FuzzyRowFilter.satisfies(new byte[]{1, (byte) -128, 2, 0, 1}, new byte[]{1, 0, 1}, new byte[]{0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NO_NEXT, FuzzyRowFilter.satisfies(new byte[]{2, 3, 1, 1, 1}, new byte[]{1, 0, 1}, new byte[]{0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.YES, FuzzyRowFilter.satisfies(new byte[]{1, 2, 1, 3, 3}, new byte[]{1, 2, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NEXT_EXISTS, FuzzyRowFilter.satisfies(new byte[]{1, 1, 1, 3, 0}, new byte[]{1, 2, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NEXT_EXISTS, FuzzyRowFilter.satisfies(new byte[]{1, 1, 1, 3, 0}, new byte[]{1, (byte) 245, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NO_NEXT, FuzzyRowFilter.satisfies(new byte[]{1, (byte) 245, 1, 3, 0}, new byte[]{1, 1, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NO_NEXT, FuzzyRowFilter.satisfies(new byte[]{1, 3, 1, 3, 0}, new byte[]{1, 2, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NO_NEXT, FuzzyRowFilter.satisfies(new byte[]{2, 1, 1, 1, 0}, new byte[]{1, 2, 0, 3}, new byte[]{0, 0, 1, 0})); Assert.assertEquals(FuzzyRowFilter.SatisfiesCode.NEXT_EXISTS, FuzzyRowFilter.satisfies(new byte[]{1, 2, 1, 0, 1}, new byte[]{0, 1, 2}, new byte[]{1, 0, 0})); }
### Question: QuorumJournalManager implements JournalManager { @Override public String toString() { return "QJM to " + loggers; } QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo); QuorumJournalManager(Configuration conf, URI uri, NamespaceInfo nsInfo, AsyncLogger.Factory loggerFactory); static void checkJournalId(String jid); @Override void format(NamespaceInfo nsInfo); @Override boolean hasSomeData(); @Override EditLogOutputStream startLogSegment(long txId); @Override void finalizeLogSegment(long firstTxId, long lastTxId); @Override void setOutputBufferCapacity(int size); @Override void purgeLogsOlderThan(long minTxIdToKeep); @Override void recoverUnfinalizedSegments(); @Override void close(); @Override void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxnId, boolean inProgressOk); @Override String toString(); }### Answer: @Test public void testToString() throws Exception { GenericTestUtils.assertMatches( qjm.toString(), "QJM to \\[127.0.0.1:\\d+, 127.0.0.1:\\d+, 127.0.0.1:\\d+\\]"); }
### Question: IPCLoggerChannel implements AsyncLogger { @Override public ListenableFuture<Void> sendEdits( final long segmentTxId, final long firstTxnId, final int numTxns, final byte[] data) { try { reserveQueueSpace(data.length); } catch (LoggerTooFarBehindException e) { return Futures.immediateFailedFuture(e); } final long submitNanos = System.nanoTime(); ListenableFuture<Void> ret = null; try { ret = executor.submit(new Callable<Void>() { @Override public Void call() throws IOException { throwIfOutOfSync(); long rpcSendTimeNanos = System.nanoTime(); try { getProxy().journal(createReqInfo(), segmentTxId, firstTxnId, numTxns, data); } catch (IOException e) { QuorumJournalManager.LOG.warn( "Remote journal " + IPCLoggerChannel.this + " failed to " + "write txns " + firstTxnId + "-" + (firstTxnId + numTxns - 1) + ". Will try to write to this JN again after the next " + "log roll.", e); synchronized (IPCLoggerChannel.this) { outOfSync = true; } throw e; } finally { long now = System.nanoTime(); long rpcTime = TimeUnit.MICROSECONDS.convert( now - rpcSendTimeNanos, TimeUnit.NANOSECONDS); long endToEndTime = TimeUnit.MICROSECONDS.convert( now - submitNanos, TimeUnit.NANOSECONDS); metrics.addWriteEndToEndLatency(endToEndTime); metrics.addWriteRpcLatency(rpcTime); } synchronized (IPCLoggerChannel.this) { highestAckedTxId = firstTxnId + numTxns - 1; lastAckNanos = submitNanos; } return null; } }); } finally { if (ret == null) { unreserveQueueSpace(data.length); } else { Futures.addCallback(ret, new FutureCallback<Void>() { @Override public void onFailure(Throwable t) { unreserveQueueSpace(data.length); } @Override public void onSuccess(Void t) { unreserveQueueSpace(data.length); } }); } } return ret; } IPCLoggerChannel(Configuration conf, NamespaceInfo nsInfo, String journalId, InetSocketAddress addr); @Override synchronized void setEpoch(long epoch); @Override synchronized void setCommittedTxId(long txid); @Override void close(); @Override URL buildURLToFetchLogs(long segmentTxId); synchronized int getQueuedEditsSize(); InetSocketAddress getRemoteAddress(); synchronized boolean isOutOfSync(); @Override ListenableFuture<Boolean> isFormatted(); @Override ListenableFuture<GetJournalStateResponseProto> getJournalState(); @Override ListenableFuture<NewEpochResponseProto> newEpoch( final long epoch); @Override ListenableFuture<Void> sendEdits( final long segmentTxId, final long firstTxnId, final int numTxns, final byte[] data); @Override ListenableFuture<Void> format(final NamespaceInfo nsInfo); @Override ListenableFuture<Void> startLogSegment(final long txid); @Override ListenableFuture<Void> finalizeLogSegment( final long startTxId, final long endTxId); @Override ListenableFuture<Void> purgeLogsOlderThan(final long minTxIdToKeep); @Override ListenableFuture<RemoteEditLogManifest> getEditLogManifest( final long fromTxnId); @Override ListenableFuture<PrepareRecoveryResponseProto> prepareRecovery( final long segmentTxId); @Override ListenableFuture<Void> acceptRecovery( final SegmentStateProto log, final URL url); @Override String toString(); @Override synchronized void appendHtmlReport(StringBuilder sb); synchronized long getLagTxns(); synchronized long getLagTimeMillis(); }### Answer: @Test public void testSimpleCall() throws Exception { ch.sendEdits(1, 1, 3, FAKE_DATA).get(); Mockito.verify(mockProxy).journal(Mockito.<RequestInfo>any(), Mockito.eq(1L), Mockito.eq(1L), Mockito.eq(3), Mockito.same(FAKE_DATA)); }
### Question: Journal implements Closeable { synchronized NewEpochResponseProto newEpoch( NamespaceInfo nsInfo, long epoch) throws IOException { checkFormatted(); storage.checkConsistentNamespace(nsInfo); if (epoch <= getLastPromisedEpoch()) { throw new IOException("Proposed epoch " + epoch + " <= last promise " + getLastPromisedEpoch()); } updateLastPromisedEpoch(epoch); abortCurSegment(); NewEpochResponseProto.Builder builder = NewEpochResponseProto.newBuilder(); EditLogFile latestFile = scanStorageForLatestEdits(); if (latestFile != null) { builder.setLastSegmentTxId(latestFile.getFirstTxId()); } return builder.build(); } Journal(File logDir, String journalId, StorageErrorReporter errorReporter); @Override // Closeable void close(); synchronized long getLastWriterEpoch(); void heartbeat(RequestInfo reqInfo); synchronized boolean isFormatted(); synchronized void startLogSegment(RequestInfo reqInfo, long txid); synchronized void finalizeLogSegment(RequestInfo reqInfo, long startTxId, long endTxId); synchronized void purgeLogsOlderThan(RequestInfo reqInfo, long minTxIdToKeep); RemoteEditLogManifest getEditLogManifest(long sinceTxId); synchronized PrepareRecoveryResponseProto prepareRecovery( RequestInfo reqInfo, long segmentTxId); synchronized void acceptRecovery(RequestInfo reqInfo, SegmentStateProto segment, URL fromUrl); }### Answer: @Test public void testNamespaceVerification() throws Exception { journal.newEpoch(FAKE_NSINFO, 1); try { journal.newEpoch(FAKE_NSINFO_2, 2); fail("Did not fail newEpoch() when namespaces mismatched"); } catch (IOException ioe) { GenericTestUtils.assertExceptionContains( "Incompatible namespaceID", ioe); } }
### Question: JournalNode implements Tool, Configurable { public InetSocketAddress getBoundIpcAddress() { return rpcServer.getAddress(); } @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override int run(String[] args); void start(); boolean isStarted(); InetSocketAddress getBoundIpcAddress(); InetSocketAddress getBoundHttpAddress(); void stop(int rc); void stopAndJoin(int rc); static void main(String[] args); static final Log LOG; }### Answer: @Test public void testJournal() throws Exception { MetricsRecordBuilder metrics = MetricsAsserts.getMetrics( journal.getMetricsForTests().getName()); MetricsAsserts.assertCounter("BatchesWritten", 0L, metrics); MetricsAsserts.assertCounter("BatchesWrittenWhileLagging", 0L, metrics); MetricsAsserts.assertGauge("CurrentLagTxns", 0L, metrics); IPCLoggerChannel ch = new IPCLoggerChannel( conf, FAKE_NSINFO, journalId, jn.getBoundIpcAddress()); ch.newEpoch(1).get(); ch.setEpoch(1); ch.startLogSegment(1).get(); ch.sendEdits(1L, 1, 1, "hello".getBytes(Charsets.UTF_8)).get(); metrics = MetricsAsserts.getMetrics( journal.getMetricsForTests().getName()); MetricsAsserts.assertCounter("BatchesWritten", 1L, metrics); MetricsAsserts.assertCounter("BatchesWrittenWhileLagging", 0L, metrics); MetricsAsserts.assertGauge("CurrentLagTxns", 0L, metrics); ch.setCommittedTxId(100L); ch.sendEdits(1L, 2, 1, "goodbye".getBytes(Charsets.UTF_8)).get(); metrics = MetricsAsserts.getMetrics( journal.getMetricsForTests().getName()); MetricsAsserts.assertCounter("BatchesWritten", 2L, metrics); MetricsAsserts.assertCounter("BatchesWrittenWhileLagging", 1L, metrics); MetricsAsserts.assertGauge("CurrentLagTxns", 98L, metrics); }
### Question: DatanodeDescriptor extends DatanodeInfo { public Block[] getInvalidateBlocks(int maxblocks) { synchronized (invalidateBlocks) { Block[] deleteList = invalidateBlocks.pollToArray(new Block[Math.min( invalidateBlocks.size(), maxblocks)]); return deleteList.length == 0 ? null : deleteList; } } DatanodeDescriptor(DatanodeID nodeID); DatanodeDescriptor(DatanodeID nodeID, String networkLocation); DatanodeDescriptor(DatanodeID nodeID, long capacity, long dfsUsed, long remaining, long bpused, int xceiverCount, int failedVolumes); DatanodeDescriptor(DatanodeID nodeID, String networkLocation, long capacity, long dfsUsed, long remaining, long bpused, int xceiverCount, int failedVolumes); boolean addBlock(BlockInfo b); boolean removeBlock(BlockInfo b); BlockInfo replaceBlock(BlockInfo oldBlock, BlockInfo newBlock); void resetBlocks(); void clearBlockQueues(); int numBlocks(); void updateHeartbeat(long capacity, long dfsUsed, long remaining, long blockPoolUsed, int xceiverCount, int volFailures); Iterator<BlockInfo> getBlockIterator(); List<BlockTargetPair> getReplicationCommand(int maxTransfers); BlockInfoUnderConstruction[] getLeaseRecoveryCommand(int maxTransfers); Block[] getInvalidateBlocks(int maxblocks); int getBlocksScheduled(); void incBlocksScheduled(); @Override int hashCode(); @Override boolean equals(Object obj); void setDisallowed(boolean flag); boolean isDisallowed(); int getVolumeFailures(); @Override void updateRegInfo(DatanodeID nodeReg); long getBalancerBandwidth(); void setBalancerBandwidth(long bandwidth); boolean areBlockContentsStale(); void markStaleAfterFailover(); void receivedBlockReport(); @Override String dumpDatanode(); public DecommissioningStatus decommissioningStatus; public boolean isAlive; public boolean needKeyUpdate; }### Answer: @Test public void testGetInvalidateBlocks() throws Exception { final int MAX_BLOCKS = 10; final int REMAINING_BLOCKS = 2; final int MAX_LIMIT = MAX_BLOCKS - REMAINING_BLOCKS; DatanodeDescriptor dd = DFSTestUtil.getLocalDatanodeDescriptor(); ArrayList<Block> blockList = new ArrayList<Block>(MAX_BLOCKS); for (int i=0; i<MAX_BLOCKS; i++) { blockList.add(new Block(i, 0, GenerationStamp.FIRST_VALID_STAMP)); } dd.addBlocksToBeInvalidated(blockList); Block[] bc = dd.getInvalidateBlocks(MAX_LIMIT); assertEquals(bc.length, MAX_LIMIT); bc = dd.getInvalidateBlocks(MAX_LIMIT); assertEquals(bc.length, REMAINING_BLOCKS); }
### Question: Host2NodesMap { boolean remove(DatanodeDescriptor node) { if (node==null) { return false; } String ipAddr = node.getIpAddr(); hostmapLock.writeLock().lock(); try { DatanodeDescriptor[] nodes = map.get(ipAddr); if (nodes==null) { return false; } if (nodes.length==1) { if (nodes[0]==node) { map.remove(ipAddr); return true; } else { return false; } } int i=0; for(; i<nodes.length; i++) { if (nodes[i]==node) { break; } } if (i==nodes.length) { return false; } else { DatanodeDescriptor[] newNodes; newNodes = new DatanodeDescriptor[nodes.length-1]; System.arraycopy(nodes, 0, newNodes, 0, i); System.arraycopy(nodes, i+1, newNodes, i, nodes.length-i-1); map.put(ipAddr, newNodes); return true; } } finally { hostmapLock.writeLock().unlock(); } } DatanodeDescriptor getDatanodeByXferAddr(String ipAddr, int xferPort); @Override String toString(); }### Answer: @Test public void testRemove() throws Exception { DatanodeDescriptor nodeNotInMap = DFSTestUtil.getDatanodeDescriptor("3.3.3.3", "/d1/r4"); assertFalse(map.remove(nodeNotInMap)); assertTrue(map.remove(dataNodes[0])); assertTrue(map.getDatanodeByHost("1.1.1.1.")==null); assertTrue(map.getDatanodeByHost("2.2.2.2")==dataNodes[1]); DatanodeDescriptor node = map.getDatanodeByHost("3.3.3.3"); assertTrue(node==dataNodes[2] || node==dataNodes[3]); assertNull(map.getDatanodeByHost("4.4.4.4")); assertTrue(map.remove(dataNodes[2])); assertNull(map.getDatanodeByHost("1.1.1.1")); assertEquals(map.getDatanodeByHost("2.2.2.2"), dataNodes[1]); assertEquals(map.getDatanodeByHost("3.3.3.3"), dataNodes[3]); assertTrue(map.remove(dataNodes[3])); assertNull(map.getDatanodeByHost("1.1.1.1")); assertEquals(map.getDatanodeByHost("2.2.2.2"), dataNodes[1]); assertNull(map.getDatanodeByHost("3.3.3.3")); assertFalse(map.remove(null)); assertTrue(map.remove(dataNodes[1])); assertFalse(map.remove(dataNodes[1])); }
### Question: JspHelper { public static String getDelegationTokenUrlParam(String tokenString) { if (tokenString == null ) { return ""; } if (UserGroupInformation.isSecurityEnabled()) { return SET_DELEGATION + tokenString; } else { return ""; } } private JspHelper(); static DatanodeInfo bestNode(LocatedBlocks blks, Configuration conf); static DatanodeInfo bestNode(LocatedBlock blk, Configuration conf); static DatanodeInfo bestNode(DatanodeInfo[] nodes, boolean doRandom, Configuration conf); static void streamBlockInAscii(InetSocketAddress addr, String poolId, long blockId, Token<BlockTokenIdentifier> blockToken, long genStamp, long blockSize, long offsetIntoBlock, long chunkSizeToView, JspWriter out, Configuration conf, DataEncryptionKey encryptionKey); static void addTableHeader(JspWriter out); static void addTableRow(JspWriter out, String[] columns); static void addTableRow(JspWriter out, String[] columns, int row); static void addTableFooter(JspWriter out); static void sortNodeList(final List<DatanodeDescriptor> nodes, String field, String order); static void printPathWithLinks(String dir, JspWriter out, int namenodeInfoPort, String tokenString, String nnAddress ); static void printGotoForm(JspWriter out, int namenodeInfoPort, String tokenString, String file, String nnAddress); static void createTitle(JspWriter out, HttpServletRequest req, String file); static int string2ChunkSizeToView(String s, int defaultValue); static String getVersionTable(); static String validatePath(String p); static Long validateLong(String value); static String validateURL(String value); static UserGroupInformation getDefaultWebUser(Configuration conf ); static UserGroupInformation getUGI(HttpServletRequest request, Configuration conf); static UserGroupInformation getUGI(ServletContext context, HttpServletRequest request, Configuration conf); static UserGroupInformation getUGI(ServletContext context, HttpServletRequest request, Configuration conf, final AuthenticationMethod secureAuthMethod, final boolean tryUgiParameter); static String getDelegationTokenUrlParam(String tokenString); static String getUrlParam(String name, String val, String paramSeparator); static String getUrlParam(String name, String val, boolean firstParam); static String getUrlParam(String name, String val); static final String CURRENT_CONF; static final String DELEGATION_PARAMETER_NAME; static final String NAMENODE_ADDRESS; }### Answer: @Test public void testDelegationTokenUrlParam() { conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); String tokenString = "xyzabc"; String delegationTokenParam = JspHelper .getDelegationTokenUrlParam(tokenString); Assert.assertEquals(JspHelper.SET_DELEGATION + "xyzabc", delegationTokenParam); conf.set(DFSConfigKeys.HADOOP_SECURITY_AUTHENTICATION, "simple"); UserGroupInformation.setConfiguration(conf); delegationTokenParam = JspHelper .getDelegationTokenUrlParam(tokenString); Assert.assertEquals("", delegationTokenParam); }
### Question: TransferFsImage { static MD5Hash getFileClient(String nnHostPort, String queryString, List<File> localPaths, Storage dstStorage, boolean getChecksum) throws IOException { String str = HttpConfig.getSchemePrefix() + nnHostPort + "/getimage?" + queryString; LOG.info("Opening connection to " + str); URL url = new URL(str); return doGetUrl(url, localPaths, dstStorage, getChecksum); } static void downloadMostRecentImageToDirectory(String fsName, File dir); static MD5Hash downloadImageToStorage( String fsName, long imageTxId, Storage dstStorage, boolean needDigest); static void uploadImageFromStorage(String fsName, InetSocketAddress imageListenAddress, Storage storage, long txid); static void getFileServer(ServletResponse response, File localfile, FileInputStream infile, DataTransferThrottler throttler); static MD5Hash doGetUrl(URL url, List<File> localPaths, Storage dstStorage, boolean getChecksum); final static String CONTENT_LENGTH; final static String MD5_HEADER; }### Answer: @Test public void testClientSideException() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(0).build(); NNStorage mockStorage = Mockito.mock(NNStorage.class); List<File> localPath = Collections.<File>singletonList( new File("/xxxxx-does-not-exist/blah")); try { String fsName = NetUtils.getHostPortString( cluster.getNameNode().getHttpAddress()); String id = "getimage=1&txid=0"; TransferFsImage.getFileClient(fsName, id, localPath, mockStorage, false); fail("Didn't get an exception!"); } catch (IOException ioe) { Mockito.verify(mockStorage).reportErrorOnFile(localPath.get(0)); assertTrue( "Unexpected exception: " + StringUtils.stringifyException(ioe), ioe.getMessage().contains("Unable to download to any storage")); } finally { cluster.shutdown(); } } @Test public void testClientSideExceptionOnJustOneDir() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .numDataNodes(0).build(); NNStorage mockStorage = Mockito.mock(NNStorage.class); List<File> localPaths = ImmutableList.of( new File("/xxxxx-does-not-exist/blah"), new File(TEST_DIR, "testfile") ); try { String fsName = NetUtils.getHostPortString( cluster.getNameNode().getHttpAddress()); String id = "getimage=1&txid=0"; TransferFsImage.getFileClient(fsName, id, localPaths, mockStorage, false); Mockito.verify(mockStorage).reportErrorOnFile(localPaths.get(0)); assertTrue("The valid local file should get saved properly", localPaths.get(1).length() > 0); } finally { cluster.shutdown(); } } @Test(timeout = 5000) public void testImageTransferTimeout() throws Exception { HttpServer testServer = HttpServerFunctionalTest.createServer("hdfs"); try { testServer.addServlet("GetImage", "/getimage", TestGetImageServlet.class); testServer.start(); URL serverURL = HttpServerFunctionalTest.getServerURL(testServer); TransferFsImage.timeout = 2000; try { TransferFsImage.getFileClient(serverURL.getAuthority(), "txid=1", null, null, false); fail("TransferImage Should fail with timeout"); } catch (SocketTimeoutException e) { assertEquals("Read should timeout", "Read timed out", e.getMessage()); } } finally { if (testServer != null) { testServer.stop(); } } }
### Question: ParseFilter { public Filter parseFilterString (String filterString) throws CharacterCodingException { return parseFilterString(Bytes.toBytes(filterString)); } Filter parseFilterString(String filterString); Filter parseFilterString(byte [] filterStringAsByteArray); byte [] extractFilterSimpleExpression(byte [] filterStringAsByteArray, int filterExpressionStartOffset); Filter parseSimpleFilterExpression(byte [] filterStringAsByteArray); static byte [] getFilterName(byte [] filterStringAsByteArray); static ArrayList<byte []> getFilterArguments(byte [] filterStringAsByteArray); void reduce(Stack<ByteBuffer> operatorStack, Stack<Filter> filterStack, ByteBuffer operator); static Filter popArguments(Stack<ByteBuffer> operatorStack, Stack <Filter> filterStack); boolean hasHigherPriority(ByteBuffer a, ByteBuffer b); static byte [] createUnescapdArgument(byte [] filterStringAsByteArray, int argumentStartIndex, int argumentEndIndex); static boolean checkForOr(byte [] filterStringAsByteArray, int indexOfOr); static boolean checkForAnd(byte [] filterStringAsByteArray, int indexOfAnd); static boolean checkForSkip(byte [] filterStringAsByteArray, int indexOfSkip); static boolean checkForWhile(byte [] filterStringAsByteArray, int indexOfWhile); static boolean isQuoteUnescaped(byte [] array, int quoteIndex); static byte [] removeQuotesFromByteArray(byte [] quotedByteArray); static int convertByteArrayToInt(byte [] numberAsByteArray); static long convertByteArrayToLong(byte [] numberAsByteArray); static boolean convertByteArrayToBoolean(byte [] booleanAsByteArray); static CompareFilter.CompareOp createCompareOp(byte [] compareOpAsByteArray); static WritableByteArrayComparable createComparator(byte [] comparator); static byte [][] parseComparator(byte [] comparator); Set<String> getSupportedFilters(); static Map<String, String> getAllFilters(); static void registerFilter(String name, String filterClass); }### Answer: @Test public void testKeyOnlyFilter() throws IOException { String filterString = "KeyOnlyFilter()"; doTestFilter(filterString, KeyOnlyFilter.class); String filterString2 = "KeyOnlyFilter ('') "; byte [] filterStringAsByteArray2 = Bytes.toBytes(filterString2); try { filter = f.parseFilterString(filterStringAsByteArray2); assertTrue(false); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } @Test public void testFirstKeyOnlyFilter() throws IOException { String filterString = " FirstKeyOnlyFilter( ) "; doTestFilter(filterString, FirstKeyOnlyFilter.class); String filterString2 = " FirstKeyOnlyFilter ('') "; byte [] filterStringAsByteArray2 = Bytes.toBytes(filterString2); try { filter = f.parseFilterString(filterStringAsByteArray2); assertTrue(false); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } @Test public void testIncorrectFilterString () throws IOException { String filterString = "()"; byte [] filterStringAsByteArray = Bytes.toBytes(filterString); try { filter = f.parseFilterString(filterStringAsByteArray); assertTrue(false); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }