You are viewing a plain text version of this content. The canonical link for it is here.
Posted to common-commits@hadoop.apache.org by cn...@apache.org on 2013/06/21 08:37:39 UTC
svn commit: r1495297 [30/46] - in /hadoop/common/branches/branch-1-win: ./
bin/ conf/ ivy/ lib/jdiff/ src/c++/libhdfs/docs/
src/c++/libhdfs/tests/conf/ src/contrib/capacity-scheduler/ivy/
src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred...
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/filecache/TestTrackerDistributedCacheManager.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/filecache/TestTrackerDistributedCacheManager.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/filecache/TestTrackerDistributedCacheManager.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/filecache/TestTrackerDistributedCacheManager.java Fri Jun 21 06:37:27 2013
@@ -24,6 +24,8 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -93,9 +95,10 @@ public class TestTrackerDistributedCache
// Prepare the tests' root dir
File TEST_ROOT = new File(TEST_ROOT_DIR);
- if (!TEST_ROOT.exists()) {
- TEST_ROOT.mkdirs();
+ if (TEST_ROOT.exists()) {
+ FileUtil.fullyDelete(new File(TEST_ROOT_DIR));
}
+ TEST_ROOT.mkdirs();
FileUtil.setPermission(TEST_ROOT, new FsPermission("755"));
conf = new Configuration();
@@ -109,7 +112,8 @@ public class TestTrackerDistributedCache
assertTrue("Test root directory " + TEST_ROOT + " and all of its " +
"parent directories must have a+x permissions",
TrackerDistributedCacheManager.isPublic(
- conf, new Path(TEST_ROOT.toString()).toUri()));
+ conf, new Path(TEST_ROOT.toString()).toUri(),
+ new HashMap<URI, FileStatus>()));
// Prepare the tests' mapred-local-dir
ROOT_MAPRED_LOCAL_DIR = new File(TEST_ROOT_DIR, "mapred/local");
@@ -188,8 +192,11 @@ public class TestTrackerDistributedCache
DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf);
DistributedCache.addFileToClassPath(secondCacheFile, subConf,
FileSystem.get(subConf));
- TrackerDistributedCacheManager.determineTimestamps(subConf);
- TrackerDistributedCacheManager.determineCacheVisibilities(subConf);
+
+ Map<URI, FileStatus> statCache = new HashMap<URI, FileStatus>();
+ TrackerDistributedCacheManager.determineTimestamps(subConf, statCache);
+ TrackerDistributedCacheManager.determineCacheVisibilities(subConf, statCache);
+ assertEquals(2, statCache.size());
// ****** End of imitating JobClient code
Path jobFile = new Path(TEST_ROOT_DIR, "job.xml");
@@ -274,8 +281,7 @@ public class TestTrackerDistributedCache
conf1.set("user.name", userName);
DistributedCache.addCacheFile(secondCacheFile.toUri(), conf1);
- TrackerDistributedCacheManager.determineTimestamps(conf1);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf1);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf1);
// Task localizing for first job
JobID jobId = new JobID("jt", 1);
@@ -303,8 +309,7 @@ public class TestTrackerDistributedCache
DistributedCache.addCacheFile(firstCacheDirPublic.toUri(), conf2);
DistributedCache.addCacheFile(firstCacheDirPrivate.toUri(), conf2);
- TrackerDistributedCacheManager.determineTimestamps(conf2);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf2);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf2);
// Task localizing for second job
JobID job2Id = new JobID("jt", 2);
@@ -340,8 +345,7 @@ public class TestTrackerDistributedCache
// add a file that is never localized
DistributedCache.addCacheFile(thirdCacheFile.toUri(), conf3);
- TrackerDistributedCacheManager.determineTimestamps(conf3);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf3);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf3);
// Task localizing for third job
// localization for the "firstCacheFile" will fail.
@@ -380,7 +384,7 @@ public class TestTrackerDistributedCache
* @throws LoginException
*/
public void testPublicPrivateCache()
- throws IOException, LoginException, InterruptedException {
+ throws IOException, LoginException, InterruptedException, URISyntaxException {
if (!canRun()) {
return;
}
@@ -405,8 +409,7 @@ public class TestTrackerDistributedCache
DistributedCache.addCacheFile(cacheFile.toUri(), conf1);
DistributedCache.addCacheArchive(cacheFile.toUri(), conf1);
- TrackerDistributedCacheManager.determineTimestamps(conf1);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf1);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf1);
dumpState(conf1);
TaskDistributedCacheManager handle = manager
@@ -492,7 +495,7 @@ public class TestTrackerDistributedCache
}
private void checkLocalizedPath(boolean visibility)
- throws IOException, LoginException, InterruptedException {
+ throws IOException, LoginException, InterruptedException, URISyntaxException {
TrackerDistributedCacheManager manager =
new TrackerDistributedCacheManager(conf, taskController);
String userName = getJobOwnerName();
@@ -507,8 +510,7 @@ public class TestTrackerDistributedCache
Configuration conf1 = new Configuration(conf);
conf1.set("user.name", userName);
DistributedCache.addCacheFile(cacheFile.toUri(), conf1);
- TrackerDistributedCacheManager.determineTimestamps(conf1);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf1);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf1);
dumpState(conf1);
// Task localizing for job
@@ -895,8 +897,7 @@ public class TestTrackerDistributedCache
createPrivateTempFile(thirdCacheFile);
createPrivateTempFile(fourthCacheFile);
DistributedCache.setCacheFiles(new URI[]{thirdCacheFile.toUri()}, conf2);
- TrackerDistributedCacheManager.determineCacheVisibilities(conf2);
- TrackerDistributedCacheManager.determineTimestamps(conf2);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf2);
stat = fs.getFileStatus(thirdCacheFile);
CacheFile cfile3 = new CacheFile(thirdCacheFile.toUri(),
CacheFile.FileType.REGULAR, false,
@@ -923,8 +924,7 @@ public class TestTrackerDistributedCache
DistributedCache.setCacheFiles(new URI[]{fourthCacheFile.toUri()}, conf2);
DistributedCache.setLocalFiles(conf2, thirdCacheFile.toUri().toString());
- TrackerDistributedCacheManager.determineCacheVisibilities(conf2);
- TrackerDistributedCacheManager.determineTimestamps(conf2);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(conf2);
Path fourthLocalCache = manager.getLocalCache(fourthCacheFile.toUri(), conf2,
TaskTracker.getPrivateDistributedCacheDir(userName),
fs.getFileStatus(fourthCacheFile), false,
@@ -1101,8 +1101,7 @@ public class TestTrackerDistributedCache
Configuration subConf = new Configuration(myConf);
subConf.set("user.name", userName);
DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf);
- TrackerDistributedCacheManager.determineTimestamps(subConf);
- TrackerDistributedCacheManager.determineCacheVisibilities(subConf);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(subConf);
// ****** End of imitating JobClient code
// ****** Imitate TaskRunner code.
@@ -1151,8 +1150,7 @@ public class TestTrackerDistributedCache
Configuration subConf2 = new Configuration(myConf);
subConf2.set("user.name", userName);
DistributedCache.addCacheFile(firstCacheFile.toUri(), subConf2);
- TrackerDistributedCacheManager.determineTimestamps(subConf2);
- TrackerDistributedCacheManager.determineCacheVisibilities(subConf2);
+ TrackerDistributedCacheManager.determineTimestampsAndCacheVisibilities(subConf2);
handle =
manager.newTaskDistributedCacheManager(new JobID("jt", 2), subConf2);
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileSystemCaching.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileSystemCaching.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileSystemCaching.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileSystemCaching.java Fri Jun 21 06:37:27 2013
@@ -29,6 +29,64 @@ import junit.framework.TestCase;
public class TestFileSystemCaching extends TestCase {
+ static class DefaultFs extends LocalFileSystem {
+ URI uri;
+ @Override
+ public void initialize(URI uri, Configuration conf) {
+ this.uri = uri;
+ }
+ @Override
+ public URI getUri() {
+ return uri;
+ }
+ }
+
+ public void testDefaultFsUris() throws Exception {
+ final Configuration conf = new Configuration();
+ conf.set("fs.defaultfs.impl", DefaultFs.class.getName());
+ final URI defaultUri = URI.create("defaultfs://host");
+ FileSystem.setDefaultUri(conf, defaultUri);
+ FileSystem fs = null;
+
+ // sanity check default fs
+ final FileSystem defaultFs = FileSystem.get(conf);
+ assertEquals(defaultUri, defaultFs.getUri());
+
+ // has scheme, no auth
+ fs = FileSystem.get(URI.create("defaultfs:/"), conf);
+ assertSame(defaultFs, fs);
+ fs = FileSystem.get(URI.create("defaultfs:///"), conf);
+ assertSame(defaultFs, fs);
+
+ // has scheme, same auth
+ fs = FileSystem.get(URI.create("defaultfs://host"), conf);
+ assertSame(defaultFs, fs);
+
+ // has scheme, different auth
+ fs = FileSystem.get(URI.create("defaultfs://host2"), conf);
+ assertNotSame(defaultFs, fs);
+
+ // no scheme, no auth
+ fs = FileSystem.get(URI.create("/"), conf);
+ assertSame(defaultFs, fs);
+
+ // no scheme, same auth
+ try {
+ fs = FileSystem.get(URI.create("//host"), conf);
+ fail("got fs with auth but no scheme");
+ } catch (Exception e) {
+ assertEquals("No FileSystem for scheme: null", e.getMessage());
+ }
+
+ // no scheme, different auth
+ try {
+ fs = FileSystem.get(URI.create("//host2"), conf);
+ fail("got fs with auth but no scheme");
+ } catch (Exception e) {
+ assertEquals("No FileSystem for scheme: null", e.getMessage());
+ }
+ }
+
public static class InitializeForeverFileSystem extends LocalFileSystem {
final static Semaphore sem = new Semaphore(0);
public void initialize(URI uri, Configuration conf) throws IOException {
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileUtil.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileUtil.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileUtil.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFileUtil.java Fri Jun 21 06:37:27 2013
@@ -17,6 +17,8 @@
*/
package org.apache.hadoop.fs;
+import static org.junit.Assert.assertTrue;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -28,6 +30,9 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.util.Shell;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
@@ -500,4 +505,51 @@ public class TestFileUtil {
doUntarAndVerify(new File(tarGzFileName), untarDir);
doUntarAndVerify(new File(tarFileName), untarDir);
}
+
+ /**
+ * Test that copies file from local filesystem to hdfs. It tests the overwrite
+ * flag is respected when copying files over.
+ */
+ @Test
+ public void testCopy() throws IOException {
+ Configuration conf = new Configuration();
+ MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null);
+ DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();
+ // local file system
+ LocalFileSystem lfs = FileSystem.getLocal(conf);
+ try {
+ String fname = "testCopyFromLocal1.txt";
+ File f = new File(TEST_DIR, fname);
+ f.createNewFile();
+ // copy the file to hdfs with overwrite = false
+ boolean status = FileUtil.copy(lfs, new Path(f.getAbsolutePath()), dfs,
+ new Path("."), false, true, conf);
+ assertTrue(status);
+ // make sure the file exists on hdfs
+ assertTrue("File " + fname + " does not exist on hdfs.",
+ dfs.exists(new Path(fname)));
+ // copy the same file to hdfs with overwrite and it should pass
+ status = FileUtil.copy(lfs, new Path(f.getAbsolutePath()), dfs, new Path(
+ "."), false, true, conf);
+ assertTrue(status);
+
+ try {
+ // copy the same file to hdfs with overwrite as false and it should
+ // thrown an exception, catch it and make sure the file name is part of
+ // the message
+ status = FileUtil.copy(lfs, new Path(f.getAbsolutePath()), dfs,
+ new Path("."), false, false, conf);
+ } catch (IOException expected) {
+ assertTrue("Exception message doesn't contain filename " + fname,
+ expected.getMessage().indexOf(fname) >= 0);
+ }
+ } finally {
+ try {
+ dfs.close();
+ lfs.close();
+ } catch (Exception e) {
+ }
+ cluster.shutdown();
+ }
+ }
}
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFsShellReturnCode.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFsShellReturnCode.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFsShellReturnCode.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestFsShellReturnCode.java Fri Jun 21 06:37:27 2013
@@ -18,15 +18,14 @@
package org.apache.hadoop.fs;
+import static org.junit.Assert.assertTrue;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
-
-import org.apache.hadoop.fs.FileSystem;
-
-import org.junit.Test;
+import org.apache.hadoop.security.UserGroupInformation;
import org.junit.Assert;
-import static org.junit.Assert.assertTrue;
+import org.junit.Test;
/**
* This test validates that chmod, chown, chgrp returning correct exit codes
@@ -152,7 +151,8 @@ public class TestFsShellReturnCode {
assertTrue(fileSys.exists(p1));
// Test 1: exit code for chown on existing file is 0
- String argv[] = { "-chown", "admin", f1 };
+ final String username = UserGroupInformation.getCurrentUser().getShortUserName();
+ String argv[] = { "-chown", username, f1 };
verify(fs, "-chown", argv, 1, fsShell, 0);
// Test 2: exit code for chown on non-existing path is 1
@@ -172,7 +172,7 @@ public class TestFsShellReturnCode {
assertTrue(fileSys.exists(p6));
// Test 4: exit code for chown on existing path with globbed input is 0
- String argv4[] = { "-chown", "admin", f7 };
+ String argv4[] = { "-chown", username, f7 };
verify(fs, "-chown", argv4, 1, fsShell, 0);
}
@@ -235,6 +235,24 @@ public class TestFsShellReturnCode {
// Test 4: exit code for chgrp on existing path with globbed input is 0
String argv4[] = { "-chgrp", "admin", f7 };
verify(fs, "-chgrp", argv4, 1, fsShell, 0);
-
+ }
+
+ @Test
+ public void testInvalidDefautlFS() throws Exception {
+ // if default fs doesn't exist or is invalid, but the path provided in
+ // arguments is valid - fsshell should work
+ FsShell shell = new FsShell();
+ Configuration conf = new Configuration();
+ conf.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY,
+ "hhhh://doesnotexist/");
+ shell.setConf(conf);
+ String[] args = new String[2];
+ args[0] = "-ls";
+ args[1] = "file:///"; // this is valid, so command should run
+ int res = shell.run(args);
+ System.out.println("res =" + res);
+ shell.setConf(conf);
+ int run = shell.run(args);
+ assertTrue("Return code should be 0", run == 0);
}
}
\ No newline at end of file
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestGetFileBlockLocations.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestGetFileBlockLocations.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestGetFileBlockLocations.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestGetFileBlockLocations.java Fri Jun 21 06:37:27 2013
@@ -122,6 +122,7 @@ public class TestGetFileBlockLocations e
oneTest(0, (int) status.getLen() * 2, status);
oneTest((int) status.getLen() * 2, (int) status.getLen() * 4, status);
oneTest((int) status.getLen() / 2, (int) status.getLen() * 3, status);
+ oneTest((int) status.getLen(), (int) status.getLen() * 2, status);
for (int i = 0; i < 10; ++i) {
oneTest((int) status.getLen() * i / 10, (int) status.getLen() * (i + 1)
/ 10, status);
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestLocalFileSystem.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestLocalFileSystem.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestLocalFileSystem.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestLocalFileSystem.java Fri Jun 21 06:37:27 2013
@@ -111,6 +111,39 @@ public class TestLocalFileSystem extends
}
}
+ public void testSyncable() throws IOException {
+ Configuration conf = new Configuration();
+ FileSystem fs = FileSystem.getLocal(conf).getRawFileSystem();
+ Path file = new Path(TEST_ROOT_DIR, "syncable");
+ FSDataOutputStream out = fs.create(file);;
+ final int bytesWritten = 1;
+ byte[] expectedBuf = new byte[] {'0', '1', '2', '3'};
+ try {
+ out.write(expectedBuf, 0, 1);
+ out.sync();
+ verifyFile(fs, file, bytesWritten, expectedBuf);
+ out.write(expectedBuf, bytesWritten, expectedBuf.length-bytesWritten);
+ out.sync();
+ verifyFile(fs, file, expectedBuf.length, expectedBuf);
+ } finally {
+ out.close();
+ }
+ }
+
+ private void verifyFile(FileSystem fs, Path file, int bytesToVerify,
+ byte[] expectedBytes) throws IOException {
+ FSDataInputStream in = fs.open(file);
+ try {
+ byte[] readBuf = new byte[bytesToVerify];
+ in.readFully(readBuf, 0, bytesToVerify);
+ for (int i=0; i<bytesToVerify; i++) {
+ assertEquals(expectedBytes[i], readBuf[i]);
+ }
+ } finally {
+ in.close();
+ }
+ }
+
public void testCopy() throws IOException {
Configuration conf = new Configuration();
LocalFileSystem fs = FileSystem.getLocal(conf);
@@ -160,4 +193,14 @@ public class TestLocalFileSystem extends
FileSystem fs = FileSystem.getLocal(conf);
assertNull(fs.getCanonicalServiceName());
}
+
+ public void testHasFileDescriptor() throws IOException {
+ Configuration conf = new Configuration();
+ LocalFileSystem fs = FileSystem.getLocal(conf);
+ Path path = new Path(TEST_ROOT_DIR, "test-file");
+ writeFile(fs, path);
+ BufferedFSInputStream bis = new BufferedFSInputStream(
+ new RawLocalFileSystem().new LocalFSFileInputStream(path), 1024);
+ assertNotNull(bis.getFileDescriptor());
+ }
}
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestPath.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestPath.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestPath.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/TestPath.java Fri Jun 21 06:37:27 2013
@@ -21,6 +21,7 @@ package org.apache.hadoop.fs;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Arrays;
import org.apache.hadoop.conf.Configuration;
@@ -177,5 +178,58 @@ public class TestPath extends TestCase {
assertEquals("foo://bar/fud#boo", new Path(new Path(new URI(
"foo://bar/baz#bud")), new Path(new URI("/fud#boo"))).toString());
}
+
+ public void testGlobEscapeStatus() throws Exception {
+ FileSystem lfs = FileSystem.getLocal(new Configuration());
+ Path testRoot = lfs.makeQualified(new Path(System.getProperty(
+ "test.build.data", "test/build/data"), "testPathGlob"));
+ lfs.delete(testRoot, true);
+ lfs.mkdirs(testRoot);
+ assertTrue(lfs.getFileStatus(testRoot).isDir());
+ lfs.setWorkingDirectory(testRoot);
+
+ // create a couple dirs with file in them
+ Path paths[] = new Path[] { new Path(testRoot, "*/f"),
+ new Path(testRoot, "d1/f"), new Path(testRoot, "d2/f") };
+ Arrays.sort(paths);
+ for (Path p : paths) {
+ lfs.create(p).close();
+ assertTrue(lfs.exists(p));
+ }
+ // try the non-globbed listStatus
+ FileStatus stats[] = lfs.listStatus(new Path(testRoot, "*"));
+ assertEquals(1, stats.length);
+ assertEquals(new Path(testRoot, "*/f"), stats[0].getPath());
+
+ // ensure globStatus with "*" finds all dir contents
+ stats = lfs.globStatus(new Path(testRoot, "*"));
+ Arrays.sort(stats);
+ assertEquals(paths.length, stats.length);
+ for (int i = 0; i < paths.length; i++) {
+ assertEquals(paths[i].getParent(), stats[i].getPath());
+ }
+
+ // ensure that globStatus with an escaped "\*" only finds "*"
+ stats = lfs.globStatus(new Path(testRoot, "\\*"));
+ assertEquals(1, stats.length);
+ assertEquals(new Path(testRoot, "*"), stats[0].getPath());
+
+ // try to glob the inner file for all dirs
+ stats = lfs.globStatus(new Path(testRoot, "*/f"));
+ assertEquals(paths.length, stats.length);
+ for (int i = 0; i < paths.length; i++) {
+ assertEquals(paths[i], stats[i].getPath());
+ }
+
+ // try to get the inner file for only the "*" dir
+ stats = lfs.globStatus(new Path(testRoot, "\\*/f"));
+ assertEquals(1, stats.length);
+ assertEquals(new Path(testRoot, "*/f"), stats[0].getPath());
+
+ // try to glob all the contents of the "*" dir
+ stats = lfs.globStatus(new Path(testRoot, "\\*/*"));
+ assertEquals(1, stats.length);
+ assertEquals(new Path(testRoot, "*/f"), stats[0].getPath());
+ }
}
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/InMemoryNativeFileSystemStore.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/InMemoryNativeFileSystemStore.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/InMemoryNativeFileSystemStore.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/InMemoryNativeFileSystemStore.java Fri Jun 21 06:37:27 2013
@@ -19,6 +19,7 @@
package org.apache.hadoop.fs.s3native;
import static org.apache.hadoop.fs.s3native.NativeS3FileSystem.PATH_DELIMITER;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
@@ -122,19 +123,13 @@ class InMemoryNativeFileSystemStore impl
public PartialListing list(String prefix, int maxListingLength)
throws IOException {
- return list(prefix, maxListingLength, null);
+ return list(prefix, maxListingLength, null, false);
}
public PartialListing list(String prefix, int maxListingLength,
- String priorLastKey) throws IOException {
-
- return list(prefix, PATH_DELIMITER, maxListingLength, priorLastKey);
- }
-
- public PartialListing listAll(String prefix, int maxListingLength,
- String priorLastKey) throws IOException {
+ String priorLastKey, boolean recursive) throws IOException {
- return list(prefix, null, maxListingLength, priorLastKey);
+ return list(prefix, recursive ? null : PATH_DELIMITER, maxListingLength, priorLastKey);
}
private PartialListing list(String prefix, String delimiter,
@@ -174,9 +169,9 @@ class InMemoryNativeFileSystemStore impl
dataMap.remove(key);
}
- public void rename(String srcKey, String dstKey) throws IOException {
- metadataMap.put(dstKey, metadataMap.remove(srcKey));
- dataMap.put(dstKey, dataMap.remove(srcKey));
+ public void copy(String srcKey, String dstKey) throws IOException {
+ metadataMap.put(dstKey, metadataMap.get(srcKey));
+ dataMap.put(dstKey, dataMap.get(srcKey));
}
public void purge(String prefix) throws IOException {
Modified: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/NativeS3FileSystemContractBaseTest.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/NativeS3FileSystemContractBaseTest.java?rev=1495297&r1=1495296&r2=1495297&view=diff
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/NativeS3FileSystemContractBaseTest.java (original)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/s3native/NativeS3FileSystemContractBaseTest.java Fri Jun 21 06:37:27 2013
@@ -55,5 +55,75 @@ public abstract class NativeS3FileSystem
assertEquals(1, paths.length);
assertEquals(path("/test"), paths[0].getPath());
}
-
+
+ private void createTestFiles(String base) throws IOException {
+ store.storeEmptyFile(base + "/file1");
+ store.storeEmptyFile(base + "/dir/file2");
+ store.storeEmptyFile(base + "/dir/file3");
+ }
+
+ public void testDirWithDifferentMarkersWorks() throws Exception {
+
+ for (int i = 0; i < 3; i++) {
+ String base = "test/hadoop" + i;
+ Path path = path("/" + base);
+
+ createTestFiles(base);
+
+ if (i == 0 ) {
+ //do nothing, we are testing correctness with no markers
+ }
+ else if (i == 1) {
+ // test for _$folder$ marker
+ store.storeEmptyFile(base + "_$folder$");
+ store.storeEmptyFile(base + "/dir_$folder$");
+ }
+ else if (i == 2) {
+ // test the end slash file marker
+ store.storeEmptyFile(base + "/");
+ store.storeEmptyFile(base + "/dir/");
+ }
+ else if (i == 3) {
+ // test both markers
+ store.storeEmptyFile(base + "_$folder$");
+ store.storeEmptyFile(base + "/dir_$folder$");
+ store.storeEmptyFile(base + "/");
+ store.storeEmptyFile(base + "/dir/");
+ }
+
+ assertTrue(fs.getFileStatus(path).isDir());
+ assertEquals(2, fs.listStatus(path).length);
+ }
+ }
+
+ public void testDeleteWithNoMarker() throws Exception {
+ String base = "test/hadoop";
+ Path path = path("/" + base);
+
+ createTestFiles(base);
+
+ fs.delete(path, true);
+
+ path = path("/test");
+ }
+
+ public void testRenameWithNoMarker() throws Exception {
+ String base = "test/hadoop";
+ Path dest = path("/test/hadoop2");
+
+ createTestFiles(base);
+
+ fs.rename(path("/" + base), dest);
+
+ Path path = path("/test");
+ assertTrue(fs.getFileStatus(path).isDir());
+ assertEquals(1, fs.listStatus(path).length);
+ assertTrue(fs.getFileStatus(dest).isDir());
+ assertEquals(2, fs.listStatus(dest).length);
+ }
+
+ public void testEmptyFile() throws Exception {
+ store.storeEmptyFile("test/hadoop/file1");
+ fs.open(path("/test/hadoop/file1")).close();
+ }
}
Added: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/AppendOp.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/AppendOp.java?rev=1495297&view=auto
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/AppendOp.java (added)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/AppendOp.java Fri Jun 21 06:37:27 2013
@@ -0,0 +1,119 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.fs.slive;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.slive.DataWriter.GenerateOutput;
+import org.apache.hadoop.fs.slive.OperationOutput.OutputType;
+
+/**
+ * Operation which selects a random file and appends a random amount of bytes
+ * (selected from the configuration for append size) to that file if it exists.
+ *
+ * This operation will capture statistics on success for bytes written, time
+ * taken (milliseconds), and success count and on failure it will capture the
+ * number of failures and the time taken (milliseconds) to fail.
+ */
+class AppendOp extends Operation {
+
+ private static final Log LOG = LogFactory.getLog(AppendOp.class);
+
+ AppendOp(ConfigExtractor cfg, Random rnd) {
+ super(AppendOp.class.getSimpleName(), cfg, rnd);
+ }
+
+ /**
+ * Gets the file to append to
+ *
+ * @return Path
+ */
+ protected Path getAppendFile() {
+ Path fn = getFinder().getFile();
+ return fn;
+ }
+
+ @Override // Operation
+ List<OperationOutput> run(FileSystem fs) {
+ List<OperationOutput> out = super.run(fs);
+ OutputStream os = null;
+ try {
+ Path fn = getAppendFile();
+ // determine file status for file length requirement
+ // to know if should fill in partial bytes
+ Range<Long> appendSizeRange = getConfig().getAppendSize();
+ if (getConfig().shouldAppendUseBlockSize()) {
+ appendSizeRange = getConfig().getBlockSize();
+ }
+ long appendSize = Range.betweenPositive(getRandom(), appendSizeRange);
+ long timeTaken = 0, bytesAppended = 0;
+ DataWriter writer = new DataWriter(getRandom());
+ LOG.info("Attempting to append to file at " + fn + " of size "
+ + Helper.toByteInfo(appendSize));
+ {
+ // open
+ long startTime = Timer.now();
+ os = fs.append(fn);
+ timeTaken += Timer.elapsed(startTime);
+ // append given length
+ GenerateOutput stats = writer.writeSegment(appendSize, os);
+ timeTaken += stats.getTimeTaken();
+ bytesAppended += stats.getBytesWritten();
+ // capture close time
+ startTime = Timer.now();
+ os.close();
+ os = null;
+ timeTaken += Timer.elapsed(startTime);
+ }
+ out.add(new OperationOutput(OutputType.LONG, getType(),
+ ReportWriter.BYTES_WRITTEN, bytesAppended));
+ out.add(new OperationOutput(OutputType.LONG, getType(),
+ ReportWriter.OK_TIME_TAKEN, timeTaken));
+ out.add(new OperationOutput(OutputType.LONG, getType(),
+ ReportWriter.SUCCESSES, 1L));
+ LOG.info("Appended " + Helper.toByteInfo(bytesAppended) + " to file "
+ + fn + " in " + timeTaken + " milliseconds");
+ } catch (FileNotFoundException e) {
+ out.add(new OperationOutput(OutputType.LONG, getType(),
+ ReportWriter.NOT_FOUND, 1L));
+ LOG.warn("Error with appending", e);
+ } catch (IOException e) {
+ out.add(new OperationOutput(OutputType.LONG, getType(),
+ ReportWriter.FAILURES, 1L));
+ LOG.warn("Error with appending", e);
+ } finally {
+ if (os != null) {
+ try {
+ os.close();
+ } catch (IOException e) {
+ LOG.warn("Error with closing append stream", e);
+ }
+ }
+ }
+ return out;
+ }
+}
Added: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ArgumentParser.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ArgumentParser.java?rev=1495297&view=auto
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ArgumentParser.java (added)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ArgumentParser.java Fri Jun 21 06:37:27 2013
@@ -0,0 +1,176 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.fs.slive;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.PosixParser;
+import org.apache.hadoop.fs.slive.Constants.Distribution;
+import org.apache.hadoop.fs.slive.Constants.OperationType;
+import org.apache.hadoop.util.StringUtils;
+
+/**
+ * Class which abstracts the parsing of command line arguments for slive test
+ */
+class ArgumentParser {
+
+ private Options optList;
+ private String[] argumentList;
+ private ParsedOutput parsed;
+
+ /**
+ * Result of a parse is the following object
+ */
+ static class ParsedOutput {
+ private CommandLine parsedData;
+ private ArgumentParser source;
+ private boolean needHelp;
+
+ ParsedOutput(CommandLine parsedData, ArgumentParser source,
+ boolean needHelp) {
+ this.parsedData = parsedData;
+ this.source = source;
+ this.needHelp = needHelp;
+ }
+
+ /**
+ * @return whether the calling object should call output help and exit
+ */
+ boolean shouldOutputHelp() {
+ return needHelp;
+ }
+
+ /**
+ * Outputs the formatted help to standard out
+ */
+ void outputHelp() {
+ if (!shouldOutputHelp()) {
+ return;
+ }
+ if (source != null) {
+ HelpFormatter hlp = new HelpFormatter();
+ hlp.printHelp(Constants.PROG_NAME + " " + Constants.PROG_VERSION,
+ source.getOptionList());
+ }
+ }
+
+ /**
+ * @param optName
+ * the option name to get the value for
+ *
+ * @return the option value or null if it does not exist
+ */
+ String getValue(String optName) {
+ if (parsedData == null) {
+ return null;
+ }
+ return parsedData.getOptionValue(optName);
+ }
+
+ public String toString() {
+ StringBuilder s = new StringBuilder();
+ if (parsedData != null) {
+ Option[] ops = parsedData.getOptions();
+ for (int i = 0; i < ops.length; ++i) {
+ s.append(ops[i].getOpt() + " = " + s.append(ops[i].getValue()) + ",");
+ }
+ }
+ return s.toString();
+ }
+
+ }
+
+ ArgumentParser(String[] args) {
+ optList = getOptions();
+ if (args == null) {
+ args = new String[] {};
+ }
+ argumentList = args;
+ parsed = null;
+ }
+
+ private Options getOptionList() {
+ return optList;
+ }
+
+ /**
+ * Parses the command line options
+ *
+ * @return false if need to print help output
+ *
+ * @throws Exception
+ * when parsing fails
+ */
+ ParsedOutput parse() throws Exception {
+ if (parsed == null) {
+ PosixParser parser = new PosixParser();
+ CommandLine popts = parser.parse(getOptionList(), argumentList, true);
+ if (popts.hasOption(ConfigOption.HELP.getOpt())) {
+ parsed = new ParsedOutput(null, this, true);
+ } else {
+ parsed = new ParsedOutput(popts, this, false);
+ }
+ }
+ return parsed;
+ }
+
+ /**
+ * @return the option set to be used in command line parsing
+ */
+ private Options getOptions() {
+ Options cliopt = new Options();
+ cliopt.addOption(ConfigOption.MAPS);
+ cliopt.addOption(ConfigOption.REDUCES);
+ cliopt.addOption(ConfigOption.PACKET_SIZE);
+ cliopt.addOption(ConfigOption.OPS);
+ cliopt.addOption(ConfigOption.DURATION);
+ cliopt.addOption(ConfigOption.EXIT_ON_ERROR);
+ cliopt.addOption(ConfigOption.SLEEP_TIME);
+ cliopt.addOption(ConfigOption.FILES);
+ cliopt.addOption(ConfigOption.DIR_SIZE);
+ cliopt.addOption(ConfigOption.BASE_DIR);
+ cliopt.addOption(ConfigOption.RESULT_FILE);
+ cliopt.addOption(ConfigOption.CLEANUP);
+ {
+ String distStrs[] = new String[Distribution.values().length];
+ Distribution distValues[] = Distribution.values();
+ for (int i = 0; i < distValues.length; ++i) {
+ distStrs[i] = distValues[i].lowerName();
+ }
+ String opdesc = String.format(Constants.OP_DESCR, StringUtils
+ .arrayToString(distStrs));
+ for (OperationType type : OperationType.values()) {
+ String opname = type.lowerName();
+ cliopt.addOption(new Option(opname, true, opdesc));
+ }
+ }
+ cliopt.addOption(ConfigOption.REPLICATION_AM);
+ cliopt.addOption(ConfigOption.BLOCK_SIZE);
+ cliopt.addOption(ConfigOption.READ_SIZE);
+ cliopt.addOption(ConfigOption.WRITE_SIZE);
+ cliopt.addOption(ConfigOption.APPEND_SIZE);
+ cliopt.addOption(ConfigOption.RANDOM_SEED);
+ cliopt.addOption(ConfigOption.QUEUE_NAME);
+ cliopt.addOption(ConfigOption.HELP);
+ return cliopt;
+ }
+
+}
Added: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/BadFileException.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/BadFileException.java?rev=1495297&view=auto
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/BadFileException.java (added)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/BadFileException.java Fri Jun 21 06:37:27 2013
@@ -0,0 +1,39 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.fs.slive;
+
+import java.io.IOException;
+
+/**
+ * Exception used to signify file reading failures where headers are bad or an
+ * unexpected EOF occurs when it should not.
+ */
+class BadFileException extends IOException {
+
+ private static final long serialVersionUID = 463201983951298129L;
+
+ BadFileException(String msg) {
+ super(msg);
+ }
+
+ BadFileException(String msg, Throwable e) {
+ super(msg, e);
+ }
+
+}
Added: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigExtractor.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigExtractor.java?rev=1495297&view=auto
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigExtractor.java (added)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigExtractor.java Fri Jun 21 06:37:27 2013
@@ -0,0 +1,733 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.fs.slive;
+
+import java.text.NumberFormat;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.slive.Constants.OperationType;
+import org.apache.hadoop.util.StringUtils;
+
+/**
+ * Simple access layer onto of a configuration object that extracts the slive
+ * specific configuration values needed for slive running
+ */
+class ConfigExtractor {
+
+ private static final Log LOG = LogFactory.getLog(ConfigExtractor.class);
+
+ private Configuration config;
+
+ ConfigExtractor(Configuration cfg) {
+ this.config = cfg;
+ }
+
+ /**
+ * @return the wrapped configuration that this extractor will use
+ */
+ Configuration getConfig() {
+ return this.config;
+ }
+
+ /**
+ * @return the location of where data should be written to
+ */
+ Path getDataPath() {
+ Path base = getBaseDirectory();
+ if (base == null) {
+ return null;
+ }
+ return new Path(base, Constants.DATA_DIR);
+ }
+
+ /**
+ * @return the location of where the reducer should write its data to
+ */
+ Path getOutputPath() {
+ Path base = getBaseDirectory();
+ if (base == null) {
+ return null;
+ }
+ return new Path(base, Constants.OUTPUT_DIR);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ *
+ * @return the base directory where output & data should be stored using
+ * primary,config,default (in that order)
+ */
+ Path getBaseDirectory(String primary) {
+ String path = primary;
+ if (path == null) {
+ path = config.get(ConfigOption.BASE_DIR.getCfgOption());
+ }
+ if (path == null) {
+ path = ConfigOption.BASE_DIR.getDefault();
+ }
+ if (path == null) {
+ return null;
+ }
+ return new Path(path);
+ }
+
+ /**
+ * @return the base directory using only config and default values
+ */
+ Path getBaseDirectory() {
+ return getBaseDirectory(null);
+ }
+
+ /**
+ * @return whether the mapper or reducer should exit when they get there first
+ * error using only config and default values
+ */
+ boolean shouldExitOnFirstError() {
+ return shouldExitOnFirstError(null);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ *
+ * @return the boolean of whether the mapper/reducer should exit when they
+ * first error from primary,config,default (in that order)
+ */
+ boolean shouldExitOnFirstError(String primary) {
+ String val = primary;
+ if (val == null) {
+ val = config.get(ConfigOption.EXIT_ON_ERROR.getCfgOption());
+ }
+ if (val == null) {
+ return ConfigOption.EXIT_ON_ERROR.getDefault();
+ }
+ return Boolean.parseBoolean(val);
+ }
+
+ /**
+ * @return the number of reducers to use
+ */
+ Integer getReducerAmount() {
+ // should be slive.reduces
+ return getInteger(null, ConfigOption.REDUCES);
+ }
+
+ /**
+ * @return the number of mappers to use using config and default values for
+ * lookup
+ */
+ Integer getMapAmount() {
+ return getMapAmount(null);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the reducer amount to use
+ */
+ Integer getMapAmount(String primary) {
+ return getInteger(primary, ConfigOption.MAPS);
+ }
+
+ /**
+ * @return the duration in seconds (or null or Integer.MAX for no limit) using
+ * the configuration and default as lookup
+ */
+ Integer getDuration() {
+ return getDuration(null);
+ }
+
+ /**
+ * @return the duration in milliseconds or null if no limit using config and
+ * default as lookup
+ */
+ Integer getDurationMilliseconds() {
+ Integer seconds = getDuration();
+ if (seconds == null || seconds == Integer.MAX_VALUE) {
+ return Integer.MAX_VALUE;
+ }
+ int milliseconds = (seconds * 1000);
+ if (milliseconds < 0) {
+ milliseconds = 0;
+ }
+ return milliseconds;
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the duration in seconds (or null or Integer.MAX for no limit)
+ */
+ Integer getDuration(String primary) {
+ return getInteger(primary, ConfigOption.DURATION);
+ }
+
+ /**
+ * @return the total number of operations to run using config and default as
+ * lookup
+ */
+ Integer getOpCount() {
+ return getOpCount(null);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the total number of operations to run
+ */
+ Integer getOpCount(String primary) {
+ return getInteger(primary, ConfigOption.OPS);
+ }
+
+ /**
+ * @return the total number of files per directory using config and default as
+ * lookup
+ */
+ Integer getDirSize() {
+ return getDirSize(null);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the total number of files per directory
+ */
+ Integer getDirSize(String primary) {
+ return getInteger(primary, ConfigOption.DIR_SIZE);
+ }
+
+ /**
+ * @param primary
+ * the primary string to attempt to convert into a integer
+ * @param opt
+ * the option to use as secondary + default if no primary given
+ * @return a parsed integer
+ */
+ private Integer getInteger(String primary, ConfigOption<Integer> opt) {
+ String value = primary;
+ if (value == null) {
+ value = config.get(opt.getCfgOption());
+ }
+ if (value == null) {
+ return opt.getDefault();
+ }
+ return Integer.parseInt(value);
+ }
+
+ /**
+ * @return the total number of files allowed using configuration and default
+ * for lookup
+ */
+ Integer getTotalFiles() {
+ return getTotalFiles(null);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the total number of files allowed
+ */
+ Integer getTotalFiles(String primary) {
+ return getInteger(primary, ConfigOption.FILES);
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the random seed start point or null if none
+ */
+ Long getRandomSeed(String primary) {
+ String seed = primary;
+ if (seed == null) {
+ seed = config.get(ConfigOption.RANDOM_SEED.getCfgOption());
+ }
+ if (seed == null) {
+ return null;
+ }
+ return Long.parseLong(seed);
+ }
+
+ /**
+ * @return the random seed start point or null if none using config and then
+ * default as lookup
+ */
+ Long getRandomSeed() {
+ return getRandomSeed(null);
+ }
+
+ /**
+ * @return the result file location or null if none using config and then
+ * default as lookup
+ */
+ String getResultFile() {
+ return getResultFile(null);
+ }
+
+ /**
+ * Gets the grid queue name to run on using config and default only
+ *
+ * @return String
+ */
+ String getQueueName() {
+ return getQueueName(null);
+ }
+
+ /**
+ * Gets the grid queue name to run on using the primary string or config or
+ * default
+ *
+ * @param primary
+ *
+ * @return String
+ */
+ String getQueueName(String primary) {
+ String q = primary;
+ if (q == null) {
+ q = config.get(ConfigOption.QUEUE_NAME.getCfgOption());
+ }
+ if (q == null) {
+ q = ConfigOption.QUEUE_NAME.getDefault();
+ }
+ return q;
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the result file location
+ */
+ String getResultFile(String primary) {
+ String fn = primary;
+ if (fn == null) {
+ fn = config.get(ConfigOption.RESULT_FILE.getCfgOption());
+ }
+ if (fn == null) {
+ fn = ConfigOption.RESULT_FILE.getDefault();
+ }
+ return fn;
+ }
+
+ /**
+ * @param primary
+ * primary the initial string to be used for the value of this
+ * configuration option (if not provided then config and then the
+ * default are used)
+ * @return the integer range allowed for the block size
+ */
+ Range<Long> getBlockSize(String primary) {
+ return getMinMaxBytes(ConfigOption.BLOCK_SIZE, primary);
+ }
+
+ /**
+ * @return the integer range allowed for the block size using config and
+ * default for lookup
+ */
+ Range<Long> getBlockSize() {
+ return getBlockSize(null);
+ }
+
+ /**
+ * @param cfgopt
+ * the configuration option to use for config and default lookup
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the parsed short range from primary, config, default
+ */
+ private Range<Short> getMinMaxShort(ConfigOption<Short> cfgopt, String primary) {
+ String sval = primary;
+ if (sval == null) {
+ sval = config.get(cfgopt.getCfgOption());
+ }
+ Range<Short> range = null;
+ if (sval != null) {
+ String pieces[] = Helper.getTrimmedStrings(sval);
+ if (pieces.length == 2) {
+ String min = pieces[0];
+ String max = pieces[1];
+ short minVal = Short.parseShort(min);
+ short maxVal = Short.parseShort(max);
+ if (minVal > maxVal) {
+ short tmp = minVal;
+ minVal = maxVal;
+ maxVal = tmp;
+ }
+ range = new Range<Short>(minVal, maxVal);
+ }
+ }
+ if (range == null) {
+ Short def = cfgopt.getDefault();
+ if (def != null) {
+ range = new Range<Short>(def, def);
+ }
+ }
+ return range;
+ }
+
+ /**
+ * @param cfgopt
+ * the configuration option to use for config and default lookup
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the parsed long range from primary, config, default
+ */
+ private Range<Long> getMinMaxLong(ConfigOption<Long> cfgopt, String primary) {
+ String sval = primary;
+ if (sval == null) {
+ sval = config.get(cfgopt.getCfgOption());
+ }
+ Range<Long> range = null;
+ if (sval != null) {
+ String pieces[] = Helper.getTrimmedStrings(sval);
+ if (pieces.length == 2) {
+ String min = pieces[0];
+ String max = pieces[1];
+ long minVal = Long.parseLong(min);
+ long maxVal = Long.parseLong(max);
+ if (minVal > maxVal) {
+ long tmp = minVal;
+ minVal = maxVal;
+ maxVal = tmp;
+ }
+ range = new Range<Long>(minVal, maxVal);
+ }
+ }
+ if (range == null) {
+ Long def = cfgopt.getDefault();
+ if (def != null) {
+ range = new Range<Long>(def, def);
+ }
+ }
+ return range;
+ }
+
+ /**
+ * @param cfgopt
+ * the configuration option to use for config and default lookup
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the parsed integer byte range from primary, config, default
+ */
+ private Range<Long> getMinMaxBytes(ConfigOption<Long> cfgopt, String primary) {
+ String sval = primary;
+ if (sval == null) {
+ sval = config.get(cfgopt.getCfgOption());
+ }
+ Range<Long> range = null;
+ if (sval != null) {
+ String pieces[] = Helper.getTrimmedStrings(sval);
+ if (pieces.length == 2) {
+ String min = pieces[0];
+ String max = pieces[1];
+ long tMin = StringUtils.TraditionalBinaryPrefix.string2long(min);
+ long tMax = StringUtils.TraditionalBinaryPrefix.string2long(max);
+ if (tMin > tMax) {
+ long tmp = tMin;
+ tMin = tMax;
+ tMax = tmp;
+ }
+ range = new Range<Long>(tMin, tMax);
+ }
+ }
+ if (range == null) {
+ Long def = cfgopt.getDefault();
+ if (def != null) {
+ range = new Range<Long>(def, def);
+ }
+ }
+ return range;
+ }
+
+ /**
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the replication range
+ */
+ Range<Short> getReplication(String primary) {
+ return getMinMaxShort(ConfigOption.REPLICATION_AM, primary);
+ }
+
+ /**
+ * @return the replication range using config and default for lookup
+ */
+ Range<Short> getReplication() {
+ return getReplication(null);
+ }
+
+ /**
+ * @return the map of operations to perform using config (percent may be null
+ * if unspecified)
+ */
+ Map<OperationType, OperationData> getOperations() {
+ Map<OperationType, OperationData> operations = new HashMap<OperationType, OperationData>();
+ for (OperationType type : OperationType.values()) {
+ String opname = type.lowerName();
+ String keyname = String.format(Constants.OP, opname);
+ String kval = config.get(keyname);
+ if (kval == null) {
+ continue;
+ }
+ operations.put(type, new OperationData(kval));
+ }
+ return operations;
+ }
+
+ /**
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the append byte size range (or null if none)
+ */
+ Range<Long> getAppendSize(String primary) {
+ return getMinMaxBytes(ConfigOption.APPEND_SIZE, primary);
+ }
+
+ /**
+ * @return the append byte size range (or null if none) using config and
+ * default for lookup
+ */
+ Range<Long> getAppendSize() {
+ return getAppendSize(null);
+ }
+
+ /**
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the sleep range (or null if none)
+ */
+ Range<Long> getSleepRange(String primary) {
+ return getMinMaxLong(ConfigOption.SLEEP_TIME, primary);
+ }
+
+ /**
+ * @return the sleep range (or null if none) using config and default for
+ * lookup
+ */
+ Range<Long> getSleepRange() {
+ return getSleepRange(null);
+ }
+
+ /**
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the write byte size range (or null if none)
+ */
+ Range<Long> getWriteSize(String primary) {
+ return getMinMaxBytes(ConfigOption.WRITE_SIZE, primary);
+ }
+
+ /**
+ * @return the write byte size range (or null if none) using config and
+ * default for lookup
+ */
+ Range<Long> getWriteSize() {
+ return getWriteSize(null);
+ }
+
+ /**
+ * Returns whether the write range should use the block size range
+ *
+ * @return true|false
+ */
+ boolean shouldWriteUseBlockSize() {
+ Range<Long> writeRange = getWriteSize();
+ if (writeRange == null
+ || (writeRange.getLower() == writeRange.getUpper() && (writeRange
+ .getUpper() == Long.MAX_VALUE))) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns whether the append range should use the block size range
+ *
+ * @return true|false
+ */
+ boolean shouldAppendUseBlockSize() {
+ Range<Long> appendRange = getAppendSize();
+ if (appendRange == null
+ || (appendRange.getLower() == appendRange.getUpper() && (appendRange
+ .getUpper() == Long.MAX_VALUE))) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Returns whether the read range should use the entire file
+ *
+ * @return true|false
+ */
+ boolean shouldReadFullFile() {
+ Range<Long> readRange = getReadSize();
+ if (readRange == null
+ || (readRange.getLower() == readRange.getUpper() && (readRange
+ .getUpper() == Long.MAX_VALUE))) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @param primary
+ * the initial string to be used for the value of this configuration
+ * option (if not provided then config and then the default are used)
+ * @return the read byte size range (or null if none)
+ */
+ Range<Long> getReadSize(String primary) {
+ return getMinMaxBytes(ConfigOption.READ_SIZE, primary);
+ }
+
+ /**
+ * Gets the bytes per checksum (if it exists or null if not)
+ *
+ * @return Long
+ */
+ Long getByteCheckSum() {
+ String val = config.get(Constants.BYTES_PER_CHECKSUM);
+ if(val == null) {
+ return null;
+ }
+ return Long.parseLong(val);
+ }
+
+ /**
+ * @return the read byte size range (or null if none) using config and default
+ * for lookup
+ */
+ Range<Long> getReadSize() {
+ return getReadSize(null);
+ }
+
+ /**
+ * Dumps out the given options for the given config extractor
+ *
+ * @param cfg
+ * the config to write to the log
+ */
+ static void dumpOptions(ConfigExtractor cfg) {
+ if (cfg == null) {
+ return;
+ }
+ LOG.info("Base directory = " + cfg.getBaseDirectory());
+ LOG.info("Data directory = " + cfg.getDataPath());
+ LOG.info("Output directory = " + cfg.getOutputPath());
+ LOG.info("Result file = " + cfg.getResultFile());
+ LOG.info("Grid queue = " + cfg.getQueueName());
+ LOG.info("Should exit on first error = " + cfg.shouldExitOnFirstError());
+ {
+ String duration = "Duration = ";
+ if (cfg.getDurationMilliseconds() == Integer.MAX_VALUE) {
+ duration += "unlimited";
+ } else {
+ duration += cfg.getDurationMilliseconds() + " milliseconds";
+ }
+ LOG.info(duration);
+ }
+ LOG.info("Map amount = " + cfg.getMapAmount());
+ LOG.info("Reducer amount = " + cfg.getReducerAmount());
+ LOG.info("Operation amount = " + cfg.getOpCount());
+ LOG.info("Total file limit = " + cfg.getTotalFiles());
+ LOG.info("Total dir file limit = " + cfg.getDirSize());
+ {
+ String read = "Read size = ";
+ if (cfg.shouldReadFullFile()) {
+ read += "entire file";
+ } else {
+ read += cfg.getReadSize() + " bytes";
+ }
+ LOG.info(read);
+ }
+ {
+ String write = "Write size = ";
+ if (cfg.shouldWriteUseBlockSize()) {
+ write += "blocksize";
+ } else {
+ write += cfg.getWriteSize() + " bytes";
+ }
+ LOG.info(write);
+ }
+ {
+ String append = "Append size = ";
+ if (cfg.shouldAppendUseBlockSize()) {
+ append += "blocksize";
+ } else {
+ append += cfg.getAppendSize() + " bytes";
+ }
+ LOG.info(append);
+ }
+ {
+ String bsize = "Block size = ";
+ bsize += cfg.getBlockSize() + " bytes";
+ LOG.info(bsize);
+ }
+ if (cfg.getRandomSeed() != null) {
+ LOG.info("Random seed = " + cfg.getRandomSeed());
+ }
+ if (cfg.getSleepRange() != null) {
+ LOG.info("Sleep range = " + cfg.getSleepRange() + " milliseconds");
+ }
+ LOG.info("Replication amount = " + cfg.getReplication());
+ LOG.info("Operations are:");
+ NumberFormat percFormatter = Formatter.getPercentFormatter();
+ Map<OperationType, OperationData> operations = cfg.getOperations();
+ for (OperationType type : operations.keySet()) {
+ String name = type.name();
+ LOG.info(name);
+ OperationData opInfo = operations.get(type);
+ LOG.info(" " + opInfo.getDistribution().name());
+ if (opInfo.getPercent() != null) {
+ LOG.info(" " + percFormatter.format(opInfo.getPercent()));
+ } else {
+ LOG.info(" ???");
+ }
+ }
+ }
+
+}
Added: hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigMerger.java
URL: http://svn.apache.org/viewvc/hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigMerger.java?rev=1495297&view=auto
==============================================================================
--- hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigMerger.java (added)
+++ hadoop/common/branches/branch-1-win/src/test/org/apache/hadoop/fs/slive/ConfigMerger.java Fri Jun 21 06:37:27 2013
@@ -0,0 +1,572 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.fs.slive;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.slive.ArgumentParser.ParsedOutput;
+import org.apache.hadoop.fs.slive.Constants.Distribution;
+import org.apache.hadoop.fs.slive.Constants.OperationType;
+import org.apache.hadoop.util.StringUtils;
+
+/**
+ * Class which merges options given from a config file and the command line and
+ * performs some basic verification of the data retrieved and sets the verified
+ * values back into the configuration object for return
+ */
+class ConfigMerger {
+ /**
+ * Exception that represents config problems...
+ */
+ static class ConfigException extends IOException {
+
+ private static final long serialVersionUID = 2047129184917444550L;
+
+ ConfigException(String msg) {
+ super(msg);
+ }
+
+ ConfigException(String msg, Throwable e) {
+ super(msg, e);
+ }
+ }
+
+ /**
+ * Merges the given command line parsed output with the given configuration
+ * object and returns the new configuration object with the correct options
+ * overwritten
+ *
+ * @param opts
+ * the parsed command line option output
+ * @param base
+ * the base configuration to merge with
+ * @return merged configuration object
+ * @throws ConfigException
+ * when configuration errors or verification occur
+ */
+ Configuration getMerged(ParsedOutput opts, Configuration base)
+ throws ConfigException {
+ return handleOptions(opts, base);
+ }
+
+ /**
+ * Gets the base set of operations to use
+ *
+ * @return Map
+ */
+ private Map<OperationType, OperationData> getBaseOperations() {
+ Map<OperationType, OperationData> base = new HashMap<OperationType, OperationData>();
+ // add in all the operations
+ // since they will all be applied unless changed
+ OperationType[] types = OperationType.values();
+ for (OperationType type : types) {
+ base.put(type, new OperationData(Distribution.UNIFORM, null));
+ }
+ return base;
+ }
+
+ /**
+ * Handles the specific task of merging operations from the command line or
+ * extractor object into the base configuration provided
+ *
+ * @param opts
+ * the parsed command line option output
+ * @param base
+ * the base configuration to merge with
+ * @param extractor
+ * the access object to fetch operations from if none from the
+ * command line
+ * @return merged configuration object
+ * @throws ConfigException
+ * when verification fails
+ */
+ private Configuration handleOperations(ParsedOutput opts, Configuration base,
+ ConfigExtractor extractor) throws ConfigException {
+ // get the base set to start off with
+ Map<OperationType, OperationData> operations = getBaseOperations();
+ // merge with what is coming from config
+ Map<OperationType, OperationData> cfgOperations = extractor.getOperations();
+ for (OperationType opType : cfgOperations.keySet()) {
+ operations.put(opType, cfgOperations.get(opType));
+ }
+ // see if any coming in from the command line
+ for (OperationType opType : OperationType.values()) {
+ String opName = opType.lowerName();
+ String opVal = opts.getValue(opName);
+ if (opVal != null) {
+ operations.put(opType, new OperationData(opVal));
+ }
+ }
+ // remove those with <= zero percent
+ {
+ Map<OperationType, OperationData> cleanedOps = new HashMap<OperationType, OperationData>();
+ for (OperationType opType : operations.keySet()) {
+ OperationData data = operations.get(opType);
+ if (data.getPercent() == null || data.getPercent() > 0.0d) {
+ cleanedOps.put(opType, data);
+ }
+ }
+ operations = cleanedOps;
+ }
+ if (operations.isEmpty()) {
+ throw new ConfigException("No operations provided!");
+ }
+ // verify and adjust
+ double currPct = 0;
+ int needFill = 0;
+ for (OperationType type : operations.keySet()) {
+ OperationData op = operations.get(type);
+ if (op.getPercent() != null) {
+ currPct += op.getPercent();
+ } else {
+ needFill++;
+ }
+ }
+ if (currPct > 1) {
+ throw new ConfigException(
+ "Unable to have accumlative percent greater than 100%");
+ }
+ if (needFill > 0 && currPct < 1) {
+ double leftOver = 1.0 - currPct;
+ Map<OperationType, OperationData> mpcp = new HashMap<OperationType, OperationData>();
+ for (OperationType type : operations.keySet()) {
+ OperationData op = operations.get(type);
+ if (op.getPercent() == null) {
+ op = new OperationData(op.getDistribution(), (leftOver / needFill));
+ }
+ mpcp.put(type, op);
+ }
+ operations = mpcp;
+ } else if (needFill == 0 && currPct < 1) {
+ // redistribute
+ double leftOver = 1.0 - currPct;
+ Map<OperationType, OperationData> mpcp = new HashMap<OperationType, OperationData>();
+ double each = leftOver / operations.keySet().size();
+ for (OperationType t : operations.keySet()) {
+ OperationData op = operations.get(t);
+ op = new OperationData(op.getDistribution(), (op.getPercent() + each));
+ mpcp.put(t, op);
+ }
+ operations = mpcp;
+ } else if (needFill > 0 && currPct >= 1) {
+ throw new ConfigException(needFill
+ + " unfilled operations but no percentage left to fill with");
+ }
+ // save into base
+ for (OperationType opType : operations.keySet()) {
+ String opName = opType.lowerName();
+ OperationData opData = operations.get(opType);
+ String distr = opData.getDistribution().lowerName();
+ String ratio = new Double(opData.getPercent() * 100.0d).toString();
+ base.set(String.format(Constants.OP, opName), opData.toString());
+ base.set(String.format(Constants.OP_DISTR, opName), distr);
+ base.set(String.format(Constants.OP_PERCENT, opName), ratio);
+ }
+ return base;
+ }
+
+ /**
+ * Handles merging all options and verifying from the given command line
+ * output and the given base configuration and returns the merged
+ * configuration
+ *
+ * @param opts
+ * the parsed command line option output
+ * @param base
+ * the base configuration to merge with
+ * @return the merged configuration
+ * @throws ConfigException
+ */
+ private Configuration handleOptions(ParsedOutput opts, Configuration base)
+ throws ConfigException {
+ // ensure variables are overwritten and verified
+ ConfigExtractor extractor = new ConfigExtractor(base);
+ // overwrite the map amount and check to ensure > 0
+ {
+ Integer mapAmount = null;
+ try {
+ mapAmount = extractor.getMapAmount(opts.getValue(ConfigOption.MAPS
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging map amount", e);
+ }
+ if (mapAmount != null) {
+ if (mapAmount <= 0) {
+ throw new ConfigException(
+ "Map amount can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.MAPS.getCfgOption(), mapAmount.toString());
+ }
+ }
+ // overwrite the reducer amount and check to ensure > 0
+ {
+ Integer reduceAmount = null;
+ try {
+ reduceAmount = extractor.getMapAmount(opts.getValue(ConfigOption.REDUCES
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging reducer amount", e);
+ }
+ if (reduceAmount != null) {
+ if (reduceAmount <= 0) {
+ throw new ConfigException(
+ "Reducer amount can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.REDUCES.getCfgOption(), reduceAmount.toString());
+ }
+ }
+ // overwrite the duration amount and ensure > 0
+ {
+ Integer duration = null;
+ try {
+ duration = extractor.getDuration(opts.getValue(ConfigOption.DURATION
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging duration", e);
+ }
+ if (duration != null) {
+ if (duration <= 0) {
+ throw new ConfigException(
+ "Duration can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.DURATION.getCfgOption(), duration.toString());
+ }
+ }
+ // overwrite the operation amount and ensure > 0
+ {
+ Integer operationAmount = null;
+ try {
+ operationAmount = extractor.getOpCount(opts.getValue(ConfigOption.OPS
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging operation amount", e);
+ }
+ if (operationAmount != null) {
+ if (operationAmount <= 0) {
+ throw new ConfigException(
+ "Operation amount can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.OPS.getCfgOption(), operationAmount.toString());
+ }
+ }
+ // overwrite the exit on error setting
+ {
+ try {
+ boolean exitOnError = extractor.shouldExitOnFirstError(opts
+ .getValue(ConfigOption.EXIT_ON_ERROR.getOpt()));
+ base.setBoolean(ConfigOption.EXIT_ON_ERROR.getCfgOption(), exitOnError);
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging exit on error value", e);
+ }
+ }
+ // verify and set file limit and ensure > 0
+ {
+ Integer fileAm = null;
+ try {
+ fileAm = extractor.getTotalFiles(opts.getValue(ConfigOption.FILES
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging total file limit amount", e);
+ }
+ if (fileAm != null) {
+ if (fileAm <= 0) {
+ throw new ConfigException(
+ "File amount can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.FILES.getCfgOption(), fileAm.toString());
+ }
+ }
+ // set the grid queue to run on
+ {
+ try {
+ String qname = extractor.getQueueName(opts
+ .getValue(ConfigOption.QUEUE_NAME.getOpt()));
+ if (qname != null) {
+ base.set(ConfigOption.QUEUE_NAME.getCfgOption(), qname);
+ }
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging queue name", e);
+ }
+ }
+ // verify and set the directory limit and ensure > 0
+ {
+ Integer directoryLimit = null;
+ try {
+ directoryLimit = extractor.getDirSize(opts
+ .getValue(ConfigOption.DIR_SIZE.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging directory file limit", e);
+ }
+ if (directoryLimit != null) {
+ if (directoryLimit <= 0) {
+ throw new ConfigException(
+ "Directory file limit can not be less than or equal to zero");
+ }
+ base.set(ConfigOption.DIR_SIZE.getCfgOption(), directoryLimit
+ .toString());
+ }
+ }
+ // set the base directory
+ {
+ Path basedir = null;
+ try {
+ basedir = extractor.getBaseDirectory(opts
+ .getValue(ConfigOption.BASE_DIR.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging base directory",
+ e);
+ }
+ if (basedir != null) {
+ // always ensure in slive dir
+ basedir = new Path(basedir, Constants.BASE_DIR);
+ base.set(ConfigOption.BASE_DIR.getCfgOption(), basedir.toString());
+ }
+ }
+ // set the result file
+ {
+ String fn = null;
+ try {
+ fn = extractor.getResultFile(opts.getValue(ConfigOption.RESULT_FILE
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging result file", e);
+ }
+ if (fn != null) {
+ base.set(ConfigOption.RESULT_FILE.getCfgOption(), fn);
+ }
+ }
+ {
+ String fn = null;
+ try {
+ fn = extractor.getResultFile(opts.getValue(ConfigOption.RESULT_FILE
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging result file", e);
+ }
+ if (fn != null) {
+ base.set(ConfigOption.RESULT_FILE.getCfgOption(), fn);
+ }
+ }
+ // set the operations
+ {
+ try {
+ base = handleOperations(opts, base, extractor);
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging operations", e);
+ }
+ }
+ // set the replication amount range
+ {
+ Range<Short> replicationAm = null;
+ try {
+ replicationAm = extractor.getReplication(opts
+ .getValue(ConfigOption.REPLICATION_AM.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging replication amount range", e);
+ }
+ if (replicationAm != null) {
+ int minRepl = base.getInt(Constants.MIN_REPLICATION, 1);
+ if (replicationAm.getLower() < minRepl) {
+ throw new ConfigException(
+ "Replication amount minimum is less than property configured minimum "
+ + minRepl);
+ }
+ if (replicationAm.getLower() > replicationAm.getUpper()) {
+ throw new ConfigException(
+ "Replication amount minimum is greater than its maximum");
+ }
+ if (replicationAm.getLower() <= 0) {
+ throw new ConfigException(
+ "Replication amount minimum must be greater than zero");
+ }
+ base.set(ConfigOption.REPLICATION_AM.getCfgOption(), replicationAm
+ .toString());
+ }
+ }
+ // set the sleep range
+ {
+ Range<Long> sleepRange = null;
+ try {
+ sleepRange = extractor.getSleepRange(opts
+ .getValue(ConfigOption.SLEEP_TIME.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging sleep size range", e);
+ }
+ if (sleepRange != null) {
+ if (sleepRange.getLower() > sleepRange.getUpper()) {
+ throw new ConfigException(
+ "Sleep range minimum is greater than its maximum");
+ }
+ if (sleepRange.getLower() <= 0) {
+ throw new ConfigException(
+ "Sleep range minimum must be greater than zero");
+ }
+ base.set(ConfigOption.SLEEP_TIME.getCfgOption(), sleepRange.toString());
+ }
+ }
+ // set the packet size if given
+ {
+ String pSize = opts.getValue(ConfigOption.PACKET_SIZE.getOpt());
+ if (pSize == null) {
+ pSize = ConfigOption.PACKET_SIZE.getDefault();
+ }
+ if (pSize != null) {
+ try {
+ Long packetSize = StringUtils.TraditionalBinaryPrefix
+ .string2long(pSize);
+ base.set(ConfigOption.PACKET_SIZE.getCfgOption(), packetSize
+ .toString());
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging write packet size", e);
+ }
+ }
+ }
+ // set the block size range
+ {
+ Range<Long> blockSize = null;
+ try {
+ blockSize = extractor.getBlockSize(opts
+ .getValue(ConfigOption.BLOCK_SIZE.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging block size range", e);
+ }
+ if (blockSize != null) {
+ if (blockSize.getLower() > blockSize.getUpper()) {
+ throw new ConfigException(
+ "Block size minimum is greater than its maximum");
+ }
+ if (blockSize.getLower() <= 0) {
+ throw new ConfigException(
+ "Block size minimum must be greater than zero");
+ }
+ // ensure block size is a multiple of BYTES_PER_CHECKSUM
+ // if a value is set in the configuration
+ Long bytesPerChecksum = extractor.getByteCheckSum();
+ if (bytesPerChecksum != null) {
+ if ((blockSize.getLower() % bytesPerChecksum) != 0) {
+ throw new ConfigException(
+ "Blocksize lower bound must be a multiple of "
+ + bytesPerChecksum);
+ }
+ if ((blockSize.getUpper() % bytesPerChecksum) != 0) {
+ throw new ConfigException(
+ "Blocksize upper bound must be a multiple of "
+ + bytesPerChecksum);
+ }
+ }
+ base.set(ConfigOption.BLOCK_SIZE.getCfgOption(), blockSize.toString());
+ }
+ }
+ // set the read size range
+ {
+ Range<Long> readSize = null;
+ try {
+ readSize = extractor.getReadSize(opts.getValue(ConfigOption.READ_SIZE
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException("Error extracting & merging read size range",
+ e);
+ }
+ if (readSize != null) {
+ if (readSize.getLower() > readSize.getUpper()) {
+ throw new ConfigException(
+ "Read size minimum is greater than its maximum");
+ }
+ if (readSize.getLower() < 0) {
+ throw new ConfigException(
+ "Read size minimum must be greater than or equal to zero");
+ }
+ base.set(ConfigOption.READ_SIZE.getCfgOption(), readSize.toString());
+ }
+ }
+ // set the write size range
+ {
+ Range<Long> writeSize = null;
+ try {
+ writeSize = extractor.getWriteSize(opts
+ .getValue(ConfigOption.WRITE_SIZE.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging write size range", e);
+ }
+ if (writeSize != null) {
+ if (writeSize.getLower() > writeSize.getUpper()) {
+ throw new ConfigException(
+ "Write size minimum is greater than its maximum");
+ }
+ if (writeSize.getLower() < 0) {
+ throw new ConfigException(
+ "Write size minimum must be greater than or equal to zero");
+ }
+ base.set(ConfigOption.WRITE_SIZE.getCfgOption(), writeSize.toString());
+ }
+ }
+ // set the append size range
+ {
+ Range<Long> appendSize = null;
+ try {
+ appendSize = extractor.getAppendSize(opts
+ .getValue(ConfigOption.APPEND_SIZE.getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging append size range", e);
+ }
+ if (appendSize != null) {
+ if (appendSize.getLower() > appendSize.getUpper()) {
+ throw new ConfigException(
+ "Append size minimum is greater than its maximum");
+ }
+ if (appendSize.getLower() < 0) {
+ throw new ConfigException(
+ "Append size minimum must be greater than or equal to zero");
+ }
+ base
+ .set(ConfigOption.APPEND_SIZE.getCfgOption(), appendSize.toString());
+ }
+ }
+ // set the seed
+ {
+ Long seed = null;
+ try {
+ seed = extractor.getRandomSeed(opts.getValue(ConfigOption.RANDOM_SEED
+ .getOpt()));
+ } catch (Exception e) {
+ throw new ConfigException(
+ "Error extracting & merging random number seed", e);
+ }
+ if (seed != null) {
+ base.set(ConfigOption.RANDOM_SEED.getCfgOption(), seed.toString());
+ }
+ }
+ return base;
+ }
+}