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 ji...@apache.org on 2016/02/24 21:02:43 UTC

[01/50] [abbrv] hadoop git commit: HADOOP-12548. Read s3a creds from a Credential Provider. Contributed by Larry McCay.

Repository: hadoop
Updated Branches:
  refs/heads/HDFS-7240 fac463323 -> 1b7df69d3


HADOOP-12548. Read s3a creds from a Credential Provider. Contributed by Larry McCay.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/76fab26c
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/76fab26c
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/76fab26c

Branch: refs/heads/HDFS-7240
Commit: 76fab26c5c02cef38924d04136407489fd9457d9
Parents: 3a23dc6
Author: cnauroth <cn...@apache.org>
Authored: Wed Feb 17 10:17:12 2016 -0800
Committer: cnauroth <cn...@apache.org>
Committed: Wed Feb 17 12:19:59 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |   3 +
 .../org/apache/hadoop/fs/s3a/S3AFileSystem.java | 212 +++++++++++++------
 .../hadoop/fs/s3a/TestS3AConfiguration.java     | 151 ++++++++++++-
 3 files changed, 301 insertions(+), 65 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/76fab26c/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index cde5f3b..9269960 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -766,6 +766,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-12426. Add Entry point for Kerberos health check
     (Steve Loughran via cnauroth)
 
+    HADOOP-12548. Read s3a creds from a Credential Provider.
+    (Larry McCay via cnauroth)
+
   IMPROVEMENTS
 
     HADOOP-12458. Retries is typoed to spell Retires in parts of

http://git-wip-us.apache.org/repos/asf/hadoop/blob/76fab26c/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java b/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java
index 5ea6bec..b9590ea 100644
--- a/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java
+++ b/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3AFileSystem.java
@@ -106,23 +106,11 @@ public class S3AFileSystem extends FileSystem {
     workingDir = new Path("/user", System.getProperty("user.name")).makeQualified(this.uri,
         this.getWorkingDirectory());
 
-    // Try to get our credentials or just connect anonymously
-    String accessKey = conf.get(ACCESS_KEY, null);
-    String secretKey = conf.get(SECRET_KEY, null);
-
-    String userInfo = name.getUserInfo();
-    if (userInfo != null) {
-      int index = userInfo.indexOf(':');
-      if (index != -1) {
-        accessKey = userInfo.substring(0, index);
-        secretKey = userInfo.substring(index + 1);
-      } else {
-        accessKey = userInfo;
-      }
-    }
+    AWSAccessKeys creds = getAWSAccessKeys(name, conf);
 
     AWSCredentialsProviderChain credentials = new AWSCredentialsProviderChain(
-        new BasicAWSCredentialsProvider(accessKey, secretKey),
+        new BasicAWSCredentialsProvider(
+            creds.getAccessKey(), creds.getAccessSecret()),
         new InstanceProfileCredentialsProvider(),
         new AnonymousAWSCredentialsProvider()
     );
@@ -146,6 +134,59 @@ public class S3AFileSystem extends FileSystem {
       awsConf.setSignerOverride(signerOverride);
     }
 
+    initProxySupport(conf, awsConf, secureConnections);
+
+    initAmazonS3Client(conf, credentials, awsConf);
+
+    maxKeys = conf.getInt(MAX_PAGING_KEYS, DEFAULT_MAX_PAGING_KEYS);
+    partSize = conf.getLong(MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE);
+    multiPartThreshold = conf.getLong(MIN_MULTIPART_THRESHOLD,
+      DEFAULT_MIN_MULTIPART_THRESHOLD);
+    enableMultiObjectsDelete = conf.getBoolean(ENABLE_MULTI_DELETE, true);
+
+    if (partSize < 5 * 1024 * 1024) {
+      LOG.error(MULTIPART_SIZE + " must be at least 5 MB");
+      partSize = 5 * 1024 * 1024;
+    }
+
+    if (multiPartThreshold < 5 * 1024 * 1024) {
+      LOG.error(MIN_MULTIPART_THRESHOLD + " must be at least 5 MB");
+      multiPartThreshold = 5 * 1024 * 1024;
+    }
+
+    int maxThreads = conf.getInt(MAX_THREADS, DEFAULT_MAX_THREADS);
+    if (maxThreads < 2) {
+      LOG.warn(MAX_THREADS + " must be at least 2: forcing to 2.");
+      maxThreads = 2;
+    }
+    int totalTasks = conf.getInt(MAX_TOTAL_TASKS, DEFAULT_MAX_TOTAL_TASKS);
+    if (totalTasks < 1) {
+      LOG.warn(MAX_TOTAL_TASKS + "must be at least 1: forcing to 1.");
+      totalTasks = 1;
+    }
+    long keepAliveTime = conf.getLong(KEEPALIVE_TIME, DEFAULT_KEEPALIVE_TIME);
+    threadPoolExecutor = new BlockingThreadPoolExecutorService(maxThreads,
+        maxThreads + totalTasks, keepAliveTime, TimeUnit.SECONDS,
+        "s3a-transfer-shared");
+
+    initTransferManager();
+
+    initCannedAcls(conf);
+
+    if (!s3.doesBucketExist(bucket)) {
+      throw new IOException("Bucket " + bucket + " does not exist");
+    }
+
+    initMultipartUploads(conf);
+
+    serverSideEncryptionAlgorithm = conf.get(SERVER_SIDE_ENCRYPTION_ALGORITHM);
+
+    setConf(conf);
+  }
+
+  void initProxySupport(Configuration conf, ClientConfiguration awsConf,
+      boolean secureConnections) throws IllegalArgumentException,
+      IllegalArgumentException {
     String proxyHost = conf.getTrimmed(PROXY_HOST, "");
     int proxyPort = conf.getInt(PROXY_PORT, -1);
     if (!proxyHost.isEmpty()) {
@@ -185,7 +226,11 @@ public class S3AFileSystem extends FileSystem {
       LOG.error(msg);
       throw new IllegalArgumentException(msg);
     }
+  }
 
+  private void initAmazonS3Client(Configuration conf,
+      AWSCredentialsProviderChain credentials, ClientConfiguration awsConf)
+      throws IllegalArgumentException {
     s3 = new AmazonS3Client(credentials, awsConf);
     String endPoint = conf.getTrimmed(ENDPOINT,"");
     if (!endPoint.isEmpty()) {
@@ -197,56 +242,27 @@ public class S3AFileSystem extends FileSystem {
         throw new IllegalArgumentException(msg, e);
       }
     }
+  }
 
-    maxKeys = conf.getInt(MAX_PAGING_KEYS, DEFAULT_MAX_PAGING_KEYS);
-    partSize = conf.getLong(MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE);
-    multiPartThreshold = conf.getLong(MIN_MULTIPART_THRESHOLD,
-      DEFAULT_MIN_MULTIPART_THRESHOLD);
-    enableMultiObjectsDelete = conf.getBoolean(ENABLE_MULTI_DELETE, true);
-
-    if (partSize < 5 * 1024 * 1024) {
-      LOG.error(MULTIPART_SIZE + " must be at least 5 MB");
-      partSize = 5 * 1024 * 1024;
-    }
-
-    if (multiPartThreshold < 5 * 1024 * 1024) {
-      LOG.error(MIN_MULTIPART_THRESHOLD + " must be at least 5 MB");
-      multiPartThreshold = 5 * 1024 * 1024;
-    }
-
-    int maxThreads = conf.getInt(MAX_THREADS, DEFAULT_MAX_THREADS);
-    if (maxThreads < 2) {
-      LOG.warn(MAX_THREADS + " must be at least 2: forcing to 2.");
-      maxThreads = 2;
-    }
-    int totalTasks = conf.getInt(MAX_TOTAL_TASKS, DEFAULT_MAX_TOTAL_TASKS);
-    if (totalTasks < 1) {
-      LOG.warn(MAX_TOTAL_TASKS + "must be at least 1: forcing to 1.");
-      totalTasks = 1;
-    }
-    long keepAliveTime = conf.getLong(KEEPALIVE_TIME, DEFAULT_KEEPALIVE_TIME);
-    threadPoolExecutor = new BlockingThreadPoolExecutorService(maxThreads,
-        maxThreads + totalTasks, keepAliveTime, TimeUnit.SECONDS,
-        "s3a-transfer-shared");
-
+  private void initTransferManager() {
     TransferManagerConfiguration transferConfiguration = new TransferManagerConfiguration();
     transferConfiguration.setMinimumUploadPartSize(partSize);
     transferConfiguration.setMultipartUploadThreshold(multiPartThreshold);
 
     transfers = new TransferManager(s3, threadPoolExecutor);
     transfers.setConfiguration(transferConfiguration);
+  }
 
+  private void initCannedAcls(Configuration conf) {
     String cannedACLName = conf.get(CANNED_ACL, DEFAULT_CANNED_ACL);
     if (!cannedACLName.isEmpty()) {
       cannedACL = CannedAccessControlList.valueOf(cannedACLName);
     } else {
       cannedACL = null;
     }
+  }
 
-    if (!s3.doesBucketExist(bucket)) {
-      throw new IOException("Bucket " + bucket + " does not exist");
-    }
-
+  private void initMultipartUploads(Configuration conf) {
     boolean purgeExistingMultipart = conf.getBoolean(PURGE_EXISTING_MULTIPART, 
       DEFAULT_PURGE_EXISTING_MULTIPART);
     long purgeExistingMultipartAge = conf.getLong(PURGE_EXISTING_MULTIPART_AGE, 
@@ -257,10 +273,51 @@ public class S3AFileSystem extends FileSystem {
 
       transfers.abortMultipartUploads(bucket, purgeBefore);
     }
+  }
 
-    serverSideEncryptionAlgorithm = conf.get(SERVER_SIDE_ENCRYPTION_ALGORITHM);
-
-    setConf(conf);
+  /**
+   * Return the access key and secret for S3 API use.
+   * Credentials may exist in configuration, within credential providers
+   * or indicated in the UserInfo of the name URI param.
+   * @param name the URI for which we need the access keys.
+   * @param conf the Configuration object to interogate for keys.
+   * @return AWSAccessKeys
+   */
+  AWSAccessKeys getAWSAccessKeys(URI name, Configuration conf)
+      throws IOException {
+    String accessKey = null;
+    String secretKey = null;
+    String userInfo = name.getUserInfo();
+    if (userInfo != null) {
+      int index = userInfo.indexOf(':');
+      if (index != -1) {
+        accessKey = userInfo.substring(0, index);
+        secretKey = userInfo.substring(index + 1);
+      } else {
+        accessKey = userInfo;
+      }
+    }
+    if (accessKey == null) {
+      try {
+        final char[] key = conf.getPassword(ACCESS_KEY);
+        if (key != null) {
+          accessKey = (new String(key)).trim();
+        }
+      } catch(IOException ioe) {
+        throw new IOException("Cannot find AWS access key.", ioe);
+      }
+    }
+    if (secretKey == null) {
+      try {
+        final char[] pass = conf.getPassword(SECRET_KEY);
+        if (pass != null) {
+          secretKey = (new String(pass)).trim();
+        }
+      } catch(IOException ioe) {
+        throw new IOException("Cannot find AWS secret key.", ioe);
+      }
+    }
+    return new AWSAccessKeys(accessKey, secretKey);
   }
 
   /**
@@ -341,14 +398,14 @@ public class S3AFileSystem extends FileSystem {
    * Create an FSDataOutputStream at the indicated Path with write-progress
    * reporting.
    * @param f the file name to open
-   * @param permission
+   * @param permission the permission to set.
    * @param overwrite if a file with this name already exists, then if true,
    *   the file will be overwritten, and if false an error will be thrown.
    * @param bufferSize the size of the buffer to be used.
    * @param replication required block replication for the file.
-   * @param blockSize
-   * @param progress
-   * @throws IOException
+   * @param blockSize the requested block size.
+   * @param progress the progress reporter.
+   * @throws IOException in the event of IO related errors.
    * @see #setPermission(Path, FsPermission)
    */
   @Override
@@ -377,7 +434,7 @@ public class S3AFileSystem extends FileSystem {
    * @param f the existing file to be appended.
    * @param bufferSize the size of the buffer to be used.
    * @param progress for reporting progress if it is not null.
-   * @throws IOException
+   * @throws IOException indicating that append is not supported.
    */
   public FSDataOutputStream append(Path f, int bufferSize, 
     Progressable progress) throws IOException {
@@ -585,7 +642,7 @@ public class S3AFileSystem extends FileSystem {
    * true, the directory is deleted else throws an exception. In
    * case of a file the recursive can be set to either true or false.
    * @return  true if delete is successful else false.
-   * @throws IOException
+   * @throws IOException due to inability to delete a directory or file.
    */
   public boolean delete(Path f, boolean recursive) throws IOException {
     if (LOG.isDebugEnabled()) {
@@ -791,7 +848,7 @@ public class S3AFileSystem extends FileSystem {
    * Set the current working directory for the given file system. All relative
    * paths will be resolved relative to it.
    *
-   * @param new_dir
+   * @param new_dir the current working directory.
    */
   public void setWorkingDirectory(Path new_dir) {
     workingDir = new_dir;
@@ -1202,4 +1259,39 @@ public class S3AFileSystem extends FileSystem {
         "such as not being able to access the network.");
     LOG.info("Error Message: {}" + ace, ace);
   }
+
+  /**
+   * This is a simple encapsulation of the
+   * S3 access key and secret.
+   */
+  static class AWSAccessKeys {
+    private String accessKey = null;
+    private String accessSecret = null;
+
+    /**
+     * Constructor.
+     * @param key - AWS access key
+     * @param secret - AWS secret key
+     */
+    public AWSAccessKeys(String key, String secret) {
+      accessKey = key;
+      accessSecret = secret;
+    }
+
+    /**
+     * Return the AWS access key.
+     * @return key
+     */
+    public String getAccessKey() {
+      return accessKey;
+    }
+
+    /**
+     * Return the AWS secret key.
+     * @return secret
+     */
+    public String getAccessSecret() {
+      return accessSecret;
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/76fab26c/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AConfiguration.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AConfiguration.java b/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AConfiguration.java
index 25068f8..3db84db 100644
--- a/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AConfiguration.java
+++ b/hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AConfiguration.java
@@ -32,7 +32,21 @@ import org.slf4j.LoggerFactory;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.fail;
 
+import java.io.File;
+import java.net.URI;
+import java.io.IOException;
+
+import org.apache.hadoop.security.ProviderUtils;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
+
+import org.junit.rules.TemporaryFolder;
+
 public class TestS3AConfiguration {
+  private static final String EXAMPLE_ID = "AKASOMEACCESSKEY";
+  private static final String EXAMPLE_KEY =
+      "RGV0cm9pdCBSZ/WQgY2xl/YW5lZCB1cAEXAMPLE";
+
   private Configuration conf;
   private S3AFileSystem fs;
 
@@ -44,6 +58,9 @@ public class TestS3AConfiguration {
   @Rule
   public Timeout testTimeout = new Timeout(30 * 60 * 1000);
 
+  @Rule
+  public final TemporaryFolder tempDir = new TemporaryFolder();
+
   /**
    * Test if custom endpoint is picked up.
    * <p/>
@@ -59,7 +76,7 @@ public class TestS3AConfiguration {
    * @throws Exception
    */
   @Test
-  public void TestEndpoint() throws Exception {
+  public void testEndpoint() throws Exception {
     conf = new Configuration();
     String endpoint = conf.getTrimmed(TEST_ENDPOINT, "");
     if (endpoint.isEmpty()) {
@@ -85,7 +102,7 @@ public class TestS3AConfiguration {
   }
 
   @Test
-  public void TestProxyConnection() throws Exception {
+  public void testProxyConnection() throws Exception {
     conf = new Configuration();
     conf.setInt(Constants.MAX_ERROR_RETRIES, 2);
     conf.set(Constants.PROXY_HOST, "127.0.0.1");
@@ -103,7 +120,7 @@ public class TestS3AConfiguration {
   }
 
   @Test
-  public void TestProxyPortWithoutHost() throws Exception {
+  public void testProxyPortWithoutHost() throws Exception {
     conf = new Configuration();
     conf.setInt(Constants.MAX_ERROR_RETRIES, 2);
     conf.setInt(Constants.PROXY_PORT, 1);
@@ -120,7 +137,7 @@ public class TestS3AConfiguration {
   }
 
   @Test
-  public void TestAutomaticProxyPortSelection() throws Exception {
+  public void testAutomaticProxyPortSelection() throws Exception {
     conf = new Configuration();
     conf.setInt(Constants.MAX_ERROR_RETRIES, 2);
     conf.set(Constants.PROXY_HOST, "127.0.0.1");
@@ -145,7 +162,7 @@ public class TestS3AConfiguration {
   }
 
   @Test
-  public void TestUsernameInconsistentWithPassword() throws Exception {
+  public void testUsernameInconsistentWithPassword() throws Exception {
     conf = new Configuration();
     conf.setInt(Constants.MAX_ERROR_RETRIES, 2);
     conf.set(Constants.PROXY_HOST, "127.0.0.1");
@@ -177,4 +194,128 @@ public class TestS3AConfiguration {
       }
     }
   }
+
+  @Test
+  public void testCredsFromCredentialProvider() throws Exception {
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    provisionAccessKeys(conf);
+
+    S3AFileSystem s3afs = new S3AFileSystem();
+    conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM");
+    S3AFileSystem.AWSAccessKeys creds =
+        s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf);
+    assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey());
+    assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret());
+  }
+
+  void provisionAccessKeys(final Configuration conf) throws Exception {
+    // add our creds to the provider
+    final CredentialProvider provider =
+        CredentialProviderFactory.getProviders(conf).get(0);
+    provider.createCredentialEntry(Constants.ACCESS_KEY,
+        EXAMPLE_ID.toCharArray());
+    provider.createCredentialEntry(Constants.SECRET_KEY,
+        EXAMPLE_KEY.toCharArray());
+    provider.flush();
+  }
+
+  @Test
+  public void testCredsFromUserInfo() throws Exception {
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    provisionAccessKeys(conf);
+
+    S3AFileSystem s3afs = new S3AFileSystem();
+    conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM");
+    URI uriWithUserInfo = new URI("s3a://123:456@foobar");
+    S3AFileSystem.AWSAccessKeys creds =
+        s3afs.getAWSAccessKeys(uriWithUserInfo, conf);
+    assertEquals("AccessKey incorrect.", "123", creds.getAccessKey());
+    assertEquals("SecretKey incorrect.", "456", creds.getAccessSecret());
+  }
+
+  @Test
+  public void testIDFromUserInfoSecretFromCredentialProvider()
+      throws Exception {
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    provisionAccessKeys(conf);
+
+    S3AFileSystem s3afs = new S3AFileSystem();
+    conf.set(Constants.ACCESS_KEY, EXAMPLE_ID + "LJM");
+    URI uriWithUserInfo = new URI("s3a://123@foobar");
+    S3AFileSystem.AWSAccessKeys creds =
+        s3afs.getAWSAccessKeys(uriWithUserInfo, conf);
+    assertEquals("AccessKey incorrect.", "123", creds.getAccessKey());
+    assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret());
+  }
+
+  @Test
+  public void testSecretFromCredentialProviderIDFromConfig() throws Exception {
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    // add our creds to the provider
+    final CredentialProvider provider =
+        CredentialProviderFactory.getProviders(conf).get(0);
+    provider.createCredentialEntry(Constants.SECRET_KEY,
+        EXAMPLE_KEY.toCharArray());
+    provider.flush();
+
+    S3AFileSystem s3afs = new S3AFileSystem();
+    conf.set(Constants.ACCESS_KEY, EXAMPLE_ID);
+    S3AFileSystem.AWSAccessKeys creds =
+        s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf);
+    assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey());
+    assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret());
+  }
+
+  @Test
+  public void testIDFromCredentialProviderSecretFromConfig() throws Exception {
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    // add our creds to the provider
+    final CredentialProvider provider =
+        CredentialProviderFactory.getProviders(conf).get(0);
+    provider.createCredentialEntry(Constants.ACCESS_KEY,
+        EXAMPLE_ID.toCharArray());
+    provider.flush();
+
+    S3AFileSystem s3afs = new S3AFileSystem();
+    conf.set(Constants.SECRET_KEY, EXAMPLE_KEY);
+    S3AFileSystem.AWSAccessKeys creds =
+        s3afs.getAWSAccessKeys(new URI("s3a://foobar"), conf);
+    assertEquals("AccessKey incorrect.", EXAMPLE_ID, creds.getAccessKey());
+    assertEquals("SecretKey incorrect.", EXAMPLE_KEY, creds.getAccessSecret());
+  }
 }


[27/50] [abbrv] hadoop git commit: HDFS-9839. Reduce verbosity of processReport logging. (Contributed by Arpit Agarwal)

Posted by ji...@apache.org.
HDFS-9839. Reduce verbosity of processReport logging. (Contributed by Arpit Agarwal)

This closes #78


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/d5abd293
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/d5abd293
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/d5abd293

Branch: refs/heads/HDFS-7240
Commit: d5abd293a890a8a1da48a166a291ae1c5644ad57
Parents: e54cc29
Author: Arpit Agarwal <ar...@apache.org>
Authored: Sat Feb 20 23:19:09 2016 -0800
Committer: Arpit Agarwal <ar...@apache.org>
Committed: Sat Feb 20 23:19:09 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt       |  2 ++
 .../hdfs/server/blockmanagement/BlockManager.java | 18 +++++++++---------
 2 files changed, 11 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/d5abd293/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 1d0379c..9215488 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2802,6 +2802,8 @@ Release 2.8.0 - UNRELEASED
     HDFS-6832. Fix the usage of 'hdfs namenode' command.
     (Manjunath Ballur via aajisaka)
 
+    HDFS-9839. Reduce verbosity of processReport logging. (Arpit Agarwal)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d5abd293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
index cc52b6e..eaebed9 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
@@ -2060,7 +2060,7 @@ public class BlockManager implements BlockStatsMXBean {
     final long startTime = Time.monotonicNow(); //after acquiring write lock
     final long endTime;
     DatanodeDescriptor node;
-    Collection<Block> invalidatedBlocks = null;
+    Collection<Block> invalidatedBlocks = Collections.emptyList();
 
     try {
       node = datanodeManager.getDatanode(nodeID);
@@ -2136,11 +2136,9 @@ public class BlockManager implements BlockStatsMXBean {
       namesystem.writeUnlock();
     }
 
-    if (invalidatedBlocks != null) {
-      for (Block b : invalidatedBlocks) {
-        blockLog.info("BLOCK* processReport: {} on node {} size {} does not " +
-            "belong to any file", b, node, b.getNumBytes());
-      }
+    for (Block b : invalidatedBlocks) {
+      blockLog.debug("BLOCK* processReport: {} on node {} size {} does not " +
+          "belong to any file", b, node, b.getNumBytes());
     }
 
     // Log the block report processing stats from Namenode perspective
@@ -2149,9 +2147,11 @@ public class BlockManager implements BlockStatsMXBean {
       metrics.addBlockReport((int) (endTime - startTime));
     }
     blockLog.info("BLOCK* processReport: from storage {} node {}, " +
-            "blocks: {}, hasStaleStorage: {}, processing time: {} msecs", storage
-            .getStorageID(), nodeID, newReport.getNumberOfBlocks(),
-        node.hasStaleStorages(), (endTime - startTime));
+        "blocks: {}, hasStaleStorage: {}, processing time: {} msecs, " +
+        "invalidatedBlocks: {}", storage.getStorageID(), nodeID,
+        newReport.getNumberOfBlocks(),
+        node.hasStaleStorages(), (endTime - startTime),
+        invalidatedBlocks.size());
     return !node.hasStaleStorages();
   }
 


[47/50] [abbrv] hadoop git commit: YARN-2046. Out of band heartbeats are sent only on container kill and possibly too early. Contributed by Ming Ma

Posted by ji...@apache.org.
YARN-2046. Out of band heartbeats are sent only on container kill and possibly too early. Contributed by Ming Ma


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/d284e187
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/d284e187
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/d284e187

Branch: refs/heads/HDFS-7240
Commit: d284e187b8db43056236032ebc2114ee462c27f6
Parents: 211c78c
Author: Jason Lowe <jl...@apache.org>
Authored: Tue Feb 23 20:49:09 2016 +0000
Committer: Jason Lowe <jl...@apache.org>
Committed: Tue Feb 23 20:49:09 2016 +0000

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |  6 +++++
 .../hadoop/yarn/server/nodemanager/Context.java |  2 ++
 .../yarn/server/nodemanager/NodeManager.java    | 10 +++++++
 .../containermanager/ContainerManagerImpl.java  | 12 +++------
 .../container/ContainerImpl.java                | 25 ++++++++++-------
 .../yarn/server/nodemanager/TestEventFlow.java  |  1 +
 .../nodemanager/TestNodeStatusUpdater.java      | 28 +++++++++++++-------
 .../amrmproxy/BaseAMRMProxyTest.java            |  5 ++++
 .../BaseContainerManagerTest.java               |  1 +
 .../containermanager/TestAuxServices.java       |  7 +++--
 .../container/TestContainer.java                | 16 ++++++++---
 .../nodemanager/webapp/TestNMWebServer.java     |  5 ++--
 12 files changed, 83 insertions(+), 35 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 439c1bb..482fb21 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1539,6 +1539,9 @@ Release 2.7.3 - UNRELEASED
     YARN-4707. Remove the extra char (>) from SecureContainer.md.
     (Brahma Reddy Battula via aajisaka)
 
+    YARN-2046. Out of band heartbeats are sent only on container kill and
+    possibly too early (Ming Ma via jlowe)
+
 Release 2.7.2 - 2016-01-25
 
   INCOMPATIBLE CHANGES
@@ -2390,6 +2393,9 @@ Release 2.6.5 - UNRELEASED
 
   BUG FIXES
 
+    YARN-2046. Out of band heartbeats are sent only on container kill and
+    possibly too early (Ming Ma via jlowe)
+
 Release 2.6.4 - 2016-02-11
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/Context.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/Context.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/Context.java
index 9c2d1fb..d3251ae 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/Context.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/Context.java
@@ -87,4 +87,6 @@ public interface Context {
 
   ConcurrentLinkedQueue<LogAggregationReport>
       getLogAggregationStatusForApps();
+
+  NodeStatusUpdater getNodeStatusUpdater();
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
index a9a5411..7c104d5 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/NodeManager.java
@@ -353,6 +353,7 @@ public class NodeManager extends CompositeService
     // StatusUpdater should be added last so that it get started last 
     // so that we make sure everything is up before registering with RM. 
     addService(nodeStatusUpdater);
+    ((NMContext) context).setNodeStatusUpdater(nodeStatusUpdater);
 
     super.serviceInit(conf);
     // TODO add local dirs to del
@@ -458,6 +459,7 @@ public class NodeManager extends CompositeService
     private boolean isDecommissioned = false;
     private final ConcurrentLinkedQueue<LogAggregationReport>
         logAggregationReportForApps;
+    private NodeStatusUpdater nodeStatusUpdater;
 
     public NMContext(NMContainerTokenSecretManager containerTokenSecretManager,
         NMTokenSecretManagerInNM nmTokenSecretManager,
@@ -585,6 +587,14 @@ public class NodeManager extends CompositeService
         getLogAggregationStatusForApps() {
       return this.logAggregationReportForApps;
     }
+
+    public NodeStatusUpdater getNodeStatusUpdater() {
+      return this.nodeStatusUpdater;
+    }
+
+    public void setNodeStatusUpdater(NodeStatusUpdater nodeStatusUpdater) {
+      this.nodeStatusUpdater = nodeStatusUpdater;
+    }
   }
 
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
index 7d51477..94d5c1e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/ContainerManagerImpl.java
@@ -361,9 +361,9 @@ public class ContainerManagerImpl extends CompositeService implements
       Credentials credentials =
           YarnServerSecurityUtils.parseCredentials(launchContext);
       Container container = new ContainerImpl(getConfig(), dispatcher,
-          context.getNMStateStore(), req.getContainerLaunchContext(),
+          req.getContainerLaunchContext(),
           credentials, metrics, token, rcs.getStatus(), rcs.getExitCode(),
-          rcs.getDiagnostics(), rcs.getKilled(), rcs.getCapability());
+          rcs.getDiagnostics(), rcs.getKilled(), rcs.getCapability(), context);
       context.getContainers().put(containerId, container);
       dispatcher.getEventHandler().handle(
           new ApplicationContainerInitEvent(container));
@@ -921,8 +921,8 @@ public class ContainerManagerImpl extends CompositeService implements
 
     Container container =
         new ContainerImpl(getConfig(), this.dispatcher,
-            context.getNMStateStore(), launchContext,
-          credentials, metrics, containerTokenIdentifier);
+            launchContext, credentials, metrics, containerTokenIdentifier,
+            context);
     ApplicationId applicationID =
         containerId.getApplicationAttemptId().getApplicationId();
     if (context.getContainers().putIfAbsent(containerId, container) != null) {
@@ -1193,10 +1193,6 @@ public class ContainerManagerImpl extends CompositeService implements
       NMAuditLogger.logSuccess(container.getUser(),    
         AuditConstants.STOP_CONTAINER, "ContainerManageImpl", containerID
           .getApplicationAttemptId().getApplicationId(), containerID);
-
-      // TODO: Move this code to appropriate place once kill_container is
-      // implemented.
-      nodeStatusUpdater.sendOutofBandHeartBeat();
     }
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
index fb1728a..da8a3a6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
@@ -67,6 +67,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.shar
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerContainerFinishedEvent;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainerStartMonitoringEvent;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainerStopMonitoringEvent;
+import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService.RecoveredContainerStatus;
@@ -125,14 +126,15 @@ public class ContainerImpl implements Container {
       RecoveredContainerStatus.REQUESTED;
   // whether container was marked as killed after recovery
   private boolean recoveredAsKilled = false;
+  private Context context;
 
   public ContainerImpl(Configuration conf, Dispatcher dispatcher,
-      NMStateStoreService stateStore, ContainerLaunchContext launchContext,
-      Credentials creds, NodeManagerMetrics metrics,
-      ContainerTokenIdentifier containerTokenIdentifier) {
+      ContainerLaunchContext launchContext, Credentials creds,
+      NodeManagerMetrics metrics,
+      ContainerTokenIdentifier containerTokenIdentifier, Context context) {
     this.daemonConf = conf;
     this.dispatcher = dispatcher;
-    this.stateStore = stateStore;
+    this.stateStore = context.getNMStateStore();
     this.launchContext = launchContext;
     this.containerTokenIdentifier = containerTokenIdentifier;
     this.containerId = containerTokenIdentifier.getContainerID();
@@ -144,19 +146,21 @@ public class ContainerImpl implements Container {
     ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
     this.readLock = readWriteLock.readLock();
     this.writeLock = readWriteLock.writeLock();
+    this.context = context;
 
     stateMachine = stateMachineFactory.make(this);
   }
 
   // constructor for a recovered container
   public ContainerImpl(Configuration conf, Dispatcher dispatcher,
-      NMStateStoreService stateStore, ContainerLaunchContext launchContext,
-      Credentials creds, NodeManagerMetrics metrics,
+      ContainerLaunchContext launchContext, Credentials creds,
+      NodeManagerMetrics metrics,
       ContainerTokenIdentifier containerTokenIdentifier,
       RecoveredContainerStatus recoveredStatus, int exitCode,
-      String diagnostics, boolean wasKilled, Resource recoveredCapability) {
-    this(conf, dispatcher, stateStore, launchContext, creds, metrics,
-        containerTokenIdentifier);
+      String diagnostics, boolean wasKilled, Resource recoveredCapability,
+      Context context) {
+    this(conf, dispatcher, launchContext, creds, metrics,
+        containerTokenIdentifier, context);
     this.recoveredStatus = recoveredStatus;
     this.exitCode = exitCode;
     this.recoveredAsKilled = wasKilled;
@@ -988,11 +992,12 @@ public class ContainerImpl implements Container {
       container.sendFinishedEvents();
       //if the current state is NEW it means the CONTAINER_INIT was never 
       // sent for the event, thus no need to send the CONTAINER_STOP
-      if (container.getCurrentState() 
+      if (container.getCurrentState()
           != org.apache.hadoop.yarn.api.records.ContainerState.NEW) {
         container.dispatcher.getEventHandler().handle(new AuxServicesEvent
             (AuxServicesEventType.CONTAINER_STOP, container));
       }
+      container.context.getNodeStatusUpdater().sendOutofBandHeartBeat();
     }
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java
index 3dc62bc..ddbfbb9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestEventFlow.java
@@ -131,6 +131,7 @@ public class TestEventFlow {
     nodeStatusUpdater.init(conf);
     ((NMContext)context).setContainerManager(containerManager);
     nodeStatusUpdater.start();
+    ((NMContext)context).setNodeStatusUpdater(nodeStatusUpdater);
     containerManager.init(conf);
     containerManager.start();
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java
index 0d85057..fa8d131 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestNodeStatusUpdater.java
@@ -254,8 +254,10 @@ public class TestNodeStatusUpdater {
                 firstContainerID, InetAddress.getByName("localhost")
                     .getCanonicalHostName(), 1234, user, resource,
                 currentTime + 10000, 123, "password".getBytes(), currentTime));
+        Context context = mock(Context.class);
+        when(context.getNMStateStore()).thenReturn(stateStore);
         Container container = new ContainerImpl(conf, mockDispatcher,
-            stateStore, launchContext, null, mockMetrics, containerToken);
+            launchContext, null, mockMetrics, containerToken, context);
         this.context.getContainers().put(firstContainerID, container);
       } else if (heartBeatID == 2) {
         // Checks on the RM end
@@ -293,8 +295,10 @@ public class TestNodeStatusUpdater {
                 secondContainerID, InetAddress.getByName("localhost")
                     .getCanonicalHostName(), 1234, user, resource,
                 currentTime + 10000, 123, "password".getBytes(), currentTime));
+        Context context = mock(Context.class);
+        when(context.getNMStateStore()).thenReturn(stateStore);
         Container container = new ContainerImpl(conf, mockDispatcher,
-            stateStore, launchContext, null, mockMetrics, containerToken);
+            launchContext, null, mockMetrics, containerToken, context);
         this.context.getContainers().put(secondContainerID, container);
       } else if (heartBeatID == 3) {
         // Checks on the RM end
@@ -1011,8 +1015,9 @@ public class TestNodeStatusUpdater {
             BuilderUtils.newResource(1024, 1), 0, 123,
             "password".getBytes(), 0);
     Container anyCompletedContainer = new ContainerImpl(conf, null,
-        null, null, null, null,
-        BuilderUtils.newContainerTokenIdentifier(containerToken)) {
+        null, null, null,
+        BuilderUtils.newContainerTokenIdentifier(containerToken),
+        nm.getNMContext()) {
 
       @Override
       public ContainerState getCurrentState() {
@@ -1032,8 +1037,9 @@ public class TestNodeStatusUpdater {
           1234, "anyUser", BuilderUtils.newResource(1024, 1), 0, 123,
           "password".getBytes(), 0);
     Container runningContainer =
-        new ContainerImpl(conf, null, null, null, null, null,
-          BuilderUtils.newContainerTokenIdentifier(runningContainerToken)) {
+        new ContainerImpl(conf, null, null, null, null,
+          BuilderUtils.newContainerTokenIdentifier(runningContainerToken),
+          nm.getNMContext()) {
           @Override
           public ContainerState getCurrentState() {
             return ContainerState.RUNNING;
@@ -1090,8 +1096,9 @@ public class TestNodeStatusUpdater {
             BuilderUtils.newResource(1024, 1), 0, 123,
             "password".getBytes(), 0);
     Container completedContainer = new ContainerImpl(conf, null,
-        null, null, null, null,
-        BuilderUtils.newContainerTokenIdentifier(containerToken)) {
+        null, null, null,
+        BuilderUtils.newContainerTokenIdentifier(containerToken),
+        nm.getNMContext()) {
       @Override
       public ContainerState getCurrentState() {
         return ContainerState.COMPLETE;
@@ -1127,8 +1134,9 @@ public class TestNodeStatusUpdater {
             BuilderUtils.newResource(1024, 1), 0, 123,
             "password".getBytes(), 0);
     Container anyCompletedContainer = new ContainerImpl(conf, null,
-        null, null, null, null,
-        BuilderUtils.newContainerTokenIdentifier(containerToken)) {
+        null, null, null,
+        BuilderUtils.newContainerTokenIdentifier(containerToken),
+        nm.getNMContext()) {
 
       @Override
       public ContainerState getCurrentState() {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
index 9bc23f6..1aea9d2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/BaseAMRMProxyTest.java
@@ -63,6 +63,7 @@ import org.apache.hadoop.yarn.server.api.records.NodeHealthStatus;
 import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
 import org.apache.hadoop.yarn.server.nodemanager.NodeResourceMonitor;
+import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
@@ -678,5 +679,9 @@ public abstract class BaseAMRMProxyTest {
       return null;
     }
 
+    @Override
+    public NodeStatusUpdater getNodeStatusUpdater() {
+      return null;
+    }
   }
 }
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
index c902fd5..787778e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/BaseContainerManagerTest.java
@@ -188,6 +188,7 @@ public abstract class BaseContainerManagerTest {
     nodeStatusUpdater.init(conf);
     containerManager.init(conf);
     nodeStatusUpdater.start();
+    ((NMContext)context).setNodeStatusUpdater(nodeStatusUpdater);
   }
 
   protected ContainerManagerImpl

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
index 1380752..91466e8 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
@@ -25,6 +25,7 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
 
 import java.io.File;
 import java.io.IOException;
@@ -53,6 +54,7 @@ import org.apache.hadoop.yarn.server.api.ApplicationTerminationContext;
 import org.apache.hadoop.yarn.server.api.AuxiliaryService;
 import org.apache.hadoop.yarn.server.api.ContainerInitializationContext;
 import org.apache.hadoop.yarn.server.api.ContainerTerminationContext;
+import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerImpl;
 import org.junit.Assert;
@@ -192,8 +194,9 @@ public class TestAuxServices {
     ContainerTokenIdentifier cti = new ContainerTokenIdentifier(
         ContainerId.newContainerId(attemptId, 1), "", "",
         Resource.newInstance(1, 1), 0,0,0, Priority.newInstance(0), 0);
-    Container container = new ContainerImpl(null, null, null, null, null,
-        null, cti);
+    Context context = mock(Context.class);
+    Container container = new ContainerImpl(null, null, null, null,
+        null, cti, context);
     ContainerId containerId = container.getContainerId();
     Resource resource = container.getResource();
     event = new AuxServicesEvent(AuxServicesEventType.CONTAINER_INIT,container);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
index 2ab9842..3e06236 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
@@ -88,6 +88,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.eve
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorEvent;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorEventType;
 import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
+import org.apache.hadoop.yarn.server.nodemanager.NodeStatusUpdater;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.junit.Assert;
@@ -261,6 +262,7 @@ public class TestContainer {
       wc.containerSuccessful();
       wc.containerResourcesCleanup();
       assertEquals(ContainerState.DONE, wc.c.getContainerState());
+      verifyOutofBandHeartBeat(wc);
       assertNull(wc.c.getLocalizedResources());
       // Now in DONE, issue INIT
       wc.initContainer();
@@ -290,6 +292,7 @@ public class TestContainer {
       wc.containerSuccessful();
       wc.containerResourcesCleanup();
       assertEquals(ContainerState.DONE, wc.c.getContainerState());
+      verifyOutofBandHeartBeat(wc);
       assertNull(wc.c.getLocalizedResources());
       // Now in DONE, issue RESOURCE_FAILED as done by LocalizeRunner
       wc.resourceFailedContainer();
@@ -336,6 +339,7 @@ public class TestContainer {
       int killed = metrics.getKilledContainers();
       wc.killContainer();
       assertEquals(ContainerState.DONE, wc.c.getContainerState());
+      verifyOutofBandHeartBeat(wc);
       assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER,
           wc.c.cloneAndGetContainerStatus().getExitStatus());
       assertTrue(wc.c.cloneAndGetContainerStatus().getDiagnostics()
@@ -653,6 +657,10 @@ public class TestContainer {
     verify(wc.localizerBus).handle(argThat(matchesReq));
   }
 
+  private void verifyOutofBandHeartBeat(WrappedContainer wc) {
+    verify(wc.context.getNodeStatusUpdater()).sendOutofBandHeartBeat();
+  }
+
   private static class ResourcesReleasedMatcher extends
       ArgumentMatcher<LocalizationEvent> {
     final HashSet<LocalResourceRequest> resources =
@@ -779,6 +787,7 @@ public class TestContainer {
     final Container c;
     final Map<String, LocalResource> localResources;
     final Map<String, ByteBuffer> serviceData;
+    final Context context = mock(Context.class);
 
     WrappedContainer(int appId, long timestamp, int id, String user)
         throws IOException {
@@ -804,11 +813,12 @@ public class TestContainer {
       dispatcher.register(ApplicationEventType.class, appBus);
       dispatcher.register(LogHandlerEventType.class, LogBus);
 
-      Context context = mock(Context.class);
       when(context.getApplications()).thenReturn(
           new ConcurrentHashMap<ApplicationId, Application>());
       NMNullStateStoreService stateStore = new NMNullStateStoreService();
       when(context.getNMStateStore()).thenReturn(stateStore);
+      NodeStatusUpdater nodeStatusUpdater = mock(NodeStatusUpdater.class);
+      when(context.getNodeStatusUpdater()).thenReturn(nodeStatusUpdater);
       ContainerExecutor executor = mock(ContainerExecutor.class);
       launcher =
           new ContainersLauncher(context, dispatcher, executor, null, null);
@@ -864,8 +874,8 @@ public class TestContainer {
       }
       when(ctxt.getServiceData()).thenReturn(serviceData);
 
-      c = new ContainerImpl(conf, dispatcher, new NMNullStateStoreService(),
-          ctxt, null, metrics, identifier);
+      c = new ContainerImpl(conf, dispatcher, ctxt, null, metrics, identifier,
+          context);
       dispatcher.register(ContainerEventType.class,
           new EventHandler<ContainerEvent>() {
             @Override

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d284e187/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java
index e1845c7..f0c7cbc 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServer.java
@@ -215,10 +215,11 @@ public class TestNMWebServer {
           BuilderUtils.newContainerToken(containerId, "127.0.0.1", 1234, user,
             BuilderUtils.newResource(1024, 1), currentTime + 10000L, 123,
             "password".getBytes(), currentTime);
+      Context context = mock(Context.class);
       Container container =
-          new ContainerImpl(conf, dispatcher, stateStore, launchContext,
+          new ContainerImpl(conf, dispatcher, launchContext,
             null, metrics,
-            BuilderUtils.newContainerTokenIdentifier(containerToken)) {
+            BuilderUtils.newContainerTokenIdentifier(containerToken), context) {
 
             @Override
             public ContainerState getContainerState() {


[40/50] [abbrv] hadoop git commit: YARN-4651. Document movetoqueue option in 'YARN Commands'. (Takashi Ohnishi via rohithsharmaks)

Posted by ji...@apache.org.
YARN-4651. Document movetoqueue option in 'YARN Commands'. (Takashi Ohnishi via rohithsharmaks)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/de09f411
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/de09f411
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/de09f411

Branch: refs/heads/HDFS-7240
Commit: de09f41147bf0b6501e82b44afe4e39fe5c3b835
Parents: c6f2d76
Author: Rohith Sharma K S <ro...@apache.org>
Authored: Tue Feb 23 18:03:42 2016 +0800
Committer: Rohith Sharma K S <ro...@apache.org>
Committed: Tue Feb 23 18:03:42 2016 +0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                                   | 3 +++
 .../hadoop-yarn-site/src/site/markdown/YarnCommands.md            | 3 +++
 2 files changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/de09f411/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 058ea87..a25a580 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -216,6 +216,9 @@ Release 2.9.0 - UNRELEASED
     YARN-4569. Remove incorrect part of maxResources in FairScheduler
     documentation. (Ray Chiang via kasha)
 
+    YARN-4651. Document movetoqueue option in 'YARN Commands'
+    (Takashi Ohnishi via rohithsharmaks)
+
 Release 2.8.0 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/de09f411/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnCommands.md
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnCommands.md b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnCommands.md
index 4d617db..5941988 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnCommands.md
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/YarnCommands.md
@@ -70,8 +70,11 @@ Usage: `yarn application [options] `
 | -appId \<ApplicationId\> | Specify Application Id to be operated |
 | -appStates \<States\> | Works with -list to filter applications based on input comma-separated list of application states. The valid application state can be one of the following:  ALL, NEW, NEW\_SAVING, SUBMITTED, ACCEPTED, RUNNING, FINISHED, FAILED, KILLED |
 | -appTypes \<Types\> | Works with -list to filter applications based on input comma-separated list of application types. |
+| -help | Help |
 | -list | Lists applications from the RM. Supports optional use of -appTypes to filter applications based on application type, and -appStates to filter applications based on application state. |
 | -kill \<ApplicationId\> | Kills the application. |
+| -movetoqueue \<Application Id\> | Moves the application to a different queue. |
+| -queue \<Queue Name\> | Works with the movetoqueue command to specify which queue to move an application to. |
 | -status \<ApplicationId\> | Prints the status of the application. |
 | -updatePriority \<Priority\> | Update priority of an application. ApplicationId can be passed using 'appId' option. |
 


[11/50] [abbrv] hadoop git commit: HADOOP-12817. Enable TLS v1.1 and 1.2 (rkanter)

Posted by ji...@apache.org.
HADOOP-12817. Enable TLS v1.1 and 1.2 (rkanter)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a365a394
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a365a394
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a365a394

Branch: refs/heads/HDFS-7240
Commit: a365a3941cf96a31c289cb22678a602738880f74
Parents: 5d1889a
Author: Robert Kanter <rk...@apache.org>
Authored: Thu Feb 18 11:09:50 2016 -0800
Committer: Robert Kanter <rk...@apache.org>
Committed: Thu Feb 18 11:09:50 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt                  | 2 ++
 .../src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java | 3 ++-
 .../hadoop-common/src/main/resources/core-default.xml            | 4 ++--
 .../src/site/markdown/EncryptedShuffle.md                        | 2 +-
 4 files changed, 7 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a365a394/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 9269960..41ba87d 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -691,6 +691,8 @@ Release 2.9.0 - UNRELEASED
     HADOOP-12710. Remove dependency on commons-httpclient for TestHttpServerLogs
     (Wei-Chiu Chuang via iwasakims)
 
+    HADOOP-12817. Enable TLS v1.1 and 1.2 (rkanter)
+
   BUG FIXES
 
     HADOOP-12605. Fix intermittent failure of TestIPC.testIpcWithReaderQueuing

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a365a394/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java
index edec347..518de80 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLFactory.java
@@ -69,7 +69,8 @@ public class SSLFactory implements ConnectionConfigurator {
 
   public static final String SSL_ENABLED_PROTOCOLS =
       "hadoop.ssl.enabled.protocols";
-  public static final String DEFAULT_SSL_ENABLED_PROTOCOLS = "TLSv1";
+  public static final String DEFAULT_SSL_ENABLED_PROTOCOLS =
+      "TLSv1,SSLv2Hello,TLSv1.1,TLSv1.2";
 
   private Configuration conf;
   private Mode mode;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a365a394/hadoop-common-project/hadoop-common/src/main/resources/core-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/resources/core-default.xml b/hadoop-common-project/hadoop-common/src/main/resources/core-default.xml
index 34e1236..dd4919c 100644
--- a/hadoop-common-project/hadoop-common/src/main/resources/core-default.xml
+++ b/hadoop-common-project/hadoop-common/src/main/resources/core-default.xml
@@ -1644,9 +1644,9 @@ for ldap providers in the same way as above does.
 
 <property>
   <name>hadoop.ssl.enabled.protocols</name>
-  <value>TLSv1</value>
+  <value>TLSv1,SSLv2Hello,TLSv1.1,TLSv1.2</value>
   <description>
-    Protocols supported by the ssl.
+    The supported SSL protocols.
   </description>
 </property>
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a365a394/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/EncryptedShuffle.md
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/EncryptedShuffle.md b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/EncryptedShuffle.md
index fddd84f..f679781 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/EncryptedShuffle.md
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/EncryptedShuffle.md
@@ -44,7 +44,7 @@ To enable encrypted shuffle, set the following properties in core-site.xml of al
 | `hadoop.ssl.keystores.factory.class` | `org.apache.hadoop.security.ssl.FileBasedKeyStoresFactory` | The KeyStoresFactory implementation to use |
 | `hadoop.ssl.server.conf` | `ssl-server.xml` | Resource file from which ssl server keystore information will be extracted. This file is looked up in the classpath, typically it should be in Hadoop conf/ directory |
 | `hadoop.ssl.client.conf` | `ssl-client.xml` | Resource file from which ssl server keystore information will be extracted. This file is looked up in the classpath, typically it should be in Hadoop conf/ directory |
-| `hadoop.ssl.enabled.protocols` | `TLSv1` | The supported SSL protocols (JDK6 can use **TLSv1**, JDK7+ can use **TLSv1,TLSv1.1,TLSv1.2**) |
+| `hadoop.ssl.enabled.protocols` | `TLSv1,SSLv2Hello,TLSv1.1,TLSv1.2` | The supported SSL protocols |
 
 **IMPORTANT:** Currently requiring client certificates should be set to false. Refer the [Client Certificates](#Client_Certificates) section for details.
 


[04/50] [abbrv] hadoop git commit: YARN-4689. Fix up CHANGES.txt

Posted by ji...@apache.org.
YARN-4689. Fix up CHANGES.txt


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/1c248ea4
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/1c248ea4
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/1c248ea4

Branch: refs/heads/HDFS-7240
Commit: 1c248ea4a8442bccc78a8ce4539ce1f4b6d6b0ee
Parents: 2ab4c47
Author: Karthik Kambatla <ka...@apache.org>
Authored: Wed Feb 17 18:18:46 2016 -0800
Committer: Karthik Kambatla <ka...@apache.org>
Committed: Wed Feb 17 18:18:46 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/1c248ea4/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index f7c69a4..4471912 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -34,8 +34,6 @@ Trunk - Unreleased
 
     YARN-3261. rewrite resourcemanager restart doc to remove roadmap bits (Gururaj Shetty via aw)
 
-    YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable.
-    (Kai Sasaki via kasha)
 
   OPTIMIZATIONS
 
@@ -134,6 +132,10 @@ Release 2.9.0 - UNRELEASED
     YARN-4655. Log uncaught exceptions/errors in various thread pools in YARN.
     (Sidharta Seethana via vvasudev)
 
+    YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable.
+    (Kai Sasaki via kasha)
+
+
   OPTIMIZATIONS
 
   BUG FIXES


[05/50] [abbrv] hadoop git commit: YARN-4569. Remove incorrect part of maxResources in FairScheduler documentation. (Ray Chiang via kasha)

Posted by ji...@apache.org.
YARN-4569. Remove incorrect part of maxResources in FairScheduler documentation. (Ray Chiang via kasha)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a0c95b5f
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a0c95b5f
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a0c95b5f

Branch: refs/heads/HDFS-7240
Commit: a0c95b5fc4c90ee3383619156619a66dfba889f7
Parents: 1c248ea
Author: Karthik Kambatla <ka...@apache.org>
Authored: Wed Feb 17 18:36:12 2016 -0800
Committer: Karthik Kambatla <ka...@apache.org>
Committed: Wed Feb 17 18:36:12 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                                   | 3 +++
 .../hadoop-yarn-site/src/site/markdown/FairScheduler.md           | 2 +-
 2 files changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0c95b5f/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 4471912..c172054 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -211,6 +211,9 @@ Release 2.9.0 - UNRELEASED
     YARN-4684. TestYarnCLI#testGetContainers failing in CN locale.
     (Bibin A Chundatt via vvasudev)
 
+    YARN-4569. Remove incorrect part of maxResources in FairScheduler
+    documentation. (Ray Chiang via kasha)
+
 Release 2.8.0 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0c95b5f/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/FairScheduler.md
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/FairScheduler.md b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/FairScheduler.md
index 26c6d22..c9c820f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/FairScheduler.md
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/FairScheduler.md
@@ -96,7 +96,7 @@ The allocation file must be in XML format. The format contains five types of ele
 
     * minResources: minimum resources the queue is entitled to, in the form "X mb, Y vcores". For the single-resource fairness policy, the vcores value is ignored. If a queue's minimum share is not satisfied, it will be offered available resources before any other queue under the same parent. Under the single-resource fairness policy, a queue is considered unsatisfied if its memory usage is below its minimum memory share. Under dominant resource fairness, a queue is considered unsatisfied if its usage for its dominant resource with respect to the cluster capacity is below its minimum share for that resource. If multiple queues are unsatisfied in this situation, resources go to the queue with the smallest ratio between relevant resource usage and minimum. Note that it is possible that a queue that is below its minimum may not immediately get up to its minimum when it submits an application, because already-running jobs may be using those resources.
 
-    * maxResources: maximum resources a queue is allowed, in the form "X mb, Y vcores". For the single-resource fairness policy, the vcores value is ignored. A queue will never be assigned a container that would put its aggregate usage over this limit.
+    * maxResources: maximum resources a queue is allowed, in the form "X mb, Y vcores". A queue will never be assigned a container that would put its aggregate usage over this limit.
 
     * maxRunningApps: limit the number of apps from the queue to run at once
 


[25/50] [abbrv] hadoop git commit: MAPREDUCE-6613. Change mapreduce.jobhistory.jhist.format default from json to binary (rchiang via rkanter)

Posted by ji...@apache.org.
MAPREDUCE-6613. Change mapreduce.jobhistory.jhist.format default from json to binary (rchiang via rkanter)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/6eae4337
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/6eae4337
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/6eae4337

Branch: refs/heads/HDFS-7240
Commit: 6eae4337d1929077ffa74734327775fb987ba910
Parents: 3757785
Author: Robert Kanter <rk...@apache.org>
Authored: Fri Feb 19 17:15:54 2016 -0800
Committer: Robert Kanter <rk...@apache.org>
Committed: Fri Feb 19 17:15:54 2016 -0800

----------------------------------------------------------------------
 hadoop-mapreduce-project/CHANGES.txt                              | 3 +++
 .../org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java  | 2 +-
 .../src/main/resources/mapred-default.xml                         | 2 +-
 3 files changed, 5 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/6eae4337/hadoop-mapreduce-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index bf9d824..f0ad171 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -16,6 +16,9 @@ Trunk (Unreleased)
     MAPREDUCE-6336. Enable v2 FileOutputCommitter by default.
     (Siqi Li via gera)
 
+    MAPREDUCE-6613. Change mapreduce.jobhistory.jhist.format default from
+    json to binary (rchiang via rkanter)
+
   NEW FEATURES
 
     MAPREDUCE-778. Rumen Anonymizer. (Amar Kamat and Chris Douglas via amarrk)

http://git-wip-us.apache.org/repos/asf/hadoop/blob/6eae4337/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java
index 86dfad3..2277ef6 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/jobhistory/JHAdminConfig.java
@@ -227,5 +227,5 @@ public class JHAdminConfig {
   public static final String MR_HS_JHIST_FORMAT =
       MR_HISTORY_PREFIX + "jhist.format";
   public static final String DEFAULT_MR_HS_JHIST_FORMAT =
-      "json";
+      "binary";
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/6eae4337/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/resources/mapred-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/resources/mapred-default.xml b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/resources/mapred-default.xml
index efbbf53..d87085f 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/resources/mapred-default.xml
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/resources/mapred-default.xml
@@ -1754,7 +1754,7 @@
   values are "json" for text output and "binary" for faster parsing.
   </description>
   <name>mapreduce.jobhistory.jhist.format</name>
-  <value>json</value>
+  <value>binary</value>
 </property>
 
 <property>


[15/50] [abbrv] hadoop git commit: HADOOP-11031. Design Document for Credential Provider API. Contributed by Larry McCay.

Posted by ji...@apache.org.
HADOOP-11031. Design Document for Credential Provider API. Contributed by Larry McCay.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/8ab76580
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/8ab76580
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/8ab76580

Branch: refs/heads/HDFS-7240
Commit: 8ab7658025616d154decd97578de3327ec6f9109
Parents: c7ac25e
Author: cnauroth <cn...@apache.org>
Authored: Thu Feb 18 14:05:18 2016 -0800
Committer: cnauroth <cn...@apache.org>
Committed: Thu Feb 18 14:06:38 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |   3 +
 .../src/site/markdown/CredentialProviderAPI.md  | 132 +++++++++++++++++++
 hadoop-project/src/site/site.xml                |   1 +
 .../src/site/markdown/tools/hadoop-aws/index.md |  45 +++++++
 4 files changed, 181 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/8ab76580/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 6cdcb7a..91ef68e 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1131,6 +1131,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-12776. Remove getaclstatus call for non-acl commands in getfacl.
     (Brahma Reddy Battula via vinayakumarb)
 
+    HADOOP-11031. Design Document for Credential Provider API.
+    (Larry McCay via cnauroth)
+
   OPTIMIZATIONS
 
     HADOOP-11785. Reduce the number of listStatus operation in distcp

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8ab76580/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md b/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
new file mode 100644
index 0000000..eccc205
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
@@ -0,0 +1,132 @@
+<!---
+  Licensed 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. See accompanying LICENSE file.
+-->
+
+CredentialProvider API Guide
+=====================
+
+---
+
+ - [Overview](#Overview)
+ - [Usage](#Usage)
+     - [Usage Overview](#Usage_Overview)
+     - [Supported Features](#Supported_Features)
+ - [Credential Management](#Credential_Management)
+    - [The hadoop credential Command](#The_hadoop_credential_Command)
+
+---
+
+Overview
+--------
+
+  The CredentialProvider API is an SPI framework for plugging in extensible
+  credential providers. Credential providers are used to separate the use of
+  sensitive tokens, secrets and passwords from the details of their storage and
+  management. The ability to choose various storage mechanisms for protecting
+  these credentials allows us to keep such sensitive assets out of clear text,
+  away from prying eyes and potentially to be managed by third party solutions.
+
+  This document aims to describe the design of the CredentialProvider API, the
+  out of the box implementations, where they are used and how to adopt their use.
+
+Usage
+-----
+### Usage Overview
+Let's provide a quick overview of the use of the credential provider framework for protecting passwords or other sensitive tokens in hadoop.
+
+##### Why is it used?
+There are certain deployments that are very sensitive to how sensitive tokens like passwords are stored and managed within the cluster. For instance, there may be security best practices and policies in place that require such things to never be stored in clear text, for example. Enterprise deployments may be required to use a preferred solution for managing credentials and we need a way to plug in integrations for them.
+
+##### General Usage Pattern
+There are numerous places within the Hadoop project and ecosystem that can leverage the credential provider API today and the number continues to grow. In general, the usage pattern consists of the same requirements and flow.
+
+1. Provision credentials within provider specific stores. This provisioning may be accomplished through the hadoop credential command or possibly through provider specific management tools.
+2. Configure the credential provider path property. The provider path property `hadoop.security.credential.provider.path` is a comma separated list of one or more credential provider URIs that is traversed while trying to resolve a credential alias.
+    - This property may be configured within core-site.xml or a component specific configuration file that is merged with core-site.xml.
+    - For command line interfaces, such as that for DistCp, the property can be added with a hadoop system property ("-D *property=value*") and dynamically added to the Configuration.
+3. Features or components that leverage the new [Configuration.getPassword](../../api/org/apache/hadoop/conf/Configuration.html#getPassword-java.lang.String-) method to resolve their credentials will automatically pick up support for the credential provider API.
+    - By using the same property names as are used for existing clear text passwords, this mechanism allows for the migration to credential providers while providing backward compatibility for clear text.
+    - The entire credential provider path is interrogated before falling back to clear text passwords in config.
+4. Features or components that do not use the hadoop Configuration class for config or have other internal uses for the credential providers may choose to write to the CredentialProvider API itself. An example of its use will be included in this document but may also be found within [Configuration.getPassword](../../api/org/apache/hadoop/conf/Configuration.html#getPassword-java.lang.String-) and within the unit tests of features that have added support and need to provision credentials for the tests.
+
+##### Provision Credentials
+Example: ssl.server.keystore.password
+
+```
+    hadoop credential create ssl.server.keystore.password -value 123
+      -provider localjceks://file/home/lmccay/aws.jceks
+```
+
+Note that the alias names are the same as the configuration properties that were used to get the
+credentials from the Configuration.get method. Reusing these names allows for intuitive
+migration to the use of credential providers and fall back logic for backward compatibility.
+
+##### Configuring the Provider Path
+Now, we need to make sure that this provisioned credential store is known at runtime by the
+[Configuration.getPassword](../../api/org/apache/hadoop/conf/Configuration.html#getPassword-java.lang.String-) method. If there is no credential provider path configuration then
+getPassword will skip the credential provider API interrogation. So, it is important that the
+following be configured within core-site.xml or your component's equivalent.
+
+```
+    <property>
+      <name>hadoop.security.credential.provider.path</name>
+      <value>localjceks://file/home/lmccay/aws.jceks</value>
+      <description>Path to interrogate for protected credentials.</description>
+    </property>
+```
+
+A couple additional things to note about the provider path:
+
+1. The scheme is used to indicate the type of provider in the above case the
+ localjceks provider does not have a dependency on the Hadoop fs abstraction
+ and is needed sometimes to avoid a recursive dependency. Another provider
+ represented by jceks, does use the Hadoop fs abstraction and therefore has
+ support for keystores provisioned within HDFS. A third provider type is the
+ user type. This provider can manage credentials stored within the Credentials
+ file for a process.
+2. The path configuration accepts a comma separated path of providers or
+ credential stores. The [Configuration.getPassword](../../api/org/apache/hadoop/conf/Configuration.html#getPassword-java.lang.String-) method will walk through
+ all of the providers until it resolves the alias or exhausts the list.
+ Depending on the runtime needs for credentials, we may need to configure
+ a chain of providers to check.
+
+In summary, first, provision the credentials into a provider then configure the provider for use by a feature or component and it will often just be picked up through the use of the [Configuration.getPassword](../../api/org/apache/hadoop/conf/Configuration.html#getPassword-java.lang.String-) method.
+
+##### Supported Features
+| Feature\Component | Description | Link |
+|:---- |:---- |:---|
+|LDAPGroupsMapping    |LDAPGroupsMapping is used to look up the groups for a given user in LDAP. The CredentialProvider API is used to protect the LDAP bind password and those needed for SSL.|TODO|
+|SSL Passwords        |FileBasedKeyStoresFactory leverages the credential provider API in order to resolve the SSL related passwords.|TODO|
+|HDFS                 |DFSUtil leverages Configuration.getPassword method to use the credential provider API and/or fallback to the clear text value stored in ssl-server.xml.|TODO|
+|YARN                 |WebAppUtils uptakes the use of the credential provider API through the new method on Configuration called getPassword. This provides an alternative to storing the passwords in clear text within the ssl-server.xml file while maintaining backward compatibility.|TODO|
+|AWS <br/> S3/S3A     |Uses Configuration.getPassword to get the S3 credentials. They may be resolved through the credential provider API or from the config for backward compatibility.|[AWS S3/S3A Usage](../../hadoop-aws/tools/hadoop-aws/index.html)|
+|Apache <br/> Accumulo|The trace.password property is used by the Tracer to authenticate with Accumulo and persist the traces in the trace table. The credential provider API is used to acquire the trace.password from a provider or from configuration for backward compatibility.|TODO|
+|Apache <br/> Slider  |A capability has been added to Slider to prompt the user for needed passwords and store them using CredentialProvider so they can be retrieved by an app later.|TODO|
+|Apache <br/> Hive    |Protection of the metastore password, SSL related passwords and JDO string password has been added through the use of the Credential Provider API|TODO|
+|Apache <br/> HBase   |The HBase RESTServer is using the new Configuration.getPassword method so that the credential provider API will be checked first then fall back to clear text - when allowed.|TODO|
+|Apache <br/> Oozie   |Protects SSL, email and JDBC passwords using the credential provider API.|TODO|
+|Apache <br/> Ranger  |Protects database, trust and keystore passwords using the credential provider API.|TODO|
+
+### Credential Management
+
+#### The hadoop credential Command
+
+Usage: `hadoop credential <subcommand> [options]`
+
+See the command options detail in the [Commands Manual](CommandsManual.html#credential)
+
+Utilizing the credential command will often be for provisioning a password or secret to a particular credential store provider. In order to explicitly indicate which provider store to use the `-provider` option should be used.
+
+Example: `hadoop credential create ssl.server.keystore.password jceks://file/tmp/test.jceks`
+
+In order to indicate a particular provider type and location, the user must provide the `hadoop.security.credential.provider.path` configuration element in core-site.xml or use the command line option `-provider` on each of the credential management commands. This provider path is a comma-separated list of URLs that indicates the type and location of a list of providers that should be consulted. For example, the following path: `user:///,jceks://file/tmp/test.jceks,jceks://hdfs@nn1.example.com/my/path/test.jceks` indicates that the current user's credentials file should be consulted through the User Provider, that the local file located at `/tmp/test.jceks` is a Java Keystore Provider and that the file located within HDFS at `nn1.example.com/my/path/test.jceks` is also a store for a Java Keystore Provider.

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8ab76580/hadoop-project/src/site/site.xml
----------------------------------------------------------------------
diff --git a/hadoop-project/src/site/site.xml b/hadoop-project/src/site/site.xml
index 00c5e65..cc737fa 100644
--- a/hadoop-project/src/site/site.xml
+++ b/hadoop-project/src/site/site.xml
@@ -66,6 +66,7 @@
       <item name="Secure Mode" href="hadoop-project-dist/hadoop-common/SecureMode.html"/>
       <item name="Service Level Authorization" href="hadoop-project-dist/hadoop-common/ServiceLevelAuth.html"/>
       <item name="HTTP Authentication" href="hadoop-project-dist/hadoop-common/HttpAuthentication.html"/>
+      <item name="Credential Provider API" href="hadoop-project-dist/hadoop-common/CredentialProviderAPI.html"/>
       <item name="Hadoop KMS" href="hadoop-kms/index.html"/>
       <item name="Tracing" href="hadoop-project-dist/hadoop-common/Tracing.html"/>
       <item name="Unix Shell Guide" href="hadoop-project-dist/hadoop-common/UnixShellGuide.html"/>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8ab76580/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md b/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md
index 73775c8..5e6eb95 100644
--- a/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md
+++ b/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md
@@ -154,6 +154,51 @@ If you do any of these: change your credentials immediately!
       <description>AWS secret key. Omit for Role-based authentication.</description>
     </property>
 
+#### Protecting the AWS Credentials in S3A
+
+To protect these credentials from prying eyes, it is recommended that you use
+the credential provider framework securely storing them and accessing them
+ through configuration. The following describes its use for AWS credentials
+in S3A FileSystem.
+
+For additional reading on the credential provider API see:
+[Credential Provider API](../../../hadoop-project-dist/hadoop-common/CredentialProviderAPI.html).
+
+##### End to End Steps for Distcp and S3 with Credential Providers
+
+###### provision
+
+```
+% hadoop credential create fs.s3a.access.key -value 123
+    -provider localjceks://file/home/lmccay/aws.jceks
+```
+
+```
+% hadoop credential create fs.s3a.secret.key -value 456
+    -provider localjceks://file/home/lmccay/aws.jceks
+```
+
+###### configure core-site.xml or command line system property
+
+```
+<property>
+  <name>hadoop.security.credential.provider.path</name>
+  <value>localjceks://file/home/lmccay/aws.jceks</value>
+  <description>Path to interrogate for protected credentials.</description>
+</property>
+```
+###### distcp
+
+```
+% hadoop distcp
+    [-D hadoop.security.credential.provider.path=localjceks://file/home/lmccay/aws.jceks]
+    hdfs://hostname:9001/user/lmccay/007020615 s3a://lmccay/
+```
+
+NOTE: You may optionally add the provider path property to the distcp command line instead of
+added job specific configuration to a generic core­site.xml. The square brackets above illustrate
+this capability.
+
 ### Other properties
 
     <property>


[16/50] [abbrv] hadoop git commit: MAPREDUCE-6627. Add machine-readable output to mapred job -history command (rkanter)

Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/jobhistory/TestHistoryViewerPrinter.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/jobhistory/TestHistoryViewerPrinter.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/jobhistory/TestHistoryViewerPrinter.java
new file mode 100644
index 0000000..358e9b2
--- /dev/null
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/jobhistory/TestHistoryViewerPrinter.java
@@ -0,0 +1,945 @@
+/**
+ * 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.mapreduce.jobhistory;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.mapred.TaskAttemptID;
+import org.apache.hadoop.mapred.TaskID;
+import org.apache.hadoop.mapred.TaskStatus;
+import org.apache.hadoop.mapreduce.Counters;
+import org.apache.hadoop.mapreduce.JobID;
+import org.apache.hadoop.mapreduce.JobStatus;
+import org.apache.hadoop.mapreduce.TaskType;
+import org.junit.Assert;
+import org.junit.Test;
+import org.skyscreamer.jsonassert.JSONAssert;
+import org.skyscreamer.jsonassert.JSONCompareMode;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.HashMap;
+import java.util.TimeZone;
+
+public class TestHistoryViewerPrinter {
+
+  private static final Log LOG = LogFactory.getLog(
+      TestHistoryViewerPrinter.class);
+
+  @Test
+  public void testHumanPrinter() throws Exception {
+    JobHistoryParser.JobInfo job = createJobInfo();
+    HumanReadableHistoryViewerPrinter printer =
+        new HumanReadableHistoryViewerPrinter(job, false, "http://",
+            TimeZone.getTimeZone("GMT"));
+    String outStr = run(printer);
+    Assert.assertEquals("\n" +
+        "Hadoop job: job_1317928501754_0001\n" +
+        "=====================================\n" +
+        "User: rkanter\n" +
+        "JobName: my job\n" +
+        "JobConf: /tmp/job.xml\n" +
+        "Submitted At: 6-Oct-2011 19:15:01\n" +
+        "Launched At: 6-Oct-2011 19:15:02 (1sec)\n" +
+        "Finished At: 6-Oct-2011 19:15:16 (14sec)\n" +
+        "Status: SUCCEEDED\n" +
+        "Counters: \n" +
+        "\n" +
+        "|Group Name                    |Counter name                  |Map Value |Reduce Value|Total Value|\n" +
+        "---------------------------------------------------------------------------------------\n" +
+        "|group1                        |counter1                      |5         |5         |5         \n" +
+        "|group1                        |counter2                      |10        |10        |10        \n" +
+        "|group2                        |counter1                      |15        |15        |15        \n" +
+        "\n" +
+        "=====================================\n" +
+        "\n" +
+        "Task Summary\n" +
+        "============================\n" +
+        "Kind\tTotal\tSuccessful\tFailed\tKilled\tStartTime\tFinishTime\n" +
+        "\n" +
+        "Setup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\n" +
+        "Map\t6\t5\t\t1\t0\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:16 (12sec)\n" +
+        "Reduce\t1\t1\t\t0\t0\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\n" +
+        "Cleanup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\n" +
+        "============================\n" +
+        "\n" +
+        "\n" +
+        "Analysis\n" +
+        "=========\n" +
+        "\n" +
+        "Time taken by best performing map task task_1317928501754_0001_m_000003: 3sec\n" +
+        "Average time taken by map tasks: 5sec\n" +
+        "Worse performing map tasks: \n" +
+        "TaskId\t\tTimetaken\n" +
+        "task_1317928501754_0001_m_000007 7sec\n" +
+        "task_1317928501754_0001_m_000006 6sec\n" +
+        "task_1317928501754_0001_m_000005 5sec\n" +
+        "task_1317928501754_0001_m_000004 4sec\n" +
+        "task_1317928501754_0001_m_000003 3sec\n" +
+        "The last map task task_1317928501754_0001_m_000007 finished at (relative to the Job launch time): 6-Oct-2011 19:15:16 (14sec)\n" +
+        "\n" +
+        "Time taken by best performing shuffle task task_1317928501754_0001_r_000008: 8sec\n" +
+        "Average time taken by shuffle tasks: 8sec\n" +
+        "Worse performing shuffle tasks: \n" +
+        "TaskId\t\tTimetaken\n" +
+        "task_1317928501754_0001_r_000008 8sec\n" +
+        "The last shuffle task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+        "\n" +
+        "Time taken by best performing reduce task task_1317928501754_0001_r_000008: 0sec\n" +
+        "Average time taken by reduce tasks: 0sec\n" +
+        "Worse performing reduce tasks: \n" +
+        "TaskId\t\tTimetaken\n" +
+        "task_1317928501754_0001_r_000008 0sec\n" +
+        "The last reduce task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+        "=========\n" +
+        "\n" +
+        "FAILED MAP task list for job_1317928501754_0001\n" +
+        "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+        "====================================================\n" +
+        "task_1317928501754_0001_m_000002\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:06 (2sec)\t\t\n" +
+        "\n" +
+        "FAILED task attempts by nodes\n" +
+        "Hostname\tFailedTasks\n" +
+        "===============================\n" +
+        "localhost\ttask_1317928501754_0001_m_000002, \n", outStr);
+  }
+
+  @Test
+  public void testHumanPrinterAll() throws Exception {
+    JobHistoryParser.JobInfo job = createJobInfo();
+    HumanReadableHistoryViewerPrinter printer =
+        new HumanReadableHistoryViewerPrinter(job, true, "http://",
+            TimeZone.getTimeZone("GMT"));
+    String outStr = run(printer);
+    if (System.getProperty("java.version").startsWith("1.7")) {
+      Assert.assertEquals("\n" +
+          "Hadoop job: job_1317928501754_0001\n" +
+          "=====================================\n" +
+          "User: rkanter\n" +
+          "JobName: my job\n" +
+          "JobConf: /tmp/job.xml\n" +
+          "Submitted At: 6-Oct-2011 19:15:01\n" +
+          "Launched At: 6-Oct-2011 19:15:02 (1sec)\n" +
+          "Finished At: 6-Oct-2011 19:15:16 (14sec)\n" +
+          "Status: SUCCEEDED\n" +
+          "Counters: \n" +
+          "\n" +
+          "|Group Name                    |Counter name                  |Map Value |Reduce Value|Total Value|\n" +
+          "---------------------------------------------------------------------------------------\n" +
+          "|group1                        |counter1                      |5         |5         |5         \n" +
+          "|group1                        |counter2                      |10        |10        |10        \n" +
+          "|group2                        |counter1                      |15        |15        |15        \n" +
+          "\n" +
+          "=====================================\n" +
+          "\n" +
+          "Task Summary\n" +
+          "============================\n" +
+          "Kind\tTotal\tSuccessful\tFailed\tKilled\tStartTime\tFinishTime\n" +
+          "\n" +
+          "Setup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\n" +
+          "Map\t6\t5\t\t1\t0\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:16 (12sec)\n" +
+          "Reduce\t1\t1\t\t0\t0\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\n" +
+          "Cleanup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\n" +
+          "============================\n" +
+          "\n" +
+          "\n" +
+          "Analysis\n" +
+          "=========\n" +
+          "\n" +
+          "Time taken by best performing map task task_1317928501754_0001_m_000003: 3sec\n" +
+          "Average time taken by map tasks: 5sec\n" +
+          "Worse performing map tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_m_000007 7sec\n" +
+          "task_1317928501754_0001_m_000006 6sec\n" +
+          "task_1317928501754_0001_m_000005 5sec\n" +
+          "task_1317928501754_0001_m_000004 4sec\n" +
+          "task_1317928501754_0001_m_000003 3sec\n" +
+          "The last map task task_1317928501754_0001_m_000007 finished at (relative to the Job launch time): 6-Oct-2011 19:15:16 (14sec)\n" +
+          "\n" +
+          "Time taken by best performing shuffle task task_1317928501754_0001_r_000008: 8sec\n" +
+          "Average time taken by shuffle tasks: 8sec\n" +
+          "Worse performing shuffle tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_r_000008 8sec\n" +
+          "The last shuffle task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+          "\n" +
+          "Time taken by best performing reduce task task_1317928501754_0001_r_000008: 0sec\n" +
+          "Average time taken by reduce tasks: 0sec\n" +
+          "Worse performing reduce tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_r_000008 0sec\n" +
+          "The last reduce task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+          "=========\n" +
+          "\n" +
+          "FAILED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000002\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:06 (2sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED JOB_SETUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_s_000001\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000006\t6-Oct-2011 19:15:08\t6-Oct-2011 19:15:14 (6sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000005\t6-Oct-2011 19:15:07\t6-Oct-2011 19:15:12 (5sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000004\t6-Oct-2011 19:15:06\t6-Oct-2011 19:15:10 (4sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000003\t6-Oct-2011 19:15:05\t6-Oct-2011 19:15:08 (3sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000007\t6-Oct-2011 19:15:09\t6-Oct-2011 19:15:16 (7sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED REDUCE task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_r_000008\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\t\n" +
+          "\n" +
+          "SUCCEEDED JOB_CLEANUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_c_000009\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\t\n" +
+          "\n" +
+          "JOB_SETUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_s_000001_1\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_s_000001_1\n" +
+          "\n" +
+          "MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_m_000002_1\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:06 (2sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000002_1\n" +
+          "attempt_1317928501754_0001_m_000006_1\t6-Oct-2011 19:15:08\t6-Oct-2011 19:15:14 (6sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000006_1\n" +
+          "attempt_1317928501754_0001_m_000005_1\t6-Oct-2011 19:15:07\t6-Oct-2011 19:15:12 (5sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000005_1\n" +
+          "attempt_1317928501754_0001_m_000004_1\t6-Oct-2011 19:15:06\t6-Oct-2011 19:15:10 (4sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000004_1\n" +
+          "attempt_1317928501754_0001_m_000003_1\t6-Oct-2011 19:15:05\t6-Oct-2011 19:15:08 (3sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000003_1\n" +
+          "attempt_1317928501754_0001_m_000007_1\t6-Oct-2011 19:15:09\t6-Oct-2011 19:15:16 (7sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000007_1\n" +
+          "\n" +
+          "REDUCE task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tShuffleFinished\tSortFinished\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_r_000008_1\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\t6-Oct-2011 19:15:18 (0sec)6-Oct-2011 19:15:18 (8sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_r_000008_1\n" +
+          "\n" +
+          "JOB_CLEANUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_c_000009_1\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_c_000009_1\n" +
+          "\n" +
+          "FAILED task attempts by nodes\n" +
+          "Hostname\tFailedTasks\n" +
+          "===============================\n" +
+          "localhost\ttask_1317928501754_0001_m_000002, \n", outStr);
+    } else {
+      Assert.assertEquals("\n" +
+          "Hadoop job: job_1317928501754_0001\n" +
+          "=====================================\n" +
+          "User: rkanter\n" +
+          "JobName: my job\n" +
+          "JobConf: /tmp/job.xml\n" +
+          "Submitted At: 6-Oct-2011 19:15:01\n" +
+          "Launched At: 6-Oct-2011 19:15:02 (1sec)\n" +
+          "Finished At: 6-Oct-2011 19:15:16 (14sec)\n" +
+          "Status: SUCCEEDED\n" +
+          "Counters: \n" +
+          "\n" +
+          "|Group Name                    |Counter name                  |Map Value |Reduce Value|Total Value|\n" +
+          "---------------------------------------------------------------------------------------\n" +
+          "|group1                        |counter1                      |5         |5         |5         \n" +
+          "|group1                        |counter2                      |10        |10        |10        \n" +
+          "|group2                        |counter1                      |15        |15        |15        \n" +
+          "\n" +
+          "=====================================\n" +
+          "\n" +
+          "Task Summary\n" +
+          "============================\n" +
+          "Kind\tTotal\tSuccessful\tFailed\tKilled\tStartTime\tFinishTime\n" +
+          "\n" +
+          "Setup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\n" +
+          "Map\t6\t5\t\t1\t0\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:16 (12sec)\n" +
+          "Reduce\t1\t1\t\t0\t0\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\n" +
+          "Cleanup\t1\t1\t\t0\t0\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\n" +
+          "============================\n" +
+          "\n" +
+          "\n" +
+          "Analysis\n" +
+          "=========\n" +
+          "\n" +
+          "Time taken by best performing map task task_1317928501754_0001_m_000003: 3sec\n" +
+          "Average time taken by map tasks: 5sec\n" +
+          "Worse performing map tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_m_000007 7sec\n" +
+          "task_1317928501754_0001_m_000006 6sec\n" +
+          "task_1317928501754_0001_m_000005 5sec\n" +
+          "task_1317928501754_0001_m_000004 4sec\n" +
+          "task_1317928501754_0001_m_000003 3sec\n" +
+          "The last map task task_1317928501754_0001_m_000007 finished at (relative to the Job launch time): 6-Oct-2011 19:15:16 (14sec)\n" +
+          "\n" +
+          "Time taken by best performing shuffle task task_1317928501754_0001_r_000008: 8sec\n" +
+          "Average time taken by shuffle tasks: 8sec\n" +
+          "Worse performing shuffle tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_r_000008 8sec\n" +
+          "The last shuffle task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+          "\n" +
+          "Time taken by best performing reduce task task_1317928501754_0001_r_000008: 0sec\n" +
+          "Average time taken by reduce tasks: 0sec\n" +
+          "Worse performing reduce tasks: \n" +
+          "TaskId\t\tTimetaken\n" +
+          "task_1317928501754_0001_r_000008 0sec\n" +
+          "The last reduce task task_1317928501754_0001_r_000008 finished at (relative to the Job launch time): 6-Oct-2011 19:15:18 (16sec)\n" +
+          "=========\n" +
+          "\n" +
+          "FAILED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000002\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:06 (2sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED JOB_SETUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_s_000001\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000007\t6-Oct-2011 19:15:09\t6-Oct-2011 19:15:16 (7sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000006\t6-Oct-2011 19:15:08\t6-Oct-2011 19:15:14 (6sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000005\t6-Oct-2011 19:15:07\t6-Oct-2011 19:15:12 (5sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000004\t6-Oct-2011 19:15:06\t6-Oct-2011 19:15:10 (4sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\tInputSplits\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_m_000003\t6-Oct-2011 19:15:05\t6-Oct-2011 19:15:08 (3sec)\t\t\n" +
+          "\n" +
+          "SUCCEEDED REDUCE task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_r_000008\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\t\n" +
+          "\n" +
+          "SUCCEEDED JOB_CLEANUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tError\n" +
+          "====================================================\n" +
+          "task_1317928501754_0001_c_000009\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\t\n" +
+          "\n" +
+          "JOB_SETUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_s_000001_1\t6-Oct-2011 19:15:03\t6-Oct-2011 19:15:04 (1sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_s_000001_1\n" +
+          "\n" +
+          "MAP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_m_000007_1\t6-Oct-2011 19:15:09\t6-Oct-2011 19:15:16 (7sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000007_1\n" +
+          "attempt_1317928501754_0001_m_000002_1\t6-Oct-2011 19:15:04\t6-Oct-2011 19:15:06 (2sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000002_1\n" +
+          "attempt_1317928501754_0001_m_000006_1\t6-Oct-2011 19:15:08\t6-Oct-2011 19:15:14 (6sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000006_1\n" +
+          "attempt_1317928501754_0001_m_000005_1\t6-Oct-2011 19:15:07\t6-Oct-2011 19:15:12 (5sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000005_1\n" +
+          "attempt_1317928501754_0001_m_000004_1\t6-Oct-2011 19:15:06\t6-Oct-2011 19:15:10 (4sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000004_1\n" +
+          "attempt_1317928501754_0001_m_000003_1\t6-Oct-2011 19:15:05\t6-Oct-2011 19:15:08 (3sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000003_1\n" +
+          "\n" +
+          "REDUCE task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tShuffleFinished\tSortFinished\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_r_000008_1\t6-Oct-2011 19:15:10\t6-Oct-2011 19:15:18 (8sec)\t6-Oct-2011 19:15:18 (0sec)6-Oct-2011 19:15:18 (8sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_r_000008_1\n" +
+          "\n" +
+          "JOB_CLEANUP task list for job_1317928501754_0001\n" +
+          "TaskId\t\tStartTime\tFinishTime\tHostName\tError\tTaskLogs\n" +
+          "====================================================\n" +
+          "attempt_1317928501754_0001_c_000009_1\t6-Oct-2011 19:15:11\t6-Oct-2011 19:15:20 (9sec)\tlocalhost\thttp://t:1234/tasklog?attemptid=attempt_1317928501754_0001_c_000009_1\n" +
+          "\n" +
+          "FAILED task attempts by nodes\n" +
+          "Hostname\tFailedTasks\n" +
+          "===============================\n" +
+          "localhost\ttask_1317928501754_0001_m_000002, \n", outStr);
+    }
+  }
+
+  @Test
+  public void testJSONPrinter() throws Exception {
+    JobHistoryParser.JobInfo job = createJobInfo();
+    JSONHistoryViewerPrinter printer =
+        new JSONHistoryViewerPrinter(job, false, "http://");
+    String outStr = run(printer);
+    JSONAssert.assertEquals("{\n" +
+        "    \"counters\": {\n" +
+        "        \"group1\": [\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter1\",\n" +
+        "                \"mapValue\": 5,\n" +
+        "                \"reduceValue\": 5,\n" +
+        "                \"totalValue\": 5\n" +
+        "            },\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter2\",\n" +
+        "                \"mapValue\": 10,\n" +
+        "                \"reduceValue\": 10,\n" +
+        "                \"totalValue\": 10\n" +
+        "            }\n" +
+        "        ],\n" +
+        "        \"group2\": [\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter1\",\n" +
+        "                \"mapValue\": 15,\n" +
+        "                \"reduceValue\": 15,\n" +
+        "                \"totalValue\": 15\n" +
+        "            }\n" +
+        "        ]\n" +
+        "    },\n" +
+        "    \"finishedAt\": 1317928516754,\n" +
+        "    \"hadoopJob\": \"job_1317928501754_0001\",\n" +
+        "    \"jobConf\": \"/tmp/job.xml\",\n" +
+        "    \"jobName\": \"my job\",\n" +
+        "    \"launchedAt\": 1317928502754,\n" +
+        "    \"status\": \"SUCCEEDED\",\n" +
+        "    \"submittedAt\": 1317928501754,\n" +
+        "    \"taskSummary\": {\n" +
+        "        \"cleanup\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928520754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928511754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        },\n" +
+        "        \"map\": {\n" +
+        "            \"failed\": 1,\n" +
+        "            \"finishTime\": 1317928516754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928504754,\n" +
+        "            \"successful\": 5,\n" +
+        "            \"total\": 6\n" +
+        "        },\n" +
+        "        \"reduce\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928518754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928510754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        },\n" +
+        "        \"setup\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928504754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928503754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        }\n" +
+        "    },\n" +
+        "    \"tasks\": [\n" +
+        "        {\n" +
+        "            \"finishTime\": 1317928506754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928504754,\n" +
+        "            \"status\": \"FAILED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000002\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        }\n" +
+        "    ],\n" +
+        "    \"user\": \"rkanter\"\n" +
+        "}\n", outStr, JSONCompareMode.NON_EXTENSIBLE);
+  }
+
+  @Test
+  public void testJSONPrinterAll() throws Exception {
+    JobHistoryParser.JobInfo job = createJobInfo();
+    JSONHistoryViewerPrinter printer =
+        new JSONHistoryViewerPrinter(job, true, "http://");
+    String outStr = run(printer);
+    JSONAssert.assertEquals("{\n" +
+        "    \"counters\": {\n" +
+        "        \"group1\": [\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter1\",\n" +
+        "                \"mapValue\": 5,\n" +
+        "                \"reduceValue\": 5,\n" +
+        "                \"totalValue\": 5\n" +
+        "            },\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter2\",\n" +
+        "                \"mapValue\": 10,\n" +
+        "                \"reduceValue\": 10,\n" +
+        "                \"totalValue\": 10\n" +
+        "            }\n" +
+        "        ],\n" +
+        "        \"group2\": [\n" +
+        "            {\n" +
+        "                \"counterName\": \"counter1\",\n" +
+        "                \"mapValue\": 15,\n" +
+        "                \"reduceValue\": 15,\n" +
+        "                \"totalValue\": 15\n" +
+        "            }\n" +
+        "        ]\n" +
+        "    },\n" +
+        "    \"finishedAt\": 1317928516754,\n" +
+        "    \"hadoopJob\": \"job_1317928501754_0001\",\n" +
+        "    \"jobConf\": \"/tmp/job.xml\",\n" +
+        "    \"jobName\": \"my job\",\n" +
+        "    \"launchedAt\": 1317928502754,\n" +
+        "    \"status\": \"SUCCEEDED\",\n" +
+        "    \"submittedAt\": 1317928501754,\n" +
+        "    \"taskSummary\": {\n" +
+        "        \"cleanup\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928520754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928511754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        },\n" +
+        "        \"map\": {\n" +
+        "            \"failed\": 1,\n" +
+        "            \"finishTime\": 1317928516754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928504754,\n" +
+        "            \"successful\": 5,\n" +
+        "            \"total\": 6\n" +
+        "        },\n" +
+        "        \"reduce\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928518754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928510754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        },\n" +
+        "        \"setup\": {\n" +
+        "            \"failed\": 0,\n" +
+        "            \"finishTime\": 1317928504754,\n" +
+        "            \"killed\": 0,\n" +
+        "            \"startTime\": 1317928503754,\n" +
+        "            \"successful\": 1,\n" +
+        "            \"total\": 1\n" +
+        "        }\n" +
+        "    },\n" +
+        "    \"tasks\": [\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000002_1\",\n" +
+        "                \"finishTime\": 1317928506754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928504754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000002_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928506754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928504754,\n" +
+        "            \"status\": \"FAILED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000002\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_s_000001_1\",\n" +
+        "                \"finishTime\": 1317928504754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928503754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_s_000001_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928504754,\n" +
+        "            \"startTime\": 1317928503754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_s_000001\",\n" +
+        "            \"type\": \"JOB_SETUP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000006_1\",\n" +
+        "                \"finishTime\": 1317928514754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928508754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000006_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928514754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928508754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000006\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000005_1\",\n" +
+        "                \"finishTime\": 1317928512754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928507754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000005_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928512754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928507754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000005\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000004_1\",\n" +
+        "                \"finishTime\": 1317928510754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928506754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000004_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928510754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928506754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000004\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000003_1\",\n" +
+        "                \"finishTime\": 1317928508754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928505754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000003_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928508754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928505754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000003\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_c_000009_1\",\n" +
+        "                \"finishTime\": 1317928520754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928511754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_c_000009_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928520754,\n" +
+        "            \"startTime\": 1317928511754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_c_000009\",\n" +
+        "            \"type\": \"JOB_CLEANUP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_m_000007_1\",\n" +
+        "                \"finishTime\": 1317928516754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"startTime\": 1317928509754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_m_000007_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928516754,\n" +
+        "            \"inputSplits\": \"\",\n" +
+        "            \"startTime\": 1317928509754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_m_000007\",\n" +
+        "            \"type\": \"MAP\"\n" +
+        "        },\n" +
+        "        {\n" +
+        "            \"attempts\": {\n" +
+        "                \"attemptId\": \"attempt_1317928501754_0001_r_000008_1\",\n" +
+        "                \"finishTime\": 1317928518754,\n" +
+        "                \"hostName\": \"localhost\",\n" +
+        "                \"shuffleFinished\": 1317928518754,\n" +
+        "                \"sortFinished\": 1317928518754,\n" +
+        "                \"startTime\": 1317928510754,\n" +
+        "                \"taskLogs\": \"http://t:1234/tasklog?attemptid=attempt_1317928501754_0001_r_000008_1\"\n" +
+        "            },\n" +
+        "            \"counters\": {\n" +
+        "                \"group1\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 5\n" +
+        "                    },\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter2\",\n" +
+        "                        \"value\": 10\n" +
+        "                    }\n" +
+        "                ],\n" +
+        "                \"group2\": [\n" +
+        "                    {\n" +
+        "                        \"counterName\": \"counter1\",\n" +
+        "                        \"value\": 15\n" +
+        "                    }\n" +
+        "                ]\n" +
+        "            },\n" +
+        "            \"finishTime\": 1317928518754,\n" +
+        "            \"startTime\": 1317928510754,\n" +
+        "            \"status\": \"SUCCEEDED\",\n" +
+        "            \"taskId\": \"task_1317928501754_0001_r_000008\",\n" +
+        "            \"type\": \"REDUCE\"\n" +
+        "        }\n" +
+        "    ],\n" +
+        "    \"user\": \"rkanter\"\n" +
+        "}\n", outStr, JSONCompareMode.NON_EXTENSIBLE);
+  }
+
+  private String run(HistoryViewerPrinter printer) throws Exception {
+    ByteArrayOutputStream boas = new ByteArrayOutputStream();
+    PrintStream out = new PrintStream(boas, true);
+    printer.print(out);
+    out.close();
+    String outStr = boas.toString("UTF-8");
+    LOG.info("out = " + outStr);
+    return outStr;
+  }
+
+  private static JobHistoryParser.JobInfo createJobInfo() {
+    JobHistoryParser.JobInfo job = new JobHistoryParser.JobInfo();
+    job.submitTime = 1317928501754L;
+    job.finishTime = job.submitTime + 15000;
+    job.jobid = JobID.forName("job_1317928501754_0001");
+    job.username = "rkanter";
+    job.jobname = "my job";
+    job.jobQueueName = "my queue";
+    job.jobConfPath = "/tmp/job.xml";
+    job.launchTime = job.submitTime + 1000;
+    job.totalMaps = 5;
+    job.totalReduces = 1;
+    job.failedMaps = 1;
+    job.failedReduces = 0;
+    job.finishedMaps = 5;
+    job.finishedReduces = 1;
+    job.jobStatus = JobStatus.State.SUCCEEDED.name();
+    job.totalCounters = createCounters();
+    job.mapCounters = createCounters();
+    job.reduceCounters = createCounters();
+    job.tasksMap = new HashMap<>();
+    addTaskInfo(job, TaskType.JOB_SETUP, 1, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.MAP, 2, TaskStatus.State.FAILED);
+    addTaskInfo(job, TaskType.MAP, 3, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.MAP, 4, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.MAP, 5, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.MAP, 6, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.MAP, 7, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.REDUCE, 8, TaskStatus.State.SUCCEEDED);
+    addTaskInfo(job, TaskType.JOB_CLEANUP, 9, TaskStatus.State.SUCCEEDED);
+    return job;
+  }
+
+  private static Counters createCounters() {
+    Counters counters = new Counters();
+    counters.findCounter("group1", "counter1").setValue(5);
+    counters.findCounter("group1", "counter2").setValue(10);
+    counters.findCounter("group2", "counter1").setValue(15);
+    return counters;
+  }
+
+  private static void addTaskInfo(JobHistoryParser.JobInfo job,
+      TaskType type, int id, TaskStatus.State status) {
+    JobHistoryParser.TaskInfo task = new JobHistoryParser.TaskInfo();
+    task.taskId = new TaskID(job.getJobId(), type, id);
+    task.startTime = job.getLaunchTime() + id * 1000;
+    task.finishTime = task.startTime + id * 1000;
+    task.taskType = type;
+    task.counters = createCounters();
+    task.status = status.name();
+    task.attemptsMap = new HashMap<>();
+    addTaskAttemptInfo(task, 1);
+    job.tasksMap.put(task.getTaskId(), task);
+  }
+
+  private static void addTaskAttemptInfo(
+      JobHistoryParser.TaskInfo task, int id) {
+    JobHistoryParser.TaskAttemptInfo attempt =
+        new JobHistoryParser.TaskAttemptInfo();
+    attempt.attemptId = new TaskAttemptID(
+        TaskID.downgrade(task.getTaskId()), id);
+    attempt.startTime = task.getStartTime();
+    attempt.finishTime = task.getFinishTime();
+    attempt.shuffleFinishTime = task.getFinishTime();
+    attempt.sortFinishTime = task.getFinishTime();
+    attempt.mapFinishTime = task.getFinishTime();
+    attempt.status = task.getTaskStatus();
+    attempt.taskType = task.getTaskType();
+    attempt.trackerName = "localhost";
+    attempt.httpPort = 1234;
+    attempt.hostname = "localhost";
+    task.attemptsMap.put(attempt.getAttemptId(), attempt);
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMRJobClient.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMRJobClient.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMRJobClient.java
index 2382239..f13c163 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMRJobClient.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMRJobClient.java
@@ -22,6 +22,7 @@ import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileOutputStream;
+import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStream;
@@ -29,6 +30,8 @@ import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
 import java.io.PrintStream;
 
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
 import org.junit.Assert;
 
 import org.apache.commons.logging.Log;
@@ -359,27 +362,152 @@ public class TestMRJobClient extends ClusterMapReduceTestCase {
     String historyFileUri = new Path(f.getAbsolutePath())
         .makeQualified(localFs.getUri(), localFs.getWorkingDirectory()).toUri()
         .toString();
- 
-    // bad command
-    int exitCode = runTool(conf, jc, new String[] { "-history", "pul", 
-        historyFileUri }, out);
-    assertEquals("Exit code", -1, exitCode);
 
-    exitCode = runTool(conf, jc, new String[] { "-history", "all",
-        historyFileUri }, out);
+    // Try a bunch of different valid combinations of the command to test
+    // argument parsing
+    int exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        "all",
+        historyFileUri,
+      }, out);
     assertEquals("Exit code", 0, exitCode);
-    String line;
+    checkHistoryHumanOutput(out);
+    File outFile = File.createTempFile("myout", ".txt");
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        "all",
+        historyFileUri,
+        "-outfile",
+        outFile.getAbsolutePath()
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryHumanFileOutput(out, outFile);
+    outFile = File.createTempFile("myout", ".txt");
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        "all",
+        historyFileUri,
+        "-outfile",
+        outFile.getAbsolutePath(),
+        "-format",
+        "human"
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryHumanFileOutput(out, outFile);
+
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        historyFileUri,
+        "-format",
+        "human"
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryHumanOutput(out);
+
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        "all",
+        historyFileUri,
+        "-format",
+        "json"
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryJSONOutput(out);
+    outFile = File.createTempFile("myout", ".txt");
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        "all",
+        historyFileUri,
+        "-outfile",
+        outFile.getAbsolutePath(),
+        "-format",
+        "json"
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryJSONFileOutput(out, outFile);
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        historyFileUri,
+        "-format",
+        "json"
+      }, out);
+    assertEquals("Exit code", 0, exitCode);
+    checkHistoryJSONOutput(out);
+
+    // Check some bad arguments
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        historyFileUri,
+        "foo"
+    }, out);
+    assertEquals("Exit code", -1, exitCode);
+    exitCode = runTool(conf, jc, new String[] {
+        "-history",
+        historyFileUri,
+        "-format"
+      }, out);
+    assertEquals("Exit code", -1, exitCode);
+    runTool(conf, jc, new String[] {
+        "-history",
+        historyFileUri,
+        "-outfile",
+    }, out);
+    assertEquals("Exit code", -1, exitCode);
+    try {
+      runTool(conf, jc, new String[]{
+          "-history",
+          historyFileUri,
+          "-format",
+          "foo"
+      }, out);
+      fail();
+    } catch (IllegalArgumentException e) {
+      // Expected
+    }
+  }
+
+  private void checkHistoryHumanOutput(ByteArrayOutputStream out)
+      throws IOException, JSONException {
     BufferedReader br = new BufferedReader(new InputStreamReader(
         new ByteArrayInputStream(out.toByteArray())));
-    int counter = 0;
-    while ((line = br.readLine()) != null) {
-      LOG.info("line = " + line);
-      if (line.startsWith("task_")) {
-        counter++;
-      }
-    }
-    assertEquals(23, counter);
+    br.readLine();
+    String line = br.readLine();
+    br.close();
+    assertEquals("Hadoop job: job_1329348432655_0001", line);
+    out.reset();
+  }
+
+  private void checkHistoryJSONOutput(ByteArrayOutputStream out)
+      throws IOException, JSONException {
+    BufferedReader br = new BufferedReader(new InputStreamReader(
+        new ByteArrayInputStream(out.toByteArray())));
+    String line = org.apache.commons.io.IOUtils.toString(br);
+    br.close();
+    JSONObject json = new JSONObject(line);
+    assertEquals("job_1329348432655_0001", json.getString("hadoopJob"));
+    out.reset();
+  }
+
+  private void checkHistoryHumanFileOutput(ByteArrayOutputStream out,
+      File outFile) throws IOException, JSONException {
+    BufferedReader br = new BufferedReader(new FileReader(outFile));
+    br.readLine();
+    String line = br.readLine();
+    br.close();
+    assertEquals("Hadoop job: job_1329348432655_0001", line);
+    assertEquals(0, out.size());
+  }
+
+  private void checkHistoryJSONFileOutput(ByteArrayOutputStream out,
+      File outFile) throws IOException, JSONException {
+    BufferedReader br = new BufferedReader(new FileReader(outFile));
+    String line = org.apache.commons.io.IOUtils.toString(br);
+    br.close();
+    JSONObject json = new JSONObject(line);
+    assertEquals("job_1329348432655_0001", json.getString("hadoopJob"));
+    assertEquals(0, out.size());
   }
+
   /**
    * print job events list 
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-project/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-project/pom.xml b/hadoop-project/pom.xml
index 6078573..f23b46e 100644
--- a/hadoop-project/pom.xml
+++ b/hadoop-project/pom.xml
@@ -992,6 +992,12 @@
         </exclusions>
       </dependency>
 
+        <dependency>
+            <groupId>org.skyscreamer</groupId>
+            <artifactId>jsonassert</artifactId>
+            <version>1.3.0</version>
+        </dependency>
+
     </dependencies>
   </dependencyManagement>
 


[26/50] [abbrv] hadoop git commit: HDFS-9818. Correctly handle EC reconstruction work caused by not enough racks. Contributed by Jing Zhao.

Posted by ji...@apache.org.
HDFS-9818. Correctly handle EC reconstruction work caused by not enough racks. Contributed by Jing Zhao.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/e54cc293
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/e54cc293
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/e54cc293

Branch: refs/heads/HDFS-7240
Commit: e54cc2931262bf49682a8323da9811976218c03b
Parents: 6eae433
Author: Jing Zhao <ji...@apache.org>
Authored: Fri Feb 19 19:02:23 2016 -0800
Committer: Jing Zhao <ji...@apache.org>
Committed: Fri Feb 19 19:02:23 2016 -0800

----------------------------------------------------------------------
 .../hadoop/hdfs/DFSStripedInputStream.java      |   7 +-
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |   3 +
 .../server/blockmanagement/BlockManager.java    |  40 ++--
 .../BlockPlacementPolicyDefault.java            |   5 +-
 .../BlockPlacementPolicyRackFaultTolerant.java  |  10 +-
 .../BlockPlacementStatusDefault.java            |  10 +-
 .../BlockReconstructionWork.java                |   5 +
 .../blockmanagement/ErasureCodingWork.java      | 106 ++++++++-
 .../server/blockmanagement/ReplicationWork.java |   5 +
 .../erasurecode/ErasureCodingWorker.java        |  25 ++-
 .../TestBlocksWithNotEnoughRacks.java           |  12 +-
 ...constructStripedBlocksWithRackAwareness.java | 213 +++++++++++++++++++
 12 files changed, 388 insertions(+), 53 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
index d15e536..3483255 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSStripedInputStream.java
@@ -260,7 +260,12 @@ public class DFSStripedInputStream extends DFSInputStream {
 
   private void closeReader(BlockReaderInfo readerInfo) {
     if (readerInfo != null) {
-//      IOUtils.cleanup(null, readerInfo.reader);
+      if (readerInfo.reader != null) {
+        try {
+          readerInfo.reader.close();
+        } catch (Throwable ignored) {
+        }
+      }
       readerInfo.skip();
     }
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index a377243..1d0379c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -432,6 +432,9 @@ Trunk (Unreleased)
     HDFS-9794. Streamer threads may leak if failure happens when closing the
     striped outputstream. (jing9)
 
+    HDFS-9818. Correctly handle EC reconstruction work caused by not enough
+    racks. (jing9)
+
     BREAKDOWN OF HDFS-7285 SUBTASKS AND RELATED JIRAS
 
       HDFS-7347. Configurable erasure coding policy for individual files and

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
index 67f5026..cc52b6e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
@@ -1628,7 +1628,7 @@ public class BlockManager implements BlockStatsMXBean {
       for (int i = 0 ; i < liveBlockIndices.size(); i++) {
         indices[i] = liveBlockIndices.get(i);
       }
-      return new ErasureCodingWork(block, bc, srcNodes,
+      return new ErasureCodingWork(getBlockPoolId(), block, bc, srcNodes,
           containingNodes, liveReplicaNodes, additionalReplRequired,
           priority, indices);
     } else {
@@ -1638,6 +1638,16 @@ public class BlockManager implements BlockStatsMXBean {
     }
   }
 
+  private boolean isInNewRack(DatanodeDescriptor[] srcs,
+      DatanodeDescriptor target) {
+    for (DatanodeDescriptor src : srcs) {
+      if (src.getNetworkLocation().equals(target.getNetworkLocation())) {
+        return false;
+      }
+    }
+    return true;
+  }
+
   private boolean validateReconstructionWork(BlockReconstructionWork rw) {
     BlockInfo block = rw.getBlock();
     int priority = rw.getPriority();
@@ -1665,31 +1675,14 @@ public class BlockManager implements BlockStatsMXBean {
     DatanodeStorageInfo[] targets = rw.getTargets();
     if ( (numReplicas.liveReplicas() >= requiredReplication) &&
         (!isPlacementPolicySatisfied(block)) ) {
-      if (rw.getSrcNodes()[0].getNetworkLocation().equals(
-          targets[0].getDatanodeDescriptor().getNetworkLocation())) {
-        //No use continuing, unless a new rack in this case
+      if (!isInNewRack(rw.getSrcNodes(), targets[0].getDatanodeDescriptor())) {
+        // No use continuing, unless a new rack in this case
         return false;
       }
     }
 
-    // Add block to the to be reconstructed list
-    if (block.isStriped()) {
-      assert rw instanceof ErasureCodingWork;
-      assert rw.getTargets().length > 0;
-      assert pendingNum == 0 : "Should wait the previous reconstruction"
-          + " to finish";
-      final ErasureCodingPolicy ecPolicy =
-          ((BlockInfoStriped) block).getErasureCodingPolicy();
-      assert ecPolicy != null;
-
-      rw.getTargets()[0].getDatanodeDescriptor().addBlockToBeErasureCoded(
-          new ExtendedBlock(getBlockPoolId(), block),
-          rw.getSrcNodes(), rw.getTargets(),
-          ((ErasureCodingWork) rw).getLiveBlockIndicies(), ecPolicy);
-    } else {
-      rw.getSrcNodes()[0].addBlockToBeReplicated(block, targets);
-    }
-
+    // Add block to the datanode's task list
+    rw.addTaskToDatanode();
     DatanodeStorageInfo.incrementBlocksScheduled(targets);
 
     // Move the block-replication into a "pending" state.
@@ -3973,7 +3966,8 @@ public class BlockManager implements BlockStatsMXBean {
         .getPolicy(storedBlock.isStriped());
     int numReplicas = storedBlock.isStriped() ? ((BlockInfoStriped) storedBlock)
         .getRealDataBlockNum() : storedBlock.getReplication();
-    return placementPolicy.verifyBlockPlacement(locs, numReplicas).isPlacementPolicySatisfied();
+    return placementPolicy.verifyBlockPlacement(locs, numReplicas)
+        .isPlacementPolicySatisfied();
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
index ee891a5..e1a47ae 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
@@ -901,7 +901,7 @@ public class BlockPlacementPolicyDefault extends BlockPlacementPolicy {
       locs = DatanodeDescriptor.EMPTY_ARRAY;
     if (!clusterMap.hasClusterEverBeenMultiRack()) {
       // only one rack
-      return new BlockPlacementStatusDefault(1, 1);
+      return new BlockPlacementStatusDefault(1, 1, 1);
     }
     int minRacks = 2;
     minRacks = Math.min(minRacks, numberOfReplicas);
@@ -910,7 +910,8 @@ public class BlockPlacementPolicyDefault extends BlockPlacementPolicy {
     Set<String> racks = new TreeSet<>();
     for (DatanodeInfo dn : locs)
       racks.add(dn.getNetworkLocation());
-    return new BlockPlacementStatusDefault(racks.size(), minRacks);
+    return new BlockPlacementStatusDefault(racks.size(), minRacks,
+        clusterMap.getNumOfRacks());
   }
   /**
    * Decide whether deleting the specified replica of the block still makes

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyRackFaultTolerant.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyRackFaultTolerant.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyRackFaultTolerant.java
index c803b97..c0d981c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyRackFaultTolerant.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyRackFaultTolerant.java
@@ -160,14 +160,16 @@ public class BlockPlacementPolicyRackFaultTolerant extends BlockPlacementPolicyD
       locs = DatanodeDescriptor.EMPTY_ARRAY;
     if (!clusterMap.hasClusterEverBeenMultiRack()) {
       // only one rack
-      return new BlockPlacementStatusDefault(1, 1);
+      return new BlockPlacementStatusDefault(1, 1, 1);
     }
     // 1. Check that all locations are different.
     // 2. Count locations on different racks.
-    Set<String> racks = new TreeSet<String>();
-    for (DatanodeInfo dn : locs)
+    Set<String> racks = new TreeSet<>();
+    for (DatanodeInfo dn : locs) {
       racks.add(dn.getNetworkLocation());
-    return new BlockPlacementStatusDefault(racks.size(), numberOfReplicas);
+    }
+    return new BlockPlacementStatusDefault(racks.size(), numberOfReplicas,
+        clusterMap.getNumOfRacks());
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementStatusDefault.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementStatusDefault.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementStatusDefault.java
index 0b8b965..75bb65d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementStatusDefault.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementStatusDefault.java
@@ -21,15 +21,18 @@ public class BlockPlacementStatusDefault implements BlockPlacementStatus {
 
   private int requiredRacks = 0;
   private int currentRacks = 0;
+  private final int totalRacks;
   
-  public BlockPlacementStatusDefault(int currentRacks, int requiredRacks){
+  public BlockPlacementStatusDefault(int currentRacks, int requiredRacks,
+      int totalRacks){
     this.requiredRacks = requiredRacks;
     this.currentRacks = currentRacks;
+    this.totalRacks = totalRacks;
   }
   
   @Override
   public boolean isPlacementPolicySatisfied() {
-    return requiredRacks <= currentRacks;
+    return requiredRacks <= currentRacks || currentRacks >= totalRacks;
   }
 
   @Override
@@ -38,7 +41,8 @@ public class BlockPlacementStatusDefault implements BlockPlacementStatus {
       return null;
     }
     return "Block should be additionally replicated on " + 
-        (requiredRacks - currentRacks) + " more rack(s).";
+        (requiredRacks - currentRacks) +
+        " more rack(s). Total number of racks in the cluster: " + totalRacks;
   }
 
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java
index df9c164..c1998ee 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockReconstructionWork.java
@@ -108,4 +108,9 @@ abstract class BlockReconstructionWork {
   abstract void chooseTargets(BlockPlacementPolicy blockplacement,
       BlockStoragePolicySuite storagePolicySuite,
       Set<Node> excludedNodes);
+
+  /**
+   * add reconstruction task into a source datanode
+   */
+  abstract void addTaskToDatanode();
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ErasureCodingWork.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ErasureCodingWork.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ErasureCodingWork.java
index 85a25d5..38ad324 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ErasureCodingWork.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ErasureCodingWork.java
@@ -17,15 +17,23 @@
  */
 package org.apache.hadoop.hdfs.server.blockmanagement;
 
+import org.apache.hadoop.hdfs.protocol.Block;
+import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
+import org.apache.hadoop.hdfs.util.StripedBlockUtil;
 import org.apache.hadoop.net.Node;
 
+import java.util.ArrayList;
+import java.util.BitSet;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 class ErasureCodingWork extends BlockReconstructionWork {
   private final byte[] liveBlockIndicies;
+  private final String blockPoolId;
 
-  public ErasureCodingWork(BlockInfo block,
+  public ErasureCodingWork(String blockPoolId, BlockInfo block,
       BlockCollection bc,
       DatanodeDescriptor[] srcNodes,
       List<DatanodeDescriptor> containingNodes,
@@ -34,6 +42,7 @@ class ErasureCodingWork extends BlockReconstructionWork {
       int priority, byte[] liveBlockIndicies) {
     super(block, bc, srcNodes, containingNodes,
         liveReplicaStorages, additionalReplRequired, priority);
+    this.blockPoolId = blockPoolId;
     this.liveBlockIndicies = liveBlockIndicies;
     BlockManager.LOG.debug("Creating an ErasureCodingWork to {} reconstruct ",
         block);
@@ -47,15 +56,92 @@ class ErasureCodingWork extends BlockReconstructionWork {
   void chooseTargets(BlockPlacementPolicy blockplacement,
       BlockStoragePolicySuite storagePolicySuite,
       Set<Node> excludedNodes) {
-    try {
-      // TODO: new placement policy for EC considering multiple writers
-      DatanodeStorageInfo[] chosenTargets = blockplacement.chooseTarget(
-          getBc().getName(), getAdditionalReplRequired(), getSrcNodes()[0],
-          getLiveReplicaStorages(), false, excludedNodes,
-          getBlock().getNumBytes(),
-          storagePolicySuite.getPolicy(getBc().getStoragePolicyID()));
-      setTargets(chosenTargets);
-    } finally {
+    // TODO: new placement policy for EC considering multiple writers
+    DatanodeStorageInfo[] chosenTargets = blockplacement.chooseTarget(
+        getBc().getName(), getAdditionalReplRequired(), getSrcNodes()[0],
+        getLiveReplicaStorages(), false, excludedNodes,
+        getBlock().getNumBytes(),
+        storagePolicySuite.getPolicy(getBc().getStoragePolicyID()));
+    setTargets(chosenTargets);
+  }
+
+  /**
+   * @return true if the current source nodes cover all the internal blocks.
+   * I.e., we only need to have more racks.
+   */
+  private boolean hasAllInternalBlocks() {
+    final BlockInfoStriped block = (BlockInfoStriped) getBlock();
+    if (getSrcNodes().length < block.getRealTotalBlockNum()) {
+      return false;
+    }
+    BitSet bitSet = new BitSet(block.getTotalBlockNum());
+    for (byte index : liveBlockIndicies) {
+      bitSet.set(index);
+    }
+    for (int i = 0; i < block.getRealDataBlockNum(); i++) {
+      if (!bitSet.get(i)) {
+        return false;
+      }
+    }
+    for (int i = block.getDataBlockNum(); i < block.getTotalBlockNum(); i++) {
+      if (!bitSet.get(i)) {
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * We have all the internal blocks but not enough racks. Thus we do not need
+   * to do decoding but only simply make an extra copy of an internal block. In
+   * this scenario, use this method to choose the source datanode for simple
+   * replication.
+   * @return The index of the source datanode.
+   */
+  private int chooseSource4SimpleReplication() {
+    Map<String, List<Integer>> map = new HashMap<>();
+    for (int i = 0; i < getSrcNodes().length; i++) {
+      final String rack = getSrcNodes()[i].getNetworkLocation();
+      List<Integer> dnList = map.get(rack);
+      if (dnList == null) {
+        dnList = new ArrayList<>();
+        map.put(rack, dnList);
+      }
+      dnList.add(i);
+    }
+    List<Integer> max = null;
+    for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
+      if (max == null || entry.getValue().size() > max.size()) {
+        max = entry.getValue();
+      }
+    }
+    assert max != null;
+    return max.get(0);
+  }
+
+  @Override
+  void addTaskToDatanode() {
+    assert getTargets().length > 0;
+    BlockInfoStriped stripedBlk = (BlockInfoStriped) getBlock();
+
+    // if we already have all the internal blocks, but not enough racks,
+    // we only need to replicate one internal block to a new rack
+    if (hasAllInternalBlocks()) {
+      int sourceIndex = chooseSource4SimpleReplication();
+      final byte blockIndex = liveBlockIndicies[sourceIndex];
+      final DatanodeDescriptor source = getSrcNodes()[sourceIndex];
+      final long internBlkLen = StripedBlockUtil.getInternalBlockLength(
+          stripedBlk.getNumBytes(), stripedBlk.getCellSize(),
+          stripedBlk.getDataBlockNum(), blockIndex);
+      final Block targetBlk = new Block(
+          stripedBlk.getBlockId() + blockIndex, internBlkLen,
+          stripedBlk.getGenerationStamp());
+      source.addBlockToBeReplicated(targetBlk, getTargets());
+    } else {
+      getTargets()[0].getDatanodeDescriptor().addBlockToBeErasureCoded(
+          new ExtendedBlock(blockPoolId, stripedBlk),
+          getSrcNodes(), getTargets(), getLiveBlockIndicies(),
+          stripedBlk.getErasureCodingPolicy());
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
index b44b9b1..24601a2 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/ReplicationWork.java
@@ -53,4 +53,9 @@ class ReplicationWork extends BlockReconstructionWork {
       getSrcNodes()[0].decrementPendingReplicationWithoutTargets();
     }
   }
+
+  @Override
+  void addTaskToDatanode() {
+    getSrcNodes()[0].addBlockToBeReplicated(getBlock(), getTargets());
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
index b08aa2e..1017e1e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
@@ -177,8 +177,14 @@ public final class ErasureCodingWorker {
       Collection<BlockECReconstructionInfo> ecTasks) {
     for (BlockECReconstructionInfo reconstructionInfo : ecTasks) {
       try {
-        EC_RECONSTRUCTION_STRIPED_BLK_THREAD_POOL
-            .submit(new ReconstructAndTransferBlock(reconstructionInfo));
+        ReconstructAndTransferBlock task =
+            new ReconstructAndTransferBlock(reconstructionInfo);
+        if (task.hasValidTargets()) {
+          EC_RECONSTRUCTION_STRIPED_BLK_THREAD_POOL.submit(task);
+        } else {
+          LOG.warn("No missing internal block. Skip reconstruction for task:{}",
+              reconstructionInfo);
+        }
       } catch (Throwable e) {
         LOG.warn("Failed to reconstruct striped block {}",
             reconstructionInfo.getExtendedBlock().getLocalBlock(), e);
@@ -292,6 +298,7 @@ public final class ErasureCodingWorker {
     private final CompletionService<Void> readService =
         new ExecutorCompletionService<>(
             EC_RECONSTRUCTION_STRIPED_READ_THREAD_POOL);
+    private final boolean hasValidTargets;
 
     ReconstructAndTransferBlock(BlockECReconstructionInfo reconstructionInfo) {
       ErasureCodingPolicy ecPolicy = reconstructionInfo
@@ -339,10 +346,14 @@ public final class ErasureCodingWorker {
         seqNo4Targets[i] = 0;
       }
 
-      getTargetIndices();
+      hasValidTargets = getTargetIndices();
       cachingStrategy = CachingStrategy.newDefaultStrategy();
     }
 
+    boolean hasValidTargets() {
+      return hasValidTargets;
+    }
+
     private ByteBuffer allocateBuffer(int length) {
       return ByteBuffer.allocate(length);
     }
@@ -505,24 +516,30 @@ public final class ErasureCodingWorker {
       }
     }
 
-    private void getTargetIndices() {
+    /**
+     * @return true if there is valid target for reconstruction
+     */
+    private boolean getTargetIndices() {
       BitSet bitset = new BitSet(dataBlkNum + parityBlkNum);
       for (int i = 0; i < sources.length; i++) {
         bitset.set(liveIndices[i]);
       }
       int m = 0;
       int k = 0;
+      boolean hasValidTarget = false;
       for (int i = 0; i < dataBlkNum + parityBlkNum; i++) {
         if (!bitset.get(i)) {
           if (getBlockLen(blockGroup, i) > 0) {
             if (m < targets.length) {
               targetIndices[m++] = (short)i;
+              hasValidTarget = true;
             }
           } else {
             zeroStripeIndices[k++] = (short)i;
           }
         }
       }
+      return hasValidTarget;
     }
 
     /** the reading length should not exceed the length for reconstruction. */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlocksWithNotEnoughRacks.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlocksWithNotEnoughRacks.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlocksWithNotEnoughRacks.java
index ea994a2..d91155a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlocksWithNotEnoughRacks.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlocksWithNotEnoughRacks.java
@@ -285,7 +285,7 @@ public class TestBlocksWithNotEnoughRacks {
     final DatanodeManager dm = ns.getBlockManager().getDatanodeManager();
 
     try {
-      // Create a file with one block with a replication factor of 2
+      // Create a file with one block with a replication factor of 3
       final FileSystem fs = cluster.getFileSystem();
       DFSTestUtil.createFile(fs, filePath, 1L, REPLICATION_FACTOR, 1L);
       ExtendedBlock b = DFSTestUtil.getFirstBlock(fs, filePath);
@@ -315,8 +315,9 @@ public class TestBlocksWithNotEnoughRacks {
       dm.removeDatanode(dnId);
 
       // Make sure we have enough live replicas even though we are
-      // short one rack and therefore need one replica
-      DFSTestUtil.waitForReplication(cluster, b, 1, REPLICATION_FACTOR, 1);
+      // short one rack. The cluster now has only 1 rack thus we just make sure
+      // we still have 3 replicas.
+      DFSTestUtil.waitForReplication(cluster, b, 1, REPLICATION_FACTOR, 0);
     } finally {
       cluster.shutdown();
     }
@@ -357,9 +358,8 @@ public class TestBlocksWithNotEnoughRacks {
 
       // The block gets re-replicated to another datanode so it has a 
       // sufficient # replicas, but not across racks, so there should
-      // be 1 rack, and 1 needed replica (even though there are 2 hosts 
-      // available and only 2 replicas required).
-      DFSTestUtil.waitForReplication(cluster, b, 1, REPLICATION_FACTOR, 1);
+      // be 1 rack.
+      DFSTestUtil.waitForReplication(cluster, b, 1, REPLICATION_FACTOR, 0);
 
       // Start the "failed" datanode, which has a replica so the block is
       // now over-replicated and therefore a replica should be removed but

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e54cc293/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReconstructStripedBlocksWithRackAwareness.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReconstructStripedBlocksWithRackAwareness.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReconstructStripedBlocksWithRackAwareness.java
new file mode 100644
index 0000000..2164957
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestReconstructStripedBlocksWithRackAwareness.java
@@ -0,0 +1,213 @@
+/**
+ * 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.hdfs.server.blockmanagement;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.DFSTestUtil;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
+import org.apache.hadoop.hdfs.HdfsConfiguration;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.hdfs.protocol.Block;
+import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
+import org.apache.hadoop.hdfs.server.datanode.DataNode;
+import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
+import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
+import org.apache.hadoop.hdfs.server.namenode.INodeFile;
+import org.apache.hadoop.net.NetworkTopology;
+import org.apache.hadoop.test.GenericTestUtils;
+import org.apache.log4j.Level;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.apache.hadoop.hdfs.StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
+import static org.apache.hadoop.hdfs.StripedFileTestUtil.NUM_DATA_BLOCKS;
+import static org.apache.hadoop.hdfs.StripedFileTestUtil.NUM_PARITY_BLOCKS;
+
+public class TestReconstructStripedBlocksWithRackAwareness {
+  public static final Logger LOG = LoggerFactory.getLogger(
+      TestReconstructStripedBlocksWithRackAwareness.class);
+
+  static {
+    GenericTestUtils.setLogLevel(BlockPlacementPolicy.LOG, Level.ALL);
+    GenericTestUtils.setLogLevel(BlockManager.blockLog, Level.ALL);
+  }
+
+  private static final String[] hosts = new String[]{"host1", "host2", "host3",
+      "host4", "host5", "host6", "host7", "host8", "host9", "host10"};
+  private static final String[] racks = new String[]{"/r1", "/r1", "/r2", "/r2",
+      "/r3", "/r3", "/r4", "/r4", "/r5", "/r6"};
+  private static final List<String> singleNodeRacks = Arrays.asList("host9", "host10");
+  private static final short blockNum = (short) (NUM_DATA_BLOCKS + NUM_PARITY_BLOCKS);
+
+  private MiniDFSCluster cluster;
+  private DistributedFileSystem fs;
+  private FSNamesystem fsn;
+  private BlockManager bm;
+
+  @Before
+  public void setup() throws Exception {
+    final HdfsConfiguration conf = new HdfsConfiguration();
+    conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_INTERVAL_KEY, 1);
+    conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_REPLICATION_CONSIDERLOAD_KEY,
+        false);
+
+    cluster = new MiniDFSCluster.Builder(conf).racks(racks).hosts(hosts)
+        .numDataNodes(hosts.length).build();
+    cluster.waitActive();
+
+    fsn = cluster.getNamesystem();
+    bm = fsn.getBlockManager();
+
+    fs = cluster.getFileSystem();
+    fs.setErasureCodingPolicy(new Path("/"), null);
+  }
+
+  @After
+  public void tearDown() {
+    if (cluster != null) {
+      cluster.shutdown();
+    }
+  }
+
+  /**
+   * When there are all the internal blocks available but they are not placed on
+   * enough racks, NameNode should avoid normal decoding reconstruction but copy
+   * an internal block to a new rack.
+   *
+   * In this test, we first need to create a scenario that a striped block has
+   * all the internal blocks but distributed in <6 racks. Then we check if the
+   * replication monitor can correctly schedule the reconstruction work for it.
+   *
+   * For the 9 internal blocks + 5 racks setup, the test does the following:
+   * 1. create a 6 rack cluster with 10 datanodes, where there are 2 racks only
+   * containing 1 datanodes each
+   * 2. for a striped block with 9 internal blocks, there must be one internal
+   * block locating in a single-node rack. find this node and stop it
+   * 3. namenode will trigger reconstruction for the block and since the cluster
+   * has only 5 racks remaining, after the reconstruction we have 9 internal
+   * blocks distributed in 5 racks.
+   * 4. we bring the datanode back, now the cluster has 6 racks again
+   * 5. let the datanode call reportBadBlock, this will make the namenode to
+   * check if the striped block is placed in >= 6 racks, and the namenode will
+   * put the block into the under-replicated queue
+   * 6. now we can check if the replication monitor works as expected
+   */
+  @Test
+  public void testReconstructForNotEnoughRacks() throws Exception {
+    final Path file = new Path("/foo");
+    DFSTestUtil.createFile(fs, file,
+        BLOCK_STRIPED_CELL_SIZE * NUM_DATA_BLOCKS * 2, (short) 1, 0L);
+    Assert.assertEquals(0, bm.numOfUnderReplicatedBlocks());
+
+    final INodeFile fileNode = fsn.getFSDirectory()
+        .getINode4Write(file.toString()).asFile();
+    BlockInfoStriped blockInfo = (BlockInfoStriped) fileNode.getLastBlock();
+
+    // find the internal block located in the single node rack
+    Block internalBlock = null;
+    String hostToStop = null;
+    for (DatanodeStorageInfo storage : blockInfo.storages) {
+      if (singleNodeRacks.contains(storage.getDatanodeDescriptor().getHostName())) {
+        hostToStop = storage.getDatanodeDescriptor().getHostName();
+        internalBlock = blockInfo.getBlockOnStorage(storage);
+      }
+    }
+    Assert.assertNotNull(internalBlock);
+    Assert.assertNotNull(hostToStop);
+
+    // delete the block on the chosen datanode
+    cluster.corruptBlockOnDataNodesByDeletingBlockFile(
+        new ExtendedBlock(bm.getBlockPoolId(), internalBlock));
+
+    // stop the chosen datanode
+    MiniDFSCluster.DataNodeProperties dnProp = null;
+    for (int i = 0; i < cluster.getDataNodes().size(); i++) {
+      DataNode dn = cluster.getDataNodes().get(i);
+      if (dn.getDatanodeId().getHostName().equals(hostToStop)) {
+        dnProp = cluster.stopDataNode(i);
+        cluster.setDataNodeDead(dn.getDatanodeId());
+        LOG.info("stop datanode " + dn.getDatanodeId().getHostName());
+      }
+    }
+    NetworkTopology topology = bm.getDatanodeManager().getNetworkTopology();
+    Assert.assertEquals(5, topology.getNumOfRacks());
+
+    // make sure the reconstruction work can finish
+    // now we have 9 internal blocks in 5 racks
+    DFSTestUtil.waitForReplication(fs, file, blockNum, 15 * 1000);
+
+    // we now should have 9 internal blocks distributed in 5 racks
+    Set<String> rackSet = new HashSet<>();
+    for (DatanodeStorageInfo storage : blockInfo.storages) {
+      rackSet.add(storage.getDatanodeDescriptor().getNetworkLocation());
+    }
+    Assert.assertEquals(5, rackSet.size());
+
+    // restart the stopped datanode
+    cluster.restartDataNode(dnProp);
+    cluster.waitActive();
+
+    // make sure we have 6 racks again
+    topology = bm.getDatanodeManager().getNetworkTopology();
+    Assert.assertEquals(hosts.length, topology.getNumOfLeaves());
+    Assert.assertEquals(6, topology.getNumOfRacks());
+
+    // pause all the heartbeats
+    DataNode badDn = null;
+    for (DataNode dn : cluster.getDataNodes()) {
+      DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
+      if (dn.getDatanodeId().getHostName().equals(hostToStop)) {
+        badDn = dn;
+      }
+    }
+    assert badDn != null;
+    // let the DN report the bad block, so that the namenode will put the block
+    // into under-replicated queue. note that the block still has 9 internal
+    // blocks but in 5 racks
+    badDn.reportBadBlocks(new ExtendedBlock(bm.getBlockPoolId(), internalBlock));
+
+    // check if replication monitor correctly schedule the replication work
+    boolean scheduled = false;
+    for (int i = 0; i < 5; i++) { // retry 5 times
+      for (DatanodeStorageInfo storage : blockInfo.storages) {
+        if (storage != null) {
+          DatanodeDescriptor dn = storage.getDatanodeDescriptor();
+          Assert.assertEquals(0, dn.getNumberOfBlocksToBeErasureCoded());
+          if (dn.getNumberOfBlocksToBeReplicated() == 1) {
+            scheduled = true;
+          }
+        }
+      }
+      if (scheduled) {
+        break;
+      }
+      Thread.sleep(1000);
+    }
+    Assert.assertTrue(scheduled);
+  }
+}


[32/50] [abbrv] hadoop git commit: YARN-4386. refreshNodesGracefully() should send recommission event to active RMNodes only. Contributed by Kuhu Shukla.

Posted by ji...@apache.org.
YARN-4386. refreshNodesGracefully() should send recommission event to active RMNodes only. Contributed by Kuhu Shukla.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/3fab8854
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/3fab8854
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/3fab8854

Branch: refs/heads/HDFS-7240
Commit: 3fab88540f079591e5dae1c9184f8b26bb843427
Parents: 5e7d4d5
Author: Junping Du <ju...@apache.org>
Authored: Mon Feb 22 07:04:19 2016 -0800
Committer: Junping Du <ju...@apache.org>
Committed: Mon Feb 22 07:04:19 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |  3 ++
 .../resourcemanager/NodesListManager.java       |  3 +-
 .../TestResourceTrackerService.java             | 35 ++++++++++++++++++++
 3 files changed, 39 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/3fab8854/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index e39917f..9b57666 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1433,6 +1433,9 @@ Release 2.8.0 - UNRELEASED
     YARN-4654. Yarn node label CLI should parse "=" correctly when trying to 
     remove all labels on a node. (Naganarasimha G R via rohithsharmaks)
 
+    YARN-4386. refreshNodesGracefully() should send recommission event to active
+    RMNodes only. (Kuhu Shukla via junping_du)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3fab8854/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/NodesListManager.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/NodesListManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/NodesListManager.java
index e6251fe..4cdf67a 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/NodesListManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/NodesListManager.java
@@ -400,8 +400,7 @@ public class NodesListManager extends CompositeService implements
             new RMNodeEvent(nodeId, RMNodeEventType.GRACEFUL_DECOMMISSION));
       } else {
         // Recommissioning the nodes
-        if (entry.getValue().getState() == NodeState.DECOMMISSIONING
-            || entry.getValue().getState() == NodeState.DECOMMISSIONED) {
+        if (entry.getValue().getState() == NodeState.DECOMMISSIONING) {
           this.rmContext.getDispatcher().getEventHandler()
               .handle(new RMNodeEvent(nodeId, RMNodeEventType.RECOMMISSION));
         }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3fab8854/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java
index e0fd9ab..9ed79a3 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestResourceTrackerService.java
@@ -1269,6 +1269,41 @@ public class TestResourceTrackerService extends NodeLabelTestBase {
     rm1.stop();
   }
 
+  @Test
+  public void testIncorrectRecommission() throws Exception {
+    //Check decommissioned node not get recommissioned with graceful refresh
+    Configuration conf = new Configuration();
+    rm = new MockRM(conf);
+    rm.start();
+    MockNM nm1 = rm.registerNode("host1:1234", 5120);
+    MockNM nm2 = rm.registerNode("host2:5678", 10240);
+    nm1.nodeHeartbeat(true);
+    nm2.nodeHeartbeat(true);
+    File excludeHostFile =
+        new File(TEMP_DIR + File.separator + "excludeHostFile.txt");
+    writeToHostsFile(excludeHostFile, "host3", "host2");
+    conf.set(YarnConfiguration.RM_NODES_EXCLUDE_FILE_PATH,
+        excludeHostFile.getAbsolutePath());
+    writeToHostsFile(hostFile, "host1", "host2");
+    writeToHostsFile(excludeHostFile, "host1");
+    rm.getNodesListManager().refreshNodesGracefully(conf);
+    rm.drainEvents();
+    nm1.nodeHeartbeat(true);
+    rm.drainEvents();
+    Assert.assertTrue("Node " + nm1.getNodeId().getHost() +
+        " should be Decommissioned", rm.getRMContext()
+        .getInactiveRMNodes().get(nm1.getNodeId()).getState() == NodeState
+        .DECOMMISSIONED);
+    writeToHostsFile(excludeHostFile, "");
+    rm.getNodesListManager().refreshNodesGracefully(conf);
+    rm.drainEvents();
+    Assert.assertTrue("Node " + nm1.getNodeId().getHost() +
+        " should be Decommissioned", rm.getRMContext()
+        .getInactiveRMNodes().get(nm1.getNodeId()).getState() == NodeState
+        .DECOMMISSIONED);
+    rm.stop();
+  }
+
   private void writeToHostsFile(String... hosts) throws IOException {
    writeToHostsFile(hostFile, hosts);
   }


[06/50] [abbrv] hadoop git commit: YARN-4690. Skip object allocation in FSAppAttempt#getResourceUsage when possible (Ming Ma via sjlee)

Posted by ji...@apache.org.
YARN-4690. Skip object allocation in FSAppAttempt#getResourceUsage when possible (Ming Ma via sjlee)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/7de70680
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/7de70680
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/7de70680

Branch: refs/heads/HDFS-7240
Commit: 7de70680fe44967e2afc92ba4c92f8e7afa7b151
Parents: a0c95b5
Author: Sangjin Lee <sj...@apache.org>
Authored: Wed Feb 17 20:55:21 2016 -0800
Committer: Sangjin Lee <sj...@twitter.com>
Committed: Wed Feb 17 20:55:21 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                               | 3 +++
 .../server/resourcemanager/scheduler/fair/FSAppAttempt.java   | 7 ++++++-
 2 files changed, 9 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/7de70680/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index c172054..fa0ba44 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -2362,6 +2362,9 @@ Release 2.6.5 - UNRELEASED
 
   OPTIMIZATIONS
 
+    YARN-4690. Skip object allocation in FSAppAttempt#getResourceUsage when
+    possible (Ming Ma via sjlee)
+
   BUG FIXES
 
 Release 2.6.4 - 2016-02-11

http://git-wip-us.apache.org/repos/asf/hadoop/blob/7de70680/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java
index 488f34e..7e0a693 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSAppAttempt.java
@@ -890,7 +890,12 @@ public class FSAppAttempt extends SchedulerApplicationAttempt
   public Resource getResourceUsage() {
     // Here the getPreemptedResources() always return zero, except in
     // a preemption round
-    return Resources.subtract(getCurrentConsumption(), getPreemptedResources());
+    // In the common case where preempted resource is zero, return the
+    // current consumption Resource object directly without calling
+    // Resources.subtract which creates a new Resource object for each call.
+    return getPreemptedResources().equals(Resources.none()) ?
+        getCurrentConsumption() :
+        Resources.subtract(getCurrentConsumption(), getPreemptedResources());
   }
 
   @Override


[45/50] [abbrv] hadoop git commit: HADOOP-12829. StatisticsDataReferenceCleaner swallows interrupt exceptions (Gregory Chanan via cmccabe)

Posted by ji...@apache.org.
HADOOP-12829. StatisticsDataReferenceCleaner swallows interrupt exceptions (Gregory Chanan via cmccabe)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/d9c409a4
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/d9c409a4
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/d9c409a4

Branch: refs/heads/HDFS-7240
Commit: d9c409a4286e36387fb39e7d622e850c13315465
Parents: 9ed17f1
Author: Colin Patrick Mccabe <cm...@cloudera.com>
Authored: Tue Feb 23 11:11:22 2016 -0800
Committer: Colin Patrick Mccabe <cm...@cloudera.com>
Committed: Tue Feb 23 11:11:22 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt             | 3 +++
 .../src/main/java/org/apache/hadoop/fs/FileSystem.java      | 9 +++++----
 2 files changed, 8 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/d9c409a4/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 361859a..d405af3 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -719,6 +719,9 @@ Release 2.9.0 - UNRELEASED
    HADOOP-12714. Fix hadoop-mapreduce-client-nativetask unit test which fails
    because it is not able to open the "glibc bug spill" file. (cmccabe)
 
+   HADOOP-12829. StatisticsDataReferenceCleaner swallows interrupt exceptions
+   (Gregory Chanan via cmccabe)
+
 Release 2.8.0 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d9c409a4/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
index 3e26f68..8c1d57b 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
@@ -3184,15 +3184,16 @@ public abstract class FileSystem extends Configured implements Closeable {
     private static class StatisticsDataReferenceCleaner implements Runnable {
       @Override
       public void run() {
-        while (true) {
+        while (!Thread.interrupted()) {
           try {
             StatisticsDataReference ref =
                 (StatisticsDataReference)STATS_DATA_REF_QUEUE.remove();
             ref.cleanUp();
+          } catch (InterruptedException ie) {
+            LOG.warn("Cleaner thread interrupted, will stop", ie);
+            Thread.currentThread().interrupt();
           } catch (Throwable th) {
-            // the cleaner thread should continue to run even if there are
-            // exceptions, including InterruptedException
-            LOG.warn("exception in the cleaner thread but it will continue to "
+            LOG.warn("Exception in the cleaner thread but it will continue to "
                 + "run", th);
           }
         }


[21/50] [abbrv] hadoop git commit: HDFS-9764. DistCp doesn't print value for several arguments including -numListstatusThreads. (Wei-Chiu Chuang via Yongjun Zhang)

Posted by ji...@apache.org.
HDFS-9764. DistCp doesn't print value for several arguments including -numListstatusThreads. (Wei-Chiu Chuang via Yongjun Zhang)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/ba1c9d48
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/ba1c9d48
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/ba1c9d48

Branch: refs/heads/HDFS-7240
Commit: ba1c9d484a8d6a18b4b7365c49d09635d24e579a
Parents: a963bab
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Fri Feb 19 10:17:37 2016 -0800
Committer: Yongjun Zhang <yz...@cloudera.com>
Committed: Fri Feb 19 10:17:37 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt          |  3 +++
 .../java/org/apache/hadoop/tools/DistCpOptions.java  | 10 +++++++++-
 .../org/apache/hadoop/tools/TestOptionsParser.java   | 15 ++++++++++-----
 3 files changed, 22 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba1c9d48/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 2129a69..1f5d65d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1942,6 +1942,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-8923. Add -source flag to balancer usage message.  (Chris Trezzo
     via szetszwo)
 
+    HDFS-9764. DistCp doesn't print value for several arguments including
+    -numListstatusThreads. (Wei-Chiu Chuang via Yongjun Zhang) 
+
   OPTIMIZATIONS
 
     HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba1c9d48/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptions.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptions.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptions.java
index 10cf388..cbd4ac0 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptions.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptions.java
@@ -664,14 +664,22 @@ public class DistCpOptions {
         ", syncFolder=" + syncFolder +
         ", deleteMissing=" + deleteMissing +
         ", ignoreFailures=" + ignoreFailures +
+        ", overwrite=" + overwrite +
+        ", skipCRC=" + skipCRC +
+        ", blocking=" + blocking +
+        ", numListstatusThreads=" + numListstatusThreads +
         ", maxMaps=" + maxMaps +
+        ", mapBandwidth=" + mapBandwidth +
         ", sslConfigurationFile='" + sslConfigurationFile + '\'' +
         ", copyStrategy='" + copyStrategy + '\'' +
+        ", preserveStatus=" + preserveStatus +
+        ", preserveRawXattrs=" + preserveRawXattrs +
+        ", atomicWorkPath=" + atomicWorkPath +
+        ", logPath=" + logPath +
         ", sourceFileListing=" + sourceFileListing +
         ", sourcePaths=" + sourcePaths +
         ", targetPath=" + targetPath +
         ", targetPathExists=" + targetPathExists +
-        ", preserveRawXattrs=" + preserveRawXattrs +
         ", filtersFile='" + filtersFile + '\'' +
         '}';
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba1c9d48/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestOptionsParser.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestOptionsParser.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestOptionsParser.java
index 78ae415..4c136a8 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestOptionsParser.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestOptionsParser.java
@@ -399,11 +399,16 @@ public class TestOptionsParser {
   @Test
   public void testToString() {
     DistCpOptions option = new DistCpOptions(new Path("abc"), new Path("xyz"));
-    String val = "DistCpOptions{atomicCommit=false, syncFolder=false, deleteMissing=false, " +
-        "ignoreFailures=false, maxMaps=20, sslConfigurationFile='null', copyStrategy='uniformsize', " +
-        "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, targetPathExists=true, " +
-        "preserveRawXattrs=false, filtersFile='null'}";
-    Assert.assertEquals(val, option.toString());
+    String val = "DistCpOptions{atomicCommit=false, syncFolder=false, "
+        + "deleteMissing=false, ignoreFailures=false, overwrite=false, "
+        + "skipCRC=false, blocking=true, numListstatusThreads=0, maxMaps=20, "
+        + "mapBandwidth=100.0, sslConfigurationFile='null', "
+        + "copyStrategy='uniformsize', preserveStatus=[], "
+        + "preserveRawXattrs=false, atomicWorkPath=null, logPath=null, "
+        + "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, "
+        + "targetPathExists=true, filtersFile='null'}";
+    String optionString = option.toString();
+    Assert.assertEquals(val, optionString);
     Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),
         DistCpOptionSwitch.ATOMIC_COMMIT.name());
   }


[29/50] [abbrv] hadoop git commit: HDFS-7452. skip StandbyException log for getCorruptFiles() (Contributed by Bramha Reddy Battula)

Posted by ji...@apache.org.
HDFS-7452. skip StandbyException log for getCorruptFiles() (Contributed by Bramha Reddy Battula)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/f3135167
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/f3135167
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/f3135167

Branch: refs/heads/HDFS-7240
Commit: f313516731d787f6be64c9406ca83d941d47ee99
Parents: b68901d
Author: Vinayakumar B <vi...@apache.org>
Authored: Mon Feb 22 09:21:46 2016 +0530
Committer: Vinayakumar B <vi...@apache.org>
Committed: Mon Feb 22 09:21:46 2016 +0530

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt                      | 3 +++
 .../org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java     | 4 ++++
 2 files changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/f3135167/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 9215488..9a156a5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2804,6 +2804,9 @@ Release 2.8.0 - UNRELEASED
 
     HDFS-9839. Reduce verbosity of processReport logging. (Arpit Agarwal)
 
+    HDFS-7452. skip StandbyException log for getCorruptFiles()
+    (Bramha Reddy Battula via vinayakumarb)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/f3135167/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
index 4722ac1..64f23dd 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSNamesystem.java
@@ -5596,6 +5596,10 @@ public class FSNamesystem implements Namesystem, FSNamesystemMBean,
           list.add(c.toString());
         }
       }
+    } catch (StandbyException e) {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Get corrupt file blocks returned error: " + e.getMessage());
+      }
     } catch (IOException e) {
       LOG.warn("Get corrupt file blocks returned error: " + e.getMessage());
     }


[30/50] [abbrv] hadoop git commit: HDFS-9425. Expose number of blocks per volume as a metric (Contributed by Brahma Reddy Battula)

Posted by ji...@apache.org.
HDFS-9425. Expose number of blocks per volume as a metric (Contributed by Brahma Reddy Battula)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/342c9572
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/342c9572
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/342c9572

Branch: refs/heads/HDFS-7240
Commit: 342c9572bf6a623287f34c5cc0bc3be6038c191a
Parents: f313516
Author: Vinayakumar B <vi...@apache.org>
Authored: Mon Feb 22 09:29:23 2016 +0530
Committer: Vinayakumar B <vi...@apache.org>
Committed: Mon Feb 22 09:29:23 2016 +0530

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  3 ++
 .../datanode/fsdataset/impl/BlockPoolSlice.java | 29 ++++++++++-
 .../datanode/fsdataset/impl/FsDatasetImpl.java  | 12 ++++-
 .../datanode/fsdataset/impl/FsVolumeImpl.java   | 30 +++++++++--
 .../server/datanode/TestDataNodeMXBean.java     | 55 ++++++++++++++++++++
 5 files changed, 121 insertions(+), 8 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/342c9572/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 9a156a5..3552c8e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2024,6 +2024,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-9768. Reuse ObjectMapper instance in HDFS to improve the performance.
     (Lin Yiqun via aajisaka)
 
+    HDFS-9425. Expose number of blocks per volume as a metric
+    (Brahma Reddy Battula via vinayakumarb)
+
   BUG FIXES
 
     HDFS-7501. TransactionsSinceLastCheckpoint can be negative on SBNs.

http://git-wip-us.apache.org/repos/asf/hadoop/blob/342c9572/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/BlockPoolSlice.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/BlockPoolSlice.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/BlockPoolSlice.java
index 188ab68..aa33851 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/BlockPoolSlice.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/BlockPoolSlice.java
@@ -30,6 +30,7 @@ import java.io.RandomAccessFile;
 import java.io.Writer;
 import java.util.Iterator;
 import java.util.Scanner;
+import java.util.concurrent.atomic.AtomicLong;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.logging.Log;
@@ -86,6 +87,7 @@ class BlockPoolSlice {
   private final boolean deleteDuplicateReplicas;
   private static final String REPLICA_CACHE_FILE = "replicas";
   private final long replicaCacheExpiry = 5*60*1000;
+  private AtomicLong numOfBlocks = new AtomicLong();
   private final long cachedDfsUsedCheckTime;
   private final Timer timer;
 
@@ -273,7 +275,11 @@ class BlockPoolSlice {
    */
   File createTmpFile(Block b) throws IOException {
     File f = new File(tmpDir, b.getBlockName());
-    return DatanodeUtil.createTmpFile(b, f);
+    File tmpFile = DatanodeUtil.createTmpFile(b, f);
+    // If any exception during creation, its expected that counter will not be
+    // incremented, So no need to decrement
+    incrNumBlocks();
+    return tmpFile;
   }
 
   /**
@@ -282,7 +288,11 @@ class BlockPoolSlice {
    */
   File createRbwFile(Block b) throws IOException {
     File f = new File(rbwDir, b.getBlockName());
-    return DatanodeUtil.createTmpFile(b, f);
+    File rbwFile = DatanodeUtil.createTmpFile(b, f);
+    // If any exception during creation, its expected that counter will not be
+    // incremented, So no need to decrement
+    incrNumBlocks();
+    return rbwFile;
   }
 
   File addFinalizedBlock(Block b, File f) throws IOException {
@@ -493,6 +503,9 @@ class BlockPoolSlice {
     } else {
       lazyWriteReplicaMap.discardReplica(bpid, blockId, false);
     }
+    if (oldReplica == null) {
+      incrNumBlocks();
+    }
   }
   
 
@@ -825,4 +838,16 @@ class BlockPoolSlice {
       }
     }
   }
+
+  void incrNumBlocks() {
+    numOfBlocks.incrementAndGet();
+  }
+
+  void decrNumBlocks() {
+    numOfBlocks.decrementAndGet();
+  }
+
+  public long getNumOfBlocks() {
+    return numOfBlocks.get();
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/342c9572/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
index 819d097..d1cb836 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
@@ -965,6 +965,11 @@ class FsDatasetImpl implements FsDatasetSpi<FsVolumeImpl> {
       newReplicaInfo.setNumBytes(blockFiles[1].length());
       // Finalize the copied files
       newReplicaInfo = finalizeReplica(block.getBlockPoolId(), newReplicaInfo);
+      synchronized (this) {
+        // Increment numBlocks here as this block moved without knowing to BPS
+        FsVolumeImpl volume = (FsVolumeImpl) newReplicaInfo.getVolume();
+        volume.getBlockPoolSlice(block.getBlockPoolId()).incrNumBlocks();
+      }
 
       removeOldReplica(replicaInfo, newReplicaInfo, oldBlockFile, oldMetaFile,
           oldBlockFile.length(), oldMetaFile.length(), block.getBlockPoolId());
@@ -2599,6 +2604,7 @@ class FsDatasetImpl implements FsDatasetSpi<FsVolumeImpl> {
     final long reservedSpace; // size of space reserved for non-HDFS
     final long reservedSpaceForReplicas; // size of space reserved RBW or
                                     // re-replication
+    final long numBlocks;
 
     VolumeInfo(FsVolumeImpl v, long usedSpace, long freeSpace) {
       this.directory = v.toString();
@@ -2606,6 +2612,7 @@ class FsDatasetImpl implements FsDatasetSpi<FsVolumeImpl> {
       this.freeSpace = freeSpace;
       this.reservedSpace = v.getReserved();
       this.reservedSpaceForReplicas = v.getReservedForReplicas();
+      this.numBlocks = v.getNumBlocks();
     }
   }  
 
@@ -2640,6 +2647,7 @@ class FsDatasetImpl implements FsDatasetSpi<FsVolumeImpl> {
       innerInfo.put("freeSpace", v.freeSpace);
       innerInfo.put("reservedSpace", v.reservedSpace);
       innerInfo.put("reservedSpaceForReplicas", v.reservedSpaceForReplicas);
+      innerInfo.put("numBlocks", v.numBlocks);
       info.put(v.directory, innerInfo);
     }
     return info;
@@ -2728,8 +2736,8 @@ class FsDatasetImpl implements FsDatasetSpi<FsVolumeImpl> {
     synchronized (FsDatasetImpl.this) {
       ramDiskReplicaTracker.recordEndLazyPersist(bpId, blockId, savedFiles);
 
-      targetVolume.incDfsUsed(bpId,
-          savedFiles[0].length() + savedFiles[1].length());
+      targetVolume.incDfsUsedAndNumBlocks(bpId, savedFiles[0].length()
+          + savedFiles[1].length());
 
       // Update metrics (ignore the metadata file size)
       datanode.getMetrics().incrRamDiskBlocksLazyPersisted();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/342c9572/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java
index 1533a32..857d0ad 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java
@@ -284,21 +284,35 @@ public class FsVolumeImpl implements FsVolumeSpi {
   }
 
   void onBlockFileDeletion(String bpid, long value) {
-    decDfsUsed(bpid, value);
+    decDfsUsedAndNumBlocks(bpid, value, true);
     if (isTransientStorage()) {
       dataset.releaseLockedMemory(value, true);
     }
   }
 
   void onMetaFileDeletion(String bpid, long value) {
-    decDfsUsed(bpid, value);
+    decDfsUsedAndNumBlocks(bpid, value, false);
   }
 
-  private void decDfsUsed(String bpid, long value) {
+  private void decDfsUsedAndNumBlocks(String bpid, long value,
+                                      boolean blockFileDeleted) {
     synchronized(dataset) {
       BlockPoolSlice bp = bpSlices.get(bpid);
       if (bp != null) {
         bp.decDfsUsed(value);
+        if (blockFileDeleted) {
+          bp.decrNumBlocks();
+        }
+      }
+    }
+  }
+
+  void incDfsUsedAndNumBlocks(String bpid, long value) {
+    synchronized (dataset) {
+      BlockPoolSlice bp = bpSlices.get(bpid);
+      if (bp != null) {
+        bp.incDfsUsed(value);
+        bp.incrNumBlocks();
       }
     }
   }
@@ -847,7 +861,15 @@ public class FsVolumeImpl implements FsVolumeSpi {
       throws IOException {
     getBlockPoolSlice(bpid).getVolumeMap(volumeMap, ramDiskReplicaMap);
   }
-  
+
+  long getNumBlocks() {
+    long numBlocks = 0;
+    for (BlockPoolSlice s : bpSlices.values()) {
+      numBlocks += s.getNumOfBlocks();
+    }
+    return numBlocks;
+  }
+
   @Override
   public String toString() {
     return currentDir.getAbsolutePath();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/342c9572/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeMXBean.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeMXBean.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeMXBean.java
index a7d0a5e..6d520ae 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeMXBean.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeMXBean.java
@@ -18,15 +18,23 @@
 package org.apache.hadoop.hdfs.server.datanode;
 
 import java.lang.management.ManagementFactory;
+import java.util.Collection;
 import java.util.List;
+import java.util.Map;
 
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
 
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.DFSTestUtil;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
 import org.junit.Assert;
 import org.junit.Test;
+import org.mortbay.util.ajax.JSON;
+
+import static org.junit.Assert.assertEquals;
 
 /**
  * Class for testing {@link DataNodeMXBean} implementation
@@ -84,4 +92,51 @@ public class TestDataNodeMXBean {
   private static String replaceDigits(final String s) {
     return s.replaceAll("[0-9]+", "_DIGITS_");
   }
+
+  @Test
+  public void testDataNodeMXBeanBlockCount() throws Exception {
+    Configuration conf = new Configuration();
+    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
+
+    try {
+      List<DataNode> datanodes = cluster.getDataNodes();
+      assertEquals(datanodes.size(), 1);
+
+      MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+      ObjectName mxbeanName =
+              new ObjectName("Hadoop:service=DataNode,name=DataNodeInfo");
+      FileSystem fs = cluster.getFileSystem();
+      for (int i = 0; i < 5; i++) {
+        DFSTestUtil.createFile(fs, new Path("/tmp.txt" + i), 1024, (short) 1,
+                1L);
+      }
+      assertEquals("Before restart DN", 5, getTotalNumBlocks(mbs, mxbeanName));
+      cluster.restartDataNode(0);
+      cluster.waitActive();
+      assertEquals("After restart DN", 5, getTotalNumBlocks(mbs, mxbeanName));
+      fs.delete(new Path("/tmp.txt1"), true);
+      // Wait till replica gets deleted on disk.
+      Thread.sleep(5000);
+      assertEquals("After delete one file", 4,
+              getTotalNumBlocks(mbs, mxbeanName));
+    } finally {
+      if (cluster != null) {
+        cluster.shutdown();
+      }
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  int getTotalNumBlocks(MBeanServer mbs, ObjectName mxbeanName)
+          throws Exception {
+    int totalBlocks = 0;
+    String volumeInfo = (String) mbs.getAttribute(mxbeanName, "VolumeInfo");
+    Map<?, ?> m = (Map<?, ?>) JSON.parse(volumeInfo);
+    Collection<Map<String, Long>> values =
+            (Collection<Map<String, Long>>) m.values();
+    for (Map<String, Long> volumeInfoMap : values) {
+      totalBlocks += volumeInfoMap.get("numBlocks");
+    }
+    return totalBlocks;
+  }
 }


[20/50] [abbrv] hadoop git commit: HADOOP-12828. Print user when services are started. (Wei-Chiu Chuang via Yongjun Zhang)

Posted by ji...@apache.org.
HADOOP-12828. Print user when services are started. (Wei-Chiu Chuang via Yongjun Zhang)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a963baba
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a963baba
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a963baba

Branch: refs/heads/HDFS-7240
Commit: a963baba10648859ad88d4ed9a4325b66b1af0d5
Parents: 748b6c0
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Fri Feb 19 09:41:22 2016 -0800
Committer: Yongjun Zhang <yz...@cloudera.com>
Committed: Fri Feb 19 09:41:22 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt                   | 3 +++
 .../src/main/java/org/apache/hadoop/util/StringUtils.java         | 1 +
 .../java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java   | 1 +
 3 files changed, 5 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a963baba/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 91ef68e..bf84d7a 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1134,6 +1134,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-11031. Design Document for Credential Provider API.
     (Larry McCay via cnauroth)
 
+    HADOOP-12828. Print user when services are started.
+    (Wei-Chiu Chuang via Yongjun Zhang) 
+
   OPTIMIZATIONS
 
     HADOOP-11785. Reduce the number of listStatus operation in distcp

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a963baba/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/StringUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/StringUtils.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/StringUtils.java
index 1ccdb22..31f6914 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/StringUtils.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/StringUtils.java
@@ -687,6 +687,7 @@ public class StringUtils {
     LOG.info(
         toStartupShutdownString("STARTUP_MSG: ", new String[] {
             "Starting " + classname,
+            "  user = " + System.getProperty("user.name"),
             "  host = " + hostname,
             "  args = " + Arrays.asList(args),
             "  version = " + VersionInfo.getVersion(),

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a963baba/hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java b/hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java
index 325f8db..3b439a4 100644
--- a/hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java
+++ b/hadoop-common-project/hadoop-kms/src/main/java/org/apache/hadoop/crypto/key/kms/server/KMSWebApp.java
@@ -124,6 +124,7 @@ public class KMSWebApp implements ServletContextListener {
       LOG.info("-------------------------------------------------------------");
       LOG.info("  Java runtime version : {}", System.getProperty(
           "java.runtime.version"));
+      LOG.info("  User: {}", System.getProperty("user.name"));
       LOG.info("  KMS Hadoop Version: " + VersionInfo.getVersion());
       LOG.info("-------------------------------------------------------------");
 


[44/50] [abbrv] hadoop git commit: YARN-3223. Resource update during NM graceful decommission. Contributed by Brook Zhou.

Posted by ji...@apache.org.
YARN-3223. Resource update during NM graceful decommission. Contributed by Brook Zhou.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/9ed17f18
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/9ed17f18
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/9ed17f18

Branch: refs/heads/HDFS-7240
Commit: 9ed17f181d96b8719a0ef54a129081948781d57e
Parents: 0e12114
Author: Junping Du <ju...@apache.org>
Authored: Tue Feb 23 03:29:46 2016 -0800
Committer: Junping Du <ju...@apache.org>
Committed: Tue Feb 23 03:30:26 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |   3 +
 .../resourcemanager/rmnode/RMNodeImpl.java      |  30 +++++-
 .../scheduler/capacity/CapacityScheduler.java   |  16 +++
 .../scheduler/fair/FairScheduler.java           |  15 +++
 .../scheduler/fifo/FifoScheduler.java           |  16 +++
 .../resourcemanager/TestRMNodeTransitions.java  |  34 ++++++
 .../capacity/TestCapacityScheduler.java         |  89 ++++++++++++++-
 .../scheduler/fair/TestFairScheduler.java       |  91 ++++++++++++++++
 .../scheduler/fifo/TestFifoScheduler.java       | 107 ++++++++++++++++++-
 9 files changed, 395 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index e2ffec0..439c1bb 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -441,6 +441,9 @@ Release 2.8.0 - UNRELEASED
     YARN-4411. RMAppAttemptImpl#createApplicationAttemptReport throws
     IllegalArgumentException. (Bibin A Chundatt, yarntime via devaraj)
 
+    YARN-3223. Resource update during NM graceful decommission. (Brook Zhou
+    via junping_du)
+
   IMPROVEMENTS
 
     YARN-644. Basic null check is not performed on passed in arguments before

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/RMNodeImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/RMNodeImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/RMNodeImpl.java
index f4e483b..ca9df38 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/RMNodeImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmnode/RMNodeImpl.java
@@ -79,6 +79,7 @@ import org.apache.hadoop.yarn.state.MultipleArcTransition;
 import org.apache.hadoop.yarn.state.SingleArcTransition;
 import org.apache.hadoop.yarn.state.StateMachine;
 import org.apache.hadoop.yarn.state.StateMachineFactory;
+import org.apache.hadoop.yarn.util.resource.Resources;
 
 import com.google.common.annotations.VisibleForTesting;
 
@@ -110,6 +111,8 @@ public class RMNodeImpl implements RMNode, EventHandler<RMNodeEvent> {
   private int httpPort;
   private final String nodeAddress; // The containerManager address
   private String httpAddress;
+  /* Snapshot of total resources before receiving decommissioning command */
+  private volatile Resource originalTotalCapability;
   private volatile Resource totalCapability;
   private final Node node;
 
@@ -236,6 +239,9 @@ public class RMNodeImpl implements RMNode, EventHandler<RMNodeEvent> {
       .addTransition(NodeState.DECOMMISSIONING, NodeState.RUNNING,
           RMNodeEventType.RECOMMISSION,
           new RecommissionNodeTransition(NodeState.RUNNING))
+      .addTransition(NodeState.DECOMMISSIONING, NodeState.DECOMMISSIONING,
+          RMNodeEventType.RESOURCE_UPDATE,
+          new UpdateNodeResourceWhenRunningTransition())
       .addTransition(NodeState.DECOMMISSIONING,
           EnumSet.of(NodeState.DECOMMISSIONING, NodeState.DECOMMISSIONED),
           RMNodeEventType.STATUS_UPDATE,
@@ -1064,7 +1070,12 @@ public class RMNodeImpl implements RMNode, EventHandler<RMNodeEvent> {
       LOG.info("Put Node " + rmNode.nodeId + " in DECOMMISSIONING.");
       // Update NM metrics during graceful decommissioning.
       rmNode.updateMetricsForGracefulDecommission(initState, finalState);
-      // TODO (in YARN-3223) Keep NM's available resource to be 0
+      if (rmNode.originalTotalCapability == null){
+        rmNode.originalTotalCapability =
+            Resources.clone(rmNode.totalCapability);
+        LOG.info("Preserve original total capability: "
+            + rmNode.originalTotalCapability);
+      }
     }
   }
 
@@ -1078,11 +1089,22 @@ public class RMNodeImpl implements RMNode, EventHandler<RMNodeEvent> {
 
     @Override
     public void transition(RMNodeImpl rmNode, RMNodeEvent event) {
+      // Restore the original total capability
+      if (rmNode.originalTotalCapability != null) {
+        rmNode.totalCapability = rmNode.originalTotalCapability;
+        rmNode.originalTotalCapability = null;
+      }
       LOG.info("Node " + rmNode.nodeId + " in DECOMMISSIONING is " +
           "recommissioned back to RUNNING.");
       rmNode
           .updateMetricsForGracefulDecommission(rmNode.getState(), finalState);
-      // TODO handle NM resource resume in YARN-3223.
+      //update the scheduler with the restored original total capability
+      rmNode.context
+          .getDispatcher()
+          .getEventHandler()
+          .handle(
+              new NodeResourceUpdateSchedulerEvent(rmNode, ResourceOption
+                  .newInstance(rmNode.totalCapability, 0)));
     }
   }
 
@@ -1353,4 +1375,8 @@ public class RMNodeImpl implements RMNode, EventHandler<RMNodeEvent> {
       writeLock.unlock();
     }
    }
+
+  public Resource getOriginalTotalCapability() {
+    return this.originalTotalCapability;
+  }
  }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java
index ee3a3f9..7f844a0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacityScheduler.java
@@ -56,6 +56,7 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerResourceChangeRequest;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.QueueACL;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
@@ -91,6 +92,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEven
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeDecreaseContainerEvent;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation;
@@ -1082,6 +1084,20 @@ public class CapacityScheduler extends
       }
     }
 
+    // If the node is decommissioning, send an update to have the total
+    // resource equal to the used resource, so no available resource to
+    // schedule.
+    // TODO: Fix possible race-condition when request comes in before
+    // update is propagated
+    if (nm.getState() == NodeState.DECOMMISSIONING) {
+      this.rmContext
+          .getDispatcher()
+          .getEventHandler()
+          .handle(
+              new RMNodeResourceUpdateEvent(nm.getNodeID(), ResourceOption
+                  .newInstance(getSchedulerNode(nm.getNodeID())
+                      .getUsedResource(), 0)));
+    }
     schedulerHealth.updateSchedulerReleaseDetails(lastNodeUpdateTime,
       releaseResources);
     schedulerHealth.updateSchedulerReleaseCounts(releasedContainers);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
index 7e013e0..1dbcda2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FairScheduler.java
@@ -43,6 +43,7 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerResourceChangeRequest;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.QueueACL;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
@@ -70,6 +71,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
@@ -1057,6 +1059,19 @@ public class FairScheduler extends
           completedContainer, RMContainerEventType.FINISHED);
     }
 
+    // If the node is decommissioning, send an update to have the total
+    // resource equal to the used resource, so no available resource to
+    // schedule.
+    if (nm.getState() == NodeState.DECOMMISSIONING) {
+      this.rmContext
+          .getDispatcher()
+          .getEventHandler()
+          .handle(
+              new RMNodeResourceUpdateEvent(nm.getNodeID(), ResourceOption
+                  .newInstance(getSchedulerNode(nm.getNodeID())
+                      .getUsedResource(), 0)));
+    }
+
     if (continuousSchedulingEnabled) {
       if (!completedContainers.isEmpty()) {
         attemptScheduling(node);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java
index 5787ba6..a0e14111 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/FifoScheduler.java
@@ -43,12 +43,14 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerResourceChangeRequest;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.QueueACL;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.QueueState;
 import org.apache.hadoop.yarn.api.records.QueueUserACLInfo;
 import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.api.records.ResourceOption;
 import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
@@ -67,6 +69,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEventType;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.UpdatedContainerInfo;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ActiveUsersManager;
@@ -747,6 +750,19 @@ public class FifoScheduler extends
         rmNode.getAggregatedContainersUtilization());
     node.setNodeUtilization(rmNode.getNodeUtilization());
 
+    // If the node is decommissioning, send an update to have the total
+    // resource equal to the used resource, so no available resource to
+    // schedule.
+    if (rmNode.getState() == NodeState.DECOMMISSIONING) {
+      this.rmContext
+          .getDispatcher()
+          .getEventHandler()
+          .handle(
+              new RMNodeResourceUpdateEvent(rmNode.getNodeID(), ResourceOption
+                  .newInstance(getSchedulerNode(rmNode.getNodeID())
+                      .getUsedResource(), 0)));
+    }
+
     if (rmContext.isWorkPreservingRecoveryEnabled()
         && !rmContext.isSchedulerReadyForAllocatingContainers()) {
       return;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.java
index 78aa139..701e512 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestRMNodeTransitions.java
@@ -975,4 +975,38 @@ public class TestRMNodeTransitions {
     verify(mockExpirer).unregister(expirationInfo1);
     verify(mockExpirer).unregister(expirationInfo2);
   }
+
+  @Test
+  public void testResourceUpdateOnDecommissioningNode() {
+    RMNodeImpl node = getDecommissioningNode();
+    Resource oldCapacity = node.getTotalCapability();
+    assertEquals("Memory resource is not match.", oldCapacity.getMemory(), 4096);
+    assertEquals("CPU resource is not match.", oldCapacity.getVirtualCores(), 4);
+    node.handle(new RMNodeResourceUpdateEvent(node.getNodeID(),
+        ResourceOption.newInstance(Resource.newInstance(2048, 2),
+            ResourceOption.OVER_COMMIT_TIMEOUT_MILLIS_DEFAULT)));
+    Resource originalCapacity = node.getOriginalTotalCapability();
+    assertEquals("Memory resource is not match.", originalCapacity.getMemory(), oldCapacity.getMemory());
+    assertEquals("CPU resource is not match.", originalCapacity.getVirtualCores(), oldCapacity.getVirtualCores());
+    Resource newCapacity = node.getTotalCapability();
+    assertEquals("Memory resource is not match.", newCapacity.getMemory(), 2048);
+    assertEquals("CPU resource is not match.", newCapacity.getVirtualCores(), 2);
+
+    Assert.assertEquals(NodeState.DECOMMISSIONING, node.getState());
+    Assert.assertNotNull(nodesListManagerEvent);
+    Assert.assertEquals(NodesListManagerEventType.NODE_USABLE,
+        nodesListManagerEvent.getType());
+  }
+
+  @Test
+  public void testResourceUpdateOnRecommissioningNode() {
+    RMNodeImpl node = getDecommissioningNode();
+    Resource oldCapacity = node.getTotalCapability();
+    assertEquals("Memory resource is not match.", oldCapacity.getMemory(), 4096);
+    assertEquals("CPU resource is not match.", oldCapacity.getVirtualCores(), 4);
+    node.handle(new RMNodeEvent(node.getNodeID(),
+        RMNodeEventType.RECOMMISSION));
+    Resource originalCapacity = node.getOriginalTotalCapability();
+    assertEquals("Original total capability not null after recommission", null, originalCapacity);
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.java
index e139df6..bd2c4fe 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestCapacityScheduler.java
@@ -63,6 +63,7 @@ import org.apache.hadoop.yarn.api.records.ContainerResourceChangeRequest;
 import org.apache.hadoop.yarn.api.records.ContainerState;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.QueueState;
@@ -74,6 +75,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.event.AsyncDispatcher;
 import org.apache.hadoop.yarn.event.Dispatcher;
 import org.apache.hadoop.yarn.event.DrainDispatcher;
+import org.apache.hadoop.yarn.event.Event;
 import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
@@ -115,6 +117,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerEven
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeEventType;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
@@ -150,11 +153,11 @@ import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mockito;
 
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Sets;
-import org.mockito.Mockito;
 
 public class TestCapacityScheduler {
   private static final Log LOG = LogFactory.getLog(TestCapacityScheduler.class);
@@ -3360,4 +3363,88 @@ public class TestCapacityScheduler {
         resourceManager.getResourceScheduler().getClusterResource());
     privateResourceTrackerService.stop();
   }
+
+  @Test
+  public void testResourceUpdateDecommissioningNode() throws Exception {
+    // Mock the RMNodeResourceUpdate event handler to update SchedulerNode
+    // to have 0 available resource
+    RMContext spyContext = Mockito.spy(resourceManager.getRMContext());
+    Dispatcher mockDispatcher = mock(AsyncDispatcher.class);
+    when(mockDispatcher.getEventHandler()).thenReturn(new EventHandler() {
+      @Override
+      public void handle(Event event) {
+        if (event instanceof RMNodeResourceUpdateEvent) {
+          RMNodeResourceUpdateEvent resourceEvent =
+              (RMNodeResourceUpdateEvent) event;
+          resourceManager
+              .getResourceScheduler()
+              .getSchedulerNode(resourceEvent.getNodeId())
+              .setTotalResource(resourceEvent.getResourceOption().getResource());
+        }
+      }
+    });
+    Mockito.doReturn(mockDispatcher).when(spyContext).getDispatcher();
+    ((CapacityScheduler) resourceManager.getResourceScheduler())
+        .setRMContext(spyContext);
+    ((AsyncDispatcher) mockDispatcher).start();
+    // Register node
+    String host_0 = "host_0";
+    org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_0 =
+        registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK,
+            Resources.createResource(8 * GB, 4));
+    // ResourceRequest priorities
+    Priority priority_0 =
+        org.apache.hadoop.yarn.server.resourcemanager.resource.Priority
+            .create(0);
+
+    // Submit an application
+    Application application_0 =
+        new Application("user_0", "a1", resourceManager);
+    application_0.submit();
+
+    application_0.addNodeManager(host_0, 1234, nm_0);
+
+    Resource capability_0_0 = Resources.createResource(1 * GB, 1);
+    application_0.addResourceRequestSpec(priority_0, capability_0_0);
+
+    Task task_0_0 =
+        new Task(application_0, priority_0, new String[] { host_0 });
+    application_0.addTask(task_0_0);
+
+    // Send resource requests to the scheduler
+    application_0.schedule();
+
+    nodeUpdate(nm_0);
+    // Kick off another heartbeat with the node state mocked to decommissioning
+    // This should update the schedulernodes to have 0 available resource
+    RMNode spyNode =
+        Mockito.spy(resourceManager.getRMContext().getRMNodes()
+            .get(nm_0.getNodeId()));
+    when(spyNode.getState()).thenReturn(NodeState.DECOMMISSIONING);
+    resourceManager.getResourceScheduler().handle(
+        new NodeUpdateSchedulerEvent(spyNode));
+
+    // Get allocations from the scheduler
+    application_0.schedule();
+
+    // Check the used resource is 1 GB 1 core
+    Assert.assertEquals(1 * GB, nm_0.getUsed().getMemory());
+    Resource usedResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getUsedResource();
+    Assert.assertEquals(usedResource.getMemory(), 1 * GB);
+    Assert.assertEquals(usedResource.getVirtualCores(), 1);
+    // Check total resource of scheduler node is also changed to 1 GB 1 core
+    Resource totalResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getTotalResource();
+    Assert.assertEquals(totalResource.getMemory(), 1 * GB);
+    Assert.assertEquals(totalResource.getVirtualCores(), 1);
+    // Check the available resource is 0/0
+    Resource availableResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getAvailableResource();
+    Assert.assertEquals(availableResource.getMemory(), 0);
+    Assert.assertEquals(availableResource.getVirtualCores(), 0);
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
index 0575f33..a15e8d1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
@@ -52,6 +52,7 @@ import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
 import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
 import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.apache.hadoop.net.NetworkTopology;
 import org.apache.hadoop.security.GroupMappingServiceProvider;
 import org.apache.hadoop.yarn.MockApps;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
@@ -61,6 +62,7 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
 import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.Resource;
@@ -68,11 +70,17 @@ import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.api.records.impl.pb.ApplicationSubmissionContextPBImpl;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.event.AsyncDispatcher;
+import org.apache.hadoop.yarn.event.Dispatcher;
+import org.apache.hadoop.yarn.event.Event;
+import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
+import org.apache.hadoop.yarn.server.resourcemanager.Application;
 import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService;
 import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
 import org.apache.hadoop.yarn.server.resourcemanager.MockRM;
+import org.apache.hadoop.yarn.server.resourcemanager.RMContext;
+import org.apache.hadoop.yarn.server.resourcemanager.Task;
 import org.apache.hadoop.yarn.server.resourcemanager.resource.ResourceType;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.MockRMApp;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
@@ -84,6 +92,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptI
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
@@ -99,6 +108,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateS
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.Default;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.apache.hadoop.yarn.util.ControlledClock;
 import org.apache.hadoop.yarn.util.resource.Resources;
@@ -106,12 +116,14 @@ import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mockito;
 import org.xml.sax.SAXException;
 
 import com.google.common.collect.Sets;
 
 @SuppressWarnings("unchecked")
 public class TestFairScheduler extends FairSchedulerTestBase {
+  private final int GB = 1024;
   private final static String ALLOC_FILE =
       new File(TEST_DIR, "test-queues").getAbsolutePath();
 
@@ -4372,4 +4384,83 @@ public class TestFairScheduler extends FairSchedulerTestBase {
     long initSchedulerTime = lastScheduledContainer.get(priority);
     assertEquals(DELAY_THRESHOLD_TIME_MS, initSchedulerTime);
   }
+
+  @Test
+  public void testResourceUpdateDecommissioningNode() throws Exception {
+    // Mock the RMNodeResourceUpdate event handler to update SchedulerNode
+    // to have 0 available resource
+    RMContext spyContext = Mockito.spy(resourceManager.getRMContext());
+    Dispatcher mockDispatcher = mock(AsyncDispatcher.class);
+    when(mockDispatcher.getEventHandler()).thenReturn(new EventHandler() {
+      @Override
+      public void handle(Event event) {
+        if (event instanceof RMNodeResourceUpdateEvent) {
+          RMNodeResourceUpdateEvent resourceEvent =
+              (RMNodeResourceUpdateEvent) event;
+          resourceManager
+              .getResourceScheduler()
+              .getSchedulerNode(resourceEvent.getNodeId())
+              .setTotalResource(resourceEvent.getResourceOption().getResource());
+        }
+      }
+    });
+    Mockito.doReturn(mockDispatcher).when(spyContext).getDispatcher();
+    ((FairScheduler) resourceManager.getResourceScheduler())
+        .setRMContext(spyContext);
+    ((AsyncDispatcher) mockDispatcher).start();
+    // Register node
+    String host_0 = "host_0";
+    org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_0 =
+        registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK,
+            Resources.createResource(8 * GB, 4));
+
+    RMNode node =
+        resourceManager.getRMContext().getRMNodes().get(nm_0.getNodeId());
+    // Send a heartbeat to kick the tires on the Scheduler
+    NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node);
+    resourceManager.getResourceScheduler().handle(nodeUpdate);
+
+    // Kick off another heartbeat with the node state mocked to decommissioning
+    // This should update the schedulernodes to have 0 available resource
+    RMNode spyNode =
+        Mockito.spy(resourceManager.getRMContext().getRMNodes()
+            .get(nm_0.getNodeId()));
+    when(spyNode.getState()).thenReturn(NodeState.DECOMMISSIONING);
+    resourceManager.getResourceScheduler().handle(
+        new NodeUpdateSchedulerEvent(spyNode));
+
+    // Check the used resource is 0 GB 0 core
+    // Assert.assertEquals(1 * GB, nm_0.getUsed().getMemory());
+    Resource usedResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getUsedResource();
+    Assert.assertEquals(usedResource.getMemory(), 0);
+    Assert.assertEquals(usedResource.getVirtualCores(), 0);
+    // Check total resource of scheduler node is also changed to 0 GB 0 core
+    Resource totalResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getTotalResource();
+    Assert.assertEquals(totalResource.getMemory(), 0 * GB);
+    Assert.assertEquals(totalResource.getVirtualCores(), 0);
+    // Check the available resource is 0/0
+    Resource availableResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getAvailableResource();
+    Assert.assertEquals(availableResource.getMemory(), 0);
+    Assert.assertEquals(availableResource.getVirtualCores(), 0);
+  }
+
+  private org.apache.hadoop.yarn.server.resourcemanager.NodeManager registerNode(
+      String hostName, int containerManagerPort, int httpPort, String rackName,
+      Resource capability) throws IOException, YarnException {
+    org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm =
+        new org.apache.hadoop.yarn.server.resourcemanager.NodeManager(hostName,
+            containerManagerPort, httpPort, rackName, capability,
+            resourceManager);
+    NodeAddedSchedulerEvent nodeAddEvent1 =
+        new NodeAddedSchedulerEvent(resourceManager.getRMContext().getRMNodes()
+            .get(nm.getNodeId()));
+    resourceManager.getResourceScheduler().handle(nodeAddEvent1);
+    return nm;
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/9ed17f18/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.java
index 8111e11..86a017e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fifo/TestFifoScheduler.java
@@ -45,6 +45,7 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerState;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.Resource;
@@ -52,6 +53,9 @@ import org.apache.hadoop.yarn.api.records.ResourceOption;
 import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.event.AsyncDispatcher;
+import org.apache.hadoop.yarn.event.Dispatcher;
+import org.apache.hadoop.yarn.event.Event;
+import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.event.InlineDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
@@ -77,6 +81,7 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptMetrics;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
+import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNodeResourceUpdateEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.Allocation;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
@@ -106,6 +111,7 @@ import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mockito;
 
 public class TestFifoScheduler {
   private static final Log LOG = LogFactory.getLog(TestFifoScheduler.class);
@@ -133,9 +139,15 @@ public class TestFifoScheduler {
       registerNode(String hostName, int containerManagerPort, int nmHttpPort,
           String rackName, Resource capability) throws IOException,
           YarnException {
-    return new org.apache.hadoop.yarn.server.resourcemanager.NodeManager(
-        hostName, containerManagerPort, nmHttpPort, rackName, capability,
-        resourceManager);
+    org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm =
+        new org.apache.hadoop.yarn.server.resourcemanager.NodeManager(hostName,
+            containerManagerPort, nmHttpPort, rackName, capability,
+            resourceManager);
+    NodeAddedSchedulerEvent nodeAddEvent1 =
+        new NodeAddedSchedulerEvent(resourceManager.getRMContext().getRMNodes()
+            .get(nm.getNodeId()));
+    resourceManager.getResourceScheduler().handle(nodeAddEvent1);
+    return nm;
   }
   
   private ApplicationAttemptId createAppAttemptId(int appId, int attemptId) {
@@ -1163,6 +1175,95 @@ public class TestFifoScheduler {
     rm.stop();
   }
 
+  @Test
+  public void testResourceUpdateDecommissioningNode() throws Exception {
+    // Mock the RMNodeResourceUpdate event handler to update SchedulerNode
+    // to have 0 available resource
+    RMContext spyContext = Mockito.spy(resourceManager.getRMContext());
+    Dispatcher mockDispatcher = mock(AsyncDispatcher.class);
+    when(mockDispatcher.getEventHandler()).thenReturn(new EventHandler() {
+      @Override
+      public void handle(Event event) {
+        if (event instanceof RMNodeResourceUpdateEvent) {
+          RMNodeResourceUpdateEvent resourceEvent =
+              (RMNodeResourceUpdateEvent) event;
+          resourceManager
+              .getResourceScheduler()
+              .getSchedulerNode(resourceEvent.getNodeId())
+              .setTotalResource(resourceEvent.getResourceOption().getResource());
+        }
+      }
+    });
+    Mockito.doReturn(mockDispatcher).when(spyContext).getDispatcher();
+    ((FifoScheduler) resourceManager.getResourceScheduler())
+        .setRMContext(spyContext);
+    ((AsyncDispatcher) mockDispatcher).start();
+    // Register node
+    String host_0 = "host_0";
+    org.apache.hadoop.yarn.server.resourcemanager.NodeManager nm_0 =
+        registerNode(host_0, 1234, 2345, NetworkTopology.DEFAULT_RACK,
+            Resources.createResource(8 * GB, 4));
+    // ResourceRequest priorities
+    Priority priority_0 =
+        org.apache.hadoop.yarn.server.resourcemanager.resource.Priority
+            .create(0);
+
+    // Submit an application
+    Application application_0 =
+        new Application("user_0", "a1", resourceManager);
+    application_0.submit();
+
+    application_0.addNodeManager(host_0, 1234, nm_0);
+
+    Resource capability_0_0 = Resources.createResource(1 * GB, 1);
+    application_0.addResourceRequestSpec(priority_0, capability_0_0);
+
+    Task task_0_0 =
+        new Task(application_0, priority_0, new String[] { host_0 });
+    application_0.addTask(task_0_0);
+
+    // Send resource requests to the scheduler
+    application_0.schedule();
+
+    RMNode node =
+        resourceManager.getRMContext().getRMNodes().get(nm_0.getNodeId());
+    // Send a heartbeat to kick the tires on the Scheduler
+    NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node);
+    resourceManager.getResourceScheduler().handle(nodeUpdate);
+
+    // Kick off another heartbeat with the node state mocked to decommissioning
+    // This should update the schedulernodes to have 0 available resource
+    RMNode spyNode =
+        Mockito.spy(resourceManager.getRMContext().getRMNodes()
+            .get(nm_0.getNodeId()));
+    when(spyNode.getState()).thenReturn(NodeState.DECOMMISSIONING);
+    resourceManager.getResourceScheduler().handle(
+        new NodeUpdateSchedulerEvent(spyNode));
+
+    // Get allocations from the scheduler
+    application_0.schedule();
+
+    // Check the used resource is 1 GB 1 core
+    // Assert.assertEquals(1 * GB, nm_0.getUsed().getMemory());
+    Resource usedResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getUsedResource();
+    Assert.assertEquals(usedResource.getMemory(), 1 * GB);
+    Assert.assertEquals(usedResource.getVirtualCores(), 1);
+    // Check total resource of scheduler node is also changed to 1 GB 1 core
+    Resource totalResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getTotalResource();
+    Assert.assertEquals(totalResource.getMemory(), 1 * GB);
+    Assert.assertEquals(totalResource.getVirtualCores(), 1);
+    // Check the available resource is 0/0
+    Resource availableResource =
+        resourceManager.getResourceScheduler()
+            .getSchedulerNode(nm_0.getNodeId()).getAvailableResource();
+    Assert.assertEquals(availableResource.getMemory(), 0);
+    Assert.assertEquals(availableResource.getVirtualCores(), 0);
+  }
+
   private void checkApplicationResourceUsage(int expected, 
       Application application) {
     Assert.assertEquals(expected, application.getUsedResources().getMemory());


[07/50] [abbrv] hadoop git commit: YARN-4654. Yarn node label CLI should parse "=" correctly when trying to remove all labels on a node. (Naganarasimha G R via rohithsharmaks)

Posted by ji...@apache.org.
YARN-4654. Yarn node label CLI should parse "=" correctly when trying to remove all labels on a node. (Naganarasimha G R via rohithsharmaks)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/c1afac3a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/c1afac3a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/c1afac3a

Branch: refs/heads/HDFS-7240
Commit: c1afac3a98a4889d30a6ec7574a364fcbb6bb5b0
Parents: 7de7068
Author: Rohith Sharma K S <ro...@apache.org>
Authored: Thu Feb 18 14:10:37 2016 +0530
Committer: Rohith Sharma K S <ro...@apache.org>
Committed: Thu Feb 18 14:10:37 2016 +0530

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |  3 ++
 .../hadoop/yarn/client/cli/RMAdminCLI.java      | 25 ++++++++-------
 .../hadoop/yarn/client/cli/TestRMAdminCLI.java  | 32 +++++++++++++++++++-
 3 files changed, 48 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/c1afac3a/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index fa0ba44..9b64204 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1428,6 +1428,9 @@ Release 2.8.0 - UNRELEASED
     YARN-4667. RM Admin CLI for refreshNodesResources throws NPE when nothing
     is configured. (Naganarasimha G R via devaraj)
 
+    YARN-4654. Yarn node label CLI should parse "=" correctly when trying to 
+    remove all labels on a node. (Naganarasimha G R via rohithsharmaks)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c1afac3a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java
index 5c3b1d8..d407c20 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/RMAdminCLI.java
@@ -59,8 +59,8 @@ import org.apache.hadoop.yarn.server.api.protocolrecords.CheckForDecommissioning
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshAdminAclsRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshClusterMaxPriorityRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesRequest;
-import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshNodesResourcesRequest;
+import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshQueuesRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshServiceAclsRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshSuperUserGroupsConfigurationRequest;
 import org.apache.hadoop.yarn.server.api.protocolrecords.RefreshUserToGroupsMappingsRequest;
@@ -592,26 +592,29 @@ public class RMAdminCLI extends HAAdmin {
         continue;
       }
 
-      // "," also supported for compatibility
       String[] splits = nodeToLabels.split("=");
-      int index = 0;
-      if (splits.length != 2) {
-        splits = nodeToLabels.split(",");
-        index = 1;
-      }
-
+      int labelsStartIndex = 0;
       String nodeIdStr = splits[0];
-      if (index == 0) {
+
+      if (splits.length == 2) {
         splits = splits[1].split(",");
+      } else if (nodeToLabels.endsWith("=")) {
+        //case where no labels are mapped to a node
+        splits = new String[0];
+      } else {
+        // "," also supported for compatibility
+        splits = nodeToLabels.split(",");
+        nodeIdStr = splits[0];
+        labelsStartIndex = 1;
       }
-      
+
       Preconditions.checkArgument(!nodeIdStr.trim().isEmpty(),
           "node name cannot be empty");
 
       NodeId nodeId = ConverterUtils.toNodeIdWithDefaultPort(nodeIdStr);
       map.put(nodeId, new HashSet<String>());
 
-      for (int i = index; i < splits.length; i++) {
+      for (int i = labelsStartIndex; i < splits.length; i++) {
         if (!splits[i].trim().isEmpty()) {
           map.get(nodeId).add(splits[i].trim());
         }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c1afac3a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java
index 08e63ea..057594d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestRMAdminCLI.java
@@ -36,7 +36,9 @@ import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.PrintStream;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.ha.HAServiceProtocol;
@@ -145,7 +147,20 @@ public class TestRMAdminCLI {
   private void initDummyNodeLabelsManager() {
     Configuration conf = new YarnConfiguration();
     conf.setBoolean(YarnConfiguration.NODE_LABELS_ENABLED, true);
-    dummyNodeLabelsManager = new DummyCommonNodeLabelsManager();
+    dummyNodeLabelsManager = new DummyCommonNodeLabelsManager() {
+      @Override
+      public void replaceLabelsOnNode(
+          Map<NodeId, Set<String>> replaceLabelsToNode) throws IOException {
+        Iterator<NodeId> iterator = replaceLabelsToNode.keySet().iterator();
+        while(iterator.hasNext()) {
+          NodeId nodeId=iterator.next();
+          if(nodeId.getHost().endsWith("=")){
+            throw new IOException("Parsing of Input String failed");
+          }
+        }
+        super.replaceLabelsOnNode(replaceLabelsToNode);
+      }
+    };
     dummyNodeLabelsManager.init(conf);
   }
   
@@ -712,6 +727,21 @@ public class TestRMAdminCLI {
     assertTrue(0 != rmAdminCLI.run(args));
   }
 
+  @Test
+  public void testRemoveLabelsOnNodes() throws Exception {
+    // Successfully replace labels
+    dummyNodeLabelsManager
+        .addToCluserNodeLabelsWithDefaultExclusivity(ImmutableSet.of("x", "y"));
+    String[] args = { "-replaceLabelsOnNode", "node1=x node2=y",
+        "-directlyAccessNodeLabelStore" };
+    assertTrue(0 == rmAdminCLI.run(args));
+
+    args = new String[] { "-replaceLabelsOnNode", "node1= node2=",
+        "-directlyAccessNodeLabelStore" };
+    assertTrue("Labels should get replaced even '=' is used ",
+        0 == rmAdminCLI.run(args));
+  }
+
   private void testError(String[] args, String template,
       ByteArrayOutputStream data, int resultCode) throws Exception {
     int actualResultCode = rmAdminCLI.run(args);


[14/50] [abbrv] hadoop git commit: HDFS-9830. Remove references to hftp in ViewFs documentation in trunk. Contributed by Wei-Chiu Chuang.

Posted by ji...@apache.org.
HDFS-9830. Remove references to hftp in ViewFs documentation in trunk. Contributed by Wei-Chiu Chuang.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/c7ac25e5
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/c7ac25e5
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/c7ac25e5

Branch: refs/heads/HDFS-7240
Commit: c7ac25e52c307756c30157377fb52eced3aed5e4
Parents: bbfaf3c
Author: Akira Ajisaka <aa...@apache.org>
Authored: Fri Feb 19 05:02:09 2016 +0900
Committer: Akira Ajisaka <aa...@apache.org>
Committed: Fri Feb 19 05:02:57 2016 +0900

----------------------------------------------------------------------
 .../hadoop-common/src/site/markdown/FileSystemShell.md       | 2 +-
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt                  | 3 +++
 hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md  | 8 ++++----
 3 files changed, 8 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/c7ac25e5/hadoop-common-project/hadoop-common/src/site/markdown/FileSystemShell.md
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/site/markdown/FileSystemShell.md b/hadoop-common-project/hadoop-common/src/site/markdown/FileSystemShell.md
index ab66156..a356b8a 100644
--- a/hadoop-common-project/hadoop-common/src/site/markdown/FileSystemShell.md
+++ b/hadoop-common-project/hadoop-common/src/site/markdown/FileSystemShell.md
@@ -60,7 +60,7 @@
 Overview
 ========
 
-The File System (FS) shell includes various shell-like commands that directly interact with the Hadoop Distributed File System (HDFS) as well as other file systems that Hadoop supports, such as Local FS, HFTP FS, S3 FS, and others. The FS shell is invoked by:
+The File System (FS) shell includes various shell-like commands that directly interact with the Hadoop Distributed File System (HDFS) as well as other file systems that Hadoop supports, such as Local FS, WebHDFS, S3 FS, and others. The FS shell is invoked by:
 
     bin/hadoop fs <args>
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c7ac25e5/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index b6510b0..d54aa96 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -938,6 +938,9 @@ Trunk (Unreleased)
       HDFS-9787. SNNs stop uploading FSImage to ANN once isPrimaryCheckPointer
       changed to false. (Guocui Mi via vinayakumarb)
 
+      HDFS-9830. Remove references to hftp in ViewFs documentation in trunk.
+      (Wei-Chiu Chuang via aajisaka)
+
 Release 2.9.0 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c7ac25e5/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md
index ef5976c..067265a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ViewFs.md
@@ -75,9 +75,9 @@ Hence on Cluster X where the `core-site.xml` is set as above, the typical pathna
 
             distcp hdfs://namenodeClusterY:port/pathSrc hdfs://namenodeClusterZ:port/pathDest
 
-4.  `webhdfs://namenodeClusterX:http_port/foo/bar` and `hftp://namenodeClusterX:http_port/foo/bar`
+4.  `webhdfs://namenodeClusterX:http_port/foo/bar`
 
-    * These are file system URIs respectively for accessing files via the WebHDFS file system and the HFTP file system. Note that WebHDFS and HFTP use the HTTP port of the namenode but not the RPC port.
+    * It is an URI for accessing files via the WebHDFS file system. Note that WebHDFS uses the HTTP port of the namenode but not the RPC port.
 
 5.  `http://namenodeClusterX:http_port/webhdfs/v1/foo/bar` and `http://proxyClusterX:http_port/foo/bar`
 
@@ -133,9 +133,9 @@ Hence on Cluster X, where the `core-site.xml` is set to make the default fs to u
 
             distcp viewfs://clusterY:/pathSrc viewfs://clusterZ/pathDest
 
-4.  `viewfs://clusterX-webhdfs/foo/bar` and `viewfs://clusterX-hftp/foo/bar`
+4.  `viewfs://clusterX-webhdfs/foo/bar`
 
-    * These are URIs respectively for accessing files via the WebHDFS file system and the HFTP file system.
+    * It is an URI for accessing files via the WebHDFS file system.
 
 5.  `http://namenodeClusterX:http_port/webhdfs/v1/foo/bar` and `http://proxyClusterX:http_port/foo/bar`
 


[50/50] [abbrv] hadoop git commit: Merge changes from trunk

Posted by ji...@apache.org.
Merge changes from trunk


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/1b7df69d
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/1b7df69d
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/1b7df69d

Branch: refs/heads/HDFS-7240
Commit: 1b7df69d3774fa91eb9acfbea7667f2c9b538f2c
Parents: fac4633 def754e
Author: Jing Zhao <ji...@apache.org>
Authored: Wed Feb 24 11:55:15 2016 -0800
Committer: Jing Zhao <ji...@apache.org>
Committed: Wed Feb 24 11:55:15 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |  122 +-
 .../src/main/bin/hadoop-functions.sh            |    1 +
 .../hadoop-common/src/main/conf/hadoop-env.sh   |    6 +
 .../src/main/conf/ssl-server.xml.example        |   10 +
 .../org/apache/hadoop/conf/Reconfigurable.java  |    8 +-
 .../apache/hadoop/conf/ReconfigurableBase.java  |   47 +-
 .../hadoop/crypto/OpensslAesCtrCryptoCodec.java |    3 +
 .../org/apache/hadoop/crypto/key/KeyShell.java  |    2 +-
 .../crypto/key/kms/KMSClientProvider.java       |   14 +-
 .../java/org/apache/hadoop/fs/CanUnbuffer.java  |    2 +-
 .../java/org/apache/hadoop/fs/FileSystem.java   |   54 +-
 .../org/apache/hadoop/fs/FilterFileSystem.java  |    5 +-
 .../java/org/apache/hadoop/fs/TrashPolicy.java  |    2 +-
 .../apache/hadoop/fs/TrashPolicyDefault.java    |    9 +-
 .../org/apache/hadoop/fs/shell/AclCommands.java |   12 +-
 .../org/apache/hadoop/fs/shell/FsCommand.java   |    2 +-
 .../org/apache/hadoop/http/HttpServer2.java     |   12 +
 .../hadoop/io/compress/zlib/ZlibCompressor.java |   42 +-
 .../rawcoder/AbstractRawErasureDecoder.java     |   39 +-
 .../io/erasurecode/rawcoder/RSRawDecoder.java   |   11 +-
 .../io/erasurecode/rawcoder/RSRawDecoder2.java  |  176 +++
 .../io/erasurecode/rawcoder/RSRawEncoder2.java  |   76 +
 .../rawcoder/RSRawErasureCoderFactory2.java     |   37 +
 .../erasurecode/rawcoder/RawErasureCoder.java   |    2 +-
 .../io/erasurecode/rawcoder/util/CoderUtil.java |   83 ++
 .../io/erasurecode/rawcoder/util/DumpUtil.java  |   18 +-
 .../io/erasurecode/rawcoder/util/GF256.java     |  339 +++++
 .../io/erasurecode/rawcoder/util/RSUtil.java    |    2 +-
 .../io/erasurecode/rawcoder/util/RSUtil2.java   |  172 +++
 .../metrics2/sink/RollingFileSystemSink.java    |  409 ++++--
 .../hadoop/metrics2/source/JvmMetrics.java      |    2 +-
 .../net/NetworkTopologyWithNodeGroup.java       |    7 +-
 .../java/org/apache/hadoop/net/NodeBase.java    |    9 +-
 .../java/org/apache/hadoop/security/KDiag.java  |  976 +++++++++++++
 .../hadoop/security/UserGroupInformation.java   |   36 +-
 .../security/http/RestCsrfPreventionFilter.java |  218 ++-
 .../security/ssl/FileBasedKeyStoresFactory.java |    2 +
 .../apache/hadoop/security/ssl/SSLFactory.java  |    3 +-
 .../org/apache/hadoop/util/DataChecksum.java    |  147 +-
 .../org/apache/hadoop/util/JvmPauseMonitor.java |    2 +-
 .../org/apache/hadoop/util/StringUtils.java     |    1 +
 .../hadoop/util/concurrent/ExecutorHelper.java  |   67 +
 .../hadoop/util/concurrent/HadoopExecutors.java |   96 ++
 .../HadoopScheduledThreadPoolExecutor.java      |   71 +
 .../concurrent/HadoopThreadPoolExecutor.java    |   92 ++
 .../hadoop/util/concurrent/package-info.java    |   26 +
 .../src/main/resources/core-default.xml         |   15 +-
 ...he.hadoop.application-classloader.properties |    1 +
 .../src/site/markdown/CommandsManual.md         |   14 +-
 .../src/site/markdown/CredentialProviderAPI.md  |  133 ++
 .../src/site/markdown/FileSystemShell.md        |    2 +-
 .../hadoop-common/src/site/markdown/Metrics.md  |   27 +-
 .../src/site/markdown/SecureMode.md             |  198 +++
 .../apache/hadoop/conf/TestReconfiguration.java |  143 +-
 .../fs/contract/localfs/LocalFSContract.java    |    6 +-
 .../hadoop/fs/shell/TestCopyPreserveFlag.java   |    5 +-
 .../java/org/apache/hadoop/fs/shell/TestLs.java |    2 +-
 .../apache/hadoop/http/TestHttpCookieFlag.java  |    5 +-
 .../apache/hadoop/http/TestHttpServerLogs.java  |    2 +-
 .../apache/hadoop/http/TestSSLHttpServer.java   |  199 ++-
 .../zlib/TestZlibCompressorDecompressor.java    |   25 +
 .../hadoop/io/erasurecode/TestECSchema.java     |    6 +
 .../erasurecode/coder/TestRSErasureCoder.java   |    4 +
 .../io/erasurecode/coder/TestXORCoder.java      |    5 +
 .../io/erasurecode/rawcoder/TestRSRawCoder.java |   91 --
 .../erasurecode/rawcoder/TestRSRawCoder2.java   |   33 +
 .../rawcoder/TestRSRawCoderBase.java            |  109 +-
 .../erasurecode/rawcoder/TestXORRawCoder.java   |    1 -
 .../sink/RollingFileSystemSinkTestBase.java     |   87 +-
 .../net/TestNetworkTopologyWithNodeGroup.java   |   15 +-
 .../org/apache/hadoop/security/TestKDiag.java   |  226 +++
 .../apache/hadoop/security/TestKDiagNoKDC.java  |  123 ++
 .../security/TestUserGroupInformation.java      |    2 +-
 .../http/TestRestCsrfPreventionFilter.java      |   93 +-
 .../hadoop/security/ssl/KeyStoreTestUtil.java   |   81 +-
 .../hadoop/util/Crc32PerformanceTest.java       |  350 +++++
 .../apache/hadoop/util/TestDataChecksum.java    |    6 +
 .../apache/hadoop/security/secure-hdfs-site.xml |   26 +
 .../hadoop-kms/src/main/conf/kms-env.sh         |    4 +
 ...rKeyGeneratorKeyProviderCryptoExtension.java |   10 +
 .../key/kms/server/KMSExceptionsProvider.java   |    2 +
 .../hadoop/crypto/key/kms/server/KMSWebApp.java |    1 +
 .../hadoop-kms/src/main/libexec/kms-config.sh   |    1 +
 .../hadoop-kms/src/main/tomcat/server.xml       |    3 +-
 .../src/main/tomcat/ssl-server.xml.conf         |    1 +
 .../hadoop-kms/src/site/markdown/index.md.vm    |   78 +-
 .../hadoop/crypto/key/kms/server/TestKMS.java   |   21 +-
 .../main/java/org/apache/hadoop/fs/Hdfs.java    |  535 ++++++++
 .../java/org/apache/hadoop/fs/SWebHdfs.java     |   64 +
 .../main/java/org/apache/hadoop/fs/WebHdfs.java |   63 +
 .../main/java/org/apache/hadoop/fs/package.html |   26 +
 .../java/org/apache/hadoop/hdfs/DFSClient.java  |    1 +
 .../org/apache/hadoop/hdfs/DFSOutputStream.java |   28 +-
 .../hadoop/hdfs/DFSStripedInputStream.java      |    7 +-
 .../hadoop/hdfs/DFSStripedOutputStream.java     |  132 +-
 .../org/apache/hadoop/hdfs/DataStreamer.java    |   43 +-
 .../hadoop/hdfs/DistributedFileSystem.java      |   67 +-
 .../hdfs/client/HdfsClientConfigKeys.java       |   16 +
 .../hadoop/hdfs/client/impl/DfsClientConf.java  |   13 +
 .../hadoop/hdfs/protocol/HdfsConstants.java     |    2 +-
 .../hdfs/server/protocol/DatanodeStorage.java   |    1 +
 .../hadoop/hdfs/util/StripedBlockUtil.java      |   24 +
 .../hadoop/hdfs/web/WebHdfsFileSystem.java      |   65 +-
 ...onfRefreshTokenBasedAccessTokenProvider.java |    8 +-
 .../CredentialBasedAccessTokenProvider.java     |    8 +-
 .../src/main/proto/erasurecoding.proto          |    4 +-
 .../apache/hadoop/lib/servlet/ServerWebApp.java |   23 +-
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  222 ++-
 .../jdiff/Apache_Hadoop_HDFS_2.6.0.xml          |    2 +-
 hadoop-hdfs-project/hadoop-hdfs/pom.xml         |    4 +
 .../main/java/org/apache/hadoop/fs/Hdfs.java    |  535 --------
 .../java/org/apache/hadoop/fs/SWebHdfs.java     |   64 -
 .../main/java/org/apache/hadoop/fs/WebHdfs.java |   63 -
 .../main/java/org/apache/hadoop/fs/package.html |   26 -
 .../org/apache/hadoop/hdfs/DFSConfigKeys.java   |   36 +-
 .../java/org/apache/hadoop/hdfs/DFSUtil.java    |    4 +-
 .../java/org/apache/hadoop/hdfs/HAUtil.java     |   27 +
 .../apache/hadoop/hdfs/net/TcpPeerServer.java   |    6 +-
 .../DatanodeProtocolClientSideTranslatorPB.java |    5 +-
 .../apache/hadoop/hdfs/protocolPB/PBHelper.java |   95 +-
 .../hadoop/hdfs/server/balancer/Balancer.java   |   11 +-
 .../hdfs/server/blockmanagement/BlockInfo.java  |  202 +--
 .../blockmanagement/BlockInfoContiguous.java    |   29 +-
 .../blockmanagement/BlockInfoStriped.java       |   30 +-
 .../server/blockmanagement/BlockManager.java    |  651 +++++----
 .../BlockPlacementPolicyDefault.java            |   12 +-
 .../BlockPlacementPolicyRackFaultTolerant.java  |   10 +-
 .../BlockPlacementPolicyWithNodeGroup.java      |   46 +
 .../BlockPlacementStatusDefault.java            |   10 +-
 .../BlockPlacementStatusWithNodeGroup.java      |   81 ++
 .../BlockReconstructionWork.java                |  116 ++
 .../blockmanagement/BlockRecoveryWork.java      |  111 --
 .../BlockUnderConstructionFeature.java          |   25 +
 .../hdfs/server/blockmanagement/BlocksMap.java  |   75 +-
 .../CacheReplicationMonitor.java                |   27 +-
 .../blockmanagement/DatanodeDescriptor.java     |   13 +-
 .../server/blockmanagement/DatanodeManager.java |   21 +-
 .../blockmanagement/DatanodeStorageInfo.java    |  123 +-
 .../blockmanagement/ErasureCodingWork.java      |  111 +-
 .../PendingReplicationBlocks.java               |    9 +-
 .../server/blockmanagement/ReplicationWork.java |   11 +-
 .../hdfs/server/datanode/BPOfferService.java    |   54 +-
 .../hdfs/server/datanode/BPServiceActor.java    |  276 +---
 .../server/datanode/BlockPoolSliceStorage.java  |   56 +-
 .../server/datanode/BlockRecoveryWorker.java    |   12 +-
 .../hadoop/hdfs/server/datanode/DataNode.java   |  123 +-
 .../hdfs/server/datanode/DataStorage.java       |  187 ++-
 .../hdfs/server/datanode/DataXceiver.java       |    1 +
 .../hdfs/server/datanode/DataXceiverServer.java |    2 +-
 .../datanode/IncrementalBlockReportManager.java |  224 +++
 .../server/datanode/SecureDataNodeStarter.java  |    6 +-
 .../hdfs/server/datanode/VolumeScanner.java     |    7 +-
 .../erasurecode/ErasureCodingWorker.java        |  247 ++--
 .../AvailableSpaceVolumeChoosingPolicy.java     |   35 +-
 .../RoundRobinVolumeChoosingPolicy.java         |   53 +-
 .../datanode/fsdataset/impl/BlockPoolSlice.java |   29 +-
 .../datanode/fsdataset/impl/FsDatasetImpl.java  |   60 +-
 .../datanode/fsdataset/impl/FsVolumeImpl.java   |   69 +-
 .../datanode/fsdataset/impl/FsVolumeList.java   |   47 +-
 .../datanode/fsdataset/impl/ReplicaMap.java     |   71 +-
 .../server/datanode/web/DatanodeHttpServer.java |  113 +-
 .../web/PortUnificationServerHandler.java       |   18 +-
 .../web/RestCsrfPreventionFilterHandler.java    |  137 ++
 .../server/namenode/EncryptionZoneManager.java  |   73 +-
 .../hdfs/server/namenode/FSDirTruncateOp.java   |    8 +-
 .../hdfs/server/namenode/FSEditLogOp.java       |   41 +-
 .../hdfs/server/namenode/FSNamesystem.java      |   23 +-
 .../hadoop/hdfs/server/namenode/INode.java      |    6 +-
 .../hadoop/hdfs/server/namenode/INodeFile.java  |   40 +-
 .../hdfs/server/namenode/INodeReference.java    |    5 +-
 .../hadoop/hdfs/server/namenode/NameNode.java   |    3 +-
 .../server/namenode/NameNodeHttpServer.java     |   26 +-
 .../hadoop/hdfs/server/namenode/Namesystem.java |   23 -
 .../ha/RequestHedgingProxyProvider.java         |   41 +-
 .../server/namenode/ha/StandbyCheckpointer.java |    7 +-
 .../snapshot/DirectoryWithSnapshotFeature.java  |   11 +-
 .../snapshot/FileWithSnapshotFeature.java       |    2 +-
 .../top/window/RollingWindowManager.java        |    8 +-
 .../protocol/BlockECReconstructionCommand.java  |  148 ++
 .../server/protocol/BlockECRecoveryCommand.java |  147 --
 .../server/protocol/BlockReportContext.java     |   10 +-
 .../hdfs/server/protocol/DatanodeProtocol.java  |    3 +-
 .../org/apache/hadoop/hdfs/tools/DFSAdmin.java  |    2 +-
 .../tools/offlineImageViewer/FSImageLoader.java |   12 +-
 .../IgnoreSnapshotException.java                |   28 +
 .../PBImageDelimitedTextWriter.java             |   27 +-
 .../offlineImageViewer/PBImageTextWriter.java   |   90 +-
 .../apache/hadoop/hdfs/util/FoldedTreeSet.java  | 1285 +++++++++++++++++
 .../org/apache/hadoop/hdfs/web/AuthFilter.java  |   10 +-
 .../org/apache/hadoop/hdfs/web/JsonUtil.java    |   27 +-
 .../StorageContainerManager.java                |    5 +-
 .../StorageContainerNameService.java            |   21 -
 .../src/main/proto/DatanodeProtocol.proto       |   17 +-
 .../src/main/resources/hdfs-default.xml         |   89 +-
 .../src/main/webapps/datanode/index.html        |    2 +-
 .../src/main/webapps/hdfs/dfshealth.html        |    2 +-
 .../src/main/webapps/hdfs/explorer.html         |   18 +-
 .../src/main/webapps/hdfs/explorer.js           |   38 +
 .../src/main/webapps/journal/index.html         |    2 +-
 .../src/main/webapps/secondary/status.html      |    2 +-
 .../src/main/webapps/static/rest-csrf.js        |   91 ++
 .../src/site/markdown/HDFSCommands.md           |    2 +
 .../src/site/markdown/TransparentEncryption.md  |   64 +-
 .../hadoop-hdfs/src/site/markdown/ViewFs.md     |    8 +-
 .../hadoop-hdfs/src/site/markdown/WebHDFS.md    |   36 +
 .../apache/hadoop/cli/TestErasureCodingCLI.java |    6 +-
 .../org/apache/hadoop/hdfs/DFSTestUtil.java     |    2 +-
 .../hdfs/ErasureCodeBenchmarkThroughput.java    |   17 +-
 .../org/apache/hadoop/hdfs/MiniDFSCluster.java  |   22 +
 .../apache/hadoop/hdfs/StripedFileTestUtil.java |   13 +-
 .../TestClientProtocolForPipelineRecovery.java  |   60 +-
 .../hadoop/hdfs/TestDFSClientRetries.java       |    8 +-
 .../hadoop/hdfs/TestDFSStripedInputStream.java  |   35 +-
 .../hadoop/hdfs/TestDFSStripedOutputStream.java |    5 +
 .../TestDFSStripedOutputStreamWithFailure.java  |  119 +-
 .../apache/hadoop/hdfs/TestEncryptionZones.java |   60 +-
 .../TestErasureCodeBenchmarkThroughput.java     |    5 +
 .../TestErasureCodingPolicyWithSnapshot.java    |    8 +-
 .../org/apache/hadoop/hdfs/TestFileAppend.java  |   23 +-
 .../org/apache/hadoop/hdfs/TestFileAppend2.java |    8 -
 .../org/apache/hadoop/hdfs/TestFileAppend4.java |    5 -
 .../hadoop/hdfs/TestFileStatusWithECPolicy.java |    5 +
 .../org/apache/hadoop/hdfs/TestLargeBlock.java  |    5 -
 .../hadoop/hdfs/TestLeaseRecoveryStriped.java   |   58 +-
 .../hdfs/TestReadStripedFileWithDecoding.java   |   29 +-
 .../TestReadStripedFileWithMissingBlocks.java   |   55 +-
 .../hadoop/hdfs/TestReconstructStripedFile.java |  431 ++++++
 .../hadoop/hdfs/TestRecoverStripedFile.java     |  425 ------
 .../apache/hadoop/hdfs/TestRollingUpgrade.java  |    4 +-
 .../hdfs/TestSafeModeWithStripedFile.java       |    9 +-
 .../hadoop/hdfs/TestWriteReadStripedFile.java   |    5 +
 .../hdfs/TestWriteStripedFileWithFailure.java   |    7 +-
 .../apache/hadoop/hdfs/UpgradeUtilities.java    |   10 +
 .../hdfs/protocol/TestBlockListAsLongs.java     |    4 +-
 .../hadoop/hdfs/protocolPB/TestPBHelper.java    |   28 +-
 .../blockmanagement/BlockManagerTestUtil.java   |    2 +-
 .../server/blockmanagement/TestBlockInfo.java   |   88 --
 .../blockmanagement/TestBlockInfoStriped.java   |    5 +
 .../blockmanagement/TestBlockManager.java       |   75 +-
 .../TestBlockManagerSafeMode.java               |    8 +-
 .../TestBlockTokenWithDFSStriped.java           |    5 +
 .../TestBlocksWithNotEnoughRacks.java           |   12 +-
 .../blockmanagement/TestPendingReplication.java |    9 +-
 ...constructStripedBlocksWithRackAwareness.java |  213 +++
 .../TestReplicationPolicyWithNodeGroup.java     |  102 +-
 .../TestUnderReplicatedBlockQueues.java         |   55 +-
 .../server/datanode/SimulatedFSDataset.java     |    5 +-
 .../TestBlockHasMultipleReplicasOnSameDN.java   |   20 +-
 .../hdfs/server/datanode/TestBlockRecovery.java |   27 +-
 .../hdfs/server/datanode/TestBlockScanner.java  |    2 +-
 .../hdfs/server/datanode/TestDataNodeECN.java   |    6 +
 .../datanode/TestDataNodeHotSwapVolumes.java    |   47 +-
 .../server/datanode/TestDataNodeMXBean.java     |   55 +
 .../datanode/TestDataNodeVolumeFailure.java     |   25 +-
 .../TestDataNodeVolumeFailureReporting.java     |    9 +-
 ...TestDnRespectsBlockReportSplitThreshold.java |    4 +-
 .../datanode/TestIncrementalBlockReports.java   |   11 +-
 .../TestNNHandlesBlockReportPerStorage.java     |    3 +-
 .../TestNNHandlesCombinedBlockReport.java       |    2 +-
 .../server/datanode/TestTriggerBlockReport.java |   12 +-
 .../TestRoundRobinVolumeChoosingPolicy.java     |   56 +
 .../fsdataset/impl/TestFsDatasetImpl.java       |   33 +
 .../fsdataset/impl/TestFsVolumeList.java        |   42 +-
 .../hdfs/server/namenode/FSImageTestUtil.java   |   33 +-
 .../server/namenode/NNThroughputBenchmark.java  |   65 +-
 .../TestAddOverReplicatedStripedBlocks.java     |   16 +-
 .../server/namenode/TestAddStripedBlocks.java   |   46 +-
 .../server/namenode/TestCacheDirectives.java    |    7 +-
 .../hdfs/server/namenode/TestDeadDatanode.java  |    2 +-
 .../server/namenode/TestFSEditLogLoader.java    |    8 +-
 .../hdfs/server/namenode/TestFSImage.java       |   18 +-
 .../hadoop/hdfs/server/namenode/TestFsck.java   |   23 +-
 .../hdfs/server/namenode/TestINodeFile.java     |    3 +-
 .../namenode/TestNNThroughputBenchmark.java     |   72 +-
 .../TestNameNodeMetadataConsistency.java        |    2 +
 .../namenode/TestNestedEncryptionZones.java     |  215 +++
 .../namenode/TestQuotaWithStripedBlocks.java    |    5 +
 .../namenode/TestReconstructStripedBlocks.java  |  236 ++++
 .../namenode/TestRecoverStripedBlocks.java      |  238 ----
 .../server/namenode/TestStripedINodeFile.java   |    5 +
 .../server/namenode/ha/TestHAConfiguration.java |   23 +
 .../namenode/ha/TestStandbyCheckpoints.java     |   42 +
 .../namenode/snapshot/TestSnapshotDeletion.java |   95 +-
 .../shortcircuit/TestShortCircuitLocalRead.java |   73 +-
 .../TestOfflineImageViewer.java                 |   36 +-
 .../TestOfflineImageViewerForAcl.java           |   36 +
 .../hadoop/hdfs/util/FoldedTreeSetTest.java     |  644 +++++++++
 .../hadoop/hdfs/util/TestStripedBlockUtil.java  |    5 +
 .../apache/hadoop/hdfs/web/TestAuthFilter.java  |   15 +
 ...TestWebHdfsWithRestCsrfPreventionFilter.java |  166 +++
 .../sink/TestRollingFileSystemSinkWithHdfs.java |  286 ++++
 ...TestRollingFileSystemSinkWithSecureHdfs.java |  283 ++++
 .../src/test/resources/testCryptoConf.xml       |    8 +-
 .../test/resources/testErasureCodingConf.xml    |    4 +-
 hadoop-mapreduce-project/CHANGES.txt            |   62 +-
 .../hadoop/mapred/LocalContainerLauncher.java   |    4 +-
 .../jobhistory/JobHistoryEventHandler.java      |    6 +-
 .../v2/app/commit/CommitterEventHandler.java    |    3 +-
 .../mapreduce/v2/app/job/impl/JobImpl.java      |    3 +-
 .../v2/app/launcher/ContainerLauncherImpl.java  |    3 +-
 .../mapred/LocalDistributedCacheManager.java    |    5 +-
 .../apache/hadoop/mapred/LocalJobRunner.java    |    8 +-
 .../mapreduce/v2/jobhistory/JHAdminConfig.java  |    2 +-
 .../hadoop-mapreduce-client-core/pom.xml        |    5 +
 .../org/apache/hadoop/mapred/JobClient.java     |    8 +
 .../hadoop/mapred/LocatedFileStatusFetcher.java |    4 +-
 .../java/org/apache/hadoop/mapred/TaskLog.java  |   31 +-
 .../mapred/lib/MultithreadedMapRunner.java      |    4 +-
 .../apache/hadoop/mapreduce/JobSubmitter.java   |    7 +-
 .../mapreduce/jobhistory/HistoryViewer.java     |  480 +------
 .../jobhistory/HistoryViewerPrinter.java        |   39 +
 .../HumanReadableHistoryViewerPrinter.java      |  471 +++++++
 .../jobhistory/JSONHistoryViewerPrinter.java    |  256 ++++
 .../lib/input/UncompressedSplitLineReader.java  |    7 +-
 .../org/apache/hadoop/mapreduce/tools/CLI.java  |   79 +-
 .../src/main/resources/mapred-default.xml       |    2 +-
 .../src/site/markdown/EncryptedShuffle.md       |    2 +-
 .../src/site/markdown/MapReduceTutorial.md      |    6 +-
 .../src/site/markdown/MapredCommands.md         |    4 +-
 .../hadoop/mapred/TestFileInputFormat.java      |    2 +-
 .../hadoop/mapred/TestLineRecordReader.java     |   53 +
 .../jobhistory/TestHistoryViewerPrinter.java    |  945 +++++++++++++
 .../lib/input/TestFileInputFormat.java          |    2 +-
 .../lib/output/TestFileOutputCommitter.java     |    4 +-
 .../mapreduce/v2/hs/HistoryFileManager.java     |    6 +-
 .../hadoop/mapreduce/v2/hs/JobHistory.java      |    3 +-
 .../mapreduce/v2/hs/webapp/HsJobBlock.java      |    2 +-
 .../mapreduce/v2/hs/webapp/HsJobsBlock.java     |    2 +-
 .../mapreduce/v2/hs/webapp/dao/JobInfo.java     |   12 +
 .../mapreduce/v2/hs/webapp/dao/TestJobInfo.java |   26 +-
 .../hadoop/mapred/ResourceMgrDelegate.java      |    7 +
 .../hadoop/mapred/TestClientRedirect.java       |    8 +
 .../hadoop/mapreduce/TestMRJobClient.java       |  160 ++-
 .../mapreduce/TimelineServicePerformance.java   |    2 +-
 .../apache/hadoop/mapred/ShuffleHandler.java    |    6 +-
 .../org/apache/hadoop/examples/pi/Util.java     |    5 +-
 hadoop-project/pom.xml                          |   13 +-
 hadoop-project/src/site/site.xml                |    2 +
 .../org/apache/hadoop/fs/s3a/Constants.java     |    3 +
 .../org/apache/hadoop/fs/s3a/S3AFileSystem.java |  267 ++--
 .../src/site/markdown/tools/hadoop-aws/index.md |   54 +
 .../hadoop/fs/s3a/TestS3AConfiguration.java     |  151 +-
 .../hadoop/fs/s3a/scale/S3AScaleTestBase.java   |   11 +-
 .../fs/s3a/scale/TestS3ADeleteManyFiles.java    |    2 +-
 .../fs/azure/AzureNativeFileSystemStore.java    |   30 +
 .../hadoop/fs/azure/NativeAzureFileSystem.java  |    8 +-
 .../hadoop/fs/azure/NativeFileSystemStore.java  |    2 +
 .../hadoop/fs/azure/SimpleKeyProvider.java      |   16 +-
 .../hadoop-azure/src/site/markdown/index.md     |   52 +-
 .../hadoop/fs/azure/MockStorageInterface.java   |   33 +-
 .../fs/azure/NativeAzureFileSystemBaseTest.java |   67 +
 .../fs/azure/TestWasbUriAndConfiguration.java   |   45 +-
 .../org/apache/hadoop/tools/DistCpOptions.java  |   10 +-
 .../apache/hadoop/tools/TestOptionsParser.java  |   15 +-
 hadoop-tools/hadoop-kafka/pom.xml               |    2 -
 hadoop-yarn-project/CHANGES.txt                 |  121 +-
 .../yarn/api/ApplicationClientProtocol.java     |   49 +-
 .../protocolrecords/ReservationListRequest.java |  228 +++
 .../ReservationListResponse.java                |   79 ++
 .../hadoop/yarn/api/records/ReservationACL.java |   56 +
 .../api/records/ReservationAllocationState.java |  191 +++
 .../api/records/ResourceAllocationRequest.java  |  123 ++
 .../hadoop/yarn/conf/YarnConfiguration.java     |    5 +
 .../main/proto/applicationclient_protocol.proto |    1 +
 .../src/main/proto/yarn_protos.proto            |   17 +
 .../src/main/proto/yarn_service_protos.proto    |   12 +
 .../applications/distributedshell/Client.java   |    3 +-
 .../hadoop/yarn/client/api/YarnClient.java      |   49 +-
 .../yarn/client/api/impl/AMRMClientImpl.java    |    1 +
 .../yarn/client/api/impl/YarnClientImpl.java    |   10 +-
 .../hadoop/yarn/client/cli/RMAdminCLI.java      |   25 +-
 .../apache/hadoop/yarn/client/cli/TopCLI.java   |   18 +-
 .../yarn/client/util/YarnClientUtils.java       |  113 ++
 .../hadoop/yarn/client/util/package-info.java   |   20 +
 .../yarn/client/api/impl/TestYarnClient.java    |  173 +++
 .../hadoop/yarn/client/cli/TestRMAdminCLI.java  |   32 +-
 .../hadoop/yarn/client/cli/TestYarnCLI.java     |    9 +-
 .../yarn/client/util/TestYarnClientUtils.java   |  319 +++++
 .../ApplicationClientProtocolPBClientImpl.java  |   17 +
 .../ApplicationClientProtocolPBServiceImpl.java |   24 +-
 .../impl/pb/ReservationListRequestPBImpl.java   |  178 +++
 .../impl/pb/ReservationListResponsePBImpl.java  |  157 +++
 .../pb/ReservationAllocationStatePBImpl.java    |  288 ++++
 .../pb/ResourceAllocationRequestPBImpl.java     |  188 +++
 .../RequestHedgingRMFailoverProxyProvider.java  |    4 +-
 .../hadoop/yarn/webapp/hamlet/Hamlet.java       |   11 +-
 .../hadoop/yarn/webapp/util/WebAppUtils.java    |    4 +-
 .../src/main/resources/yarn-default.xml         |   56 +-
 .../hadoop/yarn/api/TestPBImplRecords.java      |   22 +-
 .../apache/hadoop/yarn/util/TestFSDownload.java |   15 +-
 .../yarn/webapp/WebServicesTestUtils.java       |   28 +
 .../server/services/RegistryAdminService.java   |    4 +-
 .../hadoop/yarn/server/nodemanager/Context.java |    2 +
 .../server/nodemanager/DeletionService.java     |   35 +-
 .../yarn/server/nodemanager/NodeManager.java    |   10 +
 .../containermanager/ContainerManagerImpl.java  |   26 +-
 .../container/ContainerImpl.java                |   25 +-
 .../launcher/ContainersLauncher.java            |    4 +-
 .../localizer/ContainerLocalizer.java           |    4 +-
 .../localizer/ResourceLocalizationService.java  |    8 +-
 .../sharedcache/SharedCacheUploadService.java   |    4 +-
 .../logaggregation/LogAggregationService.java   |    4 +-
 .../loghandler/NonAggregatingLogHandler.java    |    3 +-
 .../recovery/NMLeveldbStateStoreService.java    |   44 +
 .../recovery/NMStateStoreService.java           |   11 +
 .../nodemanager/webapp/dao/ContainerInfo.java   |    1 -
 .../impl/container-executor.c                   |  231 ++--
 .../test/test-container-executor.c              |   10 +-
 .../yarn/server/nodemanager/TestEventFlow.java  |    1 +
 .../nodemanager/TestNodeStatusUpdater.java      |   31 +-
 .../amrmproxy/BaseAMRMProxyTest.java            |    5 +
 .../amrmproxy/MockResourceManagerFacade.java    |   14 +-
 .../BaseContainerManagerTest.java               |    1 +
 .../containermanager/TestAuxServices.java       |    7 +-
 .../container/TestContainer.java                |   16 +-
 .../nodemanager/webapp/TestNMWebServer.java     |    5 +-
 .../webapp/TestNMWebServicesContainers.java     |   39 +-
 .../server/resourcemanager/AdminService.java    |    6 +-
 .../server/resourcemanager/ClientRMService.java |  158 ++-
 .../resourcemanager/NodesListManager.java       |  122 +-
 .../server/resourcemanager/RMAuditLogger.java   |    2 +
 .../server/resourcemanager/ResourceManager.java |    5 +
 .../blacklist/SimpleBlacklistManager.java       |    9 +-
 .../recovery/FileSystemRMStateStore.java        |    2 +-
 .../recovery/LeveldbRMStateStore.java           |    2 +-
 .../recovery/MemoryRMStateStore.java            |    2 +-
 .../recovery/NullRMStateStore.java              |    2 +-
 .../resourcemanager/recovery/RMStateStore.java  |    2 +-
 .../RMStateStoreStoreReservationEvent.java      |    2 +-
 .../recovery/ZKRMStateStore.java                |    2 +-
 .../reservation/AbstractReservationSystem.java  |   16 +-
 .../reservation/CapacityOverTimePolicy.java     |   18 +-
 .../reservation/InMemoryPlan.java               |   77 +-
 .../resourcemanager/reservation/PlanView.java   |   31 +
 .../reservation/ReservationInputValidator.java  |  122 +-
 .../ReservationSchedulerConfiguration.java      |   15 +
 .../reservation/ReservationSystem.java          |    9 +
 .../reservation/ReservationSystemUtil.java      |   45 +-
 .../planning/AlignedPlannerWithGreedy.java      |    4 +-
 .../planning/GreedyReservationAgent.java        |   40 +-
 .../reservation/planning/IterativePlanner.java  |  239 +++-
 .../planning/StageAllocatorGreedyRLE.java       |  245 ++++
 .../rmapp/attempt/RMAppAttempt.java             |    6 +
 .../rmapp/attempt/RMAppAttemptImpl.java         |   17 +
 .../rmcontainer/AllocationExpirationInfo.java   |   75 +
 .../rmcontainer/ContainerAllocationExpirer.java |   11 +-
 .../rmcontainer/RMContainer.java                |    2 +
 .../rmcontainer/RMContainerImpl.java            |  132 +-
 .../RMContainerNMDoneChangeResourceEvent.java   |   37 +
 .../resourcemanager/rmnode/RMNodeImpl.java      |   61 +-
 .../scheduler/AbstractYarnScheduler.java        |   56 +-
 .../scheduler/capacity/CapacityScheduler.java   |   59 +-
 .../CapacitySchedulerConfiguration.java         |   38 +
 .../event/ContainerExpiredSchedulerEvent.java   |   12 +-
 .../scheduler/fair/AllocationConfiguration.java |   20 +-
 .../fair/AllocationFileLoaderService.java       |   28 +-
 .../scheduler/fair/FSAppAttempt.java            |    7 +-
 .../scheduler/fair/FSParentQueue.java           |    6 +-
 .../scheduler/fair/FairScheduler.java           |   15 +
 .../scheduler/fifo/FifoScheduler.java           |   16 +
 .../security/ReservationsACLsManager.java       |   92 ++
 .../webapp/RMAppAttemptBlock.java               |   46 +-
 .../resourcemanager/webapp/RMAppBlock.java      |   32 +-
 .../resourcemanager/webapp/RMAppsBlock.java     |    5 +-
 .../resourcemanager/webapp/RMWebServices.java   |   97 +-
 .../webapp/dao/AMBlackListingRequestInfo.java   |   61 +
 .../webapp/dao/AppAttemptInfo.java              |    5 +
 .../dao/ApplicationSubmissionContextInfo.java   |   51 +
 .../webapp/dao/LogAggregationContextInfo.java   |  108 ++
 .../webapp/dao/ReservationDefinitionInfo.java   |   10 +
 .../webapp/dao/ReservationIdInfo.java           |   64 +
 .../webapp/dao/ReservationInfo.java             |  105 ++
 .../webapp/dao/ReservationListInfo.java         |   53 +
 .../webapp/dao/ReservationRequestInfo.java      |    9 +
 .../webapp/dao/ReservationRequestsInfo.java     |   11 +
 .../webapp/dao/ResourceAllocationInfo.java      |   72 +
 .../yarn_server_resourcemanager_recovery.proto  |   16 -
 .../server/resourcemanager/ACLsTestBase.java    |  123 ++
 .../server/resourcemanager/Application.java     |   10 +-
 .../yarn/server/resourcemanager/MockNM.java     |   20 +
 .../yarn/server/resourcemanager/MockRM.java     |   16 +
 .../resourcemanager/QueueACLsTestBase.java      |   87 +-
 .../ReservationACLsTestBase.java                |  600 ++++++++
 .../resourcemanager/TestClientRMService.java    |  179 +++
 .../resourcemanager/TestRMAdminService.java     |   35 +-
 .../resourcemanager/TestRMNodeTransitions.java  |   52 +-
 .../server/resourcemanager/TestRMRestart.java   |   11 +-
 .../TestReservationSystemWithRMHA.java          |    2 +-
 .../TestResourceTrackerService.java             |  189 ++-
 .../recovery/RMStateStoreTestBase.java          |    6 +-
 .../reservation/ReservationSystemTestUtil.java  |   19 +-
 .../reservation/TestInMemoryPlan.java           |  314 +++--
 .../TestReservationInputValidator.java          |  103 +-
 .../reservation/TestReservationSystemUtil.java  |  134 ++
 .../planning/TestGreedyReservationAgent.java    |  120 +-
 .../rmcontainer/TestRMContainerImpl.java        |  112 +-
 .../capacity/TestCapacityScheduler.java         |   89 +-
 .../capacity/TestContainerResizing.java         |   44 +-
 .../capacity/TestIncreaseAllocationExpirer.java |  443 ++++++
 .../scheduler/capacity/TestUtils.java           |   15 +-
 .../scheduler/fair/TestFSLeafQueue.java         |    4 +-
 .../scheduler/fair/TestFairScheduler.java       | 1295 ++----------------
 .../fair/TestFairSchedulerPreemption.java       | 1295 +++++++++++++++++-
 .../scheduler/fifo/TestFifoScheduler.java       |  107 +-
 .../webapp/TestRMWebServicesApps.java           |    2 +-
 .../TestRMWebServicesAppsModification.java      |   74 +-
 .../webapp/TestRMWebServicesReservation.java    |  542 +++++++-
 .../src/test/resources/submit-reservation.json  |    6 +-
 .../sharedcachemanager/CleanerService.java      |    4 +-
 .../store/InMemorySCMStore.java                 |    4 +-
 .../store/TestInMemorySCMStore.java             |    7 +-
 .../src/site/markdown/FairScheduler.md          |    2 +-
 .../src/site/markdown/NodeLabel.md              |   86 +-
 .../src/site/markdown/ResourceManagerRest.md    |   54 +-
 .../src/site/markdown/SecureContainer.md        |    2 +-
 .../src/site/markdown/TimelineServer.md         |   13 +-
 .../site/markdown/YarnApplicationSecurity.md    |  560 ++++++++
 .../src/site/markdown/YarnCommands.md           |    3 +
 518 files changed, 27880 insertions(+), 7250 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/pom.xml
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelper.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockInfoContiguous.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlocksMap.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlocksMap.java
index 753fee7,f7cde90..4d3bff6
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlocksMap.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlocksMap.java
@@@ -35,50 -30,14 +35,19 @@@ import java.util.Iterator
   * block's metadata currently includes blockCollection it belongs to and
   * the datanodes that store the block.
   */
 -class BlocksMap {
 +public class BlocksMap {
-   private static class StorageIterator implements Iterator<DatanodeStorageInfo> {
-     private final BlockInfo blockInfo;
-     private int nextIdx = 0;
-       
-     StorageIterator(BlockInfo blkInfo) {
-       this.blockInfo = blkInfo;
-     }
- 
-     @Override
-     public boolean hasNext() {
-       if (blockInfo == null) {
-         return false;
-       }
-       while (nextIdx < blockInfo.getCapacity() &&
-           blockInfo.getDatanode(nextIdx) == null) {
-         // note that for striped blocks there may be null in the triplets
-         nextIdx++;
-       }
-       return nextIdx < blockInfo.getCapacity();
-     }
- 
-     @Override
-     public DatanodeStorageInfo next() {
-       return blockInfo.getStorageInfo(nextIdx++);
-     }
- 
-     @Override
-     public void remove()  {
-       throw new UnsupportedOperationException("Sorry. can't remove.");
-     }
-   }
  
    /** Constant {@link LightWeightGSet} capacity. */
    private final int capacity;
    
    private GSet<Block, BlockInfo> blocks;
  
 -  BlocksMap(int capacity) {
 +  public BlocksMap(int capacity, GSet<Block, BlockInfo> b) {
 +    this.capacity = capacity;
 +    this.blocks = b;
 +  }
 +
-   BlocksMap(int capacity) {
++  public BlocksMap(int capacity) {
      // Use 2% of total memory to size the GSet capacity
      this.capacity = capacity;
      this.blocks = new LightWeightGSet<Block, BlockInfo>(capacity) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeStorageInfo.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeStorageInfo.java
index a8f3674,c4729ea..1096cb1
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeStorageInfo.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeStorageInfo.java
@@@ -29,7 -27,9 +29,8 @@@ import org.apache.hadoop.hdfs.protocol.
  import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
  import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage.State;
  import org.apache.hadoop.hdfs.server.protocol.StorageReport;
+ import org.apache.hadoop.hdfs.util.FoldedTreeSet;
  
 -import com.google.common.annotations.VisibleForTesting;
  
  /**
   * A Datanode has one or more storages. A storage in the Datanode is represented

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPOfferService.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPOfferService.java
index 3e4dc65,cc536d3..e2d46c5
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPOfferService.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPOfferService.java
@@@ -30,9 -30,8 +30,9 @@@ import org.apache.hadoop.hdfs.protocol.
  import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
  import org.apache.hadoop.hdfs.protocol.RollingUpgradeStatus;
  import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB;
 +import org.apache.hadoop.hdfs.server.datanode.dataset.DatasetSpi;
  import org.apache.hadoop.hdfs.server.protocol.*;
- import org.apache.hadoop.hdfs.server.protocol.BlockECRecoveryCommand.BlockECRecoveryInfo;
+ import org.apache.hadoop.hdfs.server.protocol.BlockECReconstructionCommand.BlockECReconstructionInfo;
  import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo.BlockStatus;
  
  import org.slf4j.Logger;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPServiceActor.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPServiceActor.java
index a85e29d,4b987b0..b7c5260
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPServiceActor.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BPServiceActor.java
@@@ -98,23 -92,8 +95,9 @@@ class BPServiceActor implements Runnabl
    }
  
    private volatile RunningState runningState = RunningState.CONNECTING;
- 
-   /**
-    * Between block reports (which happen on the order of once an hour) the
-    * DN reports smaller incremental changes to its block list. This map,
-    * keyed by block ID, contains the pending changes which have yet to be
-    * reported to the NN. Access should be synchronized on this object.
-    */
-   private final Map<DatanodeStorage, PerStoragePendingIncrementalBR>
-       pendingIncrementalBRperStorage = Maps.newHashMap();
- 
-   // IBR = Incremental Block Report. If this flag is set then an IBR will be
-   // sent immediately by the actor thread without waiting for the IBR timer
-   // to elapse.
-   private volatile boolean sendImmediateIBR = false;
    private volatile boolean shouldServiceRun = true;
    private final DataNode dn;
 +  private DatasetSpi<? extends VolumeSpi> dataset = null;
    private final DNConf dnConf;
    private long prevBlockReportId;
  
@@@ -235,129 -221,8 +225,7 @@@
      register(nsInfo);
    }
  
 -
    /**
-    * Report received blocks and delete hints to the Namenode for each
-    * storage.
-    *
-    * @throws IOException
-    */
-   private void reportReceivedDeletedBlocks() throws IOException {
- 
-     // Generate a list of the pending reports for each storage under the lock
-     ArrayList<StorageReceivedDeletedBlocks> reports =
-         new ArrayList<StorageReceivedDeletedBlocks>(pendingIncrementalBRperStorage.size());
-     synchronized (pendingIncrementalBRperStorage) {
-       for (Map.Entry<DatanodeStorage, PerStoragePendingIncrementalBR> entry :
-            pendingIncrementalBRperStorage.entrySet()) {
-         final DatanodeStorage storage = entry.getKey();
-         final PerStoragePendingIncrementalBR perStorageMap = entry.getValue();
- 
-         if (perStorageMap.getBlockInfoCount() > 0) {
-           // Send newly-received and deleted blockids to namenode
-           ReceivedDeletedBlockInfo[] rdbi = perStorageMap.dequeueBlockInfos();
-           reports.add(new StorageReceivedDeletedBlocks(storage, rdbi));
-         }
-       }
-       sendImmediateIBR = false;
-     }
- 
-     if (reports.size() == 0) {
-       // Nothing new to report.
-       return;
-     }
- 
-     // Send incremental block reports to the Namenode outside the lock
-     boolean success = false;
-     final long startTime = monotonicNow();
-     try {
-       bpNamenode.blockReceivedAndDeleted(bpRegistration,
-           bpos.getBlockPoolId(),
-           reports.toArray(new StorageReceivedDeletedBlocks[reports.size()]));
-       success = true;
-     } finally {
-       dn.getMetrics().addIncrementalBlockReport(monotonicNow() - startTime);
-       if (!success) {
-         synchronized (pendingIncrementalBRperStorage) {
-           for (StorageReceivedDeletedBlocks report : reports) {
-             // If we didn't succeed in sending the report, put all of the
-             // blocks back onto our queue, but only in the case where we
-             // didn't put something newer in the meantime.
-             PerStoragePendingIncrementalBR perStorageMap =
-                 pendingIncrementalBRperStorage.get(report.getStorage());
-             perStorageMap.putMissingBlockInfos(report.getBlocks());
-             sendImmediateIBR = true;
-           }
-         }
-       }
-     }
-   }
- 
-   /**
-    * @return pending incremental block report for given {@code storage}
-    */
-   private PerStoragePendingIncrementalBR getIncrementalBRMapForStorage(
-       DatanodeStorage storage) {
-     PerStoragePendingIncrementalBR mapForStorage =
-         pendingIncrementalBRperStorage.get(storage);
- 
-     if (mapForStorage == null) {
-       // This is the first time we are adding incremental BR state for
-       // this storage so create a new map. This is required once per
-       // storage, per service actor.
-       mapForStorage = new PerStoragePendingIncrementalBR();
-       pendingIncrementalBRperStorage.put(storage, mapForStorage);
-     }
- 
-     return mapForStorage;
-   }
- 
-   /**
-    * Add a blockInfo for notification to NameNode. If another entry
-    * exists for the same block it is removed.
-    *
-    * Caller must synchronize access using pendingIncrementalBRperStorage.
-    */
-   void addPendingReplicationBlockInfo(ReceivedDeletedBlockInfo bInfo,
-       DatanodeStorage storage) {
-     // Make sure another entry for the same block is first removed.
-     // There may only be one such entry.
-     for (Map.Entry<DatanodeStorage, PerStoragePendingIncrementalBR> entry :
-           pendingIncrementalBRperStorage.entrySet()) {
-       if (entry.getValue().removeBlockInfo(bInfo)) {
-         break;
-       }
-     }
-     getIncrementalBRMapForStorage(storage).putBlockInfo(bInfo);
-   }
- 
-   /*
-    * Informing the name node could take a long long time! Should we wait
-    * till namenode is informed before responding with success to the
-    * client? For now we don't.
-    */
-   void notifyNamenodeBlock(ReceivedDeletedBlockInfo bInfo,
-       String storageUuid, boolean now) {
-     synchronized (pendingIncrementalBRperStorage) {
-       addPendingReplicationBlockInfo(
-           bInfo, dataset.getStorage(storageUuid));
-       sendImmediateIBR = true;
-       // If now is true, the report is sent right away.
-       // Otherwise, it will be sent out in the next heartbeat.
-       if (now) {
-         pendingIncrementalBRperStorage.notifyAll();
-       }
-     }
-   }
- 
-   void notifyNamenodeDeletedBlock(
-       ReceivedDeletedBlockInfo bInfo, String storageUuid) {
-     synchronized (pendingIncrementalBRperStorage) {
-       addPendingReplicationBlockInfo(
-           bInfo, dataset.getStorage(storageUuid));
-     }
-   }
- 
-   /**
     * Run an immediate block report on this thread. Used by tests.
     */
    @VisibleForTesting

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
index 044def6,aed3eaa..f4f5342
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataNode.java
@@@ -48,9 -48,9 +48,11 @@@ import static org.apache.hadoop.hdfs.DF
  import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_MAX_NUM_BLOCKS_TO_LOG_KEY;
  import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_METRICS_LOGGER_PERIOD_SECONDS_DEFAULT;
  import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_METRICS_LOGGER_PERIOD_SECONDS_KEY;
 +import static org.apache.hadoop.ozone.OzoneConfigKeys.DFS_OBJECTSTORE_ENABLED_DEFAULT;
 +import static org.apache.hadoop.ozone.OzoneConfigKeys.DFS_OBJECTSTORE_ENABLED_KEY;
  import static org.apache.hadoop.util.ExitUtil.terminate;
+ 
+ import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
  import org.apache.hadoop.hdfs.protocol.proto.ReconfigurationProtocolProtos.ReconfigurationProtocolService;
  
  import java.io.BufferedOutputStream;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
index bf4831c,6697054..1fba200
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
@@@ -325,10 -327,10 +327,10 @@@ public class DataStorage extends Storag
      }
  
      StorageDirectory sd = loadStorageDirectory(
-         datanode, nsInfos.iterator().next(), volume, StartupOption.HOTSWAP);
 -        datanode, nsInfos.get(0), volume, StartupOption.HOTSWAP, null);
++        datanode, nsInfos.iterator().next(), volume, StartupOption.HOTSWAP, null);
      VolumeBuilder builder =
          new VolumeBuilder(this, sd);
 -    for (NamespaceInfo nsInfo : nsInfos) {
 +    for (final NamespaceInfo nsInfo : nsInfos) {
        List<File> bpDataDirs = Lists.newArrayList();
        bpDataDirs.add(BlockPoolSliceStorage.getBpRoot(
            nsInfo.getBlockPoolID(), new File(volume, STORAGE_DIR_CURRENT)));

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiver.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/VolumeScanner.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
index fa127c9,d1cb836..67ca784
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java
@@@ -453,17 -471,9 +469,9 @@@ class FsDatasetImpl implements FsDatase
      final FsVolumeReference ref = fsVolume.obtainReference();
      setupAsyncLazyPersistThread(fsVolume);
  
-     synchronized (this) {
-       volumeMap.addAll(tempVolumeMap);
-       storageMap.put(sd.getStorageUuid(),
-           new DatanodeStorage(sd.getStorageUuid(),
-               DatanodeStorage.State.NORMAL,
-               storageType));
-       asyncDiskService.addVolume(sd.getCurrentDir());
-       volumes.addVolume(ref);
-     }
 -    builder.build();
+     activateVolume(tempVolumeMap, sd, storageType, ref);
 -    LOG.info("Added volume - " + dir + ", StorageType: " + storageType);
 +    LOG.info("Added volume - " + location.getFile() +
 +                 ", StorageType: " + storageType);
    }
  
    /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
index a3b7dec,f9bdbf6..fd6f564
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
@@@ -46,8 -54,8 +55,9 @@@ import org.apache.hadoop.hdfs.server.da
  import org.apache.hadoop.http.HttpConfig;
  import org.apache.hadoop.http.HttpServer2;
  import org.apache.hadoop.net.NetUtils;
 +import org.apache.hadoop.ozone.web.netty.ObjectStoreJerseyContainer;
  import org.apache.hadoop.security.authorize.AccessControlList;
+ import org.apache.hadoop.security.http.RestCsrfPreventionFilter;
  import org.apache.hadoop.security.ssl.SSLFactory;
  
  import java.io.Closeable;
@@@ -81,17 -90,11 +92,18 @@@ public class DatanodeHttpServer impleme
  
    public DatanodeHttpServer(final Configuration conf,
        final DataNode datanode,
 -      final ServerSocketChannel externalHttpChannel)
 -    throws IOException {
 +      final ServerSocketChannel externalHttpChannel,
 +      final ObjectStoreHandler objectStoreHandler) throws IOException {
+     this.restCsrfPreventionFilter = createRestCsrfPreventionFilter(conf);
      this.conf = conf;
  
 +    final ObjectStoreJerseyContainer finalContainer;
 +    if (objectStoreHandler != null) {
 +      finalContainer = objectStoreHandler.getObjectStoreJerseyContainer();
 +    } else {
 +      finalContainer = null;
 +    }
 +
      Configuration confForInfoServer = new Configuration(conf);
      confForInfoServer.setInt(HttpServer2.HTTP_MAX_THREADS, 10);
      HttpServer2.Builder builder = new HttpServer2.Builder()
@@@ -126,8 -129,7 +138,8 @@@
          @Override
          protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new PortUnificationServerHandler(jettyAddr,
 -              conf, confForCreate, restCsrfPreventionFilter));
 +              conf, confForCreate,
-               finalContainer));
++              finalContainer, restCsrfPreventionFilter));
          }
        });
  
@@@ -175,12 -177,16 +187,16 @@@
            protected void initChannel(SocketChannel ch) throws Exception {
              ChannelPipeline p = ch.pipeline();
              p.addLast(
-               new SslHandler(sslFactory.createSSLEngine()),
-               new HttpRequestDecoder(),
-               new HttpResponseEncoder(),
-               new ChunkedWriteHandler(),
-               new URLDispatcher(jettyAddr, conf, confForCreate,
-                   finalContainer));
+                 new SslHandler(sslFactory.createSSLEngine()),
+                 new HttpRequestDecoder(),
+                 new HttpResponseEncoder());
+             if (restCsrfPreventionFilter != null) {
+               p.addLast(new RestCsrfPreventionFilterHandler(
+                   restCsrfPreventionFilter));
+             }
+             p.addLast(
+                 new ChunkedWriteHandler(),
 -                new URLDispatcher(jettyAddr, conf, confForCreate));
++                new URLDispatcher(jettyAddr, conf, confForCreate, finalContainer));
            }
          });
      } else {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
index bb5cd57,ff10c6d..a6f3cbf
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
@@@ -53,21 -52,25 +54,30 @@@ public class PortUnificationServerHandl
  
    private final Configuration confForCreate;
  
 +  private final ObjectStoreJerseyContainer objectStoreJerseyContainer;
 +
+   private final RestCsrfPreventionFilter restCsrfPreventionFilter;
+ 
    public PortUnificationServerHandler(InetSocketAddress proxyHost,
        Configuration conf, Configuration confForCreate,
-       ObjectStoreJerseyContainer container) {
++      ObjectStoreJerseyContainer container,
+       RestCsrfPreventionFilter restCsrfPreventionFilter) {
      this.proxyHost = proxyHost;
      this.conf = conf;
      this.confForCreate = confForCreate;
 +    this.objectStoreJerseyContainer = container;
+     this.restCsrfPreventionFilter = restCsrfPreventionFilter;
    }
  
 -  private void configureHttp1(ChannelHandlerContext ctx) {
 +  private void configureHttp1(ChannelHandlerContext ctx) throws IOException {
-     ctx.pipeline().addLast(new HttpServerCodec(), new ChunkedWriteHandler(),
+     ctx.pipeline().addLast(new HttpServerCodec());
+     if (this.restCsrfPreventionFilter != null) {
+       ctx.pipeline().addLast(new RestCsrfPreventionFilterHandler(
+           this.restCsrfPreventionFilter));
+     }
+     ctx.pipeline().addLast(new ChunkedWriteHandler(),
 -        new URLDispatcher(proxyHost, conf, confForCreate));
 +        new URLDispatcher(proxyHost, conf, confForCreate,
 +            objectStoreJerseyContainer));
    }
  
    private void configureHttp2(ChannelHandlerContext ctx) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerManager.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerManager.java
index c85a554,0000000..beed82e
mode 100644,000000..100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerManager.java
@@@ -1,323 -1,0 +1,324 @@@
 +/**
 + * 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.storagecontainer;
 +
 +import com.google.protobuf.BlockingService;
 +import org.apache.hadoop.ha.HAServiceProtocol;
 +import org.apache.hadoop.hdfs.DFSUtil;
 +import org.apache.hadoop.hdfs.DFSUtilClient;
 +import org.apache.hadoop.hdfs.protocol.*;
 +import org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos;
 +import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolPB;
 +import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolServerSideTranslatorPB;
 +import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
 +import org.apache.hadoop.hdfs.server.blockmanagement.BlocksMap;
 +import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
 +import org.apache.hadoop.hdfs.server.namenode.NameNode;
 +import org.apache.hadoop.hdfs.server.namenode.Namesystem;
 +import org.apache.hadoop.hdfs.server.protocol.*;
 +import org.apache.hadoop.ipc.ProtobufRpcEngine;
 +import org.apache.hadoop.ipc.RPC;
 +import org.apache.hadoop.ipc.WritableRpcEngine;
 +import org.apache.hadoop.net.NetUtils;
 +import org.apache.hadoop.ozone.OzoneConfiguration;
 +import org.apache.hadoop.storagecontainer.protocol.ContainerLocationProtocol;
 +import org.apache.hadoop.util.LightWeightGSet;
 +import org.slf4j.Logger;
 +import org.slf4j.LoggerFactory;
 +
 +import java.io.IOException;
 +import java.net.InetSocketAddress;
 +import java.util.List;
 +
 +import static org.apache.hadoop.hdfs.DFSConfigKeys.*;
 +
 +/**
 + * Service that allocates storage containers and tracks their
 + * location.
 + */
 +public class StorageContainerManager
 +    implements DatanodeProtocol, ContainerLocationProtocol {
 +
 +  public static final Logger LOG =
 +      LoggerFactory.getLogger(StorageContainerManager.class);
 +
 +  private final Namesystem ns = new StorageContainerNameService();
 +  private final BlockManager blockManager;
 +
 +  private long txnId = 234;
 +
 +  /** The RPC server that listens to requests from DataNodes. */
 +  private final RPC.Server serviceRpcServer;
 +  private final InetSocketAddress serviceRPCAddress;
 +
 +  /** The RPC server that listens to requests from clients. */
 +  private final RPC.Server clientRpcServer;
 +  private final InetSocketAddress clientRpcAddress;
 +
 +  public StorageContainerManager(OzoneConfiguration conf)
 +      throws IOException {
 +    BlocksMap containerMap = new BlocksMap(
 +        LightWeightGSet.computeCapacity(2.0, "BlocksMap"),
 +        new StorageContainerMap());
 +    this.blockManager = new BlockManager(ns, false, conf, containerMap);
 +
 +    int handlerCount =
 +        conf.getInt(DFS_NAMENODE_HANDLER_COUNT_KEY,
 +            DFS_NAMENODE_HANDLER_COUNT_DEFAULT);
 +
 +    RPC.setProtocolEngine(conf, DatanodeProtocolPB.class,
 +        ProtobufRpcEngine.class);
 +
 +    DatanodeProtocolServerSideTranslatorPB dnProtoPbTranslator =
 +        new DatanodeProtocolServerSideTranslatorPB(this);
 +    BlockingService dnProtoPbService =
 +        DatanodeProtocolProtos.DatanodeProtocolService
 +            .newReflectiveBlockingService(dnProtoPbTranslator);
 +
 +    WritableRpcEngine.ensureInitialized();
 +
 +    InetSocketAddress serviceRpcAddr = NameNode.getServiceAddress(conf, false);
 +    if (serviceRpcAddr != null) {
 +      String bindHost =
 +          conf.getTrimmed(DFS_NAMENODE_SERVICE_RPC_BIND_HOST_KEY);
 +      if (bindHost == null || bindHost.isEmpty()) {
 +        bindHost = serviceRpcAddr.getHostName();
 +      }
 +      LOG.info("Service RPC server is binding to " + bindHost + ":" +
 +          serviceRpcAddr.getPort());
 +
 +      int serviceHandlerCount =
 +          conf.getInt(DFS_NAMENODE_SERVICE_HANDLER_COUNT_KEY,
 +              DFS_NAMENODE_SERVICE_HANDLER_COUNT_DEFAULT);
 +      serviceRpcServer = new RPC.Builder(conf)
 +          .setProtocol(
 +              org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolPB.class)
 +          .setInstance(dnProtoPbService)
 +          .setBindAddress(bindHost)
 +          .setPort(serviceRpcAddr.getPort())
 +          .setNumHandlers(serviceHandlerCount)
 +          .setVerbose(false)
 +          .setSecretManager(null)
 +          .build();
 +
 +      DFSUtil.addPBProtocol(conf, DatanodeProtocolPB.class, dnProtoPbService,
 +          serviceRpcServer);
 +
 +      InetSocketAddress listenAddr = serviceRpcServer.getListenerAddress();
 +      serviceRPCAddress = new InetSocketAddress(
 +          serviceRpcAddr.getHostName(), listenAddr.getPort());
 +      conf.set(DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY,
 +          NetUtils.getHostPortString(serviceRPCAddress));
 +    } else {
 +      serviceRpcServer = null;
 +      serviceRPCAddress = null;
 +    }
 +
 +    InetSocketAddress rpcAddr = DFSUtilClient.getNNAddress(conf);
 +    String bindHost = conf.getTrimmed(DFS_NAMENODE_RPC_BIND_HOST_KEY);
 +    if (bindHost == null || bindHost.isEmpty()) {
 +      bindHost = rpcAddr.getHostName();
 +    }
 +    LOG.info("RPC server is binding to " + bindHost + ":" + rpcAddr.getPort());
 +
 +    clientRpcServer = new RPC.Builder(conf)
 +        .setProtocol(
 +            org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolPB.class)
 +        .setInstance(dnProtoPbService)
 +        .setBindAddress(bindHost)
 +        .setPort(rpcAddr.getPort())
 +        .setNumHandlers(handlerCount)
 +        .setVerbose(false)
 +        .setSecretManager(null)
 +        .build();
 +
 +    DFSUtil.addPBProtocol(conf, DatanodeProtocolPB.class, dnProtoPbService,
 +        clientRpcServer);
 +
 +    // The rpc-server port can be ephemeral... ensure we have the correct info
 +    InetSocketAddress listenAddr = clientRpcServer.getListenerAddress();
 +    clientRpcAddress = new InetSocketAddress(
 +        rpcAddr.getHostName(), listenAddr.getPort());
 +    conf.set(FS_DEFAULT_NAME_KEY,
 +        DFSUtilClient.getNNUri(clientRpcAddress).toString());
 +  }
 +
 +  @Override
 +  public DatanodeRegistration registerDatanode(
 +      DatanodeRegistration registration) throws IOException {
 +    ns.writeLock();
 +    try {
 +      blockManager.getDatanodeManager().registerDatanode(registration);
 +    } finally {
 +      ns.writeUnlock();
 +    }
 +    return registration;
 +  }
 +
 +  @Override
 +  public HeartbeatResponse sendHeartbeat(DatanodeRegistration registration,
 +      StorageReport[] reports, long dnCacheCapacity, long dnCacheUsed,
 +      int xmitsInProgress, int xceiverCount, int failedVolumes,
 +      VolumeFailureSummary volumeFailureSummary,
 +               boolean requestFullBlockReportLease) throws IOException {
 +    ns.readLock();
 +    try {
 +      final int maxTransfer = blockManager.getMaxReplicationStreams()
 +          - xmitsInProgress;
 +      DatanodeCommand[] cmds = blockManager.getDatanodeManager()
-           .handleHeartbeat(registration, reports, ns.getBlockPoolId(), 0, 0,
-               xceiverCount, maxTransfer, failedVolumes, volumeFailureSummary);
++          .handleHeartbeat(registration, reports, blockManager.getBlockPoolId(),
++              0, 0, xceiverCount, maxTransfer, failedVolumes,
++              volumeFailureSummary);
 +
 +      return new HeartbeatResponse(cmds,
 +          new NNHAStatusHeartbeat(HAServiceProtocol.HAServiceState.ACTIVE,
 +              txnId), null, 0);
 +    } finally {
 +      ns.readUnlock();
 +    }
 +  }
 +
 +  @Override
 +  public DatanodeCommand blockReport(DatanodeRegistration registration,
 +      String poolId, StorageBlockReport[] reports,
 +      BlockReportContext context) throws IOException {
 +    for (int r = 0; r < reports.length; r++) {
 +      final BlockListAsLongs storageContainerList = reports[r].getBlocks();
 +      blockManager.processReport(registration, reports[r].getStorage(),
 +          storageContainerList, context, (r == reports.length - 1));
 +    }
 +    return null;
 +  }
 +
 +  @Override
 +  public DatanodeCommand cacheReport(DatanodeRegistration registration,
 +      String poolId, List<Long> blockIds) throws IOException {
 +    throw new UnsupportedOperationException();
 +  }
 +
 +  @Override
 +  public void blockReceivedAndDeleted(DatanodeRegistration registration,
 +      String poolId, StorageReceivedDeletedBlocks[] rcvdAndDeletedBlocks)
 +      throws IOException {
 +    for(StorageReceivedDeletedBlocks r : rcvdAndDeletedBlocks) {
 +      ns.writeLock();
 +      try {
 +        blockManager.processIncrementalBlockReport(registration, r);
 +      } finally {
 +        ns.writeUnlock();
 +      }
 +    }
 +  }
 +
 +  @Override
 +  public void errorReport(DatanodeRegistration registration,
 +      int errorCode, String msg) throws IOException {
 +    String dnName =
 +        (registration == null) ? "Unknown DataNode" : registration.toString();
 +
 +    if (errorCode == DatanodeProtocol.NOTIFY) {
 +      LOG.info("Error report from " + dnName + ": " + msg);
 +      return;
 +    }
 +
 +    if (errorCode == DatanodeProtocol.DISK_ERROR) {
 +      LOG.warn("Disk error on " + dnName + ": " + msg);
 +    } else if (errorCode == DatanodeProtocol.FATAL_DISK_ERROR) {
 +      LOG.warn("Fatal disk error on " + dnName + ": " + msg);
 +      blockManager.getDatanodeManager().removeDatanode(registration);
 +    } else {
 +      LOG.info("Error report from " + dnName + ": " + msg);
 +    }
 +  }
 +
 +  @Override
 +  public NamespaceInfo versionRequest() throws IOException {
 +    ns.readLock();
 +    try {
 +      return unprotectedGetNamespaceInfo();
 +    } finally {
 +      ns.readUnlock();
 +    }
 +  }
 +
 +  private NamespaceInfo unprotectedGetNamespaceInfo() {
 +    return new NamespaceInfo(1, "random", "random", 2,
 +        NodeType.STORAGE_CONTAINER_SERVICE);
 +  }
 +
 +  @Override
 +  public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
 +    // It doesn't make sense to have LocatedBlock in this API.
 +    ns.writeLock();
 +    try {
 +      for (int i = 0; i < blocks.length; i++) {
 +        ExtendedBlock blk = blocks[i].getBlock();
 +        DatanodeInfo[] nodes = blocks[i].getLocations();
 +        String[] storageIDs = blocks[i].getStorageIDs();
 +        for (int j = 0; j < nodes.length; j++) {
 +          blockManager.findAndMarkBlockAsCorrupt(blk, nodes[j],
 +              storageIDs == null ? null: storageIDs[j],
 +              "client machine reported it");
 +        }
 +      }
 +    } finally {
 +      ns.writeUnlock();
 +    }
 +  }
 +
 +  /**
 +   * Start client and service RPC servers.
 +   */
 +  void start() {
 +    clientRpcServer.start();
 +    if (serviceRpcServer != null) {
 +      serviceRpcServer.start();
 +    }
 +  }
 +
 +  /**
 +   * Wait until the RPC servers have shutdown.
 +   */
 +  void join() throws InterruptedException {
 +    clientRpcServer.join();
 +    if (serviceRpcServer != null) {
 +      serviceRpcServer.join();
 +    }
 +  }
 +
 +  @Override
 +  public void commitBlockSynchronization(ExtendedBlock block,
 +      long newgenerationstamp, long newlength, boolean closeFile,
 +      boolean deleteblock, DatanodeID[] newtargets, String[] newtargetstorages)
 +      throws IOException {
 +    // Not needed for the purpose of object store
 +    throw new UnsupportedOperationException();
 +  }
 +
 +  public static void main(String[] argv) throws IOException {
 +    OzoneConfiguration conf = new OzoneConfiguration();
 +    StorageContainerManager scm = new StorageContainerManager(conf);
 +    scm.start();
 +    try {
 +      scm.join();
 +    } catch (InterruptedException e) {
 +      e.printStackTrace();
 +    }
 +  }
 +}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerNameService.java
----------------------------------------------------------------------
diff --cc hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerNameService.java
index 76e0bb8,0000000..751b635
mode 100644,000000..100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerNameService.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/storagecontainer/StorageContainerNameService.java
@@@ -1,154 -1,0 +1,133 @@@
 +/**
 + * 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.storagecontainer;
 +
 +import org.apache.commons.lang.NotImplementedException;
 +import org.apache.hadoop.hdfs.protocol.Block;
 +import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
 +import org.apache.hadoop.hdfs.server.blockmanagement.BlockCollection;
 +import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
 +import org.apache.hadoop.hdfs.server.namenode.CacheManager;
 +import org.apache.hadoop.hdfs.server.namenode.NameNode;
 +import org.apache.hadoop.hdfs.server.namenode.Namesystem;
 +import org.apache.hadoop.hdfs.server.namenode.ha.HAContext;
 +import org.apache.hadoop.ipc.StandbyException;
 +import org.apache.hadoop.security.AccessControlException;
 +
 +import java.io.IOException;
 +import java.util.concurrent.locks.ReentrantReadWriteLock;
 +
 +/**
 + * Namesystem implementation to be used by StorageContainerManager.
 + */
 +public class StorageContainerNameService implements Namesystem {
 +
 +  private ReentrantReadWriteLock coarseLock = new ReentrantReadWriteLock();
-   private String blockPoolId;
 +  private volatile boolean serviceRunning = true;
 +
 +  public void shutdown() {
 +    serviceRunning = false;
 +  }
 +
 +  @Override
 +  public boolean isRunning() {
 +    return serviceRunning;
 +  }
 +
 +  @Override
-   public void checkSuperuserPrivilege() throws AccessControlException {
-     // TBD
-   }
- 
-   @Override
-   public String getBlockPoolId() {
-     return blockPoolId;
-   }
- 
-   public void setBlockPoolId(String id) {
-     this.blockPoolId = id;
-   }
- 
-   @Override
 +  public BlockCollection getBlockCollection(long id) {
 +    return null;
 +  }
 +
 +  @Override
 +  public void startSecretManagerIfNecessary() {
 +     throw new NotImplementedException();
 +  }
 +
 +  @Override
-   public ErasureCodingPolicy getErasureCodingPolicyForPath(String src)
-       throws IOException {
-     return null;
-   }
- 
-   @Override
 +  public boolean isInSnapshot(long blockCollectionID) {
 +    return false;
 +  }
 +
 +  @Override
 +  public CacheManager getCacheManager() {
 +    // Cache Management is not supported
 +    return null;
 +  }
 +
 +  @Override
 +  public HAContext getHAContext() {
 +    return null;
 +  }
 +
 +  /**
 +   * @return Whether the namenode is transitioning to active state and is in the
 +   * middle of the starting active services.
 +   */
 +  @Override
 +  public boolean inTransitionToActive() {
 +    return false;
 +  }
 +
 +  @Override
 +  public void readLock() {
 +    coarseLock.readLock().lock();
 +  }
 +
 +  @Override
 +  public void readUnlock() {
 +    coarseLock.readLock().unlock();
 +  }
 +
 +  @Override
 +  public boolean hasReadLock() {
 +    return coarseLock.getReadHoldCount() > 0 || hasWriteLock();
 +  }
 +
 +  @Override
 +  public void writeLock() {
 +    coarseLock.writeLock().lock();
 +  }
 +
 +  @Override
 +  public void writeLockInterruptibly() throws InterruptedException {
 +    coarseLock.writeLock().lockInterruptibly();
 +  }
 +
 +  @Override
 +  public void writeUnlock() {
 +    coarseLock.writeLock().unlock();
 +  }
 +
 +  @Override
 +  public boolean hasWriteLock() {
 +    return coarseLock.isWriteLockedByCurrentThread();
 +  }
 +
 +  @Override
 +  public boolean isInSafeMode() {
 +    return false;
 +  }
 +
 +  @Override
 +  public boolean isInStartupSafeMode() {
 +    return false;
 +  }
 +
 +}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/SimulatedFSDataset.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeHotSwapVolumes.java
----------------------------------------------------------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/1b7df69d/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/TestFsDatasetImpl.java
----------------------------------------------------------------------


[19/50] [abbrv] hadoop git commit: Move HDFS-8923 to Release 2.8.0 in CHANGES.txt.

Posted by ji...@apache.org.
Move HDFS-8923 to Release 2.8.0 in CHANGES.txt.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/748b6c07
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/748b6c07
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/748b6c07

Branch: refs/heads/HDFS-7240
Commit: 748b6c07fe29bf52510d2e84d82fcbef7f1bb35c
Parents: 46f7790
Author: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Authored: Thu Feb 18 18:43:06 2016 -0800
Committer: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Committed: Thu Feb 18 18:43:06 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/748b6c07/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 945c911..2129a69 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1939,6 +1939,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-9773. Remove dead code related to SimulatedFSDataset in tests.
     (Brahma Reddy Battula via aajisaka)
 
+    HDFS-8923. Add -source flag to balancer usage message.  (Chris Trezzo
+    via szetszwo)
+
   OPTIMIZATIONS
 
     HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than
@@ -2817,9 +2820,6 @@ Release 2.7.3 - UNRELEASED
     HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be
     configurable (James Kinley and Nathan Roberts via kihwal)
 
-    HDFS-8923. Add -source flag to balancer usage message.  (Chris Trezzo
-    via szetszwo)
-
   OPTIMIZATIONS
 
   BUG FIXES


[31/50] [abbrv] hadoop git commit: YARN-4707. Remove the extra char (>) from SecureContainer.md. Contributed by Brahma Reddy Battula.

Posted by ji...@apache.org.
YARN-4707. Remove the extra char (>) from SecureContainer.md. Contributed by Brahma Reddy Battula.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/5e7d4d51
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/5e7d4d51
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/5e7d4d51

Branch: refs/heads/HDFS-7240
Commit: 5e7d4d51f856298e99a00895013ac665e67549b3
Parents: 342c957
Author: Akira Ajisaka <aa...@apache.org>
Authored: Mon Feb 22 17:17:40 2016 +0900
Committer: Akira Ajisaka <aa...@apache.org>
Committed: Mon Feb 22 17:17:40 2016 +0900

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                                   | 3 +++
 .../hadoop-yarn-site/src/site/markdown/SecureContainer.md         | 2 +-
 2 files changed, 4 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/5e7d4d51/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index d6aa4e4..e39917f 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1521,6 +1521,9 @@ Release 2.7.3 - UNRELEASED
     YARN-3602. TestResourceLocalizationService.testPublicResourceInitializesLocalDir
     fails Intermittently due to IOException from cleanup. (zhihai xu via xgong)
 
+    YARN-4707. Remove the extra char (>) from SecureContainer.md.
+    (Brahma Reddy Battula via aajisaka)
+
 Release 2.7.2 - 2016-01-25
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5e7d4d51/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/SecureContainer.md
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/SecureContainer.md b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/SecureContainer.md
index f32e460..cd4f913 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/SecureContainer.md
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/SecureContainer.md
@@ -30,7 +30,7 @@ Secure Containers work only in the context of secured YARN clusters.
 
 ###Linux Secure Container Executor
 
-  On Linux environment the secure container executor is the `LinuxContainerExecutor`. It uses an external program called the **container-executor**\> to launch the container. This program has the `setuid` access right flag set which allows it to launch the container with the permissions of the YARN application user.
+  On Linux environment the secure container executor is the `LinuxContainerExecutor`. It uses an external program called the **container-executor** to launch the container. This program has the `setuid` access right flag set which allows it to launch the container with the permissions of the YARN application user.
 
 ###Configuration
 


[38/50] [abbrv] hadoop git commit: YARN-4709. NMWebServices produces incorrect JSON for containers. Contributed by Varun Saxena.

Posted by ji...@apache.org.
YARN-4709. NMWebServices produces incorrect JSON for containers. Contributed by Varun Saxena.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/140cb5d7
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/140cb5d7
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/140cb5d7

Branch: refs/heads/HDFS-7240
Commit: 140cb5d74565aad848b40a251ec02b597a3a20d4
Parents: 27b7775
Author: Varun Vasudev <vv...@apache.org>
Authored: Tue Feb 23 12:29:25 2016 +0530
Committer: Varun Vasudev <vv...@apache.org>
Committed: Tue Feb 23 12:29:25 2016 +0530

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |  3 ++
 .../yarn/webapp/WebServicesTestUtils.java       | 28 ++++++++++++++
 .../nodemanager/webapp/dao/ContainerInfo.java   |  1 -
 .../webapp/TestNMWebServicesContainers.java     | 39 +++++++++++++++++---
 4 files changed, 65 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/140cb5d7/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 9b57666..058ea87 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -1436,6 +1436,9 @@ Release 2.8.0 - UNRELEASED
     YARN-4386. refreshNodesGracefully() should send recommission event to active
     RMNodes only. (Kuhu Shukla via junping_du)
 
+    YARN-4709. NMWebServices produces incorrect JSON for containers.
+    (Varun Saxena via vvasudev)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/140cb5d7/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/WebServicesTestUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/WebServicesTestUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/WebServicesTestUtils.java
index aa211a6..0454ce6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/WebServicesTestUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/webapp/WebServicesTestUtils.java
@@ -20,6 +20,9 @@ package org.apache.hadoop.yarn.webapp;
 
 import static org.junit.Assert.assertTrue;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import org.w3c.dom.Attr;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
@@ -47,6 +50,31 @@ public class WebServicesTestUtils {
     return Float.parseFloat(val);
   }
 
+  public static List<String> getXmlStrings(Element element, String name) {
+    NodeList id = element.getElementsByTagName(name);
+    List<String> strings = new ArrayList<>();
+    int len = id.getLength();
+    if (id.getLength() == 0) {
+      return strings;
+    }
+    for (int i = 0; i < len; i++) {
+      Element line = (Element) id.item(i);
+      if (line == null) {
+        continue;
+      }
+      Node first = line.getFirstChild();
+      if (first == null) {
+        continue;
+      }
+      String val = first.getNodeValue();
+      if (val == null) {
+        continue;
+      }
+      strings.add(val);
+    }
+    return strings;
+  }
+
   public static String getXmlString(Element element, String name) {
     NodeList id = element.getElementsByTagName(name);
     Element line = (Element) id.item(0);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/140cb5d7/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/ContainerInfo.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/ContainerInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/ContainerInfo.java
index e462eba..cf022b9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/ContainerInfo.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/ContainerInfo.java
@@ -53,7 +53,6 @@ public class ContainerInfo {
   @XmlTransient
   protected String exitStatus;
 
-  @XmlElementWrapper
   protected List<String> containerLogFiles;
 
   public ContainerInfo() {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/140cb5d7/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java
index 0ed56d3..3c4a660 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesContainers.java
@@ -20,13 +20,16 @@ package org.apache.hadoop.yarn.server.nodemanager.webapp;
 
 import static org.apache.hadoop.yarn.util.StringHelper.ujoin;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.io.IOException;
 import java.io.StringReader;
+import java.util.Arrays;
 import java.util.HashMap;
+import java.util.List;
 
 import javax.ws.rs.core.MediaType;
 import javax.xml.parsers.DocumentBuilder;
@@ -48,6 +51,7 @@ import org.apache.hadoop.yarn.server.nodemanager.NodeManager;
 import org.apache.hadoop.yarn.server.nodemanager.ResourceView;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
+import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerState;
 import org.apache.hadoop.yarn.server.nodemanager.webapp.WebServer.NMWebApp;
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
 import org.apache.hadoop.yarn.server.utils.BuilderUtils;
@@ -203,12 +207,27 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
         app.getAppId(), 1);
     Container container1 = new MockContainer(appAttemptId, dispatcher, conf,
         app.getUser(), app.getAppId(), 1);
+    ((MockContainer)container1).setState(ContainerState.RUNNING);
     Container container2 = new MockContainer(appAttemptId, dispatcher, conf,
         app.getUser(), app.getAppId(), 2);
+    ((MockContainer)container2).setState(ContainerState.RUNNING);
     nmContext.getContainers()
         .put(container1.getContainerId(), container1);
     nmContext.getContainers()
         .put(container2.getContainerId(), container2);
+    File appDir = new File(testLogDir + "/" + app.getAppId().toString());
+    appDir.mkdir();
+    File container1Dir =
+        new File(appDir + "/" + container1.getContainerId().toString());
+    container1Dir.mkdir();
+    // Create log files for containers.
+    new File(container1Dir + "/" + "syslog").createNewFile();
+    new File(container1Dir + "/" + "stdout").createNewFile();
+    File container2Dir =
+        new File(appDir + "/" + container2.getContainerId().toString());
+    container2Dir.mkdir();
+    new File(container2Dir + "/" + "syslog").createNewFile();
+    new File(container2Dir + "/" + "stdout").createNewFile();
 
     app.getContainers().put(container1.getContainerId(), container1);
     app.getContainers().put(container2.getContainerId(), container2);
@@ -475,9 +494,13 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
           WebServicesTestUtils.getXmlInt(element, "totalVCoresNeeded"),
           WebServicesTestUtils.getXmlString(element, "containerLogsLink"));
       // verify that the container log files element exists
-      assertTrue("containerLogFiles missing",
-          WebServicesTestUtils.getXmlString(element, "containerLogFiles")
-              != null);
+      List<String> containerLogFiles =
+          WebServicesTestUtils.getXmlStrings(element, "containerLogFiles");
+      assertFalse("containerLogFiles missing",containerLogFiles.isEmpty());
+      assertEquals(2, containerLogFiles.size());
+      assertTrue("syslog and stdout expected",
+          containerLogFiles.contains("syslog") &&
+          containerLogFiles.contains("stdout"));
     }
   }
 
@@ -492,8 +515,14 @@ public class TestNMWebServicesContainers extends JerseyTestBase {
         info.getInt("totalVCoresNeeded"),
         info.getString("containerLogsLink"));
     // verify that the container log files element exists
-    assertTrue("containerLogFiles missing",
-        info.getJSONArray("containerLogFiles") != null);
+    JSONArray containerLogFilesArr = info.getJSONArray("containerLogFiles");
+    assertTrue("containerLogFiles missing", containerLogFilesArr != null);
+    assertEquals(2, containerLogFilesArr.length());
+    for (int i = 0; i < 2; i++) {
+      assertTrue("syslog and stdout expected",
+          containerLogFilesArr.get(i).equals("syslog") ||
+          containerLogFilesArr.get(i).equals("stdout"));
+    }
   }
 
   public void verifyNodeContainerInfoGeneric(Container cont, String id,


[13/50] [abbrv] hadoop git commit: HADOOP-10865. Add a Crc32 chunked verification benchmark for both directly and non-directly buffer cases.

Posted by ji...@apache.org.
HADOOP-10865. Add a Crc32 chunked verification benchmark for both directly and non-directly buffer cases.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/bbfaf3c2
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/bbfaf3c2
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/bbfaf3c2

Branch: refs/heads/HDFS-7240
Commit: bbfaf3c2712c9ba82b0f8423bdeb314bf505a692
Parents: ba6d5ed
Author: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Authored: Thu Feb 18 11:47:33 2016 -0800
Committer: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Committed: Thu Feb 18 11:47:33 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |   3 +
 .../org/apache/hadoop/util/DataChecksum.java    | 147 ++++----
 .../hadoop/util/Crc32PerformanceTest.java       | 350 +++++++++++++++++++
 .../apache/hadoop/util/TestDataChecksum.java    |   6 +
 .../hadoop/hdfs/TestDFSClientRetries.java       |   8 +-
 5 files changed, 450 insertions(+), 64 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/bbfaf3c2/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 41ba87d..6cdcb7a 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1175,6 +1175,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-12758. Extend CSRF Filter with UserAgent Checks
     (Larry McCay via cnauroth)
 
+    HADOOP-10865. Add a Crc32 chunked verification benchmark for both directly
+    and non-directly buffer cases.  (szetszwo)
+
   BUG FIXES
 
     HADOOP-12352. Delay in checkpointing Trash can leave trash for 2 intervals

http://git-wip-us.apache.org/repos/asf/hadoop/blob/bbfaf3c2/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DataChecksum.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DataChecksum.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DataChecksum.java
index d9dc7af..faac587 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DataChecksum.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/DataChecksum.java
@@ -286,94 +286,119 @@ public class DataChecksum implements Checksum {
    * @throws ChecksumException if the checksums do not match
    */
   public void verifyChunkedSums(ByteBuffer data, ByteBuffer checksums,
-      String fileName, long basePos)
-  throws ChecksumException {
+      String fileName, long basePos) throws ChecksumException {
     if (type.size == 0) return;
     
     if (data.hasArray() && checksums.hasArray()) {
-      verifyChunkedSums(
-          data.array(), data.arrayOffset() + data.position(), data.remaining(),
-          checksums.array(), checksums.arrayOffset() + checksums.position(),
-          fileName, basePos);
+      final int dataOffset = data.arrayOffset() + data.position();
+      final int crcsOffset = checksums.arrayOffset() + checksums.position();
+      verifyChunked(type, summer, data.array(), dataOffset, data.remaining(),
+          bytesPerChecksum, checksums.array(), crcsOffset, fileName, basePos);
       return;
     }
     if (NativeCrc32.isAvailable()) {
       NativeCrc32.verifyChunkedSums(bytesPerChecksum, type.id, checksums, data,
           fileName, basePos);
-      return;
+    } else {
+      verifyChunked(type, summer, data, bytesPerChecksum, checksums, fileName,
+          basePos);
     }
-    
-    int startDataPos = data.position();
+  }
+
+  static void verifyChunked(final Type type, final Checksum algorithm,
+      final ByteBuffer data, final int bytesPerCrc, final ByteBuffer crcs,
+      final String filename, final long basePos) throws ChecksumException {
+    final byte[] bytes = new byte[bytesPerCrc];
+    final int dataOffset = data.position();
+    final int dataLength = data.remaining();
     data.mark();
-    checksums.mark();
+    crcs.mark();
+
     try {
-      byte[] buf = new byte[bytesPerChecksum];
-      byte[] sum = new byte[type.size];
-      while (data.remaining() > 0) {
-        int n = Math.min(data.remaining(), bytesPerChecksum);
-        checksums.get(sum);
-        data.get(buf, 0, n);
-        summer.reset();
-        summer.update(buf, 0, n);
-        int calculated = (int)summer.getValue();
-        int stored = (sum[0] << 24 & 0xff000000) |
-          (sum[1] << 16 & 0xff0000) |
-          (sum[2] << 8 & 0xff00) |
-          sum[3] & 0xff;
-        if (calculated != stored) {
-          long errPos = basePos + data.position() - startDataPos - n;
-          throw new ChecksumException(
-              "Checksum error: "+ fileName + " at "+ errPos +
-              " exp: " + stored + " got: " + calculated, errPos);
+      int i = 0;
+      for(final int n = dataLength - bytesPerCrc + 1; i < n; i += bytesPerCrc) {
+        data.get(bytes);
+        algorithm.reset();
+        algorithm.update(bytes, 0, bytesPerCrc);
+        final int computed = (int)algorithm.getValue();
+        final int expected = crcs.getInt();
+
+        if (computed != expected) {
+          long errPos = basePos + data.position() - dataOffset - bytesPerCrc;
+          throwChecksumException(type, algorithm, filename, errPos, expected,
+              computed);
+        }
+      }
+
+      final int remainder = dataLength - i;
+      if (remainder > 0) {
+        data.get(bytes, 0, remainder);
+        algorithm.reset();
+        algorithm.update(bytes, 0, remainder);
+        final int computed = (int)algorithm.getValue();
+        final int expected = crcs.getInt();
+
+        if (computed != expected) {
+          long errPos = basePos + data.position() - dataOffset - remainder;
+          throwChecksumException(type, algorithm, filename, errPos, expected,
+              computed);
         }
       }
     } finally {
       data.reset();
-      checksums.reset();
+      crcs.reset();
     }
   }
-  
+
   /**
    * Implementation of chunked verification specifically on byte arrays. This
    * is to avoid the copy when dealing with ByteBuffers that have array backing.
    */
-  private void verifyChunkedSums(
-      byte[] data, int dataOff, int dataLen,
-      byte[] checksums, int checksumsOff, String fileName,
-      long basePos) throws ChecksumException {
-    if (type.size == 0) return;
+  static void verifyChunked(final Type type, final Checksum algorithm,
+      final byte[] data, final int dataOffset, final int dataLength,
+      final int bytesPerCrc, final byte[] crcs, final int crcsOffset,
+      final String filename, final long basePos) throws ChecksumException {
+    final int dataEnd = dataOffset + dataLength;
+    int i = dataOffset;
+    int j = crcsOffset;
+    for(final int n = dataEnd-bytesPerCrc+1; i < n; i += bytesPerCrc, j += 4) {
+      algorithm.reset();
+      algorithm.update(data, i, bytesPerCrc);
+      final int computed = (int)algorithm.getValue();
+      final int expected = ((crcs[j] << 24) + ((crcs[j + 1] << 24) >>> 8))
+          + (((crcs[j + 2] << 24) >>> 16) + ((crcs[j + 3] << 24) >>> 24));
 
-    if (NativeCrc32.isAvailable()) {
-      NativeCrc32.verifyChunkedSumsByteArray(bytesPerChecksum, type.id,
-          checksums, checksumsOff, data, dataOff, dataLen, fileName, basePos);
-      return;
+      if (computed != expected) {
+        final long errPos = basePos + i - dataOffset;
+        throwChecksumException(type, algorithm, filename, errPos, expected,
+            computed);
+      }
     }
-    
-    int remaining = dataLen;
-    int dataPos = 0;
-    while (remaining > 0) {
-      int n = Math.min(remaining, bytesPerChecksum);
-      
-      summer.reset();
-      summer.update(data, dataOff + dataPos, n);
-      dataPos += n;
-      remaining -= n;
-      
-      int calculated = (int)summer.getValue();
-      int stored = (checksums[checksumsOff] << 24 & 0xff000000) |
-        (checksums[checksumsOff + 1] << 16 & 0xff0000) |
-        (checksums[checksumsOff + 2] << 8 & 0xff00) |
-        checksums[checksumsOff + 3] & 0xff;
-      checksumsOff += 4;
-      if (calculated != stored) {
-        long errPos = basePos + dataPos - n;
-        throw new ChecksumException(
-            "Checksum error: "+ fileName + " at "+ errPos +
-            " exp: " + stored + " got: " + calculated, errPos);
+    final int remainder = dataEnd - i;
+    if (remainder > 0) {
+      algorithm.reset();
+      algorithm.update(data, i, remainder);
+      final int computed = (int)algorithm.getValue();
+      final int expected = ((crcs[j] << 24) + ((crcs[j + 1] << 24) >>> 8))
+          + (((crcs[j + 2] << 24) >>> 16) + ((crcs[j + 3] << 24) >>> 24));
+
+      if (computed != expected) {
+        final long errPos = basePos + i - dataOffset;
+        throwChecksumException(type, algorithm, filename, errPos, expected,
+            computed);
       }
     }
   }
 
+  private static void throwChecksumException(Type type, Checksum algorithm,
+      String filename, long errPos, int expected, int computed)
+          throws ChecksumException {
+    throw new ChecksumException("Checksum " + type
+        + " not matched for file " + filename + " at position "+ errPos
+        + String.format(": expected=%X but computed=%X", expected, computed)
+        + ", algorithm=" + algorithm.getClass().getSimpleName(), errPos);
+  }
+
   /**
    * Calculate checksums for the given data.
    * 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/bbfaf3c2/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/Crc32PerformanceTest.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/Crc32PerformanceTest.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/Crc32PerformanceTest.java
new file mode 100644
index 0000000..d8963df
--- /dev/null
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/Crc32PerformanceTest.java
@@ -0,0 +1,350 @@
+/**
+ * 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.util;
+
+import java.io.PrintStream;
+import java.lang.reflect.Constructor;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.zip.CRC32;
+import java.util.zip.Checksum;
+
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.logging.impl.Log4JLogger;
+import org.apache.hadoop.fs.ChecksumException;
+import org.apache.log4j.Level;
+
+/**
+ * Performance tests to compare performance of Crc32 implementations
+ * This can be run from the command line with:
+ *
+ *   java -cp path/to/test/classes:path/to/common/classes \
+ *      'org.apache.hadoop.util.Crc32PerformanceTest'
+ *
+ *      or
+ *
+ *  hadoop org.apache.hadoop.util.Crc32PerformanceTest
+ *
+ * The output is in JIRA table format.
+ */
+public class Crc32PerformanceTest {
+  static final int MB = 1024 * 1024;
+
+  static interface Crc32 {
+
+    public void verifyChunked(ByteBuffer data, int bytesPerCrc, ByteBuffer crcs,
+        String filename, long basePos) throws ChecksumException;
+
+    static final class Native implements Crc32 {
+      @Override
+      public void verifyChunked(ByteBuffer data, int bytesPerSum,
+          ByteBuffer sums, String fileName, long basePos)
+              throws ChecksumException {
+        NativeCrc32.verifyChunkedSums(bytesPerSum, DataChecksum.Type.CRC32.id,
+            sums, data, fileName, basePos);
+      }
+    }
+
+
+    static abstract class AbstractCrc32<T extends Checksum> implements Crc32 {
+      abstract T newAlgorithm();
+
+      @Override
+      public void verifyChunked(ByteBuffer data, int bytesPerCrc,
+          ByteBuffer crcs, String filename, long basePos)
+              throws ChecksumException {
+        final Checksum algorithm = newAlgorithm();
+        if (data.hasArray() && crcs.hasArray()) {
+          DataChecksum.verifyChunked(DataChecksum.Type.CRC32, algorithm,
+              data.array(), data.position(), data.remaining(), bytesPerCrc,
+              crcs.array(), crcs.position(), filename, basePos);
+        } else {
+          DataChecksum.verifyChunked(DataChecksum.Type.CRC32, algorithm,
+              data, bytesPerCrc, crcs, filename, basePos);
+        }
+      }
+    }
+
+    static final class Zip extends AbstractCrc32<CRC32> {
+      @Override
+      public CRC32 newAlgorithm() {
+        return new CRC32();
+      }
+    }
+
+    static final class PureJava extends AbstractCrc32<PureJavaCrc32> {
+      @Override
+      public PureJavaCrc32 newAlgorithm() {
+        return new PureJavaCrc32();
+      }
+    }
+  }
+
+  final int dataLengthMB;
+  final int trials;
+  final boolean direct;
+
+  final PrintStream out = System.out;
+
+  final List<Class<? extends Crc32>> crcs = new ArrayList<>();
+
+  Crc32PerformanceTest(final int dataLengthMB, final int trials,
+      final boolean direct) {
+    this.dataLengthMB = dataLengthMB;
+    this.trials = trials;
+    this.direct = direct;
+
+    crcs.add(Crc32.Zip.class);
+    crcs.add(Crc32.PureJava.class);
+
+    if (direct && NativeCrc32.isAvailable()) {
+      crcs.add(Crc32.Native.class);
+      ((Log4JLogger)LogFactory.getLog(NativeCodeLoader.class))
+          .getLogger().setLevel(Level.ALL);
+    }
+  }
+
+  void run() throws Exception {
+    final long startTime = System.nanoTime();
+    printSystemProperties(out);
+    out.println("Data Length = " + dataLengthMB + " MB");
+    out.println("Trials      = " + trials);
+    doBench(crcs);
+    out.printf("Elapsed %.1fs\n", secondsElapsed(startTime));
+  }
+
+  public static void main(String args[]) throws Exception {
+    new Crc32PerformanceTest(64, 5, true).run();
+  }
+
+  private static void printCell(String s, int width, PrintStream out) {
+    final int w = s.length() > width? s.length(): width;
+    out.printf(" %" + w + "s |", s);
+  }
+
+  private ByteBuffer allocateByteBuffer(int length) {
+    return direct? ByteBuffer.allocateDirect(length)
+      : ByteBuffer.allocate(length);
+  }
+
+  private ByteBuffer newData() {
+    final byte[] bytes = new byte[dataLengthMB << 20];
+    new Random().nextBytes(bytes);
+    final ByteBuffer dataBufs = allocateByteBuffer(bytes.length);
+    dataBufs.mark();
+    dataBufs.put(bytes);
+    dataBufs.reset();
+    return dataBufs;
+  }
+
+  private ByteBuffer computeCrc(ByteBuffer dataBufs, int bytePerCrc) {
+    final int size = 4 * (dataBufs.remaining() - 1) / bytePerCrc + 1;
+    final ByteBuffer crcBufs = allocateByteBuffer(size);
+    final DataChecksum checksum = DataChecksum.newDataChecksum(
+        DataChecksum.Type.CRC32, bytePerCrc);
+    checksum.calculateChunkedSums(dataBufs, crcBufs);
+    return crcBufs;
+  }
+
+  private void doBench(final List<Class<? extends Crc32>> crcs)
+      throws Exception {
+    final ByteBuffer[] dataBufs = new ByteBuffer[16];
+    for(int i = 0; i < dataBufs.length; i++) {
+      dataBufs[i] = newData();
+    }
+
+    // Print header
+    out.printf("\n%s Buffer Performance Table", direct? "Direct": "Non-direct");
+    out.printf(" (bpc: byte-per-crc in MB/sec; #T: #Theads)\n");
+
+    // Warm up implementations to get jit going.
+    final ByteBuffer[] crc32 = {computeCrc(dataBufs[0], 32)};
+    final ByteBuffer[] crc512 = {computeCrc(dataBufs[0], 512)};
+    for (Class<? extends Crc32> c : crcs) {
+      doBench(c, 1, dataBufs, crc32, 32);
+      doBench(c, 1, dataBufs, crc512, 512);
+    }
+
+    // Test on a variety of sizes with different number of threads
+    for (int i = 5; i <= 16; i++) {
+      doBench(crcs, dataBufs, 1 << i, out);
+    }
+  }
+
+  private void doBench(final List<Class<? extends Crc32>> crcs,
+      final ByteBuffer[] dataBufs, final int bytePerCrc, final PrintStream out)
+          throws Exception {
+    final ByteBuffer[] crcBufs = new ByteBuffer[dataBufs.length];
+    for(int i = 0; i < crcBufs.length; i++) {
+      crcBufs[i] = computeCrc(dataBufs[i], bytePerCrc);
+    }
+
+    final String numBytesStr = " bpc ";
+    final String numThreadsStr = "#T";
+    final String diffStr = "% diff";
+
+    out.print('|');
+    printCell(numBytesStr, 0, out);
+    printCell(numThreadsStr, 0, out);
+    for (int i = 0; i < crcs.size(); i++) {
+      final Class<? extends Crc32> c = crcs.get(i);
+      out.print('|');
+      printCell(c.getSimpleName(), 8, out);
+      for(int j = 0; j < i; j++) {
+        printCell(diffStr, diffStr.length(), out);
+      }
+    }
+    out.printf("\n");
+
+    for(int numThreads = 1; numThreads <= dataBufs.length; numThreads <<= 1) {
+      out.printf("|");
+      printCell(String.valueOf(bytePerCrc), numBytesStr.length(), out);
+      printCell(String.valueOf(numThreads), numThreadsStr.length(), out);
+
+      final List<BenchResult> previous = new ArrayList<BenchResult>();
+      for(Class<? extends Crc32> c : crcs) {
+        System.gc();
+
+        final BenchResult result = doBench(c, numThreads, dataBufs, crcBufs,
+            bytePerCrc);
+        printCell(String.format("%9.1f", result.mbps),
+            c.getSimpleName().length() + 1, out);
+
+        //compare result with previous
+        for(BenchResult p : previous) {
+          final double diff = (result.mbps - p.mbps) / p.mbps * 100;
+          printCell(String.format("%5.1f%%", diff), diffStr.length(), out);
+        }
+        previous.add(result);
+      }
+      out.printf("\n");
+    }
+  }
+
+
+  private BenchResult doBench(Class<? extends Crc32> clazz,
+      final int numThreads, final ByteBuffer[] dataBufs,
+      final ByteBuffer[] crcBufs, final int bytePerCrc)
+          throws Exception {
+
+    final Thread[] threads = new Thread[numThreads];
+    final BenchResult[] results = new BenchResult[threads.length];
+
+    {
+      final Constructor<? extends Crc32> ctor = clazz.getConstructor();
+
+      for(int i = 0; i < threads.length; i++) {
+        final Crc32 crc = ctor.newInstance();
+        final long byteProcessed = dataBufs[i].remaining() * trials;
+        final int index = i;
+        threads[i] = new Thread() {
+          @Override
+          public void run() {
+            final long startTime = System.nanoTime();
+            for (int i = 0; i < trials; i++) {
+              dataBufs[index].mark();
+              crcBufs[index].mark();
+              try {
+                crc.verifyChunked(dataBufs[index], bytePerCrc, crcBufs[index],
+                    crc.getClass().getSimpleName(), dataBufs[index].position());
+              } catch (Throwable t) {
+                results[index] = new BenchResult(t);
+                return;
+              } finally {
+                dataBufs[index].reset();
+                crcBufs[index].reset();
+              }
+            }
+            final double secsElapsed = secondsElapsed(startTime);
+            results[index] = new BenchResult(byteProcessed/secsElapsed/MB);
+          }
+        };
+      }
+    }
+
+    for(Thread t : threads) {
+      t.start();
+    }
+    for(Thread t : threads) {
+      t.join();
+    }
+
+    double sum = 0;
+    for(int i = 0; i < results.length; i++) {
+      sum += results[i].getMbps();
+    }
+    return new BenchResult(sum/results.length);
+  }
+
+  private static class BenchResult {
+    /** Speed (MB per second) */
+    final double mbps;
+    final Throwable thrown;
+
+    BenchResult(double mbps) {
+      this.mbps = mbps;
+      this.thrown = null;
+    }
+
+    BenchResult(Throwable e) {
+      this.mbps = 0;
+      this.thrown = e;
+    }
+
+    double getMbps() {
+      if (thrown != null) {
+        throw new AssertionError(thrown);
+      }
+      return mbps;
+    }
+  }
+
+  static double secondsElapsed(final long startTime) {
+    return (System.nanoTime() - startTime) / 1000000000.0d;
+  }
+
+  static void printSystemProperties(PrintStream out) {
+    final String[] names = {
+        "java.version",
+        "java.runtime.name",
+        "java.runtime.version",
+        "java.vm.version",
+        "java.vm.vendor",
+        "java.vm.name",
+        "java.vm.specification.version",
+        "java.specification.version",
+        "os.arch",
+        "os.name",
+        "os.version"
+    };
+    int max = 0;
+    for(String n : names) {
+      if (n.length() > max) {
+        max = n.length();
+      }
+    }
+
+    final Properties p = System.getProperties();
+    for(String n : names) {
+      out.printf("%" + max + "s = %s\n", n, p.getProperty(n));
+    }
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/hadoop/blob/bbfaf3c2/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java
index 73fd25a..8841809 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestDataChecksum.java
@@ -197,4 +197,10 @@ public class TestDataChecksum {
     newBuf.limit(dataBuf.limit());
     return newBuf;
   }
+
+  @Test
+  public void testCrc32() throws Exception {
+    new Crc32PerformanceTest(8, 3, true).run();
+    new Crc32PerformanceTest(8, 3, false).run();
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/bbfaf3c2/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
index 1f783f6..62dfe79 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientRetries.java
@@ -52,6 +52,7 @@ import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.crypto.CryptoProtocolVersion;
+import org.apache.hadoop.fs.ChecksumException;
 import org.apache.hadoop.fs.CommonConfigurationKeys;
 import org.apache.hadoop.fs.CreateFlag;
 import org.apache.hadoop.fs.FSDataInputStream;
@@ -62,8 +63,8 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.permission.FsPermission;
 import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
-import org.apache.hadoop.hdfs.client.impl.LeaseRenewer;
 import org.apache.hadoop.hdfs.client.HdfsUtils;
+import org.apache.hadoop.hdfs.client.impl.LeaseRenewer;
 import org.apache.hadoop.hdfs.protocol.Block;
 import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
 import org.apache.hadoop.hdfs.protocol.DatanodeID;
@@ -929,11 +930,12 @@ public class TestDFSClientRetries {
         try {
           dis.read(arr, 0, (int)FILE_LENGTH);
           fail("Expected ChecksumException not thrown");
-        } catch (Exception ex) {
+        } catch (ChecksumException ex) {
           GenericTestUtils.assertExceptionContains(
-              "Checksum error", ex);
+              "Checksum", ex);
         }
       }
+      client.close();
     } finally {
       cluster.shutdown();
     }


[22/50] [abbrv] hadoop git commit: HDFS-9829. Erasure Coding: Improve few exception handling logic of ErasureCodingWorker. Contributed by Rakesh R.

Posted by ji...@apache.org.
HDFS-9829. Erasure Coding: Improve few exception handling logic of ErasureCodingWorker. Contributed by Rakesh R.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/6546d9e7
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/6546d9e7
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/6546d9e7

Branch: refs/heads/HDFS-7240
Commit: 6546d9e7ff73d2c81a803f2c61a1376a8c426987
Parents: ba1c9d4
Author: Jing Zhao <ji...@apache.org>
Authored: Fri Feb 19 10:40:11 2016 -0800
Committer: Jing Zhao <ji...@apache.org>
Committed: Fri Feb 19 10:40:28 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  3 ++
 .../erasurecode/ErasureCodingWorker.java        | 37 ++++++++------------
 2 files changed, 17 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/6546d9e7/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 1f5d65d..a377243 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -225,6 +225,9 @@ Trunk (Unreleased)
 
     HDFS-9795. OIV Delimited should show which files are ACL-enabled (lei)
 
+    HDFS-9829. Erasure Coding: Improve few exception handling logic of
+    ErasureCodingWorker. (Rakesh R via jing9)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/6546d9e7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
index 60c8417..b08aa2e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/erasurecode/ErasureCodingWorker.java
@@ -124,7 +124,7 @@ public final class ErasureCodingWorker {
   }
 
   private void initializeStripedReadThreadPool(int num) {
-    LOG.debug("Using striped reads; pool threads=" + num);
+    LOG.debug("Using striped reads; pool threads={}", num);
 
     EC_RECONSTRUCTION_STRIPED_READ_THREAD_POOL = new ThreadPoolExecutor(1, num,
         60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
@@ -150,7 +150,7 @@ public final class ErasureCodingWorker {
   }
 
   private void initializeStripedBlkReconstructionThreadPool(int num) {
-    LOG.debug("Using striped block reconstruction; pool threads=" + num);
+    LOG.debug("Using striped block reconstruction; pool threads={}" + num);
     EC_RECONSTRUCTION_STRIPED_BLK_THREAD_POOL = new ThreadPoolExecutor(2, num,
         60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
         new Daemon.DaemonFactory() {
@@ -180,8 +180,8 @@ public final class ErasureCodingWorker {
         EC_RECONSTRUCTION_STRIPED_BLK_THREAD_POOL
             .submit(new ReconstructAndTransferBlock(reconstructionInfo));
       } catch (Throwable e) {
-        LOG.warn("Failed to reconstruct striped block "
-            + reconstructionInfo.getExtendedBlock().getLocalBlock(), e);
+        LOG.warn("Failed to reconstruct striped block {}",
+            reconstructionInfo.getExtendedBlock().getLocalBlock(), e);
       }
     }
   }
@@ -476,12 +476,12 @@ public final class ErasureCodingWorker {
         // Currently we don't check the acks for packets, this is similar as
         // block replication.
       } catch (Throwable e) {
-        LOG.warn("Failed to reconstruct striped block: " + blockGroup, e);
+        LOG.warn("Failed to reconstruct striped block: {}", blockGroup, e);
       } finally {
         datanode.decrementXmitsInProgress();
         // close block readers
         for (StripedReader stripedReader : stripedReaders) {
-          closeBlockReader(stripedReader.blockReader);
+          IOUtils.closeStream(stripedReader.blockReader);
         }
         for (int i = 0; i < targets.length; i++) {
           IOUtils.closeStream(targetOutputStreams[i]);
@@ -588,7 +588,7 @@ public final class ErasureCodingWorker {
             // If read failed for some source DN, we should not use it anymore 
             // and schedule read from another source DN.
             StripedReader failedReader = stripedReaders.get(result.index);
-            closeBlockReader(failedReader.blockReader);
+            IOUtils.closeStream(failedReader.blockReader);
             failedReader.blockReader = null;
             resultIndex = scheduleNewRead(used, reconstructLength,
                 corruptionMap);
@@ -609,6 +609,8 @@ public final class ErasureCodingWorker {
           }
         } catch (InterruptedException e) {
           LOG.info("Read data interrupted.", e);
+          cancelReads(futures.keySet());
+          futures.clear();
           break;
         }
       }
@@ -736,7 +738,7 @@ public final class ErasureCodingWorker {
           StripedReader r = stripedReaders.get(i);
           toRead = getReadLength(liveIndices[i], reconstructLen);
           if (toRead > 0) {
-            closeBlockReader(r.blockReader);
+            IOUtils.closeStream(r.blockReader);
             r.blockReader = newBlockReader(
                 getBlock(blockGroup, liveIndices[i]), positionInBlock,
                 sources[i]);
@@ -784,8 +786,8 @@ public final class ErasureCodingWorker {
             actualReadFromBlock(reader.blockReader, buf);
             return null;
           } catch (ChecksumException e) {
-            LOG.warn("Found Checksum error for " + reader.block + " from "
-                + reader.source + " at " + e.getPos());
+            LOG.warn("Found Checksum error for {} from {} at {}", reader.block,
+                reader.source, e.getPos());
             addCorruptedBlock(reader.block, reader.source, corruptionMap);
             throw e;
           } catch (IOException e) {
@@ -837,17 +839,6 @@ public final class ErasureCodingWorker {
       }
     }
 
-    // close block reader
-    private void closeBlockReader(BlockReader blockReader) {
-      try {
-        if (blockReader != null) {
-          blockReader.close();
-        }
-      } catch (IOException e) {
-        // ignore
-      }
-    }
-
     private InetSocketAddress getSocketAddress4Transfer(DatanodeInfo dnInfo) {
       return NetUtils.createSocketAddr(dnInfo.getXferAddr(
           datanode.getDnConf().getConnectToDnViaHostname()));
@@ -867,8 +858,6 @@ public final class ErasureCodingWorker {
          * read directly from DN and need to check the replica is FINALIZED
          * state, notice we should not use short-circuit local read which
          * requires config for domain-socket in UNIX or legacy config in Windows.
-         *
-         * TODO: add proper tracer
          */
         return RemoteBlockReader2.newBlockReader(
             "dummy", block, blockToken, offsetInBlock, 
@@ -876,6 +865,8 @@ public final class ErasureCodingWorker {
             "", newConnectedPeer(block, dnAddr, blockToken, dnInfo), dnInfo,
             null, cachingStrategy, datanode.getTracer());
       } catch (IOException e) {
+        LOG.debug("Exception while creating remote block reader, datanode {}",
+            dnInfo, e);
         return null;
       }
     }


[46/50] [abbrv] hadoop git commit: HDFS-9549. TestCacheDirectives#testExceedsCapacity is flaky (Xiao Chen via cmccabe)

Posted by ji...@apache.org.
HDFS-9549. TestCacheDirectives#testExceedsCapacity is flaky (Xiao Chen via cmccabe)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/211c78c0
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/211c78c0
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/211c78c0

Branch: refs/heads/HDFS-7240
Commit: 211c78c09073e5b34db309b49d8de939a7a812f5
Parents: d9c409a
Author: Colin Patrick Mccabe <cm...@cloudera.com>
Authored: Tue Feb 23 12:01:20 2016 -0800
Committer: Colin Patrick Mccabe <cm...@cloudera.com>
Committed: Tue Feb 23 12:01:20 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  3 +++
 .../CacheReplicationMonitor.java                | 27 +++++++++++++++++---
 .../server/blockmanagement/DatanodeManager.java |  9 +++++++
 .../server/namenode/TestCacheDirectives.java    |  7 +----
 4 files changed, 37 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/211c78c0/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 440b7e8..526ddff 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2816,6 +2816,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-9842. dfs.datanode.balance.bandwidthPerSec should accept friendly
     size units.  (Lin Yiqun via Arpit Agarwal)
 
+    HDFS-9549. TestCacheDirectives#testExceedsCapacity is flaky (Xiao Chen via
+    cmccabe)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/211c78c0/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
index 2f81ddf..87cd716 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/CacheReplicationMonitor.java
@@ -27,6 +27,7 @@ import java.util.Date;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Set;
 import java.util.Random;
 import java.util.TreeMap;
 import java.util.concurrent.TimeUnit;
@@ -491,6 +492,26 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
    * Blocks that are over-replicated should be removed from Datanodes.
    */
   private void rescanCachedBlockMap() {
+    // Remove pendingCached blocks that will make DN out-of-capacity.
+    Set<DatanodeDescriptor> datanodes =
+        blockManager.getDatanodeManager().getDatanodes();
+    for (DatanodeDescriptor dn : datanodes) {
+      long remaining = dn.getCacheRemaining();
+      for (Iterator<CachedBlock> it = dn.getPendingCached().iterator();
+           it.hasNext();) {
+        CachedBlock cblock = it.next();
+        BlockInfo blockInfo = blockManager.
+            getStoredBlock(new Block(cblock.getBlockId()));
+        if (blockInfo.getNumBytes() > remaining) {
+          LOG.debug("Block {}: removing from PENDING_CACHED for node {} "
+                  + "because it cannot fit in remaining cache size {}.",
+              cblock.getBlockId(), dn.getDatanodeUuid(), remaining);
+          it.remove();
+        } else {
+          remaining -= blockInfo.getNumBytes();
+        }
+      }
+    }
     for (Iterator<CachedBlock> cbIter = cachedBlocks.iterator();
         cbIter.hasNext(); ) {
       scannedBlocks++;
@@ -531,7 +552,7 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
           DatanodeDescriptor datanode = iter.next();
           datanode.getPendingCached().remove(cblock);
           iter.remove();
-          LOG.trace("Block {}: removing from PENDING_CACHED for node {}"
+          LOG.trace("Block {}: removing from PENDING_CACHED for node {} "
                   + "because we already have {} cached replicas and we only" +
                   " need {}",
               cblock.getBlockId(), datanode.getDatanodeUuid(), numCached,
@@ -686,8 +707,8 @@ public class CacheReplicationMonitor extends Thread implements Closeable {
       long pendingCapacity = pendingBytes + datanode.getCacheRemaining();
       if (pendingCapacity < blockInfo.getNumBytes()) {
         LOG.trace("Block {}: DataNode {} is not a valid possibility " +
-            "because the block has size {}, but the DataNode only has {}" +
-            "bytes of cache remaining ({} pending bytes, {} already cached.",
+            "because the block has size {}, but the DataNode only has {} " +
+            "bytes of cache remaining ({} pending bytes, {} already cached.)",
             blockInfo.getBlockId(), datanode.getDatanodeUuid(),
             blockInfo.getNumBytes(), pendingCapacity, pendingBytes,
             datanode.getCacheRemaining());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/211c78c0/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
index d344ca6..999c1fa 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeManager.java
@@ -413,6 +413,15 @@ public class DatanodeManager {
     return host2DatanodeMap.getDatanodeByXferAddr(host, xferPort);
   }
 
+  /** @return the datanode descriptors for all nodes. */
+  public Set<DatanodeDescriptor> getDatanodes() {
+    final Set<DatanodeDescriptor> datanodes;
+    synchronized (this) {
+      datanodes = new HashSet<>(datanodeMap.values());
+    }
+    return datanodes;
+  }
+
   /** @return the Host2NodesMap */
   public Host2NodesMap getHost2DatanodeMap() {
     return this.host2DatanodeMap;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/211c78c0/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestCacheDirectives.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestCacheDirectives.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestCacheDirectives.java
index 45d819e..3793cae 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestCacheDirectives.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestCacheDirectives.java
@@ -72,7 +72,6 @@ import org.apache.hadoop.hdfs.protocol.CachePoolStats;
 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
 import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
 import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
-import org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor.CachedBlocksList.Type;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
@@ -86,9 +85,6 @@ import org.apache.hadoop.security.AccessControlException;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.GSet;
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-import org.apache.log4j.Logger;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -1470,6 +1466,7 @@ public class TestCacheDirectives {
    */
   private void checkPendingCachedEmpty(MiniDFSCluster cluster)
       throws Exception {
+    Thread.sleep(1000);
     cluster.getNamesystem().readLock();
     try {
       final DatanodeManager datanodeManager =
@@ -1501,7 +1498,6 @@ public class TestCacheDirectives {
     waitForCachedBlocks(namenode, -1, numCachedReplicas,
         "testExceeds:1");
     checkPendingCachedEmpty(cluster);
-    Thread.sleep(1000);
     checkPendingCachedEmpty(cluster);
 
     // Try creating a file with giant-sized blocks that exceed cache capacity
@@ -1509,7 +1505,6 @@ public class TestCacheDirectives {
     DFSTestUtil.createFile(dfs, fileName, 4096, fileLen, CACHE_CAPACITY * 2,
         (short) 1, 0xFADED);
     checkPendingCachedEmpty(cluster);
-    Thread.sleep(1000);
     checkPendingCachedEmpty(cluster);
   }
 


[33/50] [abbrv] hadoop git commit: HDFS-9842. dfs.datanode.balance.bandwidthPerSec should accept friendly size units. (Contributed by Lin Yiqun)

Posted by ji...@apache.org.
HDFS-9842. dfs.datanode.balance.bandwidthPerSec should accept friendly size units. (Contributed by Lin Yiqun)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a63301a8
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a63301a8
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a63301a8

Branch: refs/heads/HDFS-7240
Commit: a63301a8645ca9ab36b782d03af96e9c4e901db5
Parents: 3fab885
Author: Arpit Agarwal <ar...@apache.org>
Authored: Mon Feb 22 11:34:09 2016 -0800
Committer: Arpit Agarwal <ar...@apache.org>
Committed: Mon Feb 22 11:34:09 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt                    | 3 +++
 .../apache/hadoop/hdfs/server/datanode/DataXceiverServer.java  | 2 +-
 .../hadoop-hdfs/src/main/resources/hdfs-default.xml            | 6 +++++-
 3 files changed, 9 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a63301a8/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 3552c8e..c39bcee 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2810,6 +2810,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-7452. skip StandbyException log for getCorruptFiles()
     (Bramha Reddy Battula via vinayakumarb)
 
+    HDFS-9842. dfs.datanode.balance.bandwidthPerSec should accept friendly
+    size units.  (Lin Yiqun via Arpit Agarwal)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a63301a8/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java
index 36cf8a1..8152e6f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java
@@ -131,7 +131,7 @@ class DataXceiverServer implements Runnable {
     
     //set up parameter for cluster balancing
     this.balanceThrottler = new BlockBalanceThrottler(
-        conf.getLong(DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY,
+        conf.getLongBytes(DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY,
             DFSConfigKeys.DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_DEFAULT),
         conf.getInt(DFSConfigKeys.DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_KEY,
             DFSConfigKeys.DFS_DATANODE_BALANCE_MAX_NUM_CONCURRENT_MOVES_DEFAULT));

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a63301a8/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
index 1560335..716cbd4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
@@ -815,7 +815,11 @@
   <description>
         Specifies the maximum amount of bandwidth that each datanode
         can utilize for the balancing purpose in term of
-        the number of bytes per second.
+        the number of bytes per second. You can use the following
+        suffix (case insensitive):
+        k(kilo), m(mega), g(giga), t(tera), p(peta), e(exa)to specify the size
+        (such as 128k, 512m, 1g, etc.).
+        Or provide complete size in bytes (such as 134217728 for 128 MB).
   </description>
 </property>
 


[43/50] [abbrv] hadoop git commit: YARN-4648. Move preemption related tests from TestFairScheduler to TestFairSchedulerPreemption. Contributed by Kai Sasaki.

Posted by ji...@apache.org.
YARN-4648. Move preemption related tests from TestFairScheduler to TestFairSchedulerPreemption. Contributed by Kai Sasaki.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/0e12114c
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/0e12114c
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/0e12114c

Branch: refs/heads/HDFS-7240
Commit: 0e12114c9ccb0c6b16c258227a433b075418796e
Parents: 48c61cd
Author: Tsuyoshi Ozawa <oz...@apache.org>
Authored: Tue Feb 23 19:50:08 2016 +0900
Committer: Tsuyoshi Ozawa <oz...@apache.org>
Committed: Tue Feb 23 19:50:08 2016 +0900

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                 |    3 +
 .../scheduler/fair/TestFairScheduler.java       | 1204 ----------------
 .../fair/TestFairSchedulerPreemption.java       | 1295 +++++++++++++++++-
 3 files changed, 1293 insertions(+), 1209 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e12114c/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index a25a580..e2ffec0 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -138,6 +138,9 @@ Release 2.9.0 - UNRELEASED
     YARN-4708. Missing default mapper type in TimelineServer performance test tool
     usage. (Kai Sasaki via ozawa)
 
+    YARN-4648. Move preemption related tests from TestFairScheduler to
+    TestFairSchedulerPreemption. (Kai Sasaki via ozawa)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e12114c/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
index fac28b7..0575f33 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairScheduler.java
@@ -57,7 +57,6 @@ import org.apache.hadoop.yarn.MockApps;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
-import org.apache.hadoop.yarn.api.records.Container;
 import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
 import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
@@ -94,11 +93,9 @@ import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAddedSch
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptAddedSchedulerEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.AppAttemptRemovedSchedulerEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerExpiredSchedulerEvent;
-import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerPreemptEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent;
-import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.QueuePlacementRule.Default;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.DominantResourceFairnessPolicy;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.policies.FifoPolicy;
@@ -1793,1122 +1790,6 @@ public class TestFairScheduler extends FairSchedulerTestBase {
     assertEquals(0.5f, root.getFairSharePreemptionThreshold(), 0.01);
   }
 
-  @Test (timeout = 5000)
-  /**
-   * Make sure containers are chosen to be preempted in the correct order.
-   */
-  public void testChoiceOfPreemptedContainers() throws Exception {
-    conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
-    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE + ".allocation.file", ALLOC_FILE);
-    conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false");
-    
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-    
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>.25</weight>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>.25</weight>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>.25</weight>");
-    out.println("</queue>");
-    out.println("<queue name=\"default\">");
-    out.println("<weight>.25</weight>");
-    out.println("</queue>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Create two nodes
-    RMNode node1 =
-        MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 1,
-            "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    RMNode node2 =
-        MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 2,
-            "127.0.0.2");
-    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
-    scheduler.handle(nodeEvent2);
-
-    // Queue A and B each request two applications
-    ApplicationAttemptId app1 =
-        createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 1);
-    createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1);
-    ApplicationAttemptId app2 =
-        createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 3);
-    createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app2);
-
-    ApplicationAttemptId app3 =
-        createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 1);
-    createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app3);
-    ApplicationAttemptId app4 =
-        createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 3);
-    createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app4);
-
-    scheduler.update();
-
-    scheduler.getQueueManager().getLeafQueue("queueA", true)
-        .setPolicy(SchedulingPolicy.parse("fifo"));
-    scheduler.getQueueManager().getLeafQueue("queueB", true)
-        .setPolicy(SchedulingPolicy.parse("fair"));
-
-    // Sufficient node check-ins to fully schedule containers
-    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-    NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-    for (int i = 0; i < 4; i++) {
-      scheduler.handle(nodeUpdate1);
-      scheduler.handle(nodeUpdate2);
-    }
-
-    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size());
-
-    // Now new requests arrive from queueC and default
-    createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
-    scheduler.update();
-
-    // We should be able to claw back one container from queueA and queueB each.
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-
-    // First verify we are adding containers to preemption list for the app.
-    // For queueA (fifo), app2 is selected.
-    // For queueB (fair), app4 is selected.
-    assertTrue("App2 should have container to be preempted",
-        !Collections.disjoint(
-            scheduler.getSchedulerApp(app2).getLiveContainers(),
-            scheduler.getSchedulerApp(app2).getPreemptionContainers()));
-    assertTrue("App4 should have container to be preempted",
-        !Collections.disjoint(
-            scheduler.getSchedulerApp(app2).getLiveContainers(),
-            scheduler.getSchedulerApp(app2).getPreemptionContainers()));
-
-    // Pretend 15 seconds have passed
-    clock.tickSec(15);
-
-    // Trigger a kill by insisting we want containers back
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-
-    // At this point the containers should have been killed (since we are not simulating AM)
-    assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
-    // Inside each app, containers are sorted according to their priorities.
-    // Containers with priority 4 are preempted for app2 and app4.
-    Set<RMContainer> set = new HashSet<RMContainer>();
-    for (RMContainer container :
-        scheduler.getSchedulerApp(app2).getLiveContainers()) {
-      if (container.getAllocatedPriority().getPriority() == 4) {
-        set.add(container);
-      }
-    }
-    for (RMContainer container :
-        scheduler.getSchedulerApp(app4).getLiveContainers()) {
-      if (container.getAllocatedPriority().getPriority() == 4) {
-        set.add(container);
-      }
-    }
-    assertTrue("Containers with priority=4 in app2 and app4 should be " +
-        "preempted.", set.isEmpty());
-
-    // Trigger a kill by insisting we want containers back
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-
-    // Pretend 15 seconds have passed
-    clock.tickSec(15);
-
-    // We should be able to claw back another container from A and B each.
-    // For queueA (fifo), continue preempting from app2.
-    // For queueB (fair), even app4 has a lowest priority container with p=4, it
-    // still preempts from app3 as app3 is most over fair share.
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-
-    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(0, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(1, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-    assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
-
-    // Now A and B are below fair share, so preemption shouldn't do anything
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    assertTrue("App1 should have no container to be preempted",
-        scheduler.getSchedulerApp(app1).getPreemptionContainers().isEmpty());
-    assertTrue("App2 should have no container to be preempted",
-        scheduler.getSchedulerApp(app2).getPreemptionContainers().isEmpty());
-    assertTrue("App3 should have no container to be preempted",
-        scheduler.getSchedulerApp(app3).getPreemptionContainers().isEmpty());
-    assertTrue("App4 should have no container to be preempted",
-        scheduler.getSchedulerApp(app4).getPreemptionContainers().isEmpty());
-  }
-
-  @Test
-  public void testPreemptionIsNotDelayedToNextRound() throws Exception {
-    conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
-    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false");
-
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>8</weight>");
-    out.println("<queue name=\"queueA1\" />");
-    out.println("<queue name=\"queueA2\" />");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>2</weight>");
-    out.println("</queue>");
-    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Add a node of 8G
-    RMNode node1 = MockNodes.newNodeInfo(1,
-        Resources.createResource(8 * 1024, 8), 1, "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    // Run apps in queueA.A1 and queueB
-    ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, 1,
-        "queueA.queueA1", "user1", 7, 1);
-    // createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1);
-    ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, 1, "queueB",
-        "user2", 1, 1);
-
-    scheduler.update();
-
-    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-    for (int i = 0; i < 8; i++) {
-      scheduler.handle(nodeUpdate1);
-    }
-
-    // verify if the apps got the containers they requested
-    assertEquals(7, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-
-    // Now submit an app in queueA.queueA2
-    ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, 1,
-        "queueA.queueA2", "user3", 7, 1);
-    scheduler.update();
-
-    // Let 11 sec pass
-    clock.tickSec(11);
-
-    scheduler.update();
-    Resource toPreempt = scheduler.resourceDeficit(scheduler.getQueueManager()
-            .getLeafQueue("queueA.queueA2", false), clock.getTime());
-    assertEquals(3277, toPreempt.getMemory());
-
-    // verify if the 3 containers required by queueA2 are preempted in the same
-    // round
-    scheduler.preemptResources(toPreempt);
-    assertEquals(3, scheduler.getSchedulerApp(app1).getPreemptionContainers()
-        .size());
-  }
-
-  @Test (timeout = 5000)
-  /**
-   * Tests the timing of decision to preempt tasks.
-   */
-  public void testPreemptionDecision() throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("<maxResources>0mb,0vcores</maxResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueD\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Create four nodes
-    RMNode node1 =
-        MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 1,
-            "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    RMNode node2 =
-        MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 2,
-            "127.0.0.2");
-    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
-    scheduler.handle(nodeEvent2);
-
-    RMNode node3 =
-        MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 3,
-            "127.0.0.3");
-    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
-    scheduler.handle(nodeEvent3);
-
-    // Queue A and B each request three containers
-    ApplicationAttemptId app1 =
-        createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
-    ApplicationAttemptId app2 =
-        createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
-    ApplicationAttemptId app3 =
-        createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);
-
-    ApplicationAttemptId app4 =
-        createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
-    ApplicationAttemptId app5 =
-        createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
-    ApplicationAttemptId app6 =
-        createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);
-
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    for (int i = 0; i < 2; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-    }
-
-    // Now new requests arrive from queues C and D
-    ApplicationAttemptId app7 =
-        createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
-    ApplicationAttemptId app8 =
-        createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
-    ApplicationAttemptId app9 =
-        createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
-
-    ApplicationAttemptId app10 =
-        createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 1);
-    ApplicationAttemptId app11 =
-        createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 2);
-    ApplicationAttemptId app12 =
-        createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 3);
-
-    scheduler.update();
-
-    FSLeafQueue schedC =
-        scheduler.getQueueManager().getLeafQueue("queueC", true);
-    FSLeafQueue schedD =
-        scheduler.getQueueManager().getLeafQueue("queueD", true);
-
-    assertTrue(Resources.equals(
-        Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime())));
-    assertTrue(Resources.equals(
-        Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime())));
-    // After minSharePreemptionTime has passed, they should want to preempt min
-    // share.
-    clock.tickSec(6);
-    assertEquals(
-        1024, scheduler.resourceDeficit(schedC, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
-
-    // After fairSharePreemptionTime has passed, they should want to preempt
-    // fair share.
-    scheduler.update();
-    clock.tickSec(6);
-    assertEquals(
-        1536 , scheduler.resourceDeficit(schedC, clock.getTime()).getMemory());
-    assertEquals(
-        1536, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
-  }
-
-  @Test
-/**
- * Tests the timing of decision to preempt tasks.
- */
-  public void testPreemptionDecisionWithDRF() throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("<maxResources>0mb,0vcores</maxResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,1vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,2vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,3vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueD\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,2vcores</minResources>");
-    out.println("</queue>");
-    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
-    out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Create four nodes
-    RMNode node1 =
-            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 1,
-                    "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    RMNode node2 =
-            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 2,
-                    "127.0.0.2");
-    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
-    scheduler.handle(nodeEvent2);
-
-    RMNode node3 =
-            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 3,
-                    "127.0.0.3");
-    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
-    scheduler.handle(nodeEvent3);
-
-    // Queue A and B each request three containers
-    ApplicationAttemptId app1 =
-            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
-    ApplicationAttemptId app2 =
-            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
-    ApplicationAttemptId app3 =
-            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);
-
-    ApplicationAttemptId app4 =
-            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
-    ApplicationAttemptId app5 =
-            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
-    ApplicationAttemptId app6 =
-            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);
-
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    for (int i = 0; i < 2; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-    }
-
-    // Now new requests arrive from queues C and D
-    ApplicationAttemptId app7 =
-            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
-    ApplicationAttemptId app8 =
-            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
-    ApplicationAttemptId app9 =
-            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
-
-    ApplicationAttemptId app10 =
-            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 1);
-    ApplicationAttemptId app11 =
-            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 2);
-    ApplicationAttemptId app12 =
-            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 3);
-
-    scheduler.update();
-
-    FSLeafQueue schedC =
-            scheduler.getQueueManager().getLeafQueue("queueC", true);
-    FSLeafQueue schedD =
-            scheduler.getQueueManager().getLeafQueue("queueD", true);
-
-    assertTrue(Resources.equals(
-            Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime())));
-    assertTrue(Resources.equals(
-            Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime())));
-
-    // Test :
-    // 1) whether componentWise min works as expected.
-    // 2) DRF calculator is used
-
-    // After minSharePreemptionTime has passed, they should want to preempt min
-    // share.
-    clock.tickSec(6);
-    Resource res = scheduler.resourceDeficit(schedC, clock.getTime());
-    assertEquals(1024, res.getMemory());
-    // Demand = 3
-    assertEquals(3, res.getVirtualCores());
-
-    res = scheduler.resourceDeficit(schedD, clock.getTime());
-    assertEquals(1024, res.getMemory());
-    // Demand = 6, but min share = 2
-    assertEquals(2, res.getVirtualCores());
-
-    // After fairSharePreemptionTime has passed, they should want to preempt
-    // fair share.
-    scheduler.update();
-    clock.tickSec(6);
-    res = scheduler.resourceDeficit(schedC, clock.getTime());
-    assertEquals(1536, res.getMemory());
-    assertEquals(3, res.getVirtualCores());
-
-    res = scheduler.resourceDeficit(schedD, clock.getTime());
-    assertEquals(1536, res.getMemory());
-    // Demand = 6, but fair share = 3
-    assertEquals(3, res.getVirtualCores());
-  }
-
-  @Test
-  /**
-   * Tests the various timing of decision to preempt tasks.
-   */
-  public void testPreemptionDecisionWithVariousTimeout() throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("<maxResources>0mb,0vcores</maxResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>1</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>2</weight>");
-    out.println("<minSharePreemptionTimeout>10</minSharePreemptionTimeout>");
-    out.println("<fairSharePreemptionTimeout>25</fairSharePreemptionTimeout>");
-    out.println("<queue name=\"queueB1\">");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB2\">");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("<fairSharePreemptionTimeout>20</fairSharePreemptionTimeout>");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>1</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
-    out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Check the min/fair share preemption timeout for each queue
-    QueueManager queueMgr = scheduler.getQueueManager();
-    assertEquals(30000, queueMgr.getQueue("root")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("default")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueA")
-        .getFairSharePreemptionTimeout());
-    assertEquals(25000, queueMgr.getQueue("queueB")
-        .getFairSharePreemptionTimeout());
-    assertEquals(25000, queueMgr.getQueue("queueB.queueB1")
-        .getFairSharePreemptionTimeout());
-    assertEquals(20000, queueMgr.getQueue("queueB.queueB2")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueC")
-        .getFairSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("root")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("default")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueA")
-        .getMinSharePreemptionTimeout());
-    assertEquals(10000, queueMgr.getQueue("queueB")
-        .getMinSharePreemptionTimeout());
-    assertEquals(5000, queueMgr.getQueue("queueB.queueB1")
-        .getMinSharePreemptionTimeout());
-    assertEquals(10000, queueMgr.getQueue("queueB.queueB2")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueC")
-        .getMinSharePreemptionTimeout());
-
-    // Create one big node
-    RMNode node1 =
-        MockNodes.newNodeInfo(1, Resources.createResource(6 * 1024, 6), 1,
-            "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    // Queue A takes all resources
-    for (int i = 0; i < 6; i ++) {
-      createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
-    }
-
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-    for (int i = 0; i < 6; i++) {
-      scheduler.handle(nodeUpdate1);
-    }
-
-    // Now new requests arrive from queues B1, B2 and C
-    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 2);
-    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 3);
-    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 2);
-    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 3);
-    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
-    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
-    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
-
-    scheduler.update();
-
-    FSLeafQueue queueB1 = queueMgr.getLeafQueue("queueB.queueB1", true);
-    FSLeafQueue queueB2 = queueMgr.getLeafQueue("queueB.queueB2", true);
-    FSLeafQueue queueC = queueMgr.getLeafQueue("queueC", true);
-
-    assertTrue(Resources.equals(
-        Resources.none(), scheduler.resourceDeficit(queueB1, clock.getTime())));
-    assertTrue(Resources.equals(
-        Resources.none(), scheduler.resourceDeficit(queueB2, clock.getTime())));
-    assertTrue(Resources.equals(
-        Resources.none(), scheduler.resourceDeficit(queueC, clock.getTime())));
-
-    // After 5 seconds, queueB1 wants to preempt min share
-    scheduler.update();
-    clock.tickSec(6);
-    assertEquals(
-       1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        0, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-
-    // After 10 seconds, queueB2 wants to preempt min share
-    scheduler.update();
-    clock.tickSec(5);
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-
-    // After 15 seconds, queueC wants to preempt min share
-    scheduler.update();
-    clock.tickSec(5);
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-
-    // After 20 seconds, queueB2 should want to preempt fair share
-    scheduler.update();
-    clock.tickSec(5);
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-
-    // After 25 seconds, queueB1 should want to preempt fair share
-    scheduler.update();
-    clock.tickSec(5);
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-
-    // After 30 seconds, queueC should want to preempt fair share
-    scheduler.update();
-    clock.tickSec(5);
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
-    assertEquals(
-        1536, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
-  }
-
-  @Test
-  /**
-   * Tests the decision to preempt tasks respect to non-preemptable queues
-   * 1, Queues as follow:
-   *   queueA(non-preemptable)
-   *   queueB(preemptable)
-   *   parentQueue(non-preemptable)
-   *     --queueC(preemptable)
-   *   queueD(preemptable)
-   * 2, Submit request to queueA, queueB, queueC, and all of them are over MinShare
-   * 3, Now all resource are occupied
-   * 4, Submit request to queueD, and need to preempt resource from other queues
-   * 5, Only preemptable queue(queueB) would be preempted.
-   */
-  public void testPreemptionDecisionWithNonPreemptableQueue() throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("<maxResources>0mb,0vcores</maxResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"parentQueue\">");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueD\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>2048mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Create four nodes(3G each)
-    RMNode node1 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 1,
-            "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    RMNode node2 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 2,
-            "127.0.0.2");
-    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
-    scheduler.handle(nodeEvent2);
-
-    RMNode node3 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 3,
-            "127.0.0.3");
-    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
-    scheduler.handle(nodeEvent3);
-
-    RMNode node4 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 4,
-            "127.0.0.4");
-    NodeAddedSchedulerEvent nodeEvent4 = new NodeAddedSchedulerEvent(node4);
-    scheduler.handle(nodeEvent4);
-
-    // Submit apps to queueA, queueB, queueC,
-    // now all resource of the cluster is occupied
-    ApplicationAttemptId app1 =
-        createSchedulingRequest(1 * 1024, "queueA", "user1", 4, 1);
-    ApplicationAttemptId app2 =
-        createSchedulingRequest(1 * 1024, "queueB", "user1", 4, 2);
-    ApplicationAttemptId app3 =
-        createSchedulingRequest(1 * 1024, "parentQueue.queueC", "user1", 4, 3);
-
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    for (int i = 0; i < 3; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-
-      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
-      scheduler.handle(nodeUpdate4);
-    }
-
-    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-
-    // Now new requests arrive from queues D
-    ApplicationAttemptId app4 =
-        createSchedulingRequest(1 * 1024, "queueD", "user1", 4, 1);
-    scheduler.update();
-    FSLeafQueue schedD =
-        scheduler.getQueueManager().getLeafQueue("queueD", true);
-
-    // After minSharePreemptionTime has passed, 2G resource should preempted from
-    // queueB to queueD
-    clock.tickSec(6);
-    assertEquals(2048,
-        scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
-
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    // now only app2 is selected to be preempted
-    assertTrue("App2 should have container to be preempted",
-        !Collections.disjoint(
-            scheduler.getSchedulerApp(app2).getLiveContainers(),
-            scheduler.getSchedulerApp(app2).getPreemptionContainers()));
-    assertTrue("App1 should not have container to be preempted",
-        Collections.disjoint(
-            scheduler.getSchedulerApp(app1).getLiveContainers(),
-            scheduler.getSchedulerApp(app1).getPreemptionContainers()));
-    assertTrue("App3 should not have container to be preempted",
-        Collections.disjoint(
-            scheduler.getSchedulerApp(app3).getLiveContainers(),
-            scheduler.getSchedulerApp(app3).getPreemptionContainers()));
-    // Pretend 20 seconds have passed
-    clock.tickSec(20);
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    for (int i = 0; i < 3; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-
-      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
-      scheduler.handle(nodeUpdate4);
-    }
-    // after preemption
-    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-    assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size());
-  }
-
-  @Test
-  /**
-   * Tests the decision to preempt tasks when allowPreemptionFrom is set false on
-   * all queues.
-   * Then none of them would be preempted actually.
-   * 1, Queues as follow:
-   *   queueA(non-preemptable)
-   *   queueB(non-preemptable)
-   *   parentQueue(non-preemptable)
-   *     --queueC(preemptable)
-   *   parentQueue(preemptable)
-   *     --queueD(non-preemptable)
-   * 2, Submit request to queueB, queueC, queueD, and all of them are over MinShare
-   * 3, Now all resource are occupied
-   * 4, Submit request to queueA, and need to preempt resource from other queues
-   * 5, None of queues would be preempted.
-   */
-  public void testPreemptionDecisionWhenPreemptionDisabledOnAllQueues()
-      throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("<maxResources>0mb,0vcores</maxResources>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>2048mb,0vcores</minResources>");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("</queue>");
-    out.println("<queue name=\"parentQueue1\">");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("<queue name=\"queueC\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<queue name=\"parentQueue2\">");
-    out.println("<queue name=\"queueD\">");
-    out.println("<weight>.25</weight>");
-    out.println("<minResources>1024mb,0vcores</minResources>");
-    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
-    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Create four nodes(3G each)
-    RMNode node1 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 1,
-            "127.0.0.1");
-    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
-    scheduler.handle(nodeEvent1);
-
-    RMNode node2 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 2,
-            "127.0.0.2");
-    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
-    scheduler.handle(nodeEvent2);
-
-    RMNode node3 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 3,
-            "127.0.0.3");
-    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
-    scheduler.handle(nodeEvent3);
-
-    RMNode node4 =
-        MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 4,
-            "127.0.0.4");
-    NodeAddedSchedulerEvent nodeEvent4 = new NodeAddedSchedulerEvent(node4);
-    scheduler.handle(nodeEvent4);
-
-    // Submit apps to queueB, queueC, queueD
-    // now all resource of the cluster is occupied
-
-    ApplicationAttemptId app1 =
-        createSchedulingRequest(1 * 1024, "queueB", "user1", 4, 1);
-    ApplicationAttemptId app2 =
-        createSchedulingRequest(1 * 1024, "parentQueue1.queueC", "user1", 4, 2);
-    ApplicationAttemptId app3 =
-        createSchedulingRequest(1 * 1024, "parentQueue2.queueD", "user1", 4, 3);
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    for (int i = 0; i < 3; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-
-      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
-      scheduler.handle(nodeUpdate4);
-    }
-
-    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-
-    // Now new requests arrive from queues A
-    ApplicationAttemptId app4 =
-        createSchedulingRequest(1 * 1024, "queueA", "user1", 4, 1);
-    scheduler.update();
-    FSLeafQueue schedA =
-        scheduler.getQueueManager().getLeafQueue("queueA", true);
-
-    // After minSharePreemptionTime has passed, resource deficit is 2G
-    clock.tickSec(6);
-    assertEquals(2048,
-        scheduler.resourceDeficit(schedA, clock.getTime()).getMemory());
-
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    // now none app is selected to be preempted
-    assertTrue("App1 should have container to be preempted",
-        Collections.disjoint(
-            scheduler.getSchedulerApp(app1).getLiveContainers(),
-            scheduler.getSchedulerApp(app1).getPreemptionContainers()));
-    assertTrue("App2 should not have container to be preempted",
-        Collections.disjoint(
-            scheduler.getSchedulerApp(app2).getLiveContainers(),
-            scheduler.getSchedulerApp(app2).getPreemptionContainers()));
-    assertTrue("App3 should not have container to be preempted",
-        Collections.disjoint(
-            scheduler.getSchedulerApp(app3).getLiveContainers(),
-            scheduler.getSchedulerApp(app3).getPreemptionContainers()));
-    // Pretend 20 seconds have passed
-    clock.tickSec(20);
-    scheduler.preemptResources(Resources.createResource(2 * 1024));
-    for (int i = 0; i < 3; i++) {
-      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
-      scheduler.handle(nodeUpdate1);
-
-      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
-      scheduler.handle(nodeUpdate2);
-
-      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
-      scheduler.handle(nodeUpdate3);
-
-      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
-      scheduler.handle(nodeUpdate4);
-    }
-    // after preemption
-    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
-    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
-    assertEquals(0, scheduler.getSchedulerApp(app4).getLiveContainers().size());
-  }
-
-  @Test
-  public void testBackwardsCompatiblePreemptionConfiguration() throws Exception {
-    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
-
-    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<queue name=\"queueB1\">");
-    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB2\">");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("</queue>");
-    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
-    out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>");
-    out.print("<fairSharePreemptionTimeout>40</fairSharePreemptionTimeout>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    // Check the min/fair share preemption timeout for each queue
-    QueueManager queueMgr = scheduler.getQueueManager();
-    assertEquals(30000, queueMgr.getQueue("root")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("default")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueA")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueB")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueB.queueB1")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueB.queueB2")
-        .getFairSharePreemptionTimeout());
-    assertEquals(30000, queueMgr.getQueue("queueC")
-        .getFairSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("root")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("default")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueA")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueB")
-        .getMinSharePreemptionTimeout());
-    assertEquals(5000, queueMgr.getQueue("queueB.queueB1")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueB.queueB2")
-        .getMinSharePreemptionTimeout());
-    assertEquals(15000, queueMgr.getQueue("queueC")
-        .getMinSharePreemptionTimeout());
-
-    // If both exist, we take the default one
-    out = new PrintWriter(new FileWriter(ALLOC_FILE));
-    out.println("<?xml version=\"1.0\"?>");
-    out.println("<allocations>");
-    out.println("<queue name=\"default\">");
-    out.println("</queue>");
-    out.println("<queue name=\"queueA\">");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB\">");
-    out.println("<queue name=\"queueB1\">");
-    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueB2\">");
-    out.println("</queue>");
-    out.println("</queue>");
-    out.println("<queue name=\"queueC\">");
-    out.println("</queue>");
-    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
-    out.print("<defaultFairSharePreemptionTimeout>25</defaultFairSharePreemptionTimeout>");
-    out.print("<fairSharePreemptionTimeout>30</fairSharePreemptionTimeout>");
-    out.println("</allocations>");
-    out.close();
-
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    assertEquals(25000, queueMgr.getQueue("root")
-        .getFairSharePreemptionTimeout());
-  }
-
   @Test(timeout = 5000)
   public void testMultipleContainersWaitingForReservation() throws IOException {
     scheduler.init(conf);
@@ -5062,91 +3943,6 @@ public class TestFairScheduler extends FairSchedulerTestBase {
       }
     }
   }
-
-  @Test(timeout = 5000)
-  public void testRecoverRequestAfterPreemption() throws Exception {
-    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10);
-
-    ControlledClock clock = new ControlledClock();
-    scheduler.setClock(clock);
-    scheduler.init(conf);
-    scheduler.start();
-    scheduler.reinitialize(conf, resourceManager.getRMContext());
-
-    Priority priority = Priority.newInstance(20);
-    String host = "127.0.0.1";
-    int GB = 1024;
-
-    // Create Node and raised Node Added event
-    RMNode node = MockNodes.newNodeInfo(1,
-        Resources.createResource(16 * 1024, 4), 0, host);
-    NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node);
-    scheduler.handle(nodeEvent);
-
-    // Create 3 container requests and place it in ask
-    List<ResourceRequest> ask = new ArrayList<ResourceRequest>();
-    ResourceRequest nodeLocalRequest = createResourceRequest(GB, 1, host,
-        priority.getPriority(), 1, true);
-    ResourceRequest rackLocalRequest = createResourceRequest(GB, 1,
-        node.getRackName(), priority.getPriority(), 1, true);
-    ResourceRequest offRackRequest = createResourceRequest(GB, 1,
-        ResourceRequest.ANY, priority.getPriority(), 1, true);
-    ask.add(nodeLocalRequest);
-    ask.add(rackLocalRequest);
-    ask.add(offRackRequest);
-
-    // Create Request and update
-    ApplicationAttemptId appAttemptId = createSchedulingRequest("queueA",
-        "user1", ask);
-    scheduler.update();
-
-    // Sufficient node check-ins to fully schedule containers
-    NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node);
-    scheduler.handle(nodeUpdate);
-
-    assertEquals(1, scheduler.getSchedulerApp(appAttemptId).getLiveContainers()
-        .size());
-    SchedulerApplicationAttempt app = scheduler.getSchedulerApp(appAttemptId);
-
-    // ResourceRequest will be empty once NodeUpdate is completed
-    Assert.assertNull(app.getResourceRequest(priority, host));
-
-    ContainerId containerId1 = ContainerId.newContainerId(appAttemptId, 1);
-    RMContainer rmContainer = app.getRMContainer(containerId1);
-
-    // Create a preempt event and register for preemption
-    scheduler.warnOrKillContainer(rmContainer);
-    
-    // Wait for few clock ticks
-    clock.tickSec(5);
-
-    // preempt now
-    scheduler.warnOrKillContainer(rmContainer);
-
-    // Trigger container rescheduled event
-    scheduler.handle(new ContainerPreemptEvent(appAttemptId, rmContainer,
-      SchedulerEventType.KILL_PREEMPTED_CONTAINER));
-
-    List<ResourceRequest> requests = rmContainer.getResourceRequests();
-    // Once recovered, resource request will be present again in app
-    Assert.assertEquals(3, requests.size());
-    for (ResourceRequest request : requests) {
-      Assert.assertEquals(1,
-          app.getResourceRequest(priority, request.getResourceName())
-              .getNumContainers());
-    }
-
-    // Send node heartbeat
-    scheduler.update();
-    scheduler.handle(nodeUpdate);
-
-    List<Container> containers = scheduler.allocate(appAttemptId,
-        Collections.<ResourceRequest> emptyList(),
-        Collections.<ContainerId> emptyList(), null, null, null, null).getContainers();
-
-    // Now with updated ResourceRequest, a container is allocated for AM.
-    Assert.assertTrue(containers.size() == 1);
-  }
   
   @Test
   public void testBlacklistNodes() throws Exception {


[08/50] [abbrv] hadoop git commit: MAPREDUCE-6634. Log uncaught exceptions/errors in various thread pools in mapreduce. Contributed by Sidharta Seethana.

Posted by ji...@apache.org.
MAPREDUCE-6634. Log uncaught exceptions/errors in various thread pools in mapreduce. Contributed by Sidharta Seethana.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/2440671a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/2440671a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/2440671a

Branch: refs/heads/HDFS-7240
Commit: 2440671a117f165dcda5056404bc898df3c50803
Parents: c1afac3
Author: Varun Vasudev <vv...@apache.org>
Authored: Thu Feb 18 14:15:08 2016 +0530
Committer: Varun Vasudev <vv...@apache.org>
Committed: Thu Feb 18 14:18:36 2016 +0530

----------------------------------------------------------------------
 hadoop-mapreduce-project/CHANGES.txt            |  3 ++
 .../hadoop/mapred/LocalContainerLauncher.java   |  4 +--
 .../v2/app/commit/CommitterEventHandler.java    |  3 +-
 .../mapreduce/v2/app/job/impl/JobImpl.java      |  3 +-
 .../v2/app/launcher/ContainerLauncherImpl.java  |  3 +-
 .../mapred/LocalDistributedCacheManager.java    |  5 ++--
 .../apache/hadoop/mapred/LocalJobRunner.java    |  8 +++--
 .../hadoop/mapred/LocatedFileStatusFetcher.java |  4 +--
 .../java/org/apache/hadoop/mapred/TaskLog.java  | 31 ++++++++++----------
 .../mapred/lib/MultithreadedMapRunner.java      |  4 ++-
 .../lib/output/TestFileOutputCommitter.java     |  4 +--
 .../mapreduce/v2/hs/HistoryFileManager.java     |  6 ++--
 .../hadoop/mapreduce/v2/hs/JobHistory.java      |  3 +-
 .../apache/hadoop/mapred/ShuffleHandler.java    |  6 ++--
 .../org/apache/hadoop/examples/pi/Util.java     |  5 ++--
 15 files changed, 53 insertions(+), 39 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index 0b8c818..da28bc6 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -310,6 +310,9 @@ Release 2.9.0 - UNRELEASED
 
     MAPREDUCE-6431. JobClient should be an AutoClosable (haibochen via rkanter)
 
+    MAPREDUCE-6634. Log uncaught exceptions/errors in various thread pools in
+    mapreduce. (Sidharta Seethana via vvasudev)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/LocalContainerLauncher.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/LocalContainerLauncher.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/LocalContainerLauncher.java
index 1a0d5fb..da118c5 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/LocalContainerLauncher.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/LocalContainerLauncher.java
@@ -26,7 +26,6 @@ import java.util.Map;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.LinkedBlockingQueue;
 
@@ -60,6 +59,7 @@ import org.apache.hadoop.service.AbstractService;
 import org.apache.hadoop.util.ExitUtil;
 import org.apache.hadoop.util.ShutdownHookManager;
 import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 import org.apache.hadoop.yarn.api.ApplicationConstants.Environment;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 
@@ -138,7 +138,7 @@ public class LocalContainerLauncher extends AbstractService implements
     // make it a daemon thread so that the process can exit even if the task is
     // not interruptible
     taskRunner =
-        Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().
+        HadoopExecutors.newSingleThreadExecutor(new ThreadFactoryBuilder().
             setDaemon(true).setNameFormat("uber-SubtaskRunner").build());
     // create and start an event handling thread
     eventHandler = new Thread(new EventHandler(), "uber-EventHandler");

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java
index b53955f..0b1be70 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/commit/CommitterEventHandler.java
@@ -49,6 +49,7 @@ import org.apache.hadoop.mapreduce.v2.util.MRApps;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.service.AbstractService;
 import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.concurrent.HadoopThreadPoolExecutor;
 import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 
@@ -133,7 +134,7 @@ public class CommitterEventHandler extends AbstractService
       tfBuilder.setThreadFactory(backingTf);
     }
     ThreadFactory tf = tfBuilder.build();
-    launcherPool = new ThreadPoolExecutor(5, 5, 1,
+    launcherPool = new HadoopThreadPoolExecutor(5, 5, 1,
         TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf);
     eventHandlingThread = new Thread(new Runnable() {
       @Override

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
index 5ed0762..c8c5ce9 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/JobImpl.java
@@ -116,6 +116,7 @@ import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.authorize.AccessControlList;
 import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.concurrent.HadoopScheduledThreadPoolExecutor;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.NodeId;
 import org.apache.hadoop.yarn.api.records.NodeReport;
@@ -698,7 +699,7 @@ public class JobImpl implements org.apache.hadoop.mapreduce.v2.app.job.Job,
       .setNameFormat("Job Fail Wait Timeout Monitor #%d")
       .setDaemon(true)
       .build();
-    this.executor = new ScheduledThreadPoolExecutor(1, threadFactory);
+    this.executor = new HadoopScheduledThreadPoolExecutor(1, threadFactory);
 
     // This "this leak" is okay because the retained pointer is in an
     //  instance variable.

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/launcher/ContainerLauncherImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/launcher/ContainerLauncherImpl.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/launcher/ContainerLauncherImpl.java
index a7e966c..189e2ef 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/launcher/ContainerLauncherImpl.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/launcher/ContainerLauncherImpl.java
@@ -45,6 +45,7 @@ import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptEvent;
 import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptEventType;
 import org.apache.hadoop.service.AbstractService;
 import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.concurrent.HadoopThreadPoolExecutor;
 import org.apache.hadoop.yarn.api.protocolrecords.StartContainerRequest;
 import org.apache.hadoop.yarn.api.protocolrecords.StartContainersRequest;
 import org.apache.hadoop.yarn.api.protocolrecords.StartContainersResponse;
@@ -266,7 +267,7 @@ public class ContainerLauncherImpl extends AbstractService implements
         "ContainerLauncher #%d").setDaemon(true).build();
 
     // Start with a default core-pool size of 10 and change it dynamically.
-    launcherPool = new ThreadPoolExecutor(initialPoolSize,
+    launcherPool = new HadoopThreadPoolExecutor(initialPoolSize,
         Integer.MAX_VALUE, 1, TimeUnit.HOURS,
         new LinkedBlockingQueue<Runnable>(),
         tf);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java
index 8606ede..3b87197 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalDistributedCacheManager.java
@@ -35,7 +35,6 @@ import java.util.Map.Entry;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicLong;
@@ -43,7 +42,6 @@ import java.util.concurrent.atomic.AtomicLong;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.FileContext;
-import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.FileUtil;
 import org.apache.hadoop.fs.LocalDirAllocator;
 import org.apache.hadoop.fs.Path;
@@ -53,6 +51,7 @@ import org.apache.hadoop.mapreduce.filecache.DistributedCache;
 import org.apache.hadoop.mapreduce.v2.util.MRApps;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.util.StringUtils;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 import org.apache.hadoop.yarn.api.records.LocalResource;
 import org.apache.hadoop.yarn.api.records.LocalResourceType;
 import org.apache.hadoop.yarn.util.ConverterUtils;
@@ -121,7 +120,7 @@ class LocalDistributedCacheManager {
       ThreadFactory tf = new ThreadFactoryBuilder()
       .setNameFormat("LocalDistributedCacheManager Downloader #%d")
       .build();
-      exec = Executors.newCachedThreadPool(tf);
+      exec = HadoopExecutors.newCachedThreadPool(tf);
       Path destPath = localDirAllocator.getLocalPathForWrite(".", conf);
       Map<LocalResource, Future<Path>> resourcesToPaths = Maps.newHashMap();
       for (LocalResource resource : localResources.values()) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalJobRunner.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalJobRunner.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalJobRunner.java
index 45d3cc5..37c147d 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalJobRunner.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapred/LocalJobRunner.java
@@ -32,7 +32,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Random;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -74,6 +73,7 @@ import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.util.ReflectionUtils;
 
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 
 /** Implements MapReduce locally, in-process, for debugging. */
 @InterfaceAudience.Private
@@ -428,7 +428,8 @@ public class LocalJobRunner implements ClientProtocol {
       ThreadFactory tf = new ThreadFactoryBuilder()
         .setNameFormat("LocalJobRunner Map Task Executor #%d")
         .build();
-      ExecutorService executor = Executors.newFixedThreadPool(maxMapThreads, tf);
+      ExecutorService executor = HadoopExecutors.newFixedThreadPool(
+          maxMapThreads, tf);
 
       return executor;
     }
@@ -454,7 +455,8 @@ public class LocalJobRunner implements ClientProtocol {
       LOG.debug("Reduce tasks to process: " + this.numReduceTasks);
 
       // Create a new executor service to drain the work queue.
-      ExecutorService executor = Executors.newFixedThreadPool(maxReduceThreads);
+      ExecutorService executor = HadoopExecutors.newFixedThreadPool(
+          maxReduceThreads);
 
       return executor;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/LocatedFileStatusFetcher.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/LocatedFileStatusFetcher.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/LocatedFileStatusFetcher.java
index 87114ad..a039bc9 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/LocatedFileStatusFetcher.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/LocatedFileStatusFetcher.java
@@ -24,7 +24,6 @@ import java.util.List;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.Condition;
@@ -47,6 +46,7 @@ import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 
 /**
  * Utility class to fetch block locations for specified Input paths using a
@@ -92,7 +92,7 @@ public class LocatedFileStatusFetcher {
       IOException {
     int numThreads = conf.getInt(FileInputFormat.LIST_STATUS_NUM_THREADS,
         FileInputFormat.DEFAULT_LIST_STATUS_NUM_THREADS);
-    rawExec = Executors.newFixedThreadPool(
+    rawExec = HadoopExecutors.newFixedThreadPool(
         numThreads,
         new ThreadFactoryBuilder().setDaemon(true)
             .setNameFormat("GetFileInfo #%d").build());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskLog.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskLog.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskLog.java
index e07b5be..bf838c2 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskLog.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/TaskLog.java
@@ -51,6 +51,7 @@ import org.apache.hadoop.mapreduce.util.ProcessTree;
 import org.apache.hadoop.util.Shell;
 import org.apache.hadoop.util.StringUtils;
 import org.apache.hadoop.util.ShutdownHookManager;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.log4j.Appender;
 import org.apache.log4j.LogManager;
@@ -327,22 +328,22 @@ public class TaskLog {
 
   public static ScheduledExecutorService createLogSyncer() {
     final ScheduledExecutorService scheduler =
-      Executors.newSingleThreadScheduledExecutor(
-        new ThreadFactory() {
-          @Override
-          public Thread newThread(Runnable r) {
-            final Thread t = Executors.defaultThreadFactory().newThread(r);
-            t.setDaemon(true);
-            t.setName("Thread for syncLogs");
-            return t;
-          }
-        });
+        HadoopExecutors.newSingleThreadScheduledExecutor(
+            new ThreadFactory() {
+              @Override
+              public Thread newThread(Runnable r) {
+                final Thread t = Executors.defaultThreadFactory().newThread(r);
+                t.setDaemon(true);
+                t.setName("Thread for syncLogs");
+                return t;
+              }
+            });
     ShutdownHookManager.get().addShutdownHook(new Runnable() {
-        @Override
-        public void run() {
-          TaskLog.syncLogsShutdown(scheduler);
-        }
-      }, 50);
+      @Override
+      public void run() {
+        TaskLog.syncLogsShutdown(scheduler);
+      }
+    }, 50);
     scheduler.scheduleWithFixedDelay(
         new Runnable() {
           @Override

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/MultithreadedMapRunner.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/MultithreadedMapRunner.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/MultithreadedMapRunner.java
index 98d794b..05339bc 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/MultithreadedMapRunner.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/MultithreadedMapRunner.java
@@ -31,6 +31,7 @@ import org.apache.hadoop.mapred.SkipBadRecords;
 import org.apache.hadoop.mapreduce.lib.map.MultithreadedMapper;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.util.concurrent.HadoopThreadPoolExecutor;
 
 import java.io.IOException;
 import java.util.concurrent.*;
@@ -84,7 +85,8 @@ public class MultithreadedMapRunner<K1, V1, K2, V2>
 
     // Creating a threadpool of the configured size to execute the Mapper
     // map method in parallel.
-    executorService = new ThreadPoolExecutor(numberOfThreads, numberOfThreads, 
+    executorService = new HadoopThreadPoolExecutor(numberOfThreads,
+        numberOfThreads,
                                              0L, TimeUnit.MILLISECONDS,
                                              new BlockingArrayQueue
                                                (numberOfThreads));

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestFileOutputCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestFileOutputCommitter.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestFileOutputCommitter.java
index eba513b..20d8ab5 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestFileOutputCommitter.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/output/TestFileOutputCommitter.java
@@ -25,10 +25,10 @@ import java.io.IOException;
 import java.net.URI;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.TimeUnit;
 
 import junit.framework.TestCase;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 import org.junit.Assert;
 
 import org.apache.commons.logging.Log;
@@ -696,7 +696,7 @@ public class TestFileOutputCommitter extends TestCase {
       };
     }
 
-    final ExecutorService executor = Executors.newFixedThreadPool(2);
+    final ExecutorService executor = HadoopExecutors.newFixedThreadPool(2);
     try {
       for (int i = 0; i < taCtx.length; i++) {
         final int taskIdx = i;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java
index 6be0d27..677d5c2 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/HistoryFileManager.java
@@ -66,6 +66,7 @@ import org.apache.hadoop.mapreduce.v2.jobhistory.JobIndexInfo;
 import org.apache.hadoop.security.AccessControlException;
 import org.apache.hadoop.service.AbstractService;
 import org.apache.hadoop.util.ShutdownThreadsHelper;
+import org.apache.hadoop.util.concurrent.HadoopThreadPoolExecutor;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -554,8 +555,9 @@ public class HistoryFileManager extends AbstractService {
         JHAdminConfig.DEFAULT_MR_HISTORY_MOVE_THREAD_COUNT);
     ThreadFactory tf = new ThreadFactoryBuilder().setNameFormat(
         "MoveIntermediateToDone Thread #%d").build();
-    moveToDoneExecutor = new ThreadPoolExecutor(numMoveThreads, numMoveThreads,
-        1, TimeUnit.HOURS, new LinkedBlockingQueue<Runnable>(), tf);
+    moveToDoneExecutor = new HadoopThreadPoolExecutor(numMoveThreads,
+        numMoveThreads, 1, TimeUnit.HOURS,
+        new LinkedBlockingQueue<Runnable>(), tf);
 
     super.serviceInit(conf);
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JobHistory.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JobHistory.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JobHistory.java
index 41bc90a..45075c9 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JobHistory.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/JobHistory.java
@@ -44,6 +44,7 @@ import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig;
 import org.apache.hadoop.service.AbstractService;
 import org.apache.hadoop.service.Service;
 import org.apache.hadoop.util.ReflectionUtils;
+import org.apache.hadoop.util.concurrent.HadoopScheduledThreadPoolExecutor;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.event.EventHandler;
@@ -126,7 +127,7 @@ public class JobHistory extends AbstractService implements HistoryContext {
       ((Service) storage).start();
     }
 
-    scheduledExecutor = new ScheduledThreadPoolExecutor(2,
+    scheduledExecutor = new HadoopScheduledThreadPoolExecutor(2,
         new ThreadFactoryBuilder().setNameFormat("Log Scanner/Cleaner #%d")
             .build());
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java
index 2fb7811..0d6e900 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-shuffle/src/main/java/org/apache/hadoop/mapred/ShuffleHandler.java
@@ -46,7 +46,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.Executors;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -81,6 +80,7 @@ import org.apache.hadoop.security.proto.SecurityProtos.TokenProto;
 import org.apache.hadoop.security.ssl.SSLFactory;
 import org.apache.hadoop.security.token.Token;
 import org.apache.hadoop.util.Shell;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.proto.YarnServerCommonProtos.VersionProto;
@@ -475,8 +475,8 @@ public class ShuffleHandler extends AuxiliaryService {
       .build();
     
     selector = new NioServerSocketChannelFactory(
-        Executors.newCachedThreadPool(bossFactory),
-        Executors.newCachedThreadPool(workerFactory),
+        HadoopExecutors.newCachedThreadPool(bossFactory),
+        HadoopExecutors.newCachedThreadPool(workerFactory),
         maxShuffleThreads);
     super.serviceInit(new Configuration(conf));
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2440671a/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Util.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Util.java b/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Util.java
index 8afc1bd..e74c091 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Util.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/pi/Util.java
@@ -35,7 +35,6 @@ import java.util.List;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.Semaphore;
 
@@ -48,6 +47,7 @@ import org.apache.hadoop.mapreduce.Job;
 import org.apache.hadoop.util.ToolRunner;
 
 import com.google.common.base.Charsets;
+import org.apache.hadoop.util.concurrent.HadoopExecutors;
 
 /** Utility methods */
 public class Util {
@@ -157,7 +157,8 @@ public class Util {
   /** Execute the callables by a number of threads */
   public static <T, E extends Callable<T>> void execute(int nThreads, List<E> callables
       ) throws InterruptedException, ExecutionException {
-    final ExecutorService executor = Executors.newFixedThreadPool(nThreads); 
+    final ExecutorService executor = HadoopExecutors.newFixedThreadPool(
+        nThreads);
     final List<Future<T>> futures = executor.invokeAll(callables);
     for(Future<T> f : futures)
       f.get();


[18/50] [abbrv] hadoop git commit: HDFS-8923. Add -source flag to balancer usage message. Contributed by Chris Trezzo

Posted by ji...@apache.org.
HDFS-8923. Add -source flag to balancer usage message.  Contributed by Chris Trezzo


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/46f77902
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/46f77902
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/46f77902

Branch: refs/heads/HDFS-7240
Commit: 46f77902368e5d8cc2d3e24de735b98a83ad46e1
Parents: 8eee59c
Author: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Authored: Thu Feb 18 18:18:12 2016 -0800
Committer: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Committed: Thu Feb 18 18:18:12 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt                       | 3 +++
 .../java/org/apache/hadoop/hdfs/server/balancer/Balancer.java     | 2 ++
 hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md | 2 ++
 3 files changed, 7 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/46f77902/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index d54aa96..945c911 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2817,6 +2817,9 @@ Release 2.7.3 - UNRELEASED
     HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be
     configurable (James Kinley and Nathan Roberts via kihwal)
 
+    HDFS-8923. Add -source flag to balancer usage message.  (Chris Trezzo
+    via szetszwo)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/46f77902/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Balancer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Balancer.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Balancer.java
index 191e1c3..49980ff 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Balancer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Balancer.java
@@ -179,6 +179,8 @@ public class Balancer {
       + "\tExcludes the specified datanodes."
       + "\n\t[-include [-f <hosts-file> | <comma-separated list of hosts>]]"
       + "\tIncludes only the specified datanodes."
+      + "\n\t[-source [-f <hosts-file> | <comma-separated list of hosts>]]"
+      + "\tPick only the specified datanodes as source nodes."
       + "\n\t[-blockpools <comma-separated list of blockpool ids>]"
       + "\tThe balancer will only run on blockpools included in this list."
       + "\n\t[-idleiterations <idleiterations>]"

http://git-wip-us.apache.org/repos/asf/hadoop/blob/46f77902/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md
index 6584669..dc6e935 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/HDFSCommands.md
@@ -267,6 +267,7 @@ Usage:
               [-policy <policy>]
               [-exclude [-f <hosts-file> | <comma-separated list of hosts>]]
               [-include [-f <hosts-file> | <comma-separated list of hosts>]]
+              [-source [-f <hosts-file> | <comma-separated list of hosts>]]
               [-blockpools <comma-separated list of blockpool ids>]
               [-idleiterations <idleiterations>]
 
@@ -276,6 +277,7 @@ Usage:
 | `-threshold` \<threshold\> | Percentage of disk capacity. This overwrites the default threshold. |
 | `-exclude -f` \<hosts-file\> \| \<comma-separated list of hosts\> | Excludes the specified datanodes from being balanced by the balancer. |
 | `-include -f` \<hosts-file\> \| \<comma-separated list of hosts\> | Includes only the specified datanodes to be balanced by the balancer. |
+| `-source -f` \<hosts-file\> \| \<comma-separated list of hosts\> | Pick only the specified datanodes as source nodes. |
 | `-blockpools` \<comma-separated list of blockpool ids\> | The balancer will only run on blockpools included in this list. |
 | `-idleiterations` \<iterations\> | Maximum number of idle iterations before exit. This overwrites the default idleiterations(5). |
 


[24/50] [abbrv] hadoop git commit: MAPREDUCE-6637. Testcase Failure : TestFileInputFormat.testSplitLocationInfo. Contributed by Brahma Reddy Battula.

Posted by ji...@apache.org.
MAPREDUCE-6637. Testcase Failure : TestFileInputFormat.testSplitLocationInfo. Contributed by Brahma Reddy Battula.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/37577852
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/37577852
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/37577852

Branch: refs/heads/HDFS-7240
Commit: 37577852ba54ba506b0b6c4db5e95d176f5e9b63
Parents: 18f9b77
Author: Andrew Wang <wa...@apache.org>
Authored: Fri Feb 19 16:33:17 2016 -0800
Committer: Andrew Wang <wa...@apache.org>
Committed: Fri Feb 19 16:33:17 2016 -0800

----------------------------------------------------------------------
 hadoop-mapreduce-project/CHANGES.txt                              | 3 +++
 .../test/java/org/apache/hadoop/mapred/TestFileInputFormat.java   | 2 +-
 .../apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java    | 2 +-
 3 files changed, 5 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/37577852/hadoop-mapreduce-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index a6031c0..bf9d824 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -729,6 +729,9 @@ Release 2.7.3 - UNRELEASED
 
   IMPROVEMENTS
 
+    MAPREDUCE-6637. Testcase Failure : TestFileInputFormat.testSplitLocationInfo.
+    (Brahma Reddy Battula via wang)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/37577852/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileInputFormat.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileInputFormat.java
index ba636b6..141086d 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileInputFormat.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestFileInputFormat.java
@@ -243,7 +243,7 @@ public class TestFileInputFormat {
     }
 
     @Override
-    public BlockLocation[] getFileBlockLocations(Path p, long start, long len)
+    public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len)
         throws IOException {
       return new BlockLocation[] {
           new BlockLocation(new String[] { "localhost:50010", "otherhost:50010" },

http://git-wip-us.apache.org/repos/asf/hadoop/blob/37577852/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java
index 3f877f1..dff0e0d 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestFileInputFormat.java
@@ -422,7 +422,7 @@ public class TestFileInputFormat {
     }
 
     @Override
-    public BlockLocation[] getFileBlockLocations(Path p, long start, long len)
+    public BlockLocation[] getFileBlockLocations(FileStatus file, long start, long len)
         throws IOException {
       return new BlockLocation[] {
           new BlockLocation(new String[] { "localhost:50010", "otherhost:50010" },


[09/50] [abbrv] hadoop git commit: HDFS-6832. Fix the usage of 'hdfs namenode' command. Contributed by Manjunath Ballur.

Posted by ji...@apache.org.
HDFS-6832. Fix the usage of 'hdfs namenode' command. Contributed by Manjunath Ballur.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/e78d8e66
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/e78d8e66
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/e78d8e66

Branch: refs/heads/HDFS-7240
Commit: e78d8e66f748c68d2d88ee748facbfa35817d5e3
Parents: 2440671
Author: Akira Ajisaka <aa...@apache.org>
Authored: Fri Feb 19 01:35:06 2016 +0900
Committer: Akira Ajisaka <aa...@apache.org>
Committed: Fri Feb 19 01:35:06 2016 +0900

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt                       | 3 +++
 .../java/org/apache/hadoop/hdfs/server/namenode/NameNode.java     | 3 +--
 2 files changed, 4 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/e78d8e66/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 89fc187..61a783d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2782,6 +2782,9 @@ Release 2.8.0 - UNRELEASED
 
     HDFS-9799. Reimplement getCurrentTrashDir to remove incompatibility. (zhz)
 
+    HDFS-6832. Fix the usage of 'hdfs namenode' command.
+    (Manjunath Ballur via aajisaka)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e78d8e66/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNode.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNode.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNode.java
index 7c4e10f..f376901 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNode.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNode.java
@@ -282,8 +282,7 @@ public class NameNode implements NameNodeStatusMXBean {
       + StartupOption.BOOTSTRAPSTANDBY.getName() + "] | \n\t["
       + StartupOption.RECOVER.getName() + " [ "
       + StartupOption.FORCE.getName() + "] ] | \n\t["
-      + StartupOption.METADATAVERSION.getName() + " ] "
-      + " ]";
+      + StartupOption.METADATAVERSION.getName() + " ]";
 
   
   public long getProtocolVersion(String protocol, 


[41/50] [abbrv] hadoop git commit: HDFS-9084. Pagination, sorting and filtering of files/directories in the HDFS Web UI. (Contributed by Ravi Prakash)

Posted by ji...@apache.org.
HDFS-9084. Pagination, sorting and filtering of files/directories in the HDFS Web UI. (Contributed by Ravi Prakash)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/48c61cd6
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/48c61cd6
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/48c61cd6

Branch: refs/heads/HDFS-7240
Commit: 48c61cd6aa3feae6a4a71d2d1bb6d01a3d50c7b7
Parents: de09f41
Author: Tsuyoshi Ozawa <oz...@apache.org>
Authored: Tue Feb 23 19:30:58 2016 +0900
Committer: Tsuyoshi Ozawa <oz...@apache.org>
Committed: Tue Feb 23 19:30:58 2016 +0900

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  3 ++
 .../src/main/webapps/hdfs/explorer.html         | 15 ++++----
 .../src/main/webapps/hdfs/explorer.js           | 38 ++++++++++++++++++++
 3 files changed, 50 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/48c61cd6/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 256df39..440b7e8 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1951,6 +1951,9 @@ Release 2.8.0 - UNRELEASED
     HDFS-9764. DistCp doesn't print value for several arguments including
     -numListstatusThreads. (Wei-Chiu Chuang via Yongjun Zhang) 
 
+    HDFS-9084. Pagination, sorting and filtering of files/directories in the
+    HDFS Web UI. (Ravi Prakash via ozawa)
+
   OPTIMIZATIONS
 
     HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than

http://git-wip-us.apache.org/repos/asf/hadoop/blob/48c61cd6/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
index e66e1e7..5106006 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
@@ -21,6 +21,7 @@
     <meta http-equiv="X-UA-Compatible" content="IE=9" />
     <link rel="stylesheet" type="text/css" href="/static/bootstrap-3.0.2/css/bootstrap.min.css" />
     <link rel="stylesheet" type="text/css" href="/static/bootstrap-3.0.2/css/bootstrap-editable.css"/>
+    <link rel="stylesheet" type="text/css" href="/static/dataTables.bootstrap.css" />
     <link rel="stylesheet" type="text/css" href="/static/hadoop.css" />
     <title>Browsing HDFS</title>
   </head>
@@ -211,15 +212,15 @@
     </script>
 
     <script type="text/x-dust-template" id="tmpl-explorer">
-      <table class="table">
+      <table class="table" id="table-explorer">
         <thead>
           <tr>
-            <th>Permission</th>
+            <th title="Permissions">Permission</th>
             <th>Owner</th>
             <th>Group</th>
             <th>Size</th>
-            <th>Last Modified</th>
-            <th>Replication</th>
+            <th title="Last Modified">Last Modified</th>
+            <th title="Replication">Replication</th>
             <th>Block Size</th>
             <th>Name</th>
             <th></th>
@@ -235,8 +236,8 @@
               </span></td>
             <td><span class="explorer-owner-links">{owner}</span></td>
             <td><span class="explorer-group-links">{group}</span></td>
-            <td>{length|fmt_bytes}</td>
-            <td>{#helper_date_tostring value="{modificationTime}"/}</td>
+            <td>{length}</td>
+            <td>{modificationTime}</td>
             <td><span class="explorer-replication-links">{replication}</span></td>
             <td>{blockSize|fmt_bytes}</td>
             <td><a inode-type="{type}" class="explorer-browse-links">{pathSuffix}</a></td>
@@ -263,8 +264,10 @@
       </p>
     </script>
     <script type="text/javascript" src="/static/jquery-1.10.2.min.js">
+    </script><script type="text/javascript" src="/static/jquery.dataTables.min.js">
     </script><script type="text/javascript" src="/static/bootstrap-3.0.2/js/bootstrap.min.js">
     </script><script type="text/javascript" src="/static/bootstrap-3.0.2/js/bootstrap-editable.min.js">
+    </script><script type="text/javascript" src="/static/dataTables.bootstrap.js">
     </script><script type="text/javascript" src="/static/dust-full-2.0.0.min.js">
     </script><script type="text/javascript" src="/static/dust-helpers-1.1.1.min.js">
     </script><script type="text/javascript" src="/static/dfs-dust.js">

http://git-wip-us.apache.org/repos/asf/hadoop/blob/48c61cd6/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.js
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.js b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.js
index 0c68209..baca798 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.js
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.js
@@ -237,6 +237,28 @@
     });
   }
 
+  function func_size_render(data, type, row, meta) {
+    if(type == 'display') {
+      return dust.filters.fmt_bytes(data);
+    }
+    else return data;
+  }
+
+  // Change the format of date-time depending on how old the
+  // the timestamp is. If older than 6 months, no need to be
+  // show exact time.
+  function func_time_render(data, type, row, meta) {
+    if(type == 'display') {
+      var cutoff = moment().subtract(6, 'months').unix() * 1000;
+      if(data < cutoff) {
+        return moment(Number(data)).format('MMM DD YYYY');
+      } else {
+        return moment(Number(data)).format('MMM DD HH:mm');
+      }
+    }
+    return data;
+  }
+
   function browse_directory(dir) {
     var HELPERS = {
       'helper_date_tostring' : function (chunk, ctx, bodies, params) {
@@ -259,6 +281,22 @@
       dust.render('explorer', base.push(d), function(err, out) {
         $('#panel').html(out);
 
+        $('#table-explorer').dataTable( {
+          'lengthMenu': [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
+          'columns': [
+            {'searchable': false }, //Permissions
+            null, //Owner
+            null, //Group
+            { 'searchable': false, 'render': func_size_render}, //Size
+            { 'searchable': false, 'render': func_time_render}, //Last Modified
+            { 'searchable': false }, //Replication
+            null, //Block Size
+            null, //Name
+            { 'sortable' : false } //Trash
+          ],
+          "deferRender": true
+        });
+
         $('.explorer-browse-links').click(function() {
           var type = $(this).attr('inode-type');
           var path = $(this).closest('tr').attr('inode-path');


[37/50] [abbrv] hadoop git commit: HADOOP-12555. WASB to read credentials from a credential provider. Contributed by Larry McCay.

Posted by ji...@apache.org.
HADOOP-12555. WASB to read credentials from a credential provider. Contributed by Larry McCay.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/27b77751
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/27b77751
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/27b77751

Branch: refs/heads/HDFS-7240
Commit: 27b77751c1163ab4a1ce081a426e5190d1b8aff4
Parents: 66289a3
Author: cnauroth <cn...@apache.org>
Authored: Mon Feb 22 17:30:13 2016 -0800
Committer: cnauroth <cn...@apache.org>
Committed: Mon Feb 22 17:30:13 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |  3 ++
 .../src/site/markdown/CredentialProviderAPI.md  |  1 +
 .../hadoop/fs/azure/SimpleKeyProvider.java      | 16 +++++-
 .../hadoop-azure/src/site/markdown/index.md     | 52 ++++++++++++++++++--
 .../fs/azure/TestWasbUriAndConfiguration.java   | 45 ++++++++++++++++-
 5 files changed, 112 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/27b77751/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index 01bfacb8..361859a 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1143,6 +1143,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-12668. Support excluding weak Ciphers in HttpServer2 through
     ssl-server.conf. (Vijay Singh via zhz)
 
+    HADOOP-12555. WASB to read credentials from a credential provider.
+    (Larry McCay via cnauroth)
+
   OPTIMIZATIONS
 
     HADOOP-11785. Reduce the number of listStatus operation in distcp

http://git-wip-us.apache.org/repos/asf/hadoop/blob/27b77751/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md b/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
index eccc205..5ca95eb 100644
--- a/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
+++ b/hadoop-common-project/hadoop-common/src/site/markdown/CredentialProviderAPI.md
@@ -110,6 +110,7 @@ In summary, first, provision the credentials into a provider then configure the
 |HDFS                 |DFSUtil leverages Configuration.getPassword method to use the credential provider API and/or fallback to the clear text value stored in ssl-server.xml.|TODO|
 |YARN                 |WebAppUtils uptakes the use of the credential provider API through the new method on Configuration called getPassword. This provides an alternative to storing the passwords in clear text within the ssl-server.xml file while maintaining backward compatibility.|TODO|
 |AWS <br/> S3/S3A     |Uses Configuration.getPassword to get the S3 credentials. They may be resolved through the credential provider API or from the config for backward compatibility.|[AWS S3/S3A Usage](../../hadoop-aws/tools/hadoop-aws/index.html)|
+|Azure <br/> WASB     |Uses Configuration.getPassword to get the WASB credentials. They may be resolved through the credential provider API or from the config for backward compatibility.|[Azure WASB Usage](../../hadoop-azure/index.html)|
 |Apache <br/> Accumulo|The trace.password property is used by the Tracer to authenticate with Accumulo and persist the traces in the trace table. The credential provider API is used to acquire the trace.password from a provider or from configuration for backward compatibility.|TODO|
 |Apache <br/> Slider  |A capability has been added to Slider to prompt the user for needed passwords and store them using CredentialProvider so they can be retrieved by an app later.|TODO|
 |Apache <br/> Hive    |Protection of the metastore password, SSL related passwords and JDO string password has been added through the use of the Credential Provider API|TODO|

http://git-wip-us.apache.org/repos/asf/hadoop/blob/27b77751/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SimpleKeyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SimpleKeyProvider.java b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SimpleKeyProvider.java
index 3cd3eda..28e307e 100644
--- a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SimpleKeyProvider.java
+++ b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SimpleKeyProvider.java
@@ -18,6 +18,10 @@
 
 package org.apache.hadoop.fs.azure;
 
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
 
@@ -27,6 +31,7 @@ import org.apache.hadoop.conf.Configuration;
  */
 @InterfaceAudience.Private
 public class SimpleKeyProvider implements KeyProvider {
+  private static final Log LOG = LogFactory.getLog(SimpleKeyProvider.class);
 
   protected static final String KEY_ACCOUNT_KEY_PREFIX =
       "fs.azure.account.key.";
@@ -34,7 +39,16 @@ public class SimpleKeyProvider implements KeyProvider {
   @Override
   public String getStorageAccountKey(String accountName, Configuration conf)
       throws KeyProviderException {
-    return conf.get(getStorageAccountKeyName(accountName));
+    String key = null;
+    try {
+      char[] keyChars = conf.getPassword(getStorageAccountKeyName(accountName));
+      if (keyChars != null) {
+        key = new String(keyChars);
+      }
+    } catch(IOException ioe) {
+      LOG.warn("Unable to get key from credential providers.", ioe);
+    }
+    return key;
   }
 
   protected String getStorageAccountKeyName(String accountName) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/27b77751/hadoop-tools/hadoop-azure/src/site/markdown/index.md
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/site/markdown/index.md b/hadoop-tools/hadoop-azure/src/site/markdown/index.md
index 4402467..f813c88 100644
--- a/hadoop-tools/hadoop-azure/src/site/markdown/index.md
+++ b/hadoop-tools/hadoop-azure/src/site/markdown/index.md
@@ -88,9 +88,55 @@ For example:
       <value>YOUR ACCESS KEY</value>
     </property>
 
-In many Hadoop clusters, the core-site.xml file is world-readable.  If it's
-undesirable for the access key to be visible in core-site.xml, then it's also
-possible to configure it in encrypted form.  An additional configuration property
+In many Hadoop clusters, the core-site.xml file is world-readable. It is possible to
+protect the access key within a credential provider as well. This provides an encrypted
+file format along with protection with file permissions.
+
+#### Protecting the Azure Credentials for WASB with Credential Providers
+
+To protect these credentials from prying eyes, it is recommended that you use
+the credential provider framework to securely store them and access them
+through configuration. The following describes its use for Azure credentials
+in WASB FileSystem.
+
+For additional reading on the credential provider API see:
+[Credential Provider API](../hadoop-project-dist/hadoop-common/CredentialProviderAPI.html).
+
+##### End to End Steps for Distcp and WASB with Credential Providers
+
+###### provision
+
+```
+% hadoop credential create fs.azure.account.key.youraccount.blob.core.windows.net -value 123
+    -provider localjceks://file/home/lmccay/wasb.jceks
+```
+
+###### configure core-site.xml or command line system property
+
+```
+<property>
+  <name>hadoop.security.credential.provider.path</name>
+  <value>localjceks://file/home/lmccay/wasb.jceks</value>
+  <description>Path to interrogate for protected credentials.</description>
+</property>
+```
+
+###### distcp
+
+```
+% hadoop distcp
+    [-D hadoop.security.credential.provider.path=localjceks://file/home/lmccay/wasb.jceks]
+    hdfs://hostname:9001/user/lmccay/007020615 wasb://yourcontainer@youraccount.blob.core.windows.net/testDir/
+```
+
+NOTE: You may optionally add the provider path property to the distcp command line instead of
+added job specific configuration to a generic core-site.xml. The square brackets above illustrate
+this capability.
+
+#### Protecting the Azure Credentials for WASB within an Encrypted File
+
+In addition to using the credential provider framework to protect your credentials, it's
+also possible to configure it in encrypted form.  An additional configuration property
 specifies an external program to be invoked by Hadoop processes to decrypt the
 key.  The encrypted key value is passed to this external program as a command
 line argument:

http://git-wip-us.apache.org/repos/asf/hadoop/blob/27b77751/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestWasbUriAndConfiguration.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestWasbUriAndConfiguration.java b/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestWasbUriAndConfiguration.java
index 25eee47..06a5b62 100644
--- a/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestWasbUriAndConfiguration.java
+++ b/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/TestWasbUriAndConfiguration.java
@@ -34,6 +34,11 @@ import java.io.OutputStream;
 import java.net.URI;
 import java.util.Date;
 import java.util.EnumSet;
+import java.io.File;
+
+import org.apache.hadoop.security.ProviderUtils;
+import org.apache.hadoop.security.alias.CredentialProvider;
+import org.apache.hadoop.security.alias.CredentialProviderFactory;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.AbstractFileSystem;
@@ -43,7 +48,9 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.azure.AzureBlobStorageTestAccount.CreateOptions;
 import org.junit.After;
 import org.junit.Assert;
+import org.junit.Rule;
 import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
 
 import com.microsoft.azure.storage.blob.CloudBlobContainer;
 import com.microsoft.azure.storage.blob.CloudBlockBlob;
@@ -57,6 +64,9 @@ public class TestWasbUriAndConfiguration {
   protected String accountKey;
   protected static Configuration conf = null;
 
+  @Rule
+  public final TemporaryFolder tempDir = new TemporaryFolder();
+
   private AzureBlobStorageTestAccount testAccount;
 
   @After
@@ -307,6 +317,40 @@ public class TestWasbUriAndConfiguration {
   }
 
   @Test
+  public void testCredsFromCredentialProvider() throws Exception {
+    String account = "testacct";
+    String key = "testkey";
+    // set up conf to have a cred provider
+    final Configuration conf = new Configuration();
+    final File file = tempDir.newFile("test.jks");
+    final URI jks = ProviderUtils.nestURIForLocalJavaKeyStoreProvider(
+        file.toURI());
+    conf.set(CredentialProviderFactory.CREDENTIAL_PROVIDER_PATH,
+        jks.toString());
+
+    provisionAccountKey(conf, account, key);
+
+    // also add to configuration as clear text that should be overridden
+    conf.set(SimpleKeyProvider.KEY_ACCOUNT_KEY_PREFIX + account,
+        key + "cleartext");
+
+    String result = AzureNativeFileSystemStore.getAccountKeyFromConfiguration(
+        account, conf);
+    // result should contain the credential provider key not the config key
+    assertEquals("AccountKey incorrect.", key, result);
+  }
+
+  void provisionAccountKey(
+      final Configuration conf, String account, String key) throws Exception {
+    // add our creds to the provider
+    final CredentialProvider provider =
+        CredentialProviderFactory.getProviders(conf).get(0);
+    provider.createCredentialEntry(
+        SimpleKeyProvider.KEY_ACCOUNT_KEY_PREFIX + account, key.toCharArray());
+    provider.flush();
+  }
+
+  @Test
   public void testValidKeyProvider() throws Exception {
     Configuration conf = new Configuration();
     String account = "testacct";
@@ -366,7 +410,6 @@ public class TestWasbUriAndConfiguration {
         String authority = testAccount.getFileSystem().getUri().getAuthority();
         URI defaultUri = new URI(defaultScheme, authority, null, null, null);
         conf.set(FS_DEFAULT_NAME_KEY, defaultUri.toString());
-        
         // Add references to file system implementations for wasb and wasbs.
         conf.addResource("azure-test.xml");
         URI wantedUri = new URI(wantedScheme + ":///random/path");


[03/50] [abbrv] hadoop git commit: YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable. (Kai Sasaki via kasha)

Posted by ji...@apache.org.
YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable. (Kai Sasaki via kasha)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/2ab4c476
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/2ab4c476
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/2ab4c476

Branch: refs/heads/HDFS-7240
Commit: 2ab4c476ed22d3ccf15b215710b67e32bbc7e5f0
Parents: 0fb14aa
Author: Karthik Kambatla <ka...@apache.org>
Authored: Wed Feb 17 17:44:35 2016 -0800
Committer: Karthik Kambatla <ka...@apache.org>
Committed: Wed Feb 17 18:16:15 2016 -0800

----------------------------------------------------------------------
 hadoop-yarn-project/CHANGES.txt                                | 3 +++
 .../server/resourcemanager/scheduler/fair/FSParentQueue.java   | 6 ++----
 2 files changed, 5 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/2ab4c476/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 1547f10..f7c69a4 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -34,6 +34,9 @@ Trunk - Unreleased
 
     YARN-3261. rewrite resourcemanager restart doc to remove roadmap bits (Gururaj Shetty via aw)
 
+    YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable.
+    (Kai Sasaki via kasha)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/2ab4c476/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
index a028422..d9fac90 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/FSParentQueue.java
@@ -266,10 +266,8 @@ public class FSParentQueue extends FSQueue {
             LOG.debug("skipping from queue=" + getName()
                 + " because it's a non-preemptable queue");
           }
-          continue;
-        }
-        if (candidateQueue == null ||
-            comparator.compare(queue, candidateQueue) > 0) {
+        } else if (candidateQueue == null ||
+                  comparator.compare(queue, candidateQueue) > 0) {
           candidateQueue = queue;
         }
       }


[12/50] [abbrv] hadoop git commit: HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be configurable. Contributed by James Kinley and Nathan Roberts.

Posted by ji...@apache.org.
HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be configurable. Contributed by James Kinley and Nathan Roberts.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/ba6d5ed9
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/ba6d5ed9
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/ba6d5ed9

Branch: refs/heads/HDFS-7240
Commit: ba6d5ed955aa34cdcb7aaa4b1025da6ee5e91355
Parents: a365a39
Author: Kihwal Lee <ki...@apache.org>
Authored: Thu Feb 18 13:21:51 2016 -0600
Committer: Kihwal Lee <ki...@apache.org>
Committed: Thu Feb 18 13:21:51 2016 -0600

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt             |  3 +++
 .../main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java |  3 +++
 .../blockmanagement/BlockPlacementPolicyDefault.java    |  7 ++++++-
 .../hadoop-hdfs/src/main/resources/hdfs-default.xml     | 12 ++++++++++++
 4 files changed, 24 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba6d5ed9/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 2948a94..b6510b0 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2811,6 +2811,9 @@ Release 2.7.3 - UNRELEASED
     HDFS-9669. TcpPeerServer should respect ipc.server.listen.queue.size
     (Elliot Clark via cmccabe)
 
+    HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be
+    configurable (James Kinley and Nathan Roberts via kihwal)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba6d5ed9/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
index df205db..39e4fe4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
@@ -663,6 +663,9 @@ public class DFSConfigKeys extends CommonConfigurationKeys {
       "dfs.namenode.available-space-block-placement-policy.balanced-space-preference-fraction";
   public static final float   DFS_NAMENODE_AVAILABLE_SPACE_BLOCK_PLACEMENT_POLICY_BALANCED_SPACE_PREFERENCE_FRACTION_DEFAULT =
       0.6f;
+  public static final String  DFS_NAMENODE_BLOCKPLACEMENTPOLICY_DEFAULT_PREFER_LOCAL_NODE_KEY =
+      "dfs.namenode.block-placement-policy.default.prefer-local-node";
+  public static final boolean  DFS_NAMENODE_BLOCKPLACEMENTPOLICY_DEFAULT_PREFER_LOCAL_NODE_DEFAULT = true;
 
   public static final String DFS_BLOCK_LOCAL_PATH_ACCESS_USER_KEY = "dfs.block.local-path-access.user";
   public static final String DFS_DOMAIN_SOCKET_PATH_KEY =

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba6d5ed9/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
index 14439e7..ee891a5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockPlacementPolicyDefault.java
@@ -59,7 +59,7 @@ public class BlockPlacementPolicyDefault extends BlockPlacementPolicy {
 
   protected boolean considerLoad; 
   protected double considerLoadFactor;
-  private boolean preferLocalNode = true;
+  private boolean preferLocalNode;
   protected NetworkTopology clusterMap;
   protected Host2NodesMap host2datanodeMap;
   private FSClusterStats stats;
@@ -95,6 +95,11 @@ public class BlockPlacementPolicyDefault extends BlockPlacementPolicy {
     this.staleInterval = conf.getLong(
         DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY, 
         DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_DEFAULT);
+    this.preferLocalNode = conf.getBoolean(
+        DFSConfigKeys.
+            DFS_NAMENODE_BLOCKPLACEMENTPOLICY_DEFAULT_PREFER_LOCAL_NODE_KEY,
+        DFSConfigKeys.
+            DFS_NAMENODE_BLOCKPLACEMENTPOLICY_DEFAULT_PREFER_LOCAL_NODE_DEFAULT);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ba6d5ed9/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
index 0f5130a..1560335 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
@@ -922,6 +922,18 @@
 </property>
 
 <property>
+  <name>dfs.namenode.block-placement-policy.default.prefer-local-node</name>
+  <value>true</value>
+  <description>Controls how the default block placement policy places
+  the first replica of a block. When true, it will prefer the node where
+  the client is running.  When false, it will prefer a node in the same rack
+  as the client. Setting to false avoids situations where entire copies of
+  large files end up on a single node, thus creating hotspots.
+  </description>
+</property>
+
+
+<property>
   <name>dfs.stream-buffer-size</name>
   <value>4096</value>
   <description>The size of buffer to stream files.


[28/50] [abbrv] hadoop git commit: YARN-4708. Missing default mapper type in TimelineServer performance test tool usage. Contributed by Kai Sasaki.

Posted by ji...@apache.org.
YARN-4708. Missing default mapper type in TimelineServer performance test tool usage. Contributed by Kai Sasaki.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/b68901d7
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/b68901d7
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/b68901d7

Branch: refs/heads/HDFS-7240
Commit: b68901d7dde9cb48545fcf0b94f2ac266b909a5d
Parents: d5abd29
Author: Tsuyoshi Ozawa <oz...@apache.org>
Authored: Mon Feb 22 07:49:50 2016 +0900
Committer: Tsuyoshi Ozawa <oz...@apache.org>
Committed: Mon Feb 22 07:54:53 2016 +0900

----------------------------------------------------------------------
 .../hadoop/mapreduce/TimelineServicePerformance.java   |  2 +-
 hadoop-yarn-project/CHANGES.txt                        |  2 ++
 .../src/site/markdown/TimelineServer.md                | 13 +++++++------
 3 files changed, 10 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/b68901d7/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TimelineServicePerformance.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TimelineServicePerformance.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TimelineServicePerformance.java
index 9f76659..0753d7f 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TimelineServicePerformance.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TimelineServicePerformance.java
@@ -48,7 +48,7 @@ public class TimelineServicePerformance extends Configured implements Tool {
             ")\n" +
         "     [-v] timeline service version\n" +
         "     [-mtype <mapper type in integer>]\n" +
-        "          1. simple entity write mapper\n" +
+        "          1. simple entity write mapper (default)\n" +
         "          2. jobhistory files replay mapper\n" +
         "     [-s <(KBs)test>] number of KB per put (mtype=1, default: " +
              SimpleEntityWriterV1.KBS_SENT_DEFAULT + " KB)\n" +

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b68901d7/hadoop-yarn-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/CHANGES.txt b/hadoop-yarn-project/CHANGES.txt
index 9b64204..d6aa4e4 100644
--- a/hadoop-yarn-project/CHANGES.txt
+++ b/hadoop-yarn-project/CHANGES.txt
@@ -135,6 +135,8 @@ Release 2.9.0 - UNRELEASED
     YARN-4689. FairScheduler: Cleanup preemptContainer to be more readable.
     (Kai Sasaki via kasha)
 
+    YARN-4708. Missing default mapper type in TimelineServer performance test tool
+    usage. (Kai Sasaki via ozawa)
 
   OPTIMIZATIONS
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b68901d7/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/TimelineServer.md
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/TimelineServer.md b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/TimelineServer.md
index 3e589d3..b10c860 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/TimelineServer.md
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-site/src/site/markdown/TimelineServer.md
@@ -783,8 +783,8 @@ String.
 | `entitytype` | string | The entity type |
 | `relatedentities` | map | The related entities' identifiers, which are organized in a map of entityType : [entity1, entity2, ...] |
 | `events` | list | The events of the entity |
-| `primaryfilters` | map | The primary filters of the entity, which are orgainzied in a map of key : [value1, value2, ...] |
-| `otherinfo` | map | The other information of the entity, which is orgainzied in a map of key : value |
+| `primaryfilters` | map | The primary filters of the entity, which are organized in a map of key : [value1, value2, ...] |
+| `otherinfo` | map | The other information of the entity, which is organized in a map of key : value |
 | `starttime` | long | The start time of the entity |
 
 ### Response Examples:
@@ -2038,7 +2038,7 @@ this failure *will not* result in an HTTP error code being retured.
 A status code of 200 will be returned —however, there will be an error code
 in the list of failed entities for each entity which could not be added.
 
-<a name="TIMELINE_SERVER_PERFORMANCE_TEST_TOOL"></a> Timelnine Server Performance Test Tool
+<a name="TIMELINE_SERVER_PERFORMANCE_TEST_TOOL"></a> Timeline Server Performance Test Tool
 ----------
 ###<a name="HIGHLIGHTS"></a>Highlights
 
@@ -2054,7 +2054,8 @@ Mapper Types Description:
 
      1. SimpleEntityWriter mapper
         Each mapper writes a user-specified number of timeline entities
-        with a user-specified size to the timeline server.
+        with a user-specified size to the timeline server. SimpleEntityWrite
+        is a default mapper of the performance test tool.
 
      2. JobHistoryFileReplay mapper
         Each mapper replays jobhistory files under a specified directory
@@ -2071,7 +2072,7 @@ Options:
     [-m <maps>] number of mappers (default: 1)
     [-v] timeline service version
     [-mtype <mapper type in integer>]
-          1. simple entity write mapper
+          1. simple entity write mapper (default)
           2. jobhistory files replay mapper
     [-s <(KBs)test>] number of KB per put (mtype=1, default: 1 KB)
     [-t] package sending iterations per mapper (mtype=1, default: 100)
@@ -2105,7 +2106,7 @@ Example input of JobHistoryFileReplay mapper test:
     /testInput/job_2.jhist
     /testInput/job_2_conf.xml
 
-Eample output of JobHistoryFileReplay test:
+Example output of JobHistoryFileReplay test:
 
     TRANSACTION RATE (per mapper): 4000.0 ops/s
     IO RATE (per mapper): 0.0 KB/s


[23/50] [abbrv] hadoop git commit: Support additional compression levels for GzipCodec. Contributed by Ravi Mutyala.

Posted by ji...@apache.org.
Support additional compression levels for GzipCodec. Contributed by Ravi Mutyala.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/18f9b77a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/18f9b77a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/18f9b77a

Branch: refs/heads/HDFS-7240
Commit: 18f9b77a321b225677ce23c503b41d21478fc4a7
Parents: 6546d9e
Author: Junping Du <ju...@apache.org>
Authored: Fri Feb 19 14:21:25 2016 -0800
Committer: Junping Du <ju...@apache.org>
Committed: Fri Feb 19 14:21:25 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |  3 ++
 .../hadoop/io/compress/zlib/ZlibCompressor.java | 42 +++++++++++++++++++-
 .../zlib/TestZlibCompressorDecompressor.java    | 25 ++++++++++++
 3 files changed, 69 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/18f9b77a/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index bf84d7a..e53c001 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1737,6 +1737,9 @@ Release 2.7.3 - UNRELEASED
     HADOOP-12413. AccessControlList should avoid calling getGroupNames in
     isUserInList with empty groups. (Zhihai Xu via cnauroth)
 
+    HADOOP-12794. Support additional compression levels for GzipCodec.
+    (Ravi Mutyala via junping_du)
+
   OPTIMIZATIONS
 
     HADOOP-12810. FileSystem#listLocatedStatus causes unnecessary RPC calls

http://git-wip-us.apache.org/repos/asf/hadoop/blob/18f9b77a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/zlib/ZlibCompressor.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/zlib/ZlibCompressor.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/zlib/ZlibCompressor.java
index b955044..24d98a5 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/zlib/ZlibCompressor.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/zlib/ZlibCompressor.java
@@ -67,7 +67,47 @@ public class ZlibCompressor implements Compressor {
      * Compression level for fastest compression.
      */
     BEST_SPEED (1),
-    
+
+    /**
+     * Compression level 2.
+     */
+    TWO (2),
+
+
+    /**
+     * Compression level 3.
+     */
+    THREE (3),
+
+
+    /**
+     * Compression level 4.
+     */
+    FOUR (4),
+
+
+    /**
+     * Compression level 5.
+     */
+    FIVE (5),
+
+
+    /**
+     * Compression level 6.
+     */
+    SIX (6),
+
+    /**
+     * Compression level 7.
+     */
+    SEVEN (7),
+
+    /**
+     * Compression level 8.
+     */
+    EIGHT (8),
+
+
     /**
      * Compression level for best compression.
      */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/18f9b77a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/zlib/TestZlibCompressorDecompressor.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/zlib/TestZlibCompressorDecompressor.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/zlib/TestZlibCompressorDecompressor.java
index 6a4fc60..7e2ab24 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/zlib/TestZlibCompressorDecompressor.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/compress/zlib/TestZlibCompressorDecompressor.java
@@ -122,6 +122,31 @@ public class TestZlibCompressorDecompressor {
   }
 
   @Test
+  public void testZlibCompressorDecompressorWithCompressionLevels() {
+    Configuration conf = new Configuration();
+    conf.set("zlib.compress.level","FOUR");
+    if (ZlibFactory.isNativeZlibLoaded(conf)) {
+      byte[] rawData;
+      int tryNumber = 5;
+      int BYTE_SIZE = 10 * 1024;
+      Compressor zlibCompressor = ZlibFactory.getZlibCompressor(conf);
+      Decompressor zlibDecompressor = ZlibFactory.getZlibDecompressor(conf);
+      rawData = generate(BYTE_SIZE);
+      try {
+        for (int i = 0; i < tryNumber; i++)
+          compressDecompressZlib(rawData, (ZlibCompressor) zlibCompressor,
+                  (ZlibDecompressor) zlibDecompressor);
+        zlibCompressor.reinit(conf);
+      } catch (Exception ex) {
+        fail("testZlibCompressorDecompressorWithConfiguration ex error " + ex);
+      }
+    } else {
+      assertTrue("ZlibFactory is using native libs against request",
+              ZlibFactory.isNativeZlibLoaded(conf));
+    }
+  }
+
+  @Test
   public void testZlibCompressDecompress() {
     byte[] rawData = null;
     int rawDataSize = 0;


[35/50] [abbrv] hadoop git commit: HADOOP-12668. Support excluding weak Ciphers in HttpServer2 through ssl-server.conf. Contributed by Vijay Singh.

Posted by ji...@apache.org.
HADOOP-12668. Support excluding weak Ciphers in HttpServer2 through ssl-server.conf. Contributed by Vijay Singh.

Change-Id: Ie46a5427d29188935427f67e55203c19fcd83335


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/a2fdfff0
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/a2fdfff0
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/a2fdfff0

Branch: refs/heads/HDFS-7240
Commit: a2fdfff02daef85b651eda31e99868986aab5b28
Parents: d4f5fc2
Author: Zhe Zhang <zh...@apache.org>
Authored: Mon Feb 22 14:12:33 2016 -0800
Committer: Zhe Zhang <zh...@apache.org>
Committed: Mon Feb 22 14:13:54 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |   3 +
 .../src/main/conf/ssl-server.xml.example        |  10 +
 .../org/apache/hadoop/http/HttpServer2.java     |  12 ++
 .../security/ssl/FileBasedKeyStoresFactory.java |   2 +
 .../apache/hadoop/http/TestHttpCookieFlag.java  |   5 +-
 .../apache/hadoop/http/TestSSLHttpServer.java   | 199 ++++++++++++++++++-
 .../hadoop/security/ssl/KeyStoreTestUtil.java   |  81 +++++++-
 .../java/org/apache/hadoop/hdfs/DFSUtil.java    |   4 +-
 .../hadoop/yarn/webapp/util/WebAppUtils.java    |   4 +-
 9 files changed, 302 insertions(+), 18 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index ff56c63..01bfacb8 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1140,6 +1140,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-11613. Remove commons-httpclient dependency from hadoop-azure.
     (Masatake Iwasaki via cnauroth) 
 
+    HADOOP-12668. Support excluding weak Ciphers in HttpServer2 through
+    ssl-server.conf. (Vijay Singh via zhz)
+
   OPTIMIZATIONS
 
     HADOOP-11785. Reduce the number of listStatus operation in distcp

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/main/conf/ssl-server.xml.example
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/conf/ssl-server.xml.example b/hadoop-common-project/hadoop-common/src/main/conf/ssl-server.xml.example
index 02d300c..a6820e9 100644
--- a/hadoop-common-project/hadoop-common/src/main/conf/ssl-server.xml.example
+++ b/hadoop-common-project/hadoop-common/src/main/conf/ssl-server.xml.example
@@ -75,4 +75,14 @@
   </description>
 </property>
 
+<property>
+  <name>ssl.server.exclude.cipher.list</name>
+  <value>TLS_ECDHE_RSA_WITH_RC4_128_SHA,SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
+  SSL_RSA_WITH_DES_CBC_SHA,SSL_DHE_RSA_WITH_DES_CBC_SHA,
+  SSL_RSA_EXPORT_WITH_RC4_40_MD5,SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,
+  SSL_RSA_WITH_RC4_128_MD5</value>
+  <description>Optional. The weak security cipher suites that you want excluded
+  from SSL communication.</description>
+</property>
+
 </configuration>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java
index 458b65d..45417f6 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/http/HttpServer2.java
@@ -172,6 +172,7 @@ public final class HttpServer2 implements FilterContainer {
     private String hostName;
     private boolean disallowFallbackToRandomSignerSecretProvider;
     private String authFilterConfigurationPrefix = "hadoop.http.authentication.";
+    private String excludeCiphers;
 
     public Builder setName(String name){
       this.name = name;
@@ -276,6 +277,11 @@ public final class HttpServer2 implements FilterContainer {
       return this;
     }
 
+    public Builder excludeCiphers(String pExcludeCiphers) {
+      this.excludeCiphers = pExcludeCiphers;
+      return this;
+    }
+
     public HttpServer2 build() throws IOException {
       Preconditions.checkNotNull(name, "name is not set");
       Preconditions.checkState(!endpoints.isEmpty(), "No endpoints specified");
@@ -316,6 +322,12 @@ public final class HttpServer2 implements FilterContainer {
             c.setTruststoreType(trustStoreType);
             c.setTrustPassword(trustStorePassword);
           }
+
+          if(null != excludeCiphers && !excludeCiphers.isEmpty()) {
+            c.setExcludeCipherSuites(excludeCiphers.split(","));
+            LOG.info("Excluded Cipher List:" + excludeCiphers);
+          }
+
           listener = c;
 
         } else {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/FileBasedKeyStoresFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/FileBasedKeyStoresFactory.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/FileBasedKeyStoresFactory.java
index 41634a8..4e59010 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/FileBasedKeyStoresFactory.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/FileBasedKeyStoresFactory.java
@@ -67,6 +67,8 @@ public class FileBasedKeyStoresFactory implements KeyStoresFactory {
     "ssl.{0}.truststore.password";
   public static final String SSL_TRUSTSTORE_TYPE_TPL_KEY =
     "ssl.{0}.truststore.type";
+  public static final String SSL_EXCLUDE_CIPHER_LIST =
+      "ssl.{0}.exclude.cipher.list";
 
   /**
    * Default format of the keystore files.

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpCookieFlag.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpCookieFlag.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpCookieFlag.java
index f73b019..f93f663 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpCookieFlag.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpCookieFlag.java
@@ -102,7 +102,10 @@ public class TestHttpCookieFlag {
                     sslConf.get("ssl.server.keystore.type", "jks"))
             .trustStore(sslConf.get("ssl.server.truststore.location"),
                     sslConf.get("ssl.server.truststore.password"),
-                    sslConf.get("ssl.server.truststore.type", "jks")).build();
+                    sslConf.get("ssl.server.truststore.type", "jks"))
+            .excludeCiphers(
+                    sslConf.get("ssl.server.exclude.cipher.list"))
+            .build();
     server.addServlet("echo", "/echo", TestHttpServer.EchoServlet.class);
     server.start();
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
index 1371964..c5ecfa1 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestSSLHttpServer.java
@@ -19,11 +19,18 @@ package org.apache.hadoop.http;
 
 import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.IOException;
 import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.Socket;
 import java.net.URI;
 import java.net.URL;
+import java.net.UnknownHostException;
 
 import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLHandshakeException;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -43,6 +50,7 @@ import org.junit.Test;
  * corresponding HTTPS URL.
  */
 public class TestSSLHttpServer extends HttpServerFunctionalTest {
+
   private static final String BASEDIR = System.getProperty("test.build.dir",
       "target/test-dir") + "/" + TestSSLHttpServer.class.getSimpleName();
 
@@ -52,6 +60,23 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
   private static String keystoresDir;
   private static String sslConfDir;
   private static SSLFactory clientSslFactory;
+  private static final String excludeCiphers = "TLS_ECDHE_RSA_WITH_RC4_128_SHA,"
+      + "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,"
+      + "SSL_RSA_WITH_DES_CBC_SHA,"
+      + "SSL_DHE_RSA_WITH_DES_CBC_SHA,"
+      + "SSL_RSA_EXPORT_WITH_RC4_40_MD5,"
+      + "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA,"
+      + "SSL_RSA_WITH_RC4_128_MD5";
+  private static final String oneEnabledCiphers = excludeCiphers
+      + ",TLS_RSA_WITH_AES_128_CBC_SHA";
+  private static final String exclusiveEnabledCiphers
+      = "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_RSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_DHE_RSA_WITH_AES_128_CBC_SHA,"
+      + "TLS_DHE_DSS_WITH_AES_128_CBC_SHA";
 
   @BeforeClass
   public static void setup() throws Exception {
@@ -64,7 +89,9 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
     keystoresDir = new File(BASEDIR).getAbsolutePath();
     sslConfDir = KeyStoreTestUtil.getClasspathDir(TestSSLHttpServer.class);
 
-    KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfDir, conf, false);
+    KeyStoreTestUtil.setupSSLConfig(keystoresDir, sslConfDir, conf, false, true,
+        excludeCiphers);
+
     Configuration sslConf = KeyStoreTestUtil.getSslConfig();
 
     clientSslFactory = new SSLFactory(SSLFactory.Mode.CLIENT, sslConf);
@@ -80,7 +107,9 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
             sslConf.get("ssl.server.keystore.type", "jks"))
         .trustStore(sslConf.get("ssl.server.truststore.location"),
             sslConf.get("ssl.server.truststore.password"),
-            sslConf.get("ssl.server.truststore.type", "jks")).build();
+            sslConf.get("ssl.server.truststore.type", "jks"))
+        .excludeCiphers(
+            sslConf.get("ssl.server.exclude.cipher.list")).build();
     server.addServlet("echo", "/echo", TestHttpServer.EchoServlet.class);
     server.addServlet("longheader", "/longheader", LongHeaderServlet.class);
     server.start();
@@ -105,10 +134,10 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
   }
 
   /**
-   *  Test that verifies headers can be up to 64K long.
-   *  The test adds a 63K header leaving 1K for other headers.
-   *  This is because the header buffer setting is for ALL headers,
-   *  names and values included. */
+   * Test that verifies headers can be up to 64K long. The test adds a 63K
+   * header leaving 1K for other headers. This is because the header buffer
+   * setting is for ALL headers, names and values included.
+   */
   @Test
   public void testLongHeader() throws Exception {
     URL url = new URL(baseUrl, "/longheader");
@@ -126,4 +155,162 @@ public class TestSSLHttpServer extends HttpServerFunctionalTest {
     return out.toString();
   }
 
+  /**
+   * Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
+   * TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
+   * TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
+   * available for negotiation during SSL connection.
+   */
+  @Test
+  public void testExcludedCiphers() throws Exception {
+    URL url = new URL(baseUrl, "/echo?a=b&c=d");
+    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
+    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
+    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
+        = new PrefferedCipherSSLSocketFactory(sslSocketF,
+            excludeCiphers.split(","));
+    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
+    assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
+    try {
+      InputStream in = conn.getInputStream();
+      ByteArrayOutputStream out = new ByteArrayOutputStream();
+      IOUtils.copyBytes(in, out, 1024);
+      fail("No Ciphers in common, SSLHandshake must fail.");
+    } catch (SSLHandshakeException ex) {
+      LOG.info("No Ciphers in common, expected succesful test result.", ex);
+    }
+  }
+
+  /** Test that verified that additionally included cipher
+   * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
+   * TLS connection from client to server disabled for all other common ciphers.
+   */
+  @Test
+  public void testOneEnabledCiphers() throws Exception {
+    URL url = new URL(baseUrl, "/echo?a=b&c=d");
+    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
+    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
+    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
+        = new PrefferedCipherSSLSocketFactory(sslSocketF,
+            oneEnabledCiphers.split(","));
+    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
+    assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
+    try {
+      InputStream in = conn.getInputStream();
+      ByteArrayOutputStream out = new ByteArrayOutputStream();
+      IOUtils.copyBytes(in, out, 1024);
+      assertEquals(out.toString(), "a:b\nc:d\n");
+      LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
+          + " expected successful test result.");
+    } catch (SSLHandshakeException ex) {
+      fail("Atleast one additional cipher available for successful handshake."
+          + " Unexpected test failure: " + ex);
+    }
+  }
+
+  /** Test verifies that mutually exclusive server's disabled cipher suites and
+   * client's enabled cipher suites can successfully establish TLS connection.
+   */
+  @Test
+  public void testExclusiveEnabledCiphers() throws Exception {
+    URL url = new URL(baseUrl, "/echo?a=b&c=d");
+    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
+    SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
+    PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
+        = new PrefferedCipherSSLSocketFactory(sslSocketF,
+            exclusiveEnabledCiphers.split(","));
+    conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
+    assertFalse("excludedCipher list is empty",
+        exclusiveEnabledCiphers.isEmpty());
+    try {
+      InputStream in = conn.getInputStream();
+      ByteArrayOutputStream out = new ByteArrayOutputStream();
+      IOUtils.copyBytes(in, out, 1024);
+      assertEquals(out.toString(), "a:b\nc:d\n");
+      LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
+          + " expected successful test result.");
+    } catch (SSLHandshakeException ex) {
+      fail("Atleast one additional cipher available for successful handshake."
+          + " Unexpected test failure: " + ex);
+    }
+  }
+
+  private class PrefferedCipherSSLSocketFactory extends SSLSocketFactory {
+    private final SSLSocketFactory delegateSocketFactory;
+    private final String[] enabledCipherSuites;
+
+    public PrefferedCipherSSLSocketFactory(SSLSocketFactory sslSocketFactory,
+        String[] pEnabledCipherSuites) {
+      delegateSocketFactory = sslSocketFactory;
+      if (null != pEnabledCipherSuites && pEnabledCipherSuites.length > 0) {
+        enabledCipherSuites = pEnabledCipherSuites;
+      } else {
+        enabledCipherSuites = null;
+      }
+    }
+
+    @Override
+    public String[] getDefaultCipherSuites() {
+      return delegateSocketFactory.getDefaultCipherSuites();
+    }
+
+    @Override
+    public String[] getSupportedCipherSuites() {
+      return delegateSocketFactory.getSupportedCipherSuites();
+    }
+
+    @Override
+    public Socket createSocket(Socket socket, String string, int i, boolean bln)
+        throws IOException {
+      SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket(
+          socket, string, i, bln);
+      if (null != enabledCipherSuites) {
+        sslSocket.setEnabledCipherSuites(enabledCipherSuites);
+      }
+      return sslSocket;
+    }
+
+    @Override
+    public Socket createSocket(String string, int i) throws IOException,
+        UnknownHostException {
+      SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket(
+          string, i);
+      if (null != enabledCipherSuites) {
+        sslSocket.setEnabledCipherSuites(enabledCipherSuites);
+      }
+      return sslSocket;
+    }
+
+    @Override
+    public Socket createSocket(String string, int i, InetAddress ia, int i1)
+        throws IOException, UnknownHostException {
+      SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket(
+          string, i, ia, i1);
+      if (null != enabledCipherSuites) {
+        sslSocket.setEnabledCipherSuites(enabledCipherSuites);
+      }
+      return sslSocket;
+    }
+
+    @Override
+    public Socket createSocket(InetAddress ia, int i) throws IOException {
+      SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket(ia,
+          i);
+      if (null != enabledCipherSuites) {
+        sslSocket.setEnabledCipherSuites(enabledCipherSuites);
+      }
+      return sslSocket;
+    }
+
+    @Override
+    public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1)
+        throws IOException {
+      SSLSocket sslSocket = (SSLSocket) delegateSocketFactory.createSocket(ia,
+          i, ia1, i1);
+      if (null != enabledCipherSuites) {
+        sslSocket.setEnabledCipherSuites(enabledCipherSuites);
+      }
+      return sslSocket;
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/KeyStoreTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/KeyStoreTestUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/KeyStoreTestUtil.java
index 453ae48..00cd1cb 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/KeyStoreTestUtil.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/ssl/KeyStoreTestUtil.java
@@ -218,11 +218,33 @@ public class KeyStoreTestUtil {
    * @param useClientCert boolean true to make the client present a cert in the
    * SSL handshake
    * @param trustStore boolean true to create truststore, false not to create it
+   * @throws java.lang.Exception
    */
   public static void setupSSLConfig(String keystoresDir, String sslConfDir,
                                     Configuration conf, boolean useClientCert,
       boolean trustStore)
     throws Exception {
+    setupSSLConfig(keystoresDir, sslConfDir, conf, useClientCert, true,"");
+  }
+
+    /**
+     * Performs complete setup of SSL configuration in preparation for testing an
+     * SSLFactory.  This includes keys, certs, keystores, truststores, the server
+     * SSL configuration file, the client SSL configuration file, and the master
+     * configuration file read by the SSLFactory.
+     *
+     * @param keystoresDir
+     * @param sslConfDir
+     * @param conf
+     * @param useClientCert
+     * @param trustStore
+     * @param excludeCiphers
+     * @throws Exception
+     */
+    public static void setupSSLConfig(String keystoresDir, String sslConfDir,
+                                    Configuration conf, boolean useClientCert,
+      boolean trustStore, String excludeCiphers)
+    throws Exception {
     String clientKS = keystoresDir + "/clientKS.jks";
     String clientPassword = "clientP";
     String serverKS = keystoresDir + "/serverKS.jks";
@@ -259,9 +281,9 @@ public class KeyStoreTestUtil {
     }
 
     Configuration clientSSLConf = createClientSSLConfig(clientKS, clientPassword,
-      clientPassword, trustKS);
+      clientPassword, trustKS, excludeCiphers);
     Configuration serverSSLConf = createServerSSLConfig(serverKS, serverPassword,
-      serverPassword, trustKS);
+      serverPassword, trustKS, excludeCiphers);
 
     saveConfig(sslClientConfFile, clientSSLConf);
     saveConfig(sslServerConfFile, serverSSLConf);
@@ -285,9 +307,26 @@ public class KeyStoreTestUtil {
    */
   public static Configuration createClientSSLConfig(String clientKS,
       String password, String keyPassword, String trustKS) {
-    Configuration clientSSLConf = createSSLConfig(SSLFactory.Mode.CLIENT,
-      clientKS, password, keyPassword, trustKS);
-    return clientSSLConf;
+    return createSSLConfig(SSLFactory.Mode.CLIENT,
+      clientKS, password, keyPassword, trustKS, "");
+  }
+
+  /**
+   * Creates SSL configuration for a client.
+   *
+   * @param clientKS String client keystore file
+   * @param password String store password, or null to avoid setting store
+   *   password
+   * @param keyPassword String key password, or null to avoid setting key
+   *   password
+   * @param trustKS String truststore file
+   * @param excludeCiphers String comma separated ciphers to exclude
+   * @return Configuration for client SSL
+   */
+    public static Configuration createClientSSLConfig(String clientKS,
+      String password, String keyPassword, String trustKS, String excludeCiphers) {
+    return createSSLConfig(SSLFactory.Mode.CLIENT,
+      clientKS, password, keyPassword, trustKS, excludeCiphers);
   }
 
   /**
@@ -300,12 +339,31 @@ public class KeyStoreTestUtil {
    *   password
    * @param trustKS String truststore file
    * @return Configuration for server SSL
+   * @throws java.io.IOException
    */
   public static Configuration createServerSSLConfig(String serverKS,
       String password, String keyPassword, String trustKS) throws IOException {
-    Configuration serverSSLConf = createSSLConfig(SSLFactory.Mode.SERVER,
-      serverKS, password, keyPassword, trustKS);
-    return serverSSLConf;
+    return createSSLConfig(SSLFactory.Mode.SERVER,
+      serverKS, password, keyPassword, trustKS, "");
+  }
+
+  /**
+   * Creates SSL configuration for a server.
+   *
+   * @param serverKS String server keystore file
+   * @param password String store password, or null to avoid setting store
+   * password
+   * @param keyPassword String key password, or null to avoid setting key
+   * password
+   * @param trustKS String truststore file
+   * @param excludeCiphers String comma separated ciphers to exclude
+   * @return
+   * @throws IOException
+   */
+    public static Configuration createServerSSLConfig(String serverKS,
+      String password, String keyPassword, String trustKS, String excludeCiphers) throws IOException {
+    return createSSLConfig(SSLFactory.Mode.SERVER,
+      serverKS, password, keyPassword, trustKS, excludeCiphers);
   }
 
   /**
@@ -357,7 +415,7 @@ public class KeyStoreTestUtil {
    * @return Configuration for SSL
    */
   private static Configuration createSSLConfig(SSLFactory.Mode mode,
-      String keystore, String password, String keyPassword, String trustKS) {
+    String keystore, String password, String keyPassword, String trustKS, String excludeCiphers) {
     String trustPassword = "trustP";
 
     Configuration sslConf = new Configuration(false);
@@ -383,6 +441,11 @@ public class KeyStoreTestUtil {
         FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY),
         trustPassword);
     }
+    if(null != excludeCiphers && !excludeCiphers.isEmpty()) {
+      sslConf.set(FileBasedKeyStoresFactory.resolvePropertyName(mode,
+      FileBasedKeyStoresFactory.SSL_EXCLUDE_CIPHER_LIST),
+        excludeCiphers);
+    }
     sslConf.set(FileBasedKeyStoresFactory.resolvePropertyName(mode,
       FileBasedKeyStoresFactory.SSL_TRUSTSTORE_RELOAD_INTERVAL_TPL_KEY), "1000");
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSUtil.java
index d018130..b697a9c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSUtil.java
@@ -1295,7 +1295,9 @@ public class DFSUtil {
             sslConf.get("ssl.server.keystore.type", "jks"))
         .trustStore(sslConf.get("ssl.server.truststore.location"),
             getPassword(sslConf, DFS_SERVER_HTTPS_TRUSTSTORE_PASSWORD_KEY),
-            sslConf.get("ssl.server.truststore.type", "jks"));
+            sslConf.get("ssl.server.truststore.type", "jks"))
+        .excludeCiphers(
+            sslConf.get("ssl.server.exclude.cipher.list"));
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a2fdfff0/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/util/WebAppUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/util/WebAppUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/util/WebAppUtils.java
index 459c110..f8e67ee 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/util/WebAppUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/util/WebAppUtils.java
@@ -352,7 +352,9 @@ public class WebAppUtils {
             sslConf.get("ssl.server.keystore.type", "jks"))
         .trustStore(sslConf.get("ssl.server.truststore.location"),
             getPassword(sslConf, WEB_APP_TRUSTSTORE_PASSWORD_KEY),
-            sslConf.get("ssl.server.truststore.type", "jks"));
+            sslConf.get("ssl.server.truststore.type", "jks"))
+        .excludeCiphers(
+            sslConf.get("ssl.server.exclude.cipher.list"));
   }
 
   /**


[02/50] [abbrv] hadoop git commit: HDFS-9799. Reimplement getCurrentTrashDir to remove incompatibility. (zhz)

Posted by ji...@apache.org.
HDFS-9799. Reimplement getCurrentTrashDir to remove incompatibility. (zhz)

Change-Id: I7834bcebffed38cb384db5395ddb8b6dd9e79a0b


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/0fb14aac
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/0fb14aac
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/0fb14aac

Branch: refs/heads/HDFS-7240
Commit: 0fb14aaced7afdbbb72e59316c186ebf6ec2d091
Parents: 76fab26
Author: Zhe Zhang <zh...@apache.org>
Authored: Wed Feb 17 13:30:50 2016 -0800
Committer: Zhe Zhang <zh...@apache.org>
Committed: Wed Feb 17 13:30:50 2016 -0800

----------------------------------------------------------------------
 .../java/org/apache/hadoop/fs/FileSystem.java   | 41 ++++++-------
 .../org/apache/hadoop/fs/FilterFileSystem.java  |  5 +-
 .../java/org/apache/hadoop/fs/TrashPolicy.java  |  2 +-
 .../apache/hadoop/fs/TrashPolicyDefault.java    |  9 +--
 .../hadoop/hdfs/DistributedFileSystem.java      | 63 +++++++++++---------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  2 +
 6 files changed, 64 insertions(+), 58 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
index f4a2e7d..3e26f68 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
@@ -2689,9 +2689,8 @@ public abstract class FileSystem extends Configured implements Closeable {
    *
    * @param path the trash root of the path to be determined.
    * @return the default implementation returns "/user/$USER/.Trash".
-   * @throws IOException
    */
-  public Path getTrashRoot(Path path) throws IOException {
+  public Path getTrashRoot(Path path) {
     return this.makeQualified(new Path(getHomeDirectory().toUri().getPath(),
         TRASH_PREFIX));
   }
@@ -2703,29 +2702,31 @@ public abstract class FileSystem extends Configured implements Closeable {
    * @return all the trash root directories.
    *         Default FileSystem returns .Trash under users' home directories if
    *         /user/$USER/.Trash exists.
-   * @throws IOException
    */
-  public Collection<FileStatus> getTrashRoots(boolean allUsers)
-      throws IOException {
+  public Collection<FileStatus> getTrashRoots(boolean allUsers) {
     Path userHome = new Path(getHomeDirectory().toUri().getPath());
-    List<FileStatus> ret = new ArrayList<FileStatus>();
-    if (!allUsers) {
-      Path userTrash = new Path(userHome, TRASH_PREFIX);
-      if (exists(userTrash)) {
-        ret.add(getFileStatus(userTrash));
-      }
-    } else {
-      Path homeParent = userHome.getParent();
-      if (exists(homeParent)) {
-        FileStatus[] candidates = listStatus(homeParent);
-        for (FileStatus candidate : candidates) {
-          Path userTrash = new Path(candidate.getPath(), TRASH_PREFIX);
-          if (exists(userTrash)) {
-            candidate.setPath(userTrash);
-            ret.add(candidate);
+    List<FileStatus> ret = new ArrayList<>();
+    try {
+      if (!allUsers) {
+        Path userTrash = new Path(userHome, TRASH_PREFIX);
+        if (exists(userTrash)) {
+          ret.add(getFileStatus(userTrash));
+        }
+      } else {
+        Path homeParent = userHome.getParent();
+        if (exists(homeParent)) {
+          FileStatus[] candidates = listStatus(homeParent);
+          for (FileStatus candidate : candidates) {
+            Path userTrash = new Path(candidate.getPath(), TRASH_PREFIX);
+            if (exists(userTrash)) {
+              candidate.setPath(userTrash);
+              ret.add(candidate);
+            }
           }
         }
       }
+    } catch (IOException e) {
+      LOG.warn("Cannot get all trash roots", e);
     }
     return ret;
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FilterFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FilterFileSystem.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FilterFileSystem.java
index 53678e0..4ee7514 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FilterFileSystem.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FilterFileSystem.java
@@ -645,13 +645,12 @@ public class FilterFileSystem extends FileSystem {
   }
 
   @Override
-  public Path getTrashRoot(Path path) throws IOException {
+  public Path getTrashRoot(Path path) {
     return fs.getTrashRoot(path);
   }
 
   @Override
-  public Collection<FileStatus> getTrashRoots(boolean allUsers)
-      throws IOException {
+  public Collection<FileStatus> getTrashRoots(boolean allUsers) {
     return fs.getTrashRoots(allUsers);
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicy.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicy.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicy.java
index 1d901c1..92a4d1f 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicy.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicy.java
@@ -89,7 +89,7 @@ public abstract class TrashPolicy extends Configured {
    * It returns the trash location correctly for the path specified no matter
    * the path is in encryption zone or not.
    */
-  public abstract Path getCurrentTrashDir() throws IOException;
+  public abstract Path getCurrentTrashDir();
 
   /**
    * Get the current trash directory for path specified based on the Trash

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicyDefault.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicyDefault.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicyDefault.java
index b5d245b..012ce32 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicyDefault.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/TrashPolicyDefault.java
@@ -196,7 +196,7 @@ public class TrashPolicyDefault extends TrashPolicy {
   }
 
   @Override
-  public Path getCurrentTrashDir() throws IOException {
+  public Path getCurrentTrashDir() {
     return new Path(fs.getTrashRoot(null), CURRENT);
   }
 
@@ -250,12 +250,7 @@ public class TrashPolicyDefault extends TrashPolicy {
           now = Time.now();
           if (now >= end) {
             Collection<FileStatus> trashRoots;
-            try {
-              trashRoots = fs.getTrashRoots(true);      // list all home dirs
-            } catch (IOException e) {
-              LOG.warn("Trash can't list all trash roots: "+e+" Sleeping.");
-              continue;
-            }
+            trashRoots = fs.getTrashRoots(true);      // list all trash dirs
 
             for (FileStatus trashRoot : trashRoots) {   // dump each trash
               if (!trashRoot.isDirectory())

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
index 6de7659..69f3871 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
@@ -2338,27 +2338,31 @@ public class DistributedFileSystem extends FileSystem {
   /**
    * Get the root directory of Trash for a path in HDFS.
    * 1. File in encryption zone returns /ez1/.Trash/username
-   * 2. File not in encryption zone returns /users/username/.Trash
+   * 2. File not in encryption zone, or encountered exception when checking
+   *    the encryption zone of the path, returns /users/username/.Trash
    * Caller appends either Current or checkpoint timestamp for trash destination
    * @param path the trash root of the path to be determined.
    * @return trash root
-   * @throws IOException
    */
   @Override
-  public Path getTrashRoot(Path path) throws IOException {
+  public Path getTrashRoot(Path path) {
     if ((path == null) || path.isRoot() || !dfs.isHDFSEncryptionEnabled()) {
       return super.getTrashRoot(path);
     }
 
     String parentSrc = path.getParent().toUri().getPath();
-    EncryptionZone ez = dfs.getEZForPath(parentSrc);
-    if ((ez != null)) {
-      return this.makeQualified(
-          new Path(ez.getPath() + "/" + FileSystem.TRASH_PREFIX +
-              dfs.ugi.getShortUserName()));
-    } else {
-      return super.getTrashRoot(path);
+    try {
+      EncryptionZone ez = dfs.getEZForPath(parentSrc);
+      if ((ez != null)) {
+        return this.makeQualified(
+            new Path(ez.getPath() + "/" + FileSystem.TRASH_PREFIX +
+                dfs.ugi.getShortUserName()));
+      }
+    } catch (IOException e) {
+      DFSClient.LOG.warn("Exception in checking the encryption zone for the " +
+          "path " + parentSrc + ". " + e.getMessage());
     }
+    return super.getTrashRoot(path);
   }
 
   /**
@@ -2366,32 +2370,37 @@ public class DistributedFileSystem extends FileSystem {
    * 1. File deleted from non-encryption zone /user/username/.Trash
    * 2. File deleted from encryption zones
    *    e.g., ez1 rooted at /ez1 has its trash root at /ez1/.Trash/$USER
-   * @allUsers return trashRoots of all users if true, used by emptier
+   * @param allUsers return trashRoots of all users if true, used by emptier
    * @return trash roots of HDFS
-   * @throws IOException
    */
   @Override
-  public Collection<FileStatus> getTrashRoots(boolean allUsers) throws IOException {
-    List<FileStatus> ret = new ArrayList<FileStatus>();
+  public Collection<FileStatus> getTrashRoots(boolean allUsers) {
+    List<FileStatus> ret = new ArrayList<>();
     // Get normal trash roots
     ret.addAll(super.getTrashRoots(allUsers));
 
-    // Get EZ Trash roots
-    final RemoteIterator<EncryptionZone> it = dfs.listEncryptionZones();
-    while (it.hasNext()) {
-      Path ezTrashRoot = new Path(it.next().getPath(), FileSystem.TRASH_PREFIX);
-      if (allUsers) {
-        for (FileStatus candidate : listStatus(ezTrashRoot)) {
-          if (exists(candidate.getPath())) {
-            ret.add(candidate);
+    try {
+      // Get EZ Trash roots
+      final RemoteIterator<EncryptionZone> it = dfs.listEncryptionZones();
+      while (it.hasNext()) {
+        Path ezTrashRoot = new Path(it.next().getPath(),
+            FileSystem.TRASH_PREFIX);
+        if (allUsers) {
+          for (FileStatus candidate : listStatus(ezTrashRoot)) {
+            if (exists(candidate.getPath())) {
+              ret.add(candidate);
+            }
+          }
+        } else {
+          Path userTrash = new Path(ezTrashRoot, System.getProperty(
+              "user.name"));
+          if (exists(userTrash)) {
+            ret.add(getFileStatus(userTrash));
           }
-        }
-      } else {
-        Path userTrash = new Path(ezTrashRoot, System.getProperty("user.name"));
-        if (exists(userTrash)) {
-          ret.add(getFileStatus(userTrash));
         }
       }
+    } catch (IOException e){
+      DFSClient.LOG.warn("Cannot get all encrypted trash roots", e);
     }
     return ret;
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0fb14aac/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 36bb60d..89fc187 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2780,6 +2780,8 @@ Release 2.8.0 - UNRELEASED
     HDFS-9815. Move o.a.h.fs.Hdfs to hadoop-hdfs-client.
     (Vinayakumar B via wheat9)
 
+    HDFS-9799. Reimplement getCurrentTrashDir to remove incompatibility. (zhz)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES


[39/50] [abbrv] hadoop git commit: MAPREDUCE-6635. Unsafe long to int conversion in UncompressedSplitLineReader and IndexOutOfBoundsException. Contributed by Junping Du.

Posted by ji...@apache.org.
MAPREDUCE-6635. Unsafe long to int conversion in UncompressedSplitLineReader and IndexOutOfBoundsException. Contributed by Junping Du.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/c6f2d761
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/c6f2d761
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/c6f2d761

Branch: refs/heads/HDFS-7240
Commit: c6f2d761d5430eac6b9f07f137a7028de4e0660c
Parents: 140cb5d
Author: Varun Vasudev <vv...@apache.org>
Authored: Tue Feb 23 13:05:18 2016 +0530
Committer: Varun Vasudev <vv...@apache.org>
Committed: Tue Feb 23 13:05:18 2016 +0530

----------------------------------------------------------------------
 hadoop-mapreduce-project/CHANGES.txt            |  9 ++++
 .../lib/input/UncompressedSplitLineReader.java  |  7 ++-
 .../hadoop/mapred/TestLineRecordReader.java     | 53 ++++++++++++++++++++
 3 files changed, 67 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/c6f2d761/hadoop-mapreduce-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index f0ad171..9628d49 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -724,6 +724,9 @@ Release 2.8.0 - UNRELEASED
     MAPREDUCE-6616. Fail to create jobhistory file if there are some multibyte
     characters in the job name. (Kousuke Saruta via aajisaka)
 
+    MAPREDUCE-6635. Unsafe long to int conversion in UncompressedSplitLineReader
+    and IndexOutOfBoundsException. (Junping Du via vvasudev)
+
 Release 2.7.3 - UNRELEASED
 
   INCOMPATIBLE CHANGES
@@ -763,6 +766,9 @@ Release 2.7.3 - UNRELEASED
     MAPREDUCE-6191. Improve clearing stale state of Java serialization
                     testcase.  (Sam Liu via Eric Yang)
 
+    MAPREDUCE-6635. Unsafe long to int conversion in UncompressedSplitLineReader
+    and IndexOutOfBoundsException. (Junping Du via vvasudev)
+
 Release 2.7.2 - 2016-01-25
 
   INCOMPATIBLE CHANGES
@@ -1056,6 +1062,9 @@ Release 2.6.5 - UNRELEASED
     MAPREDUCE-6191. Improve clearing stale state of Java serialization
                     testcase.  (Sam Liu via Eric Yang)
 
+    MAPREDUCE-6635. Unsafe long to int conversion in UncompressedSplitLineReader
+    and IndexOutOfBoundsException. (Junping Du via vvasudev)
+
 Release 2.6.4 - 2016-02-11
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c6f2d761/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java
index 6d495ef..bda0218 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java
@@ -53,8 +53,11 @@ public class UncompressedSplitLineReader extends SplitLineReader {
       throws IOException {
     int maxBytesToRead = buffer.length;
     if (totalBytesRead < splitLength) {
-      maxBytesToRead = Math.min(maxBytesToRead,
-                                (int)(splitLength - totalBytesRead));
+      long leftBytesForSplit = splitLength - totalBytesRead;
+      // check if leftBytesForSplit exceed Integer.MAX_VALUE
+      if (leftBytesForSplit <= Integer.MAX_VALUE) {
+        maxBytesToRead = Math.min(maxBytesToRead, (int)leftBytesForSplit);
+      }
     }
     int bytesRead = in.read(buffer, 0, maxBytesToRead);
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c6f2d761/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java
index f0cf9f5..f50e1ef 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestLineRecordReader.java
@@ -110,6 +110,43 @@ public class TestLineRecordReader {
         numRecordsNoSplits, numRecordsFirstSplit + numRecordsRemainingSplits);
   }
 
+  private void testLargeSplitRecordForFile(Configuration conf,
+      long firstSplitLength, long testFileSize, Path testFilePath)
+      throws IOException {
+    conf.setInt(org.apache.hadoop.mapreduce.lib.input.
+        LineRecordReader.MAX_LINE_LENGTH, Integer.MAX_VALUE);
+    assertTrue("unexpected firstSplitLength:" + firstSplitLength,
+        testFileSize < firstSplitLength);
+    String delimiter = conf.get("textinputformat.record.delimiter");
+    byte[] recordDelimiterBytes = null;
+    if (null != delimiter) {
+      recordDelimiterBytes = delimiter.getBytes(Charsets.UTF_8);
+    }
+    // read the data without splitting to count the records
+    FileSplit split = new FileSplit(testFilePath, 0, testFileSize,
+        (String[])null);
+    LineRecordReader reader = new LineRecordReader(conf, split,
+        recordDelimiterBytes);
+    LongWritable key = new LongWritable();
+    Text value = new Text();
+    int numRecordsNoSplits = 0;
+    while (reader.next(key, value)) {
+      ++numRecordsNoSplits;
+    }
+    reader.close();
+
+    // count the records in the first split
+    split = new FileSplit(testFilePath, 0, firstSplitLength, (String[])null);
+    reader = new LineRecordReader(conf, split, recordDelimiterBytes);
+    int numRecordsFirstSplit = 0;
+    while (reader.next(key, value)) {
+      ++numRecordsFirstSplit;
+    }
+    reader.close();
+    assertEquals("Unexpected number of records in split",
+        numRecordsNoSplits, numRecordsFirstSplit);
+  }
+
   @Test
   public void testBzip2SplitEndsAtCR() throws IOException {
     // the test data contains a carriage-return at the end of the first
@@ -332,6 +369,22 @@ public class TestLineRecordReader {
   }
 
   @Test
+  public void testUncompressedInputWithLargeSplitSize() throws Exception {
+    Configuration conf = new Configuration();
+    // single char delimiter
+    String inputData = "abcde +fghij+ klmno+pqrst+uvwxyz";
+    Path inputFile = createInputFile(conf, inputData);
+    conf.set("textinputformat.record.delimiter", "+");
+    // split size over max value of integer
+    long longSplitSize = (long)Integer.MAX_VALUE + 1;
+    for (int bufferSize = 1; bufferSize <= inputData.length(); bufferSize++) {
+      conf.setInt("io.file.buffer.size", bufferSize);
+      testLargeSplitRecordForFile(conf, longSplitSize, inputData.length(),
+          inputFile);
+    }
+  }
+
+  @Test
   public void testUncompressedInput() throws Exception {
     Configuration conf = new Configuration();
     // single char delimiter, best case


[17/50] [abbrv] hadoop git commit: MAPREDUCE-6627. Add machine-readable output to mapred job -history command (rkanter)

Posted by ji...@apache.org.
MAPREDUCE-6627. Add machine-readable output to mapred job -history command (rkanter)


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/8eee59ce
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/8eee59ce
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/8eee59ce

Branch: refs/heads/HDFS-7240
Commit: 8eee59ce6b3044cb73bb41fed6b7ece959e7c2f8
Parents: 8ab7658
Author: Robert Kanter <rk...@apache.org>
Authored: Thu Feb 18 17:58:26 2016 -0800
Committer: Robert Kanter <rk...@apache.org>
Committed: Thu Feb 18 17:58:26 2016 -0800

----------------------------------------------------------------------
 hadoop-mapreduce-project/CHANGES.txt            |   3 +
 .../hadoop-mapreduce-client-core/pom.xml        |   5 +
 .../mapreduce/jobhistory/HistoryViewer.java     | 480 +---------
 .../jobhistory/HistoryViewerPrinter.java        |  39 +
 .../HumanReadableHistoryViewerPrinter.java      | 471 +++++++++
 .../jobhistory/JSONHistoryViewerPrinter.java    | 256 +++++
 .../org/apache/hadoop/mapreduce/tools/CLI.java  |  79 +-
 .../src/site/markdown/MapredCommands.md         |   4 +-
 .../jobhistory/TestHistoryViewerPrinter.java    | 945 +++++++++++++++++++
 .../hadoop/mapreduce/TestMRJobClient.java       | 160 +++-
 hadoop-project/pom.xml                          |   6 +
 11 files changed, 1986 insertions(+), 462 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/CHANGES.txt b/hadoop-mapreduce-project/CHANGES.txt
index da28bc6..a6031c0 100644
--- a/hadoop-mapreduce-project/CHANGES.txt
+++ b/hadoop-mapreduce-project/CHANGES.txt
@@ -313,6 +313,9 @@ Release 2.9.0 - UNRELEASED
     MAPREDUCE-6634. Log uncaught exceptions/errors in various thread pools in
     mapreduce. (Sidharta Seethana via vvasudev)
 
+    MAPREDUCE-6627. Add machine-readable output to mapred job -history
+    command (rkanter)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/pom.xml b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/pom.xml
index 61f3c53..f0952bc 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/pom.xml
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/pom.xml
@@ -42,6 +42,11 @@
       <artifactId>hadoop-hdfs</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.skyscreamer</groupId>
+      <artifactId>jsonassert</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 
   <build>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewer.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewer.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewer.java
index f343d7c..e5db2e5 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewer.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewer.java
@@ -19,13 +19,8 @@ package org.apache.hadoop.mapreduce.jobhistory;
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.text.DecimalFormat;
-import java.text.Format;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Comparator;
+import java.io.PrintStream;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
@@ -37,46 +32,52 @@ import org.apache.hadoop.classification.InterfaceStability;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.mapred.JobStatus;
 import org.apache.hadoop.mapred.TaskStatus;
-import org.apache.hadoop.mapreduce.CounterGroup;
-import org.apache.hadoop.mapreduce.Counters;
 import org.apache.hadoop.mapreduce.TaskAttemptID;
 import org.apache.hadoop.mapreduce.TaskID;
 import org.apache.hadoop.mapreduce.TaskType;
 import org.apache.hadoop.mapreduce.counters.Limits;
 import org.apache.hadoop.mapreduce.jobhistory.JobHistoryParser.JobInfo;
-import org.apache.hadoop.mapreduce.jobhistory.JobHistoryParser.TaskInfo;
 import org.apache.hadoop.mapreduce.util.HostUtil;
-import org.apache.hadoop.util.StringUtils;
 import org.apache.hadoop.yarn.webapp.util.WebAppUtils;
 
 /**
- * HistoryViewer is used to parse and view the JobHistory files 
- *
+ * HistoryViewer is used to parse and view the JobHistory files.  They can be
+ * printed in human-readable format or machine-readable JSON format using the
+ * {@link HistoryViewerPrinter}.
  */
 @InterfaceAudience.Private
 @InterfaceStability.Unstable
 public class HistoryViewer {
   private static final Log LOG = LogFactory.getLog(HistoryViewer.class);
-  private static final SimpleDateFormat dateFormat =
-    new SimpleDateFormat("d-MMM-yyyy HH:mm:ss");
   private FileSystem fs;
   private JobInfo job;
-  private String jobId;
-  private boolean printAll;
+  private HistoryViewerPrinter jhvp;
+  public static final String HUMAN_FORMAT = "human";
+  public static final String JSON_FORMAT = "json";
 
-/**
- * Constructs the HistoryViewer object
- * @param historyFile The fully qualified Path of the History File
- * @param conf The Configuration file
- * @param printAll Toggle to print all status to only killed/failed status
- * @throws IOException
- */
-  public HistoryViewer(String historyFile, 
-                       Configuration conf,
+  /**
+   * Constructs the HistoryViewer object.
+   * @param historyFile the fully qualified Path of the History File
+   * @param conf the Configuration file
+   * @param printAll toggle to print all status to only killed/failed status
+   * @throws IOException when there is a problem parsing the history file
+   */
+  public HistoryViewer(String historyFile, Configuration conf,
                        boolean printAll) throws IOException {
-    this.printAll = printAll;
+    this(historyFile, conf, printAll, HUMAN_FORMAT);
+  }
+
+  /**
+   * Constructs the HistoryViewer object.
+   * @param historyFile the fully qualified Path of the History File
+   * @param conf the Configuration file
+   * @param printAll toggle to print all status to only killed/failed status
+   * @param format the output format to use
+   * @throws IOException when there is a problem parsing the history file
+   */
+  public HistoryViewer(String historyFile, Configuration conf, boolean printAll,
+                       String format) throws IOException {
     String errorMsg = "Unable to initialize History Viewer";
     try {
       Path jobFile = new Path(historyFile);
@@ -101,366 +102,41 @@ public class HistoryViewer {
       }
       JobHistoryParser parser = new JobHistoryParser(fs, jobFile);
       job = parser.parse();
-      jobId = job.getJobId().toString();
-    } catch(Exception e) {
+      String scheme = WebAppUtils.getHttpSchemePrefix(fs.getConf());
+      if (HUMAN_FORMAT.equalsIgnoreCase(format)) {
+        jhvp = new HumanReadableHistoryViewerPrinter(job, printAll, scheme);
+      } else if (JSON_FORMAT.equalsIgnoreCase(format)) {
+        jhvp = new JSONHistoryViewerPrinter(job, printAll, scheme);
+      } else {
+        System.err.println("Invalid format specified: " + format);
+        throw new IllegalArgumentException(errorMsg);
+      }
+    } catch(IOException e) {
       throw new IOException(errorMsg, e);
     }
   }
 
   /**
-   * Print the job/task/attempt summary information
-   * @throws IOException
+   * Print the job/task/attempt summary information to stdout.
+   * @throws IOException when there is a problem printing the history
    */
-  public void print() throws IOException{
-    printJobDetails();
-    printTaskSummary();
-    printJobAnalysis();
-    printTasks(TaskType.JOB_SETUP, TaskStatus.State.FAILED.toString());
-    printTasks(TaskType.JOB_SETUP, TaskStatus.State.KILLED.toString());
-    printTasks(TaskType.MAP, TaskStatus.State.FAILED.toString());
-    printTasks(TaskType.MAP, TaskStatus.State.KILLED.toString());
-    printTasks(TaskType.REDUCE, TaskStatus.State.FAILED.toString());
-    printTasks(TaskType.REDUCE, TaskStatus.State.KILLED.toString());
-    printTasks(TaskType.JOB_CLEANUP, TaskStatus.State.FAILED.toString());
-    printTasks(TaskType.JOB_CLEANUP, 
-        JobStatus.getJobRunState(JobStatus.KILLED));
-    if (printAll) {
-      printTasks(TaskType.JOB_SETUP, TaskStatus.State.SUCCEEDED.toString());
-      printTasks(TaskType.MAP, TaskStatus.State.SUCCEEDED.toString());
-      printTasks(TaskType.REDUCE, TaskStatus.State.SUCCEEDED.toString());
-      printTasks(TaskType.JOB_CLEANUP, TaskStatus.State.SUCCEEDED.toString());
-      printAllTaskAttempts(TaskType.JOB_SETUP);
-      printAllTaskAttempts(TaskType.MAP);
-      printAllTaskAttempts(TaskType.REDUCE);
-      printAllTaskAttempts(TaskType.JOB_CLEANUP);
-    }
-    
-    FilteredJob filter = new FilteredJob(job, 
-        TaskStatus.State.FAILED.toString());
-    printFailedAttempts(filter);
-    
-    filter = new FilteredJob(job,
-        TaskStatus.State.KILLED.toString());
-    printFailedAttempts(filter);
-  }
- 
-  private void printJobDetails() {
-    StringBuffer jobDetails = new StringBuffer();
-    jobDetails.append("\nHadoop job: " ).append(job.getJobId());
-    jobDetails.append("\n=====================================");
-    jobDetails.append("\nUser: ").append(job.getUsername()); 
-    jobDetails.append("\nJobName: ").append(job.getJobname()); 
-    jobDetails.append("\nJobConf: ").append(job.getJobConfPath()); 
-    jobDetails.append("\nSubmitted At: ").append(StringUtils.
-                        getFormattedTimeWithDiff(dateFormat,
-                        job.getSubmitTime(), 0)); 
-    jobDetails.append("\nLaunched At: ").append(StringUtils.
-                        getFormattedTimeWithDiff(dateFormat,
-                        job.getLaunchTime(),
-                        job.getSubmitTime()));
-    jobDetails.append("\nFinished At: ").append(StringUtils.
-                        getFormattedTimeWithDiff(dateFormat,
-                        job.getFinishTime(),
-                        job.getLaunchTime()));
-    jobDetails.append("\nStatus: ").append(((job.getJobStatus() == null) ? 
-                      "Incomplete" :job.getJobStatus()));
-    printCounters(jobDetails, job.getTotalCounters(), job.getMapCounters(),
-        job.getReduceCounters());
-    jobDetails.append("\n");
-    jobDetails.append("\n=====================================");
-    System.out.println(jobDetails.toString());
-  }
-
-  private void printCounters(StringBuffer buff, Counters totalCounters,
-      Counters mapCounters, Counters reduceCounters) {
-    // Killed jobs might not have counters
-    if (totalCounters == null) {
-      return;
-    }
-    buff.append("\nCounters: \n\n");
-    buff.append(String.format("|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s|", 
-        "Group Name",
-        "Counter name",
-        "Map Value",
-        "Reduce Value",
-        "Total Value"));
-    buff.append("\n------------------------------------------"+
-        "---------------------------------------------");
-    for (String groupName : totalCounters.getGroupNames()) {
-         CounterGroup totalGroup = totalCounters.getGroup(groupName);
-         CounterGroup mapGroup = mapCounters.getGroup(groupName);
-         CounterGroup reduceGroup = reduceCounters.getGroup(groupName);
-      
-         Format decimal = new DecimalFormat();
-         Iterator<org.apache.hadoop.mapreduce.Counter> ctrItr =
-           totalGroup.iterator();
-         while(ctrItr.hasNext()) {
-           org.apache.hadoop.mapreduce.Counter counter = ctrItr.next();
-           String name = counter.getName();
-           String mapValue = 
-             decimal.format(mapGroup.findCounter(name).getValue());
-           String reduceValue = 
-             decimal.format(reduceGroup.findCounter(name).getValue());
-           String totalValue = 
-             decimal.format(counter.getValue());
-
-           buff.append(
-               String.format("%n|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s", 
-                   totalGroup.getDisplayName(),
-                   counter.getDisplayName(),
-                   mapValue, reduceValue, totalValue));
-      }
-    }
-  }
-  
-  private void printAllTaskAttempts(TaskType taskType) {
-    Map<TaskID, TaskInfo> tasks = job.getAllTasks();
-    StringBuffer taskList = new StringBuffer();
-    taskList.append("\n").append(taskType);
-    taskList.append(" task list for ").append(job.getJobId());
-    taskList.append("\nTaskId\t\tStartTime");
-    if (TaskType.REDUCE.equals(taskType)) {
-      taskList.append("\tShuffleFinished\tSortFinished");
-    }
-    taskList.append("\tFinishTime\tHostName\tError\tTaskLogs");
-    taskList.append("\n====================================================");
-    System.out.println(taskList.toString());
-    for (JobHistoryParser.TaskInfo task : tasks.values()) {
-      for (JobHistoryParser.TaskAttemptInfo attempt : 
-        task.getAllTaskAttempts().values()) {
-        if (taskType.equals(task.getTaskType())){
-          taskList.setLength(0); 
-          taskList.append(attempt.getAttemptId()).append("\t");
-          taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
-                          attempt.getStartTime(), 0)).append("\t");
-          if (TaskType.REDUCE.equals(taskType)) {
-            taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
-                            attempt.getShuffleFinishTime(),
-                            attempt.getStartTime()));
-            taskList.append("\t"); 
-            taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat, 
-                            attempt.getSortFinishTime(),
-                            attempt.getShuffleFinishTime())); 
-          } 
-          taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
-                          attempt.getFinishTime(),
-                          attempt.getStartTime())); 
-          taskList.append("\t"); 
-          taskList.append(attempt.getHostname()).append("\t");
-          taskList.append(attempt.getError());
-          String taskLogsUrl = getTaskLogsUrl(
-              WebAppUtils.getHttpSchemePrefix(fs.getConf()), attempt);
-          taskList.append(taskLogsUrl != null ? taskLogsUrl : "n/a");
-          System.out.println(taskList.toString());
-        }
-      }
-    }
-  }
-
-  private void printTaskSummary() {
-    SummarizedJob ts = new SummarizedJob(job);
-    StringBuffer taskSummary = new StringBuffer();
-    taskSummary.append("\nTask Summary");
-    taskSummary.append("\n============================");
-    taskSummary.append("\nKind\tTotal\t");
-    taskSummary.append("Successful\tFailed\tKilled\tStartTime\tFinishTime");
-    taskSummary.append("\n");
-    taskSummary.append("\nSetup\t").append(ts.totalSetups);
-    taskSummary.append("\t").append(ts.numFinishedSetups);
-    taskSummary.append("\t\t").append(ts.numFailedSetups);
-    taskSummary.append("\t").append(ts.numKilledSetups);
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                               dateFormat, ts.setupStarted, 0));
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                               dateFormat, ts.setupFinished, ts.setupStarted));
-    taskSummary.append("\nMap\t").append(ts.totalMaps);
-    taskSummary.append("\t").append(job.getFinishedMaps());
-    taskSummary.append("\t\t").append(ts.numFailedMaps);
-    taskSummary.append("\t").append(ts.numKilledMaps);
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                               dateFormat, ts.mapStarted, 0));
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                               dateFormat, ts.mapFinished, ts.mapStarted));
-    taskSummary.append("\nReduce\t").append(ts.totalReduces);
-    taskSummary.append("\t").append(job.getFinishedReduces());
-    taskSummary.append("\t\t").append(ts.numFailedReduces);
-    taskSummary.append("\t").append(ts.numKilledReduces);
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                               dateFormat, ts.reduceStarted, 0));
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                            dateFormat, ts.reduceFinished, ts.reduceStarted));
-    taskSummary.append("\nCleanup\t").append(ts.totalCleanups);
-    taskSummary.append("\t").append(ts.numFinishedCleanups);
-    taskSummary.append("\t\t").append(ts.numFailedCleanups);
-    taskSummary.append("\t").append(ts.numKilledCleanups);
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                            dateFormat, ts.cleanupStarted, 0));
-    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                            dateFormat, ts.cleanupFinished, 
-                            ts.cleanupStarted)); 
-    taskSummary.append("\n============================\n");
-    System.out.println(taskSummary.toString());
-  }
-
-  private void printJobAnalysis() {
-    if (!job.getJobStatus().equals
-        (JobStatus.getJobRunState(JobStatus.SUCCEEDED))) {
-      System.out.println("No Analysis available as job did not finish");
-      return;
-    }
-    
-    AnalyzedJob avg = new AnalyzedJob(job);
-    
-    System.out.println("\nAnalysis");
-    System.out.println("=========");
-    printAnalysis(avg.getMapTasks(), cMap, "map", avg.getAvgMapTime(), 10);
-    printLast(avg.getMapTasks(), "map", cFinishMapRed);
-
-    if (avg.getReduceTasks().length > 0) {
-      printAnalysis(avg.getReduceTasks(), cShuffle, "shuffle", 
-          avg.getAvgShuffleTime(), 10);
-      printLast(avg.getReduceTasks(), "shuffle", cFinishShuffle);
-
-      printAnalysis(avg.getReduceTasks(), cReduce, "reduce",
-          avg.getAvgReduceTime(), 10);
-      printLast(avg.getReduceTasks(), "reduce", cFinishMapRed);
-    }
-    System.out.println("=========");
-  }
-
-  private void printAnalysis(JobHistoryParser.TaskAttemptInfo [] tasks,
-      Comparator<JobHistoryParser.TaskAttemptInfo> cmp,
-      String taskType,
-      long avg,
-      int showTasks) {
-    Arrays.sort(tasks, cmp);
-    JobHistoryParser.TaskAttemptInfo min = tasks[tasks.length-1];
-    StringBuffer details = new StringBuffer();
-    details.append("\nTime taken by best performing ");
-    details.append(taskType).append(" task ");
-    details.append(min.getAttemptId().getTaskID().toString()).append(": ");
-    if ("map".equals(taskType)) {
-      details.append(StringUtils.formatTimeDiff(
-          min.getFinishTime(),
-          min.getStartTime()));
-    } else if ("shuffle".equals(taskType)) {
-      details.append(StringUtils.formatTimeDiff(
-          min.getShuffleFinishTime(),
-          min.getStartTime()));
-    } else {
-      details.append(StringUtils.formatTimeDiff(
-          min.getFinishTime(),
-          min.getShuffleFinishTime()));
-    }
-    details.append("\nAverage time taken by ");
-    details.append(taskType).append(" tasks: "); 
-    details.append(StringUtils.formatTimeDiff(avg, 0));
-    details.append("\nWorse performing ");
-    details.append(taskType).append(" tasks: ");
-    details.append("\nTaskId\t\tTimetaken");
-    System.out.println(details.toString());
-    for (int i = 0; i < showTasks && i < tasks.length; i++) {
-      details.setLength(0);
-      details.append(tasks[i].getAttemptId().getTaskID()).append(" ");
-      if ("map".equals(taskType)) {
-        details.append(StringUtils.formatTimeDiff(
-            tasks[i].getFinishTime(),
-            tasks[i].getStartTime()));
-      } else if ("shuffle".equals(taskType)) {
-        details.append(StringUtils.formatTimeDiff(
-            tasks[i].getShuffleFinishTime(),
-            tasks[i].getStartTime()));
-      } else {
-        details.append(StringUtils.formatTimeDiff(
-            tasks[i].getFinishTime(),
-            tasks[i].getShuffleFinishTime()));
-      }
-      System.out.println(details.toString());
-    }
+  public void print() throws IOException {
+    print(System.out);
   }
 
-  private void printLast(JobHistoryParser.TaskAttemptInfo [] tasks,
-      String taskType,
-      Comparator<JobHistoryParser.TaskAttemptInfo> cmp
-  ) {
-    Arrays.sort(tasks, cFinishMapRed);
-    JobHistoryParser.TaskAttemptInfo last = tasks[0];
-    StringBuffer lastBuf = new StringBuffer();
-    lastBuf.append("The last ").append(taskType);
-    lastBuf.append(" task ").append(last.getAttemptId().getTaskID());
-    Long finishTime;
-    if ("shuffle".equals(taskType)) {
-      finishTime = last.getShuffleFinishTime();
-    } else {
-      finishTime = last.getFinishTime();
-    }
-    lastBuf.append(" finished at (relative to the Job launch time): ");
-    lastBuf.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
-        finishTime, job.getLaunchTime()));
-    System.out.println(lastBuf.toString());
-  }
-
-  private void printTasks(TaskType taskType, String status) {
-    Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();
-    StringBuffer header = new StringBuffer();
-    header.append("\n").append(status).append(" ");
-    header.append(taskType).append(" task list for ").append(jobId);
-    header.append("\nTaskId\t\tStartTime\tFinishTime\tError");
-    if (TaskType.MAP.equals(taskType)) {
-      header.append("\tInputSplits");
-    }
-    header.append("\n====================================================");
-    StringBuffer taskList = new StringBuffer();
-    for (JobHistoryParser.TaskInfo task : tasks.values()) {
-      if (taskType.equals(task.getTaskType()) &&
-         (status.equals(task.getTaskStatus())
-          || status.equalsIgnoreCase("ALL"))) {
-        taskList.setLength(0);
-        taskList.append(task.getTaskId());
-        taskList.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                   dateFormat, task.getStartTime(), 0));
-        taskList.append("\t").append(StringUtils.getFormattedTimeWithDiff(
-                   dateFormat, task.getFinishTime(),
-                   task.getStartTime())); 
-        taskList.append("\t").append(task.getError());
-        if (TaskType.MAP.equals(taskType)) {
-          taskList.append("\t").append(task.getSplitLocations());
-        }
-        if (taskList != null) {
-          System.out.println(header.toString());
-          System.out.println(taskList.toString());
-        }
-      }
-    }
-  }
-
-  private void printFailedAttempts(FilteredJob filteredJob) {
-      Map<String, Set<TaskID>> badNodes = filteredJob.getFilteredMap();
-      StringBuffer attempts = new StringBuffer();
-      if (badNodes.size() > 0) {
-        attempts.append("\n").append(filteredJob.getFilter());
-        attempts.append(" task attempts by nodes");
-        attempts.append("\nHostname\tFailedTasks");
-        attempts.append("\n===============================");
-        System.out.println(attempts.toString());
-        for (Map.Entry<String, 
-            Set<TaskID>> entry : badNodes.entrySet()) {
-          String node = entry.getKey();
-          Set<TaskID> failedTasks = entry.getValue();
-          attempts.setLength(0);
-          attempts.append(node).append("\t");
-          for (TaskID t : failedTasks) {
-            attempts.append(t).append(", ");
-          }
-          System.out.println(attempts.toString());
-        }
-      }
+  /**
+   * Print the job/task/attempt summary information to the PrintStream.
+   * @param ps The PrintStream to print to
+   * @throws IOException when there is a problem printing the history
+   */
+  public void print(PrintStream ps) throws IOException {
+    jhvp.print(ps);
   }
   
   /**
-   * Return the TaskLogsUrl of a particular TaskAttempt
+   * Return the TaskLogsUrl of a particular TaskAttempt.
    * 
-   * @param attempt
+   * @param attempt info about the task attempt
    * @return the taskLogsUrl. null if http-port or tracker-name or
    *         task-attempt-id are unavailable.
    */
@@ -480,58 +156,6 @@ public class HistoryViewer {
         attempt.getAttemptId().toString());
   }
 
-  private Comparator<JobHistoryParser.TaskAttemptInfo> cMap = 
-    new Comparator<JobHistoryParser.TaskAttemptInfo>() {
-    public int compare(JobHistoryParser.TaskAttemptInfo t1, 
-        JobHistoryParser.TaskAttemptInfo t2) {
-      long l1 = t1.getFinishTime() - t1.getStartTime();
-      long l2 = t2.getFinishTime() - t2.getStartTime();
-      return (l2 < l1 ? -1 : (l2 == l1 ? 0 : 1));
-    }
-  };
-
-  private Comparator<JobHistoryParser.TaskAttemptInfo> cShuffle = 
-    new Comparator<JobHistoryParser.TaskAttemptInfo>() {
-    public int compare(JobHistoryParser.TaskAttemptInfo t1, 
-        JobHistoryParser.TaskAttemptInfo t2) {
-      long l1 = t1.getShuffleFinishTime() - t1.getStartTime();
-      long l2 = t2.getShuffleFinishTime() - t2.getStartTime();
-      return (l2 < l1 ? -1 : (l2 == l1 ? 0 : 1));
-    }
-  };
-
-  private Comparator<JobHistoryParser.TaskAttemptInfo> cFinishShuffle = 
-    new Comparator<JobHistoryParser.TaskAttemptInfo>() {
-    public int compare(JobHistoryParser.TaskAttemptInfo t1, 
-        JobHistoryParser.TaskAttemptInfo t2) {
-      long l1 = t1.getShuffleFinishTime(); 
-      long l2 = t2.getShuffleFinishTime();
-      return (l2 < l1 ? -1 : (l2 == l1 ? 0 : 1));
-    }
-  };
-
-  private Comparator<JobHistoryParser.TaskAttemptInfo> cFinishMapRed = 
-    new Comparator<JobHistoryParser.TaskAttemptInfo>() {
-    public int compare(JobHistoryParser.TaskAttemptInfo t1, 
-        JobHistoryParser.TaskAttemptInfo t2) {
-      long l1 = t1.getFinishTime(); 
-      long l2 = t2.getFinishTime();
-      return (l2 < l1 ? -1 : (l2 == l1 ? 0 : 1));
-    }
-  };
-  
-  private Comparator<JobHistoryParser.TaskAttemptInfo> cReduce = 
-    new Comparator<JobHistoryParser.TaskAttemptInfo>() {
-    public int compare(JobHistoryParser.TaskAttemptInfo t1, 
-        JobHistoryParser.TaskAttemptInfo t2) {
-      long l1 = t1.getFinishTime() -
-                t1.getShuffleFinishTime();
-      long l2 = t2.getFinishTime() -
-                t2.getShuffleFinishTime();
-      return (l2 < l1 ? -1 : (l2 == l1 ? 0 : 1));
-    }
-  }; 
-
   /**
    * Utility class used the summarize the job. 
    * Used by HistoryViewer and the JobHistory UI.
@@ -694,7 +318,6 @@ public class HistoryViewer {
    * Utility class used while analyzing the job. 
    * Used by HistoryViewer and the JobHistory UI.
    */
- 
   public static class AnalyzedJob {
     private long avgMapTime;
     private long avgReduceTime;
@@ -765,7 +388,6 @@ public class HistoryViewer {
 
   /**
    * Utility to filter out events based on the task status
-   *
    */
   public static class FilteredJob {
     

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewerPrinter.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewerPrinter.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewerPrinter.java
new file mode 100644
index 0000000..406b439
--- /dev/null
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HistoryViewerPrinter.java
@@ -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.mapreduce.jobhistory;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+
+import java.io.IOException;
+import java.io.PrintStream;
+
+/**
+ * Used by the {@link HistoryViewer} to print job history in different formats.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Unstable
+interface HistoryViewerPrinter {
+
+  /**
+   * Print out the Job History to the given {@link PrintStream}.
+   * @param ps the {@link PrintStream} to print to
+   * @throws IOException when a problem occurs while printing
+   */
+  void print(PrintStream ps) throws IOException;
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HumanReadableHistoryViewerPrinter.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HumanReadableHistoryViewerPrinter.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HumanReadableHistoryViewerPrinter.java
new file mode 100644
index 0000000..30903af
--- /dev/null
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/HumanReadableHistoryViewerPrinter.java
@@ -0,0 +1,471 @@
+/**
+ * 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.mapreduce.jobhistory;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.mapred.JobStatus;
+import org.apache.hadoop.mapred.TaskStatus;
+import org.apache.hadoop.mapreduce.Counter;
+import org.apache.hadoop.mapreduce.CounterGroup;
+import org.apache.hadoop.mapreduce.Counters;
+import org.apache.hadoop.mapreduce.TaskID;
+import org.apache.hadoop.mapreduce.TaskType;
+import org.apache.hadoop.util.StringUtils;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.text.DecimalFormat;
+import java.text.Format;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+
+/**
+ * Used by the {@link HistoryViewer} to print job history in a human-readable
+ * format.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Unstable
+class HumanReadableHistoryViewerPrinter implements HistoryViewerPrinter {
+
+  private JobHistoryParser.JobInfo job;
+  private final SimpleDateFormat dateFormat;
+  private boolean printAll;
+  private String scheme;
+
+  HumanReadableHistoryViewerPrinter(JobHistoryParser.JobInfo job,
+                                    boolean printAll, String scheme) {
+    this.job = job;
+    this.printAll = printAll;
+    this.scheme = scheme;
+    this.dateFormat = new SimpleDateFormat("d-MMM-yyyy HH:mm:ss");
+  }
+
+  HumanReadableHistoryViewerPrinter(JobHistoryParser.JobInfo job,
+                                    boolean printAll, String scheme,
+                                    TimeZone tz) {
+    this(job, printAll, scheme);
+    this.dateFormat.setTimeZone(tz);
+  }
+
+  /**
+   * Print out the Job History to the given {@link PrintStream} in a
+   * human-readable format.
+   * @param ps the {@link PrintStream} to print to
+   * @throws IOException when a problem occurs while printing
+   */
+  @Override
+  public void print(PrintStream ps) throws IOException {
+    printJobDetails(ps);
+    printTaskSummary(ps);
+    printJobAnalysis(ps);
+    printTasks(ps, TaskType.JOB_SETUP, TaskStatus.State.FAILED.toString());
+    printTasks(ps, TaskType.JOB_SETUP, TaskStatus.State.KILLED.toString());
+    printTasks(ps, TaskType.MAP, TaskStatus.State.FAILED.toString());
+    printTasks(ps, TaskType.MAP, TaskStatus.State.KILLED.toString());
+    printTasks(ps, TaskType.REDUCE, TaskStatus.State.FAILED.toString());
+    printTasks(ps, TaskType.REDUCE, TaskStatus.State.KILLED.toString());
+    printTasks(ps, TaskType.JOB_CLEANUP, TaskStatus.State.FAILED.toString());
+    printTasks(ps, TaskType.JOB_CLEANUP,
+        JobStatus.getJobRunState(JobStatus.KILLED));
+    if (printAll) {
+      printTasks(ps, TaskType.JOB_SETUP, TaskStatus.State.SUCCEEDED.toString());
+      printTasks(ps, TaskType.MAP, TaskStatus.State.SUCCEEDED.toString());
+      printTasks(ps, TaskType.REDUCE, TaskStatus.State.SUCCEEDED.toString());
+      printTasks(ps, TaskType.JOB_CLEANUP,
+          TaskStatus.State.SUCCEEDED.toString());
+      printAllTaskAttempts(ps, TaskType.JOB_SETUP);
+      printAllTaskAttempts(ps, TaskType.MAP);
+      printAllTaskAttempts(ps, TaskType.REDUCE);
+      printAllTaskAttempts(ps, TaskType.JOB_CLEANUP);
+    }
+
+    HistoryViewer.FilteredJob filter = new HistoryViewer.FilteredJob(job,
+        TaskStatus.State.FAILED.toString());
+    printFailedAttempts(ps, filter);
+
+    filter = new HistoryViewer.FilteredJob(job,
+        TaskStatus.State.KILLED.toString());
+    printFailedAttempts(ps, filter);
+  }
+
+  private void printJobDetails(PrintStream ps) {
+    StringBuilder jobDetails = new StringBuilder();
+    jobDetails.append("\nHadoop job: ").append(job.getJobId());
+    jobDetails.append("\n=====================================");
+    jobDetails.append("\nUser: ").append(job.getUsername());
+    jobDetails.append("\nJobName: ").append(job.getJobname());
+    jobDetails.append("\nJobConf: ").append(job.getJobConfPath());
+    jobDetails.append("\nSubmitted At: ").append(StringUtils.
+        getFormattedTimeWithDiff(dateFormat,
+            job.getSubmitTime(), 0));
+    jobDetails.append("\nLaunched At: ").append(StringUtils.
+        getFormattedTimeWithDiff(dateFormat,
+            job.getLaunchTime(),
+            job.getSubmitTime()));
+    jobDetails.append("\nFinished At: ").append(StringUtils.
+        getFormattedTimeWithDiff(dateFormat,
+            job.getFinishTime(),
+            job.getLaunchTime()));
+    jobDetails.append("\nStatus: ").append(((job.getJobStatus() == null) ?
+        "Incomplete" :job.getJobStatus()));
+    printJobCounters(jobDetails, job.getTotalCounters(), job.getMapCounters(),
+        job.getReduceCounters());
+    jobDetails.append("\n");
+    jobDetails.append("\n=====================================");
+    ps.println(jobDetails);
+  }
+
+  private void printJobCounters(StringBuilder buff, Counters totalCounters,
+                                Counters mapCounters, Counters reduceCounters) {
+    // Killed jobs might not have counters
+    if (totalCounters != null) {
+      buff.append("\nCounters: \n\n");
+      buff.append(String.format("|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s|",
+          "Group Name",
+          "Counter name",
+          "Map Value",
+          "Reduce Value",
+          "Total Value"));
+      buff.append("\n------------------------------------------" +
+          "---------------------------------------------");
+      for (String groupName : totalCounters.getGroupNames()) {
+        CounterGroup totalGroup = totalCounters.getGroup(groupName);
+        CounterGroup mapGroup = mapCounters.getGroup(groupName);
+        CounterGroup reduceGroup = reduceCounters.getGroup(groupName);
+
+        Format decimal = new DecimalFormat();
+        Iterator<Counter> ctrItr =
+            totalGroup.iterator();
+        while (ctrItr.hasNext()) {
+          org.apache.hadoop.mapreduce.Counter counter = ctrItr.next();
+          String name = counter.getName();
+          String mapValue =
+              decimal.format(mapGroup.findCounter(name).getValue());
+          String reduceValue =
+              decimal.format(reduceGroup.findCounter(name).getValue());
+          String totalValue =
+              decimal.format(counter.getValue());
+
+          buff.append(
+              String.format("%n|%1$-30s|%2$-30s|%3$-10s|%4$-10s|%5$-10s",
+                  totalGroup.getDisplayName(),
+                  counter.getDisplayName(),
+                  mapValue, reduceValue, totalValue));
+        }
+      }
+    }
+  }
+
+  private void printAllTaskAttempts(PrintStream ps, TaskType taskType) {
+    Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();
+    StringBuilder taskList = new StringBuilder();
+    taskList.append("\n").append(taskType);
+    taskList.append(" task list for ").append(job.getJobId());
+    taskList.append("\nTaskId\t\tStartTime");
+    if (TaskType.REDUCE.equals(taskType)) {
+      taskList.append("\tShuffleFinished\tSortFinished");
+    }
+    taskList.append("\tFinishTime\tHostName\tError\tTaskLogs");
+    taskList.append("\n====================================================");
+    ps.println(taskList.toString());
+    for (JobHistoryParser.TaskInfo task : tasks.values()) {
+      for (JobHistoryParser.TaskAttemptInfo attempt :
+          task.getAllTaskAttempts().values()) {
+        if (taskType.equals(task.getTaskType())){
+          taskList.setLength(0);
+          taskList.append(attempt.getAttemptId()).append("\t");
+          taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
+              attempt.getStartTime(), 0)).append("\t");
+          if (TaskType.REDUCE.equals(taskType)) {
+            taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
+                attempt.getShuffleFinishTime(),
+                attempt.getStartTime()));
+            taskList.append("\t");
+            taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
+                attempt.getSortFinishTime(),
+                attempt.getShuffleFinishTime()));
+          }
+          taskList.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
+              attempt.getFinishTime(),
+              attempt.getStartTime()));
+          taskList.append("\t");
+          taskList.append(attempt.getHostname()).append("\t");
+          taskList.append(attempt.getError());
+          String taskLogsUrl = HistoryViewer.getTaskLogsUrl(scheme, attempt);
+          taskList.append(taskLogsUrl != null ? taskLogsUrl : "n/a");
+          ps.println(taskList);
+        }
+      }
+    }
+  }
+
+  private void printTaskSummary(PrintStream ps) {
+    HistoryViewer.SummarizedJob ts = new HistoryViewer.SummarizedJob(job);
+    StringBuilder taskSummary = new StringBuilder();
+    taskSummary.append("\nTask Summary");
+    taskSummary.append("\n============================");
+    taskSummary.append("\nKind\tTotal\t");
+    taskSummary.append("Successful\tFailed\tKilled\tStartTime\tFinishTime");
+    taskSummary.append("\n");
+    taskSummary.append("\nSetup\t").append(ts.totalSetups);
+    taskSummary.append("\t").append(ts.numFinishedSetups);
+    taskSummary.append("\t\t").append(ts.numFailedSetups);
+    taskSummary.append("\t").append(ts.numKilledSetups);
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.setupStarted, 0));
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.setupFinished, ts.setupStarted));
+    taskSummary.append("\nMap\t").append(ts.totalMaps);
+    taskSummary.append("\t").append(job.getFinishedMaps());
+    taskSummary.append("\t\t").append(ts.numFailedMaps);
+    taskSummary.append("\t").append(ts.numKilledMaps);
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.mapStarted, 0));
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.mapFinished, ts.mapStarted));
+    taskSummary.append("\nReduce\t").append(ts.totalReduces);
+    taskSummary.append("\t").append(job.getFinishedReduces());
+    taskSummary.append("\t\t").append(ts.numFailedReduces);
+    taskSummary.append("\t").append(ts.numKilledReduces);
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.reduceStarted, 0));
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.reduceFinished, ts.reduceStarted));
+    taskSummary.append("\nCleanup\t").append(ts.totalCleanups);
+    taskSummary.append("\t").append(ts.numFinishedCleanups);
+    taskSummary.append("\t\t").append(ts.numFailedCleanups);
+    taskSummary.append("\t").append(ts.numKilledCleanups);
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.cleanupStarted, 0));
+    taskSummary.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+        dateFormat, ts.cleanupFinished,
+        ts.cleanupStarted));
+    taskSummary.append("\n============================\n");
+    ps.println(taskSummary);
+  }
+
+  private void printJobAnalysis(PrintStream ps) {
+    if (job.getJobStatus().equals(
+        JobStatus.getJobRunState(JobStatus.SUCCEEDED))) {
+      HistoryViewer.AnalyzedJob avg = new HistoryViewer.AnalyzedJob(job);
+
+      ps.println("\nAnalysis");
+      ps.println("=========");
+      printAnalysis(ps, avg.getMapTasks(), cMap, "map", avg.getAvgMapTime(),
+          10);
+      printLast(ps, avg.getMapTasks(), "map", cFinishMapRed);
+
+      if (avg.getReduceTasks().length > 0) {
+        printAnalysis(ps, avg.getReduceTasks(), cShuffle, "shuffle",
+            avg.getAvgShuffleTime(), 10);
+        printLast(ps, avg.getReduceTasks(), "shuffle", cFinishShuffle);
+
+        printAnalysis(ps, avg.getReduceTasks(), cReduce, "reduce",
+            avg.getAvgReduceTime(), 10);
+        printLast(ps, avg.getReduceTasks(), "reduce", cFinishMapRed);
+      }
+      ps.println("=========");
+    } else {
+      ps.println("No Analysis available as job did not finish");
+    }
+  }
+
+  protected void printAnalysis(PrintStream ps,
+      JobHistoryParser.TaskAttemptInfo[] tasks,
+      Comparator<JobHistoryParser.TaskAttemptInfo> cmp,
+      String taskType, long avg, int showTasks) {
+    Arrays.sort(tasks, cmp);
+    JobHistoryParser.TaskAttemptInfo min = tasks[tasks.length-1];
+    StringBuilder details = new StringBuilder();
+    details.append("\nTime taken by best performing ");
+    details.append(taskType).append(" task ");
+    details.append(min.getAttemptId().getTaskID().toString()).append(": ");
+    if ("map".equals(taskType)) {
+      details.append(StringUtils.formatTimeDiff(
+          min.getFinishTime(),
+          min.getStartTime()));
+    } else if ("shuffle".equals(taskType)) {
+      details.append(StringUtils.formatTimeDiff(
+          min.getShuffleFinishTime(),
+          min.getStartTime()));
+    } else {
+      details.append(StringUtils.formatTimeDiff(
+          min.getFinishTime(),
+          min.getShuffleFinishTime()));
+    }
+    details.append("\nAverage time taken by ");
+    details.append(taskType).append(" tasks: ");
+    details.append(StringUtils.formatTimeDiff(avg, 0));
+    details.append("\nWorse performing ");
+    details.append(taskType).append(" tasks: ");
+    details.append("\nTaskId\t\tTimetaken");
+    ps.println(details);
+    for (int i = 0; i < showTasks && i < tasks.length; i++) {
+      details.setLength(0);
+      details.append(tasks[i].getAttemptId().getTaskID()).append(" ");
+      if ("map".equals(taskType)) {
+        details.append(StringUtils.formatTimeDiff(
+            tasks[i].getFinishTime(),
+            tasks[i].getStartTime()));
+      } else if ("shuffle".equals(taskType)) {
+        details.append(StringUtils.formatTimeDiff(
+            tasks[i].getShuffleFinishTime(),
+            tasks[i].getStartTime()));
+      } else {
+        details.append(StringUtils.formatTimeDiff(
+            tasks[i].getFinishTime(),
+            tasks[i].getShuffleFinishTime()));
+      }
+      ps.println(details);
+    }
+  }
+
+  protected void printLast(PrintStream ps,
+      JobHistoryParser.TaskAttemptInfo[] tasks, String taskType,
+      Comparator<JobHistoryParser.TaskAttemptInfo> cmp) {
+    Arrays.sort(tasks, cFinishMapRed);
+    JobHistoryParser.TaskAttemptInfo last = tasks[0];
+    StringBuilder lastBuf = new StringBuilder();
+    lastBuf.append("The last ").append(taskType);
+    lastBuf.append(" task ").append(last.getAttemptId().getTaskID());
+    Long finishTime;
+    if ("shuffle".equals(taskType)) {
+      finishTime = last.getShuffleFinishTime();
+    } else {
+      finishTime = last.getFinishTime();
+    }
+    lastBuf.append(" finished at (relative to the Job launch time): ");
+    lastBuf.append(StringUtils.getFormattedTimeWithDiff(dateFormat,
+        finishTime, job.getLaunchTime()));
+    ps.println(lastBuf);
+  }
+
+  private void printTasks(PrintStream ps, TaskType taskType, String status) {
+    Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();
+    StringBuilder header = new StringBuilder();
+    header.append("\n").append(status).append(" ");
+    header.append(taskType).append(" task list for ")
+        .append(job.getJobId().toString());
+    header.append("\nTaskId\t\tStartTime\tFinishTime\tError");
+    if (TaskType.MAP.equals(taskType)) {
+      header.append("\tInputSplits");
+    }
+    header.append("\n====================================================");
+    StringBuilder taskList = new StringBuilder();
+    for (JobHistoryParser.TaskInfo task : tasks.values()) {
+      if (taskType.equals(task.getTaskType()) &&
+          (status.equals(task.getTaskStatus())
+              || status.equalsIgnoreCase("ALL"))) {
+        taskList.setLength(0);
+        taskList.append(task.getTaskId());
+        taskList.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+            dateFormat, task.getStartTime(), 0));
+        taskList.append("\t").append(StringUtils.getFormattedTimeWithDiff(
+            dateFormat, task.getFinishTime(),
+            task.getStartTime()));
+        taskList.append("\t").append(task.getError());
+        if (TaskType.MAP.equals(taskType)) {
+          taskList.append("\t").append(task.getSplitLocations());
+        }
+        if (taskList != null) {
+          ps.println(header);
+          ps.println(taskList);
+        }
+      }
+    }
+  }
+
+  private void printFailedAttempts(PrintStream ps,
+                                   HistoryViewer.FilteredJob filteredJob) {
+    Map<String, Set<TaskID>> badNodes = filteredJob.getFilteredMap();
+    StringBuilder attempts = new StringBuilder();
+    if (badNodes.size() > 0) {
+      attempts.append("\n").append(filteredJob.getFilter());
+      attempts.append(" task attempts by nodes");
+      attempts.append("\nHostname\tFailedTasks");
+      attempts.append("\n===============================");
+      ps.println(attempts);
+      for (Map.Entry<String, Set<TaskID>> entry : badNodes.entrySet()) {
+        String node = entry.getKey();
+        Set<TaskID> failedTasks = entry.getValue();
+        attempts.setLength(0);
+        attempts.append(node).append("\t");
+        for (TaskID t : failedTasks) {
+          attempts.append(t).append(", ");
+        }
+        ps.println(attempts);
+      }
+    }
+  }
+
+  private static Comparator<JobHistoryParser.TaskAttemptInfo> cMap =
+      new Comparator<JobHistoryParser.TaskAttemptInfo>() {
+        public int compare(JobHistoryParser.TaskAttemptInfo t1,
+                           JobHistoryParser.TaskAttemptInfo t2) {
+          long l1 = t1.getFinishTime() - t1.getStartTime();
+          long l2 = t2.getFinishTime() - t2.getStartTime();
+          return Long.compare(l2, l1);
+        }
+      };
+
+  private static Comparator<JobHistoryParser.TaskAttemptInfo> cShuffle =
+      new Comparator<JobHistoryParser.TaskAttemptInfo>() {
+        public int compare(JobHistoryParser.TaskAttemptInfo t1,
+                           JobHistoryParser.TaskAttemptInfo t2) {
+          long l1 = t1.getShuffleFinishTime() - t1.getStartTime();
+          long l2 = t2.getShuffleFinishTime() - t2.getStartTime();
+          return Long.compare(l2, l1);
+        }
+      };
+
+  private static Comparator<JobHistoryParser.TaskAttemptInfo> cFinishShuffle =
+      new Comparator<JobHistoryParser.TaskAttemptInfo>() {
+        public int compare(JobHistoryParser.TaskAttemptInfo t1,
+                           JobHistoryParser.TaskAttemptInfo t2) {
+          long l1 = t1.getShuffleFinishTime();
+          long l2 = t2.getShuffleFinishTime();
+          return Long.compare(l2, l1);
+        }
+      };
+
+  private static Comparator<JobHistoryParser.TaskAttemptInfo> cFinishMapRed =
+      new Comparator<JobHistoryParser.TaskAttemptInfo>() {
+        public int compare(JobHistoryParser.TaskAttemptInfo t1,
+                           JobHistoryParser.TaskAttemptInfo t2) {
+          long l1 = t1.getFinishTime();
+          long l2 = t2.getFinishTime();
+          return Long.compare(l2, l1);
+        }
+      };
+
+  private static Comparator<JobHistoryParser.TaskAttemptInfo> cReduce =
+      new Comparator<JobHistoryParser.TaskAttemptInfo>() {
+        public int compare(JobHistoryParser.TaskAttemptInfo t1,
+                           JobHistoryParser.TaskAttemptInfo t2) {
+          long l1 = t1.getFinishTime() - t1.getShuffleFinishTime();
+          long l2 = t2.getFinishTime() - t2.getShuffleFinishTime();
+          return Long.compare(l2, l1);
+        }
+      };
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JSONHistoryViewerPrinter.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JSONHistoryViewerPrinter.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JSONHistoryViewerPrinter.java
new file mode 100644
index 0000000..456dcf7
--- /dev/null
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JSONHistoryViewerPrinter.java
@@ -0,0 +1,256 @@
+/**
+ * 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.mapreduce.jobhistory;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.mapred.TaskStatus;
+import org.apache.hadoop.mapreduce.Counter;
+import org.apache.hadoop.mapreduce.CounterGroup;
+import org.apache.hadoop.mapreduce.Counters;
+import org.apache.hadoop.mapreduce.TaskID;
+import org.apache.hadoop.mapreduce.TaskType;
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
+import org.codehaus.jettison.json.JSONObject;
+
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.Writer;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * Used by the {@link HistoryViewer} to print job history in a machine-readable
+ * JSON format.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Unstable
+class JSONHistoryViewerPrinter implements HistoryViewerPrinter {
+
+  private JobHistoryParser.JobInfo job;
+  private boolean printAll;
+  private String scheme;
+  private JSONObject json;
+
+  JSONHistoryViewerPrinter(JobHistoryParser.JobInfo job, boolean printAll,
+                           String scheme) {
+    this.job = job;
+    this.printAll = printAll;
+    this.scheme = scheme;
+  }
+
+  /**
+   * Print out the Job History to the given {@link PrintStream} in a
+   * machine-readable JSON format.
+   * @param ps the {@link PrintStream} to print to
+   * @throws IOException when a problem occurs while printing
+   */
+  @Override
+  public void print(PrintStream ps) throws IOException {
+    json = new JSONObject();
+
+    Writer writer = null;
+    try {
+      printJobDetails();
+      printTaskSummary();
+      printTasks();
+
+      writer = new OutputStreamWriter(ps, "UTF-8");
+      json.write(writer);
+      writer.flush();
+    } catch (JSONException je) {
+      throw new IOException("Failure parsing JSON document: " + je.getMessage(),
+          je);
+    } finally {
+      if (writer != null) {
+        writer.close();
+      }
+    }
+  }
+
+  private void printJobDetails() throws JSONException {
+    json.put("hadoopJob", job.getJobId().toString());
+    json.put("user", job.getUsername());
+    json.put("jobName", job.getJobname());
+    json.put("jobConf", job.getJobConfPath());
+    json.put("submittedAt", job.getSubmitTime());
+    json.put("launchedAt", job.getLaunchTime());
+    json.put("finishedAt", job.getFinishTime());
+    json.put("status", ((job.getJobStatus() == null) ?
+        "Incomplete" :job.getJobStatus()));
+    printJobCounters(job.getTotalCounters(), job.getMapCounters(),
+        job.getReduceCounters());
+  }
+
+  private void printJobCounters(Counters totalCounters, Counters mapCounters,
+                                Counters reduceCounters) throws JSONException {
+    // Killed jobs might not have counters
+    if (totalCounters != null) {
+      JSONObject jGroups = new JSONObject();
+      for (String groupName : totalCounters.getGroupNames()) {
+        CounterGroup totalGroup = totalCounters.getGroup(groupName);
+        CounterGroup mapGroup = mapCounters.getGroup(groupName);
+        CounterGroup reduceGroup = reduceCounters.getGroup(groupName);
+
+        Iterator<Counter> ctrItr =
+            totalGroup.iterator();
+        JSONArray jGroup = new JSONArray();
+        while (ctrItr.hasNext()) {
+          JSONObject jCounter = new JSONObject();
+          org.apache.hadoop.mapreduce.Counter counter = ctrItr.next();
+          String name = counter.getName();
+          long mapValue = mapGroup.findCounter(name).getValue();
+          long reduceValue = reduceGroup.findCounter(name).getValue();
+          long totalValue = counter.getValue();
+
+          jCounter.put("counterName", name);
+          jCounter.put("mapValue", mapValue);
+          jCounter.put("reduceValue", reduceValue);
+          jCounter.put("totalValue", totalValue);
+          jGroup.put(jCounter);
+        }
+        jGroups.put(fixGroupNameForShuffleErrors(totalGroup.getName()), jGroup);
+      }
+      json.put("counters", jGroups);
+    }
+  }
+
+  private void printTaskSummary() throws JSONException {
+    HistoryViewer.SummarizedJob ts = new HistoryViewer.SummarizedJob(job);
+    JSONObject jSums = new JSONObject();
+    JSONObject jSumSetup = new JSONObject();
+    jSumSetup.put("total", ts.totalSetups);
+    jSumSetup.put("successful", ts.numFinishedSetups);
+    jSumSetup.put("failed", ts.numFailedSetups);
+    jSumSetup.put("killed", ts.numKilledSetups);
+    jSumSetup.put("startTime", ts.setupStarted);
+    jSumSetup.put("finishTime", ts.setupFinished);
+    jSums.put("setup", jSumSetup);
+    JSONObject jSumMap = new JSONObject();
+    jSumMap.put("total", ts.totalMaps);
+    jSumMap.put("successful", job.getFinishedMaps());
+    jSumMap.put("failed", ts.numFailedMaps);
+    jSumMap.put("killed", ts.numKilledMaps);
+    jSumMap.put("startTime", ts.mapStarted);
+    jSumMap.put("finishTime", ts.mapFinished);
+    jSums.put("map", jSumMap);
+    JSONObject jSumReduce = new JSONObject();
+    jSumReduce.put("total", ts.totalReduces);
+    jSumReduce.put("successful", job.getFinishedReduces());
+    jSumReduce.put("failed", ts.numFailedReduces);
+    jSumReduce.put("killed", ts.numKilledReduces);
+    jSumReduce.put("startTime", ts.reduceStarted);
+    jSumReduce.put("finishTime", ts.reduceFinished);
+    jSums.put("reduce", jSumReduce);
+    JSONObject jSumCleanup = new JSONObject();
+    jSumCleanup.put("total", ts.totalCleanups);
+    jSumCleanup.put("successful", ts.numFinishedCleanups);
+    jSumCleanup.put("failed", ts.numFailedCleanups);
+    jSumCleanup.put("killed", ts.numKilledCleanups);
+    jSumCleanup.put("startTime", ts.cleanupStarted);
+    jSumCleanup.put("finishTime", ts.cleanupFinished);
+    jSums.put("cleanup", jSumCleanup);
+    json.put("taskSummary", jSums);
+  }
+
+  private void printTasks() throws JSONException {
+    Map<TaskID, JobHistoryParser.TaskInfo> tasks = job.getAllTasks();
+    JSONArray jTasks = new JSONArray();
+    for (JobHistoryParser.TaskInfo task : tasks.values()) {
+      if (!task.getTaskType().equals(TaskType.TASK_CLEANUP) &&
+          ((printAll && task.getTaskStatus().equals(
+              TaskStatus.State.SUCCEEDED.toString()))
+          || task.getTaskStatus().equals(TaskStatus.State.KILLED.toString())
+          || task.getTaskStatus().equals(TaskStatus.State.FAILED.toString()))) {
+        JSONObject jTask = new JSONObject();
+        jTask.put("taskId", task.getTaskId().toString());
+        jTask.put("type", task.getTaskType().toString());
+        jTask.put("status", task.getTaskStatus());
+        jTask.put("startTime", task.getStartTime());
+        jTask.put("finishTime", task.getFinishTime());
+        if (!task.getError().isEmpty()) {
+          jTask.put("error", task.getError());
+        }
+        if (task.getTaskType().equals(TaskType.MAP)) {
+          jTask.put("inputSplits", task.getSplitLocations());
+        }
+        if (printAll) {
+          printTaskCounters(jTask, task.getCounters());
+          JSONObject jAtt = new JSONObject();
+          for (JobHistoryParser.TaskAttemptInfo attempt :
+              task.getAllTaskAttempts().values()) {
+            jAtt.put("attemptId", attempt.getAttemptId());
+            jAtt.put("startTime", attempt.getStartTime());
+            if (task.getTaskType().equals(TaskType.REDUCE)) {
+              jAtt.put("shuffleFinished", attempt.getShuffleFinishTime());
+              jAtt.put("sortFinished", attempt.getSortFinishTime());
+            }
+            jAtt.put("finishTime", attempt.getFinishTime());
+            jAtt.put("hostName", attempt.getHostname());
+            if (!attempt.getError().isEmpty()) {
+              jAtt.put("error", task.getError());
+            }
+            String taskLogsUrl = HistoryViewer.getTaskLogsUrl(scheme, attempt);
+            if (taskLogsUrl != null) {
+              jAtt.put("taskLogs", taskLogsUrl);
+            }
+          }
+          jTask.put("attempts", jAtt);
+        }
+        jTasks.put(jTask);
+      }
+      json.put("tasks", jTasks);
+    }
+  }
+
+  private void printTaskCounters(JSONObject jTask, Counters taskCounters)
+      throws JSONException {
+    // Killed tasks might not have counters
+    if (taskCounters != null) {
+      JSONObject jGroups = new JSONObject();
+      for (String groupName : taskCounters.getGroupNames()) {
+        CounterGroup group = taskCounters.getGroup(groupName);
+
+        Iterator<Counter> ctrItr = group.iterator();
+        JSONArray jGroup = new JSONArray();
+        while (ctrItr.hasNext()) {
+          JSONObject jCounter = new JSONObject();
+          org.apache.hadoop.mapreduce.Counter counter = ctrItr.next();
+
+          jCounter.put("counterName", counter.getName());
+          jCounter.put("value", counter.getValue());
+          jGroup.put(jCounter);
+        }
+        jGroups.put(fixGroupNameForShuffleErrors(group.getName()), jGroup);
+      }
+      jTask.put("counters", jGroups);
+    }
+  }
+
+  private String fixGroupNameForShuffleErrors(String name) {
+    String retName = name;
+
+    if (name.equals("Shuffle Errors")) {
+      retName = "org.apache.hadoop.mapreduce.task.reduce.Fetcher.ShuffleErrors";
+    }
+
+    return retName;
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/tools/CLI.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/tools/CLI.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/tools/CLI.java
index db87d9d..ea9c1c0 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/tools/CLI.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/tools/CLI.java
@@ -17,8 +17,12 @@
  */
 package org.apache.hadoop.mapreduce.tools;
 
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
+import java.io.PrintStream;
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.List;
@@ -92,6 +96,8 @@ public class CLI extends Configured implements Tool {
     String jobid = null;
     String taskid = null;
     String historyFile = null;
+    String historyOutFile = null;
+    String historyOutFormat = HistoryViewer.HUMAN_FORMAT;
     String counterGroupName = null;
     String counterName = null;
     JobPriority jp = null;
@@ -173,16 +179,51 @@ public class CLI extends Configured implements Tool {
       nEvents = Integer.parseInt(argv[3]);
       listEvents = true;
     } else if ("-history".equals(cmd)) {
-      if (argv.length != 2 && !(argv.length == 3 && "all".equals(argv[1]))) {
-         displayUsage(cmd);
-         return exitCode;
-      }
       viewHistory = true;
-      if (argv.length == 3 && "all".equals(argv[1])) {
+      if (argv.length < 2 || argv.length > 7) {
+        displayUsage(cmd);
+        return exitCode;
+      }
+
+      // Some arguments are optional while others are not, and some require
+      // second arguments.  Due to this, the indexing can vary depending on
+      // what's specified and what's left out, as summarized in the below table:
+      // [all] <jobHistoryFile> [-outfile <file>] [-format <human|json>]
+      //   1          2             3       4         5         6
+      //   1          2             3       4
+      //   1          2                               3         4
+      //   1          2
+      //              1             2       3         4         5
+      //              1             2       3
+      //              1                               2         3
+      //              1
+
+      // "all" is optional, but comes first if specified
+      int index = 1;
+      if ("all".equals(argv[index])) {
+        index++;
         viewAllHistory = true;
-        historyFile = argv[2];
-      } else {
-        historyFile = argv[1];
+        if (argv.length == 2) {
+          displayUsage(cmd);
+          return exitCode;
+        }
+      }
+      // Get the job history file argument
+      historyFile = argv[index++];
+      // "-outfile" is optional, but if specified requires a second argument
+      if (argv.length > index + 1 && "-outfile".equals(argv[index])) {
+        index++;
+        historyOutFile = argv[index++];
+      }
+      // "-format" is optional, but if specified required a second argument
+      if (argv.length > index + 1 && "-format".equals(argv[index])) {
+        index++;
+        historyOutFormat = argv[index++];
+      }
+      // Check for any extra arguments that don't belong here
+      if (argv.length > index) {
+        displayUsage(cmd);
+        return exitCode;
       }
     } else if ("-list".equals(cmd)) {
       if (argv.length != 1 && !(argv.length == 2 && "all".equals(argv[1]))) {
@@ -338,7 +379,8 @@ public class CLI extends Configured implements Tool {
           exitCode = 0;
         } 
       } else if (viewHistory) {
-        viewHistory(historyFile, viewAllHistory);
+        viewHistory(historyFile, viewAllHistory, historyOutFile,
+            historyOutFormat);
         exitCode = 0;
       } else if (listEvents) {
         listEvents(getJob(JobID.forName(jobid)), fromEvent, nEvents);
@@ -451,7 +493,8 @@ public class CLI extends Configured implements Tool {
       System.err.println(prefix + "[" + cmd + 
         " <job-id> <from-event-#> <#-of-events>]. Event #s start from 1.");
     } else if ("-history".equals(cmd)) {
-      System.err.println(prefix + "[" + cmd + " <jobHistoryFile>]");
+      System.err.println(prefix + "[" + cmd +
+          " [all] <jobHistoryFile> [-outfile <file>] [-format <human|json>]]");
     } else if ("-list".equals(cmd)) {
       System.err.println(prefix + "[" + cmd + " [all]]");
     } else if ("-kill-task".equals(cmd) || "-fail-task".equals(cmd)) {
@@ -484,7 +527,8 @@ public class CLI extends Configured implements Tool {
           "Valid values for priorities are: " + jobPriorityValues +
           ". In addition to this, integers also can be used." + "%n");
       System.err.printf("\t[-events <job-id> <from-event-#> <#-of-events>]%n");
-      System.err.printf("\t[-history <jobHistoryFile>]%n");
+      System.err.printf("\t[-history [all] <jobHistoryFile> [-outfile <file>]" +
+          " [-format <human|json>]]%n");
       System.err.printf("\t[-list [all]]%n");
       System.err.printf("\t[-list-active-trackers]%n");
       System.err.printf("\t[-list-blacklisted-trackers]%n");
@@ -499,11 +543,16 @@ public class CLI extends Configured implements Tool {
     }
   }
     
-  private void viewHistory(String historyFile, boolean all) 
-    throws IOException {
+  private void viewHistory(String historyFile, boolean all,
+      String historyOutFile, String format) throws IOException {
     HistoryViewer historyViewer = new HistoryViewer(historyFile,
-                                        getConf(), all);
-    historyViewer.print();
+        getConf(), all, format);
+    PrintStream ps = System.out;
+    if (historyOutFile != null) {
+      ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(
+          new File(historyOutFile))), true, "UTF-8");
+    }
+    historyViewer.print(ps);
   }
 
   protected long getCounter(Counters counters, String counterGroupName,

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8eee59ce/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/MapredCommands.md
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/MapredCommands.md b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/MapredCommands.md
index 7d6f5ff..dda2dde 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/MapredCommands.md
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/site/markdown/MapredCommands.md
@@ -81,7 +81,7 @@ Copy file or directories recursively. More information can be found at
 
 Command to interact with Map Reduce Jobs.
 
-Usage: `mapred job | [GENERIC_OPTIONS] | [-submit <job-file>] | [-status <job-id>] | [-counter <job-id> <group-name> <counter-name>] | [-kill <job-id>] | [-events <job-id> <from-event-#> <#-of-events>] | [-history [all] <jobOutputDir>] | [-list [all]] | [-kill-task <task-id>] | [-fail-task <task-id>] | [-set-priority <job-id> <priority>] | [-list-active-trackers] | [-list-blacklisted-trackers] | [-list-attempt-ids <job-id> <task-type> <task-state>] [-logs <job-id> <task-attempt-id>]`
+Usage: `mapred job | [GENERIC_OPTIONS] | [-submit <job-file>] | [-status <job-id>] | [-counter <job-id> <group-name> <counter-name>] | [-kill <job-id>] | [-events <job-id> <from-event-#> <#-of-events>] | [-history [all] <jobHistoryFile> [-outfile <file>] [-format <human|json>]] | [-list [all]] | [-kill-task <task-id>] | [-fail-task <task-id>] | [-set-priority <job-id> <priority>] | [-list-active-trackers] | [-list-blacklisted-trackers] | [-list-attempt-ids <job-id> <task-type> <task-state>] [-logs <job-id> <task-attempt-id>]`
 
 | COMMAND\_OPTION | Description |
 |:---- |:---- |
@@ -90,7 +90,7 @@ Usage: `mapred job | [GENERIC_OPTIONS] | [-submit <job-file>] | [-status <job-id
 | -counter *job-id* *group-name* *counter-name* | Prints the counter value. |
 | -kill *job-id* | Kills the job. |
 | -events *job-id* *from-event-\#* *\#-of-events* | Prints the events' details received by jobtracker for the given range. |
-| -history [all]*jobOutputDir* | Prints job details, failed and killed tip details. More details about the job such as successful tasks and task attempts made for each task can be viewed by specifying the [all] option. |
+| -history [all] *jobHistoryFile* [-outfile *file*] [-format *human|json*] | Prints job details, failed and killed task details. More details about the job such as successful tasks, task attempts made for each task, task counters, etc can be viewed by specifying the [all] option. An optional file output path (instead of stdout) can be specified. The format defaults to human-readable but can also be changed to JSON with the [-format] option. |
 | -list [all] | Displays jobs which are yet to complete. `-list all` displays all jobs. |
 | -kill-task *task-id* | Kills the task. Killed tasks are NOT counted against failed attempts. |
 | -fail-task *task-id* | Fails the task. Failed tasks are counted against failed attempts. |


[42/50] [abbrv] hadoop git commit: YARN-4648. Move preemption related tests from TestFairScheduler to TestFairSchedulerPreemption. Contributed by Kai Sasaki.

Posted by ji...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e12114c/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
index 6f759ce..5bdcc08 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestFairSchedulerPreemption.java
@@ -18,18 +18,31 @@
 package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
 
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
+import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
+import org.apache.hadoop.yarn.api.records.Container;
+import org.apache.hadoop.yarn.api.records.ContainerId;
+import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.Resource;
+import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
+import org.apache.hadoop.yarn.event.AsyncDispatcher;
 import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
 import org.apache.hadoop.yarn.server.resourcemanager.MockRM;
+import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
 import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.QueueMetrics;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerApplicationAttempt;
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.ContainerPreemptEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent;
-
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEventType;
 import org.apache.hadoop.yarn.util.ControlledClock;
 import org.apache.hadoop.yarn.util.resource.Resources;
+
 import org.junit.After;
+import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
@@ -37,6 +50,11 @@ import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
@@ -84,7 +102,7 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
     conf = null;
   }
 
-  private void startResourceManager(float utilizationThreshold) {
+  private void startResourceManagerWithStubbedFairScheduler(float utilizationThreshold) {
     conf.setFloat(FairSchedulerConfiguration.PREEMPTION_THRESHOLD,
         utilizationThreshold);
     resourceManager = new MockRM(conf);
@@ -98,6 +116,51 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
     scheduler.updateInterval = 60 * 1000;
   }
 
+  // YARN-4648: The starting code for ResourceManager mock is originated from
+  // TestFairScheduler. It should be keep as it was to guarantee no changing
+  // behaviour of ResourceManager preemption.
+  private void startResourceManagerWithRealFairScheduler() {
+    scheduler = new FairScheduler();
+    conf = new YarnConfiguration();
+    conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class,
+            ResourceScheduler.class);
+    conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 0);
+    conf.setInt(FairSchedulerConfiguration.RM_SCHEDULER_INCREMENT_ALLOCATION_MB,
+            1024);
+    conf.setInt(YarnConfiguration.RM_SCHEDULER_MAXIMUM_ALLOCATION_MB, 10240);
+    conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, false);
+    conf.setFloat(FairSchedulerConfiguration.PREEMPTION_THRESHOLD, 0f);
+    conf.setFloat(
+            FairSchedulerConfiguration
+                    .RM_SCHEDULER_RESERVATION_THRESHOLD_INCERMENT_MULTIPLE,
+            TEST_RESERVATION_THRESHOLD);
+
+    resourceManager = new MockRM(conf);
+
+    // TODO: This test should really be using MockRM. For now starting stuff
+    // that is needed at a bare minimum.
+    ((AsyncDispatcher)resourceManager.getRMContext().getDispatcher()).start();
+    resourceManager.getRMContext().getStateStore().start();
+
+    // to initialize the master key
+    resourceManager.getRMContext().getContainerTokenSecretManager().rollMasterKey();
+
+    scheduler.setRMContext(resourceManager.getRMContext());
+  }
+
+  private void stopResourceManager() {
+    if (scheduler != null) {
+      scheduler.stop();
+      scheduler = null;
+    }
+    if (resourceManager != null) {
+      resourceManager.stop();
+      resourceManager = null;
+    }
+    QueueMetrics.clearQueueMetrics();
+    DefaultMetricsSystem.shutdown();
+  }
+
   private void registerNodeAndSubmitApp(
       int memory, int vcores, int appContainers, int appMemory) {
     RMNode node1 = MockNodes.newNodeInfo(
@@ -143,7 +206,7 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
     out.println("</allocations>");
     out.close();
 
-    startResourceManager(0f);
+    startResourceManagerWithStubbedFairScheduler(0f);
     // Create node with 4GB memory and 4 vcores
     registerNodeAndSubmitApp(4 * 1024, 4, 2, 1024);
 
@@ -159,7 +222,7 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
 
     resourceManager.stop();
 
-    startResourceManager(0.8f);
+    startResourceManagerWithStubbedFairScheduler(0.8f);
     // Create node with 4GB memory and 4 vcores
     registerNodeAndSubmitApp(4 * 1024, 4, 3, 1024);
 
@@ -175,7 +238,7 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
 
     resourceManager.stop();
 
-    startResourceManager(0.7f);
+    startResourceManagerWithStubbedFairScheduler(0.7f);
     // Create node with 4GB memory and 4 vcores
     registerNodeAndSubmitApp(4 * 1024, 4, 3, 1024);
 
@@ -189,4 +252,1226 @@ public class TestFairSchedulerPreemption extends FairSchedulerTestBase {
     assertEquals("preemptResources() should have been called", 1024,
         ((StubbedFairScheduler) scheduler).lastPreemptMemory);
   }
+
+  @Test (timeout = 5000)
+  /**
+   * Make sure containers are chosen to be preempted in the correct order.
+   */
+  public void testChoiceOfPreemptedContainers() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
+    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE + ".allocation.file", ALLOC_FILE);
+    conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false");
+
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>.25</weight>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>.25</weight>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>.25</weight>");
+    out.println("</queue>");
+    out.println("<queue name=\"default\">");
+    out.println("<weight>.25</weight>");
+    out.println("</queue>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Create two nodes
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    RMNode node2 =
+            MockNodes.newNodeInfo(1, Resources.createResource(4 * 1024, 4), 2,
+                    "127.0.0.2");
+    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
+    scheduler.handle(nodeEvent2);
+
+    // Queue A and B each request two applications
+    ApplicationAttemptId app1 =
+            createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 1);
+    createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1);
+    ApplicationAttemptId app2 =
+            createSchedulingRequest(1 * 1024, 1, "queueA", "user1", 1, 3);
+    createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app2);
+
+    ApplicationAttemptId app3 =
+            createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 1);
+    createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app3);
+    ApplicationAttemptId app4 =
+            createSchedulingRequest(1 * 1024, 1, "queueB", "user1", 1, 3);
+    createSchedulingRequestExistingApplication(1 * 1024, 1, 4, app4);
+
+    scheduler.update();
+
+    scheduler.getQueueManager().getLeafQueue("queueA", true)
+            .setPolicy(SchedulingPolicy.parse("fifo"));
+    scheduler.getQueueManager().getLeafQueue("queueB", true)
+            .setPolicy(SchedulingPolicy.parse("fair"));
+
+    // Sufficient node check-ins to fully schedule containers
+    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+    NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+    for (int i = 0; i < 4; i++) {
+      scheduler.handle(nodeUpdate1);
+      scheduler.handle(nodeUpdate2);
+    }
+
+    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+
+    // Now new requests arrive from queueC and default
+    createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, 1, "queueC", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, 1, "default", "user1", 1, 1);
+    scheduler.update();
+
+    // We should be able to claw back one container from queueA and queueB each.
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+
+    // First verify we are adding containers to preemption list for the app.
+    // For queueA (fifo), app2 is selected.
+    // For queueB (fair), app4 is selected.
+    assertTrue("App2 should have container to be preempted",
+            !Collections.disjoint(
+                    scheduler.getSchedulerApp(app2).getLiveContainers(),
+                    scheduler.getSchedulerApp(app2).getPreemptionContainers()));
+    assertTrue("App4 should have container to be preempted",
+            !Collections.disjoint(
+                    scheduler.getSchedulerApp(app2).getLiveContainers(),
+                    scheduler.getSchedulerApp(app2).getPreemptionContainers()));
+
+    // Pretend 15 seconds have passed
+    clock.tickSec(15);
+
+    // Trigger a kill by insisting we want containers back
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+
+    // At this point the containers should have been killed (since we are not simulating AM)
+    assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+    // Inside each app, containers are sorted according to their priorities.
+    // Containers with priority 4 are preempted for app2 and app4.
+    Set<RMContainer> set = new HashSet<RMContainer>();
+    for (RMContainer container :
+            scheduler.getSchedulerApp(app2).getLiveContainers()) {
+      if (container.getAllocatedPriority().getPriority() == 4) {
+        set.add(container);
+      }
+    }
+    for (RMContainer container :
+            scheduler.getSchedulerApp(app4).getLiveContainers()) {
+      if (container.getAllocatedPriority().getPriority() == 4) {
+        set.add(container);
+      }
+    }
+    assertTrue("Containers with priority=4 in app2 and app4 should be " +
+            "preempted.", set.isEmpty());
+
+    // Trigger a kill by insisting we want containers back
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+
+    // Pretend 15 seconds have passed
+    clock.tickSec(15);
+
+    // We should be able to claw back another container from A and B each.
+    // For queueA (fifo), continue preempting from app2.
+    // For queueB (fair), even app4 has a lowest priority container with p=4, it
+    // still preempts from app3 as app3 is most over fair share.
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+
+    assertEquals(2, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(0, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(1, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+    assertEquals(1, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+
+    // Now A and B are below fair share, so preemption shouldn't do anything
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    assertTrue("App1 should have no container to be preempted",
+            scheduler.getSchedulerApp(app1).getPreemptionContainers().isEmpty());
+    assertTrue("App2 should have no container to be preempted",
+            scheduler.getSchedulerApp(app2).getPreemptionContainers().isEmpty());
+    assertTrue("App3 should have no container to be preempted",
+            scheduler.getSchedulerApp(app3).getPreemptionContainers().isEmpty());
+    assertTrue("App4 should have no container to be preempted",
+            scheduler.getSchedulerApp(app4).getPreemptionContainers().isEmpty());
+    stopResourceManager();
+  }
+
+  @Test
+  public void testPreemptionIsNotDelayedToNextRound() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+
+    conf.setLong(FairSchedulerConfiguration.PREEMPTION_INTERVAL, 5000);
+    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10000);
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    conf.set(FairSchedulerConfiguration.USER_AS_DEFAULT_QUEUE, "false");
+
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>8</weight>");
+    out.println("<queue name=\"queueA1\" />");
+    out.println("<queue name=\"queueA2\" />");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>2</weight>");
+    out.println("</queue>");
+    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Add a node of 8G
+    RMNode node1 = MockNodes.newNodeInfo(1,
+            Resources.createResource(8 * 1024, 8), 1, "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    // Run apps in queueA.A1 and queueB
+    ApplicationAttemptId app1 = createSchedulingRequest(1 * 1024, 1,
+            "queueA.queueA1", "user1", 7, 1);
+    // createSchedulingRequestExistingApplication(1 * 1024, 1, 2, app1);
+    ApplicationAttemptId app2 = createSchedulingRequest(1 * 1024, 1, "queueB",
+            "user2", 1, 1);
+
+    scheduler.update();
+
+    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+    for (int i = 0; i < 8; i++) {
+      scheduler.handle(nodeUpdate1);
+    }
+
+    // verify if the apps got the containers they requested
+    assertEquals(7, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(1, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+
+    // Now submit an app in queueA.queueA2
+    ApplicationAttemptId app3 = createSchedulingRequest(1 * 1024, 1,
+            "queueA.queueA2", "user3", 7, 1);
+    scheduler.update();
+
+    // Let 11 sec pass
+    clock.tickSec(11);
+
+    scheduler.update();
+    Resource toPreempt = scheduler.resourceDeficit(scheduler.getQueueManager()
+            .getLeafQueue("queueA.queueA2", false), clock.getTime());
+    assertEquals(3277, toPreempt.getMemory());
+
+    // verify if the 3 containers required by queueA2 are preempted in the same
+    // round
+    scheduler.preemptResources(toPreempt);
+    assertEquals(3, scheduler.getSchedulerApp(app1).getPreemptionContainers()
+            .size());
+    stopResourceManager();
+  }
+
+  @Test (timeout = 5000)
+  /**
+   * Tests the timing of decision to preempt tasks.
+   */
+  public void testPreemptionDecision() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("<maxResources>0mb,0vcores</maxResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueD\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Create four nodes
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    RMNode node2 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 2,
+                    "127.0.0.2");
+    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
+    scheduler.handle(nodeEvent2);
+
+    RMNode node3 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 2), 3,
+                    "127.0.0.3");
+    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
+    scheduler.handle(nodeEvent3);
+
+    // Queue A and B each request three containers
+    ApplicationAttemptId app1 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
+    ApplicationAttemptId app2 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
+    ApplicationAttemptId app3 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);
+
+    ApplicationAttemptId app4 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
+    ApplicationAttemptId app5 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
+    ApplicationAttemptId app6 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);
+
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    for (int i = 0; i < 2; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+    }
+
+    // Now new requests arrive from queues C and D
+    ApplicationAttemptId app7 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
+    ApplicationAttemptId app8 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
+    ApplicationAttemptId app9 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
+
+    ApplicationAttemptId app10 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 1);
+    ApplicationAttemptId app11 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 2);
+    ApplicationAttemptId app12 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 1, 3);
+
+    scheduler.update();
+
+    FSLeafQueue schedC =
+            scheduler.getQueueManager().getLeafQueue("queueC", true);
+    FSLeafQueue schedD =
+            scheduler.getQueueManager().getLeafQueue("queueD", true);
+
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime())));
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime())));
+    // After minSharePreemptionTime has passed, they should want to preempt min
+    // share.
+    clock.tickSec(6);
+    assertEquals(
+            1024, scheduler.resourceDeficit(schedC, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
+
+    // After fairSharePreemptionTime has passed, they should want to preempt
+    // fair share.
+    scheduler.update();
+    clock.tickSec(6);
+    assertEquals(
+            1536 , scheduler.resourceDeficit(schedC, clock.getTime()).getMemory());
+    assertEquals(
+            1536, scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
+    stopResourceManager();
+  }
+
+  @Test
+/**
+ * Tests the timing of decision to preempt tasks.
+ */
+  public void testPreemptionDecisionWithDRF() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("<maxResources>0mb,0vcores</maxResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,1vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,2vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,3vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueD\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,2vcores</minResources>");
+    out.println("</queue>");
+    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
+    out.println("<defaultQueueSchedulingPolicy>drf</defaultQueueSchedulingPolicy>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Create four nodes
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    RMNode node2 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 2,
+                    "127.0.0.2");
+    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
+    scheduler.handle(nodeEvent2);
+
+    RMNode node3 =
+            MockNodes.newNodeInfo(1, Resources.createResource(2 * 1024, 4), 3,
+                    "127.0.0.3");
+    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
+    scheduler.handle(nodeEvent3);
+
+    // Queue A and B each request three containers
+    ApplicationAttemptId app1 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
+    ApplicationAttemptId app2 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 2);
+    ApplicationAttemptId app3 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 3);
+
+    ApplicationAttemptId app4 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 1);
+    ApplicationAttemptId app5 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 2);
+    ApplicationAttemptId app6 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 1, 3);
+
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    for (int i = 0; i < 2; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+    }
+
+    // Now new requests arrive from queues C and D
+    ApplicationAttemptId app7 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
+    ApplicationAttemptId app8 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
+    ApplicationAttemptId app9 =
+            createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
+
+    ApplicationAttemptId app10 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 1);
+    ApplicationAttemptId app11 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 2);
+    ApplicationAttemptId app12 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 2, 3);
+
+    scheduler.update();
+
+    FSLeafQueue schedC =
+            scheduler.getQueueManager().getLeafQueue("queueC", true);
+    FSLeafQueue schedD =
+            scheduler.getQueueManager().getLeafQueue("queueD", true);
+
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(schedC, clock.getTime())));
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(schedD, clock.getTime())));
+
+    // Test :
+    // 1) whether componentWise min works as expected.
+    // 2) DRF calculator is used
+
+    // After minSharePreemptionTime has passed, they should want to preempt min
+    // share.
+    clock.tickSec(6);
+    Resource res = scheduler.resourceDeficit(schedC, clock.getTime());
+    assertEquals(1024, res.getMemory());
+    // Demand = 3
+    assertEquals(3, res.getVirtualCores());
+
+    res = scheduler.resourceDeficit(schedD, clock.getTime());
+    assertEquals(1024, res.getMemory());
+    // Demand = 6, but min share = 2
+    assertEquals(2, res.getVirtualCores());
+
+    // After fairSharePreemptionTime has passed, they should want to preempt
+    // fair share.
+    scheduler.update();
+    clock.tickSec(6);
+    res = scheduler.resourceDeficit(schedC, clock.getTime());
+    assertEquals(1536, res.getMemory());
+    assertEquals(3, res.getVirtualCores());
+
+    res = scheduler.resourceDeficit(schedD, clock.getTime());
+    assertEquals(1536, res.getMemory());
+    // Demand = 6, but fair share = 3
+    assertEquals(3, res.getVirtualCores());
+    stopResourceManager();
+  }
+
+  @Test
+  /**
+   * Tests the various timing of decision to preempt tasks.
+   */
+  public void testPreemptionDecisionWithVariousTimeout() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("<maxResources>0mb,0vcores</maxResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>1</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>2</weight>");
+    out.println("<minSharePreemptionTimeout>10</minSharePreemptionTimeout>");
+    out.println("<fairSharePreemptionTimeout>25</fairSharePreemptionTimeout>");
+    out.println("<queue name=\"queueB1\">");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB2\">");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("<fairSharePreemptionTimeout>20</fairSharePreemptionTimeout>");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>1</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
+    out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Check the min/fair share preemption timeout for each queue
+    QueueManager queueMgr = scheduler.getQueueManager();
+    assertEquals(30000, queueMgr.getQueue("root")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("default")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueA")
+            .getFairSharePreemptionTimeout());
+    assertEquals(25000, queueMgr.getQueue("queueB")
+            .getFairSharePreemptionTimeout());
+    assertEquals(25000, queueMgr.getQueue("queueB.queueB1")
+            .getFairSharePreemptionTimeout());
+    assertEquals(20000, queueMgr.getQueue("queueB.queueB2")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueC")
+            .getFairSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("root")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("default")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueA")
+            .getMinSharePreemptionTimeout());
+    assertEquals(10000, queueMgr.getQueue("queueB")
+            .getMinSharePreemptionTimeout());
+    assertEquals(5000, queueMgr.getQueue("queueB.queueB1")
+            .getMinSharePreemptionTimeout());
+    assertEquals(10000, queueMgr.getQueue("queueB.queueB2")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueC")
+            .getMinSharePreemptionTimeout());
+
+    // Create one big node
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(6 * 1024, 6), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    // Queue A takes all resources
+    for (int i = 0; i < 6; i ++) {
+      createSchedulingRequest(1 * 1024, "queueA", "user1", 1, 1);
+    }
+
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+    for (int i = 0; i < 6; i++) {
+      scheduler.handle(nodeUpdate1);
+    }
+
+    // Now new requests arrive from queues B1, B2 and C
+    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 2);
+    createSchedulingRequest(1 * 1024, "queueB.queueB1", "user1", 1, 3);
+    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 2);
+    createSchedulingRequest(1 * 1024, "queueB.queueB2", "user1", 1, 3);
+    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 1);
+    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 2);
+    createSchedulingRequest(1 * 1024, "queueC", "user1", 1, 3);
+
+    scheduler.update();
+
+    FSLeafQueue queueB1 = queueMgr.getLeafQueue("queueB.queueB1", true);
+    FSLeafQueue queueB2 = queueMgr.getLeafQueue("queueB.queueB2", true);
+    FSLeafQueue queueC = queueMgr.getLeafQueue("queueC", true);
+
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(queueB1, clock.getTime())));
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(queueB2, clock.getTime())));
+    assertTrue(Resources.equals(
+            Resources.none(), scheduler.resourceDeficit(queueC, clock.getTime())));
+
+    // After 5 seconds, queueB1 wants to preempt min share
+    scheduler.update();
+    clock.tickSec(6);
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            0, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+
+    // After 10 seconds, queueB2 wants to preempt min share
+    scheduler.update();
+    clock.tickSec(5);
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            0, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+
+    // After 15 seconds, queueC wants to preempt min share
+    scheduler.update();
+    clock.tickSec(5);
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+
+    // After 20 seconds, queueB2 should want to preempt fair share
+    scheduler.update();
+    clock.tickSec(5);
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+
+    // After 25 seconds, queueB1 should want to preempt fair share
+    scheduler.update();
+    clock.tickSec(5);
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            1024, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+
+    // After 30 seconds, queueC should want to preempt fair share
+    scheduler.update();
+    clock.tickSec(5);
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueB1, clock.getTime()).getMemory());
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueB2, clock.getTime()).getMemory());
+    assertEquals(
+            1536, scheduler.resourceDeficit(queueC, clock.getTime()).getMemory());
+    stopResourceManager();
+  }
+
+  @Test
+  /**
+   * Tests the decision to preempt tasks respect to non-preemptable queues
+   * 1, Queues as follow:
+   *   queueA(non-preemptable)
+   *   queueB(preemptable)
+   *   parentQueue(non-preemptable)
+   *     --queueC(preemptable)
+   *   queueD(preemptable)
+   * 2, Submit request to queueA, queueB, queueC, and all of them are over MinShare
+   * 3, Now all resource are occupied
+   * 4, Submit request to queueD, and need to preempt resource from other queues
+   * 5, Only preemptable queue(queueB) would be preempted.
+   */
+  public void testPreemptionDecisionWithNonPreemptableQueue() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("<maxResources>0mb,0vcores</maxResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"parentQueue\">");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueD\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>2048mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Create four nodes(3G each)
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    RMNode node2 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 2,
+                    "127.0.0.2");
+    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
+    scheduler.handle(nodeEvent2);
+
+    RMNode node3 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 3,
+                    "127.0.0.3");
+    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
+    scheduler.handle(nodeEvent3);
+
+    RMNode node4 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 4,
+                    "127.0.0.4");
+    NodeAddedSchedulerEvent nodeEvent4 = new NodeAddedSchedulerEvent(node4);
+    scheduler.handle(nodeEvent4);
+
+    // Submit apps to queueA, queueB, queueC,
+    // now all resource of the cluster is occupied
+    ApplicationAttemptId app1 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 4, 1);
+    ApplicationAttemptId app2 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 4, 2);
+    ApplicationAttemptId app3 =
+            createSchedulingRequest(1 * 1024, "parentQueue.queueC", "user1", 4, 3);
+
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    for (int i = 0; i < 3; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+
+      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
+      scheduler.handle(nodeUpdate4);
+    }
+
+    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+
+    // Now new requests arrive from queues D
+    ApplicationAttemptId app4 =
+            createSchedulingRequest(1 * 1024, "queueD", "user1", 4, 1);
+    scheduler.update();
+    FSLeafQueue schedD =
+            scheduler.getQueueManager().getLeafQueue("queueD", true);
+
+    // After minSharePreemptionTime has passed, 2G resource should preempted from
+    // queueB to queueD
+    clock.tickSec(6);
+    assertEquals(2048,
+            scheduler.resourceDeficit(schedD, clock.getTime()).getMemory());
+
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    // now only app2 is selected to be preempted
+    assertTrue("App2 should have container to be preempted",
+            !Collections.disjoint(
+                    scheduler.getSchedulerApp(app2).getLiveContainers(),
+                    scheduler.getSchedulerApp(app2).getPreemptionContainers()));
+    assertTrue("App1 should not have container to be preempted",
+            Collections.disjoint(
+                    scheduler.getSchedulerApp(app1).getLiveContainers(),
+                    scheduler.getSchedulerApp(app1).getPreemptionContainers()));
+    assertTrue("App3 should not have container to be preempted",
+            Collections.disjoint(
+                    scheduler.getSchedulerApp(app3).getLiveContainers(),
+                    scheduler.getSchedulerApp(app3).getPreemptionContainers()));
+    // Pretend 20 seconds have passed
+    clock.tickSec(20);
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    for (int i = 0; i < 3; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+
+      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
+      scheduler.handle(nodeUpdate4);
+    }
+    // after preemption
+    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+    assertEquals(2, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+    stopResourceManager();
+  }
+
+  @Test
+  /**
+   * Tests the decision to preempt tasks when allowPreemptionFrom is set false on
+   * all queues.
+   * Then none of them would be preempted actually.
+   * 1, Queues as follow:
+   *   queueA(non-preemptable)
+   *   queueB(non-preemptable)
+   *   parentQueue(non-preemptable)
+   *     --queueC(preemptable)
+   *   parentQueue(preemptable)
+   *     --queueD(non-preemptable)
+   * 2, Submit request to queueB, queueC, queueD, and all of them are over MinShare
+   * 3, Now all resource are occupied
+   * 4, Submit request to queueA, and need to preempt resource from other queues
+   * 5, None of queues would be preempted.
+   */
+  public void testPreemptionDecisionWhenPreemptionDisabledOnAllQueues()
+          throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("<maxResources>0mb,0vcores</maxResources>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>2048mb,0vcores</minResources>");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("</queue>");
+    out.println("<queue name=\"parentQueue1\">");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("<queue name=\"queueC\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<queue name=\"parentQueue2\">");
+    out.println("<queue name=\"queueD\">");
+    out.println("<weight>.25</weight>");
+    out.println("<minResources>1024mb,0vcores</minResources>");
+    out.println("<allowPreemptionFrom>false</allowPreemptionFrom>");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<defaultMinSharePreemptionTimeout>5</defaultMinSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionTimeout>10</defaultFairSharePreemptionTimeout>");
+    out.println("<defaultFairSharePreemptionThreshold>.5</defaultFairSharePreemptionThreshold>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Create four nodes(3G each)
+    RMNode node1 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 1,
+                    "127.0.0.1");
+    NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
+    scheduler.handle(nodeEvent1);
+
+    RMNode node2 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 2,
+                    "127.0.0.2");
+    NodeAddedSchedulerEvent nodeEvent2 = new NodeAddedSchedulerEvent(node2);
+    scheduler.handle(nodeEvent2);
+
+    RMNode node3 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 3,
+                    "127.0.0.3");
+    NodeAddedSchedulerEvent nodeEvent3 = new NodeAddedSchedulerEvent(node3);
+    scheduler.handle(nodeEvent3);
+
+    RMNode node4 =
+            MockNodes.newNodeInfo(1, Resources.createResource(3 * 1024, 3), 4,
+                    "127.0.0.4");
+    NodeAddedSchedulerEvent nodeEvent4 = new NodeAddedSchedulerEvent(node4);
+    scheduler.handle(nodeEvent4);
+
+    // Submit apps to queueB, queueC, queueD
+    // now all resource of the cluster is occupied
+
+    ApplicationAttemptId app1 =
+            createSchedulingRequest(1 * 1024, "queueB", "user1", 4, 1);
+    ApplicationAttemptId app2 =
+            createSchedulingRequest(1 * 1024, "parentQueue1.queueC", "user1", 4, 2);
+    ApplicationAttemptId app3 =
+            createSchedulingRequest(1 * 1024, "parentQueue2.queueD", "user1", 4, 3);
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    for (int i = 0; i < 3; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+
+      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
+      scheduler.handle(nodeUpdate4);
+    }
+
+    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+
+    // Now new requests arrive from queues A
+    ApplicationAttemptId app4 =
+            createSchedulingRequest(1 * 1024, "queueA", "user1", 4, 1);
+    scheduler.update();
+    FSLeafQueue schedA =
+            scheduler.getQueueManager().getLeafQueue("queueA", true);
+
+    // After minSharePreemptionTime has passed, resource deficit is 2G
+    clock.tickSec(6);
+    assertEquals(2048,
+            scheduler.resourceDeficit(schedA, clock.getTime()).getMemory());
+
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    // now none app is selected to be preempted
+    assertTrue("App1 should have container to be preempted",
+            Collections.disjoint(
+                    scheduler.getSchedulerApp(app1).getLiveContainers(),
+                    scheduler.getSchedulerApp(app1).getPreemptionContainers()));
+    assertTrue("App2 should not have container to be preempted",
+            Collections.disjoint(
+                    scheduler.getSchedulerApp(app2).getLiveContainers(),
+                    scheduler.getSchedulerApp(app2).getPreemptionContainers()));
+    assertTrue("App3 should not have container to be preempted",
+            Collections.disjoint(
+                    scheduler.getSchedulerApp(app3).getLiveContainers(),
+                    scheduler.getSchedulerApp(app3).getPreemptionContainers()));
+    // Pretend 20 seconds have passed
+    clock.tickSec(20);
+    scheduler.preemptResources(Resources.createResource(2 * 1024));
+    for (int i = 0; i < 3; i++) {
+      NodeUpdateSchedulerEvent nodeUpdate1 = new NodeUpdateSchedulerEvent(node1);
+      scheduler.handle(nodeUpdate1);
+
+      NodeUpdateSchedulerEvent nodeUpdate2 = new NodeUpdateSchedulerEvent(node2);
+      scheduler.handle(nodeUpdate2);
+
+      NodeUpdateSchedulerEvent nodeUpdate3 = new NodeUpdateSchedulerEvent(node3);
+      scheduler.handle(nodeUpdate3);
+
+      NodeUpdateSchedulerEvent nodeUpdate4 = new NodeUpdateSchedulerEvent(node4);
+      scheduler.handle(nodeUpdate4);
+    }
+    // after preemption
+    assertEquals(4, scheduler.getSchedulerApp(app1).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app2).getLiveContainers().size());
+    assertEquals(4, scheduler.getSchedulerApp(app3).getLiveContainers().size());
+    assertEquals(0, scheduler.getSchedulerApp(app4).getLiveContainers().size());
+    stopResourceManager();
+  }
+
+  @Test
+  public void testBackwardsCompatiblePreemptionConfiguration() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, ALLOC_FILE);
+
+    PrintWriter out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<queue name=\"queueB1\">");
+    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB2\">");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("</queue>");
+    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
+    out.print("<defaultFairSharePreemptionTimeout>30</defaultFairSharePreemptionTimeout>");
+    out.print("<fairSharePreemptionTimeout>40</fairSharePreemptionTimeout>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    // Check the min/fair share preemption timeout for each queue
+    QueueManager queueMgr = scheduler.getQueueManager();
+    assertEquals(30000, queueMgr.getQueue("root")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("default")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueA")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueB")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueB.queueB1")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueB.queueB2")
+            .getFairSharePreemptionTimeout());
+    assertEquals(30000, queueMgr.getQueue("queueC")
+            .getFairSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("root")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("default")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueA")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueB")
+            .getMinSharePreemptionTimeout());
+    assertEquals(5000, queueMgr.getQueue("queueB.queueB1")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueB.queueB2")
+            .getMinSharePreemptionTimeout());
+    assertEquals(15000, queueMgr.getQueue("queueC")
+            .getMinSharePreemptionTimeout());
+
+    // If both exist, we take the default one
+    out = new PrintWriter(new FileWriter(ALLOC_FILE));
+    out.println("<?xml version=\"1.0\"?>");
+    out.println("<allocations>");
+    out.println("<queue name=\"default\">");
+    out.println("</queue>");
+    out.println("<queue name=\"queueA\">");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB\">");
+    out.println("<queue name=\"queueB1\">");
+    out.println("<minSharePreemptionTimeout>5</minSharePreemptionTimeout>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueB2\">");
+    out.println("</queue>");
+    out.println("</queue>");
+    out.println("<queue name=\"queueC\">");
+    out.println("</queue>");
+    out.print("<defaultMinSharePreemptionTimeout>15</defaultMinSharePreemptionTimeout>");
+    out.print("<defaultFairSharePreemptionTimeout>25</defaultFairSharePreemptionTimeout>");
+    out.print("<fairSharePreemptionTimeout>30</fairSharePreemptionTimeout>");
+    out.println("</allocations>");
+    out.close();
+
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    assertEquals(25000, queueMgr.getQueue("root")
+            .getFairSharePreemptionTimeout());
+    stopResourceManager();
+  }
+
+  @Test(timeout = 5000)
+  public void testRecoverRequestAfterPreemption() throws Exception {
+    startResourceManagerWithRealFairScheduler();
+    conf.setLong(FairSchedulerConfiguration.WAIT_TIME_BEFORE_KILL, 10);
+
+    ControlledClock clock = new ControlledClock();
+    scheduler.setClock(clock);
+    scheduler.init(conf);
+    scheduler.start();
+    scheduler.reinitialize(conf, resourceManager.getRMContext());
+
+    Priority priority = Priority.newInstance(20);
+    String host = "127.0.0.1";
+    int GB = 1024;
+
+    // Create Node and raised Node Added event
+    RMNode node = MockNodes.newNodeInfo(1,
+            Resources.createResource(16 * 1024, 4), 0, host);
+    NodeAddedSchedulerEvent nodeEvent = new NodeAddedSchedulerEvent(node);
+    scheduler.handle(nodeEvent);
+
+    // Create 3 container requests and place it in ask
+    List<ResourceRequest> ask = new ArrayList<ResourceRequest>();
+    ResourceRequest nodeLocalRequest = createResourceRequest(GB, 1, host,
+            priority.getPriority(), 1, true);
+    ResourceRequest rackLocalRequest = createResourceRequest(GB, 1,
+            node.getRackName(), priority.getPriority(), 1, true);
+    ResourceRequest offRackRequest = createResourceRequest(GB, 1,
+            ResourceRequest.ANY, priority.getPriority(), 1, true);
+    ask.add(nodeLocalRequest);
+    ask.add(rackLocalRequest);
+    ask.add(offRackRequest);
+
+    // Create Request and update
+    ApplicationAttemptId appAttemptId = createSchedulingRequest("queueA",
+            "user1", ask);
+    scheduler.update();
+
+    // Sufficient node check-ins to fully schedule containers
+    NodeUpdateSchedulerEvent nodeUpdate = new NodeUpdateSchedulerEvent(node);
+    scheduler.handle(nodeUpdate);
+
+    assertEquals(1, scheduler.getSchedulerApp(appAttemptId).getLiveContainers()
+            .size());
+    SchedulerApplicationAttempt app = scheduler.getSchedulerApp(appAttemptId);
+
+    // ResourceRequest will be empty once NodeUpdate is completed
+    Assert.assertNull(app.getResourceRequest(priority, host));
+
+    ContainerId containerId1 = ContainerId.newContainerId(appAttemptId, 1);
+    RMContainer rmContainer = app.getRMContainer(containerId1);
+
+    // Create a preempt event and register for preemption
+    scheduler.warnOrKillContainer(rmContainer);
+
+    // Wait for few clock ticks
+    clock.tickSec(5);
+
+    // preempt now
+    scheduler.warnOrKillContainer(rmContainer);
+
+    // Trigger container rescheduled event
+    scheduler.handle(new ContainerPreemptEvent(appAttemptId, rmContainer,
+            SchedulerEventType.KILL_PREEMPTED_CONTAINER));
+
+    List<ResourceRequest> requests = rmContainer.getResourceRequests();
+    // Once recovered, resource request will be present again in app
+    Assert.assertEquals(3, requests.size());
+    for (ResourceRequest request : requests) {
+      Assert.assertEquals(1,
+              app.getResourceRequest(priority, request.getResourceName())
+                      .getNumContainers());
+    }
+
+    // Send node heartbeat
+    scheduler.update();
+    scheduler.handle(nodeUpdate);
+
+    List<Container> containers = scheduler.allocate(appAttemptId,
+            Collections.<ResourceRequest> emptyList(),
+            Collections.<ContainerId> emptyList(), null, null, null, null).getContainers();
+
+    // Now with updated ResourceRequest, a container is allocated for AM.
+    Assert.assertTrue(containers.size() == 1);
+    stopResourceManager();
+  }
 }


[49/50] [abbrv] hadoop git commit: HDFS-9816. Erasure Coding: allow to use multiple EC policies in striping related tests [Part 3]. Contributed by Rui Li.

Posted by ji...@apache.org.
HDFS-9816. Erasure Coding: allow to use multiple EC policies in striping related tests [Part 3]. Contributed by Rui Li.

Change-Id: I64b57bab4722cdc6e1e3148c3a3a401370249afe


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/def754ec
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/def754ec
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/def754ec

Branch: refs/heads/HDFS-7240
Commit: def754ec064c8502fbd736efae738bcbdc735f0a
Parents: 647a35e
Author: Zhe Zhang <zh...@apache.org>
Authored: Tue Feb 23 14:05:17 2016 -0800
Committer: Zhe Zhang <zh...@apache.org>
Committed: Tue Feb 23 14:05:17 2016 -0800

----------------------------------------------------------------------
 .../hadoop/hdfs/util/StripedBlockUtil.java      | 24 ++++++++
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |  3 +
 .../server/datanode/BlockRecoveryWorker.java    | 12 +---
 .../hadoop/hdfs/TestLeaseRecoveryStriped.java   | 58 +++++++++++++-------
 .../TestUnderReplicatedBlockQueues.java         | 55 +++++++++----------
 .../hdfs/server/datanode/TestBlockRecovery.java | 27 ++++++++-
 .../TestAddOverReplicatedStripedBlocks.java     | 11 ++--
 .../server/namenode/TestAddStripedBlocks.java   |  2 +-
 .../server/namenode/TestFSEditLogLoader.java    |  8 ++-
 .../hdfs/server/namenode/TestFSImage.java       | 18 +++---
 .../hadoop/hdfs/server/namenode/TestFsck.java   | 23 +++++---
 .../namenode/TestReconstructStripedBlocks.java  | 11 ++--
 .../test/resources/testErasureCodingConf.xml    |  4 +-
 13 files changed, 161 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/StripedBlockUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/StripedBlockUtil.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/StripedBlockUtil.java
index dbd53a3..43772e2 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/StripedBlockUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/util/StripedBlockUtil.java
@@ -171,6 +171,30 @@ public class StripedBlockUtil {
         + lastCellSize(lastStripeDataLen, cellSize, numDataBlocks, i);
   }
 
+  /**
+   * Compute the safe length given the internal block lengths.
+   *
+   * @param ecPolicy The EC policy used for the block group
+   * @param blockLens The lengths of internal blocks
+   * @return The safe length
+   */
+  public static long getSafeLength(ErasureCodingPolicy ecPolicy,
+      long[] blockLens) {
+    final int cellSize = ecPolicy.getCellSize();
+    final int dataBlkNum = ecPolicy.getNumDataUnits();
+    Preconditions.checkArgument(blockLens.length >= dataBlkNum);
+    final int stripeSize = dataBlkNum * cellSize;
+    long[] cpy = Arrays.copyOf(blockLens, blockLens.length);
+    Arrays.sort(cpy);
+    // full stripe is a stripe has at least dataBlkNum full cells.
+    // lastFullStripeIdx is the index of the last full stripe.
+    int lastFullStripeIdx =
+        (int) (cpy[cpy.length - dataBlkNum] / cellSize);
+    return lastFullStripeIdx * stripeSize; // return the safeLength
+    // TODO: Include lastFullStripeIdx+1 stripe in safeLength, if there exists
+    // such a stripe (and it must be partial).
+  }
+
   private static int lastCellSize(int size, int cellSize, int numDataBlocks,
       int i) {
     if (i < numDataBlocks) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 83eacc3..b5ba238 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -947,6 +947,9 @@ Trunk (Unreleased)
       HDFS-9830. Remove references to hftp in ViewFs documentation in trunk.
       (Wei-Chiu Chuang via aajisaka)
 
+      HDFS-9816. Erasure Coding: allow to use multiple EC policies in striping
+      related tests [Part 3]. (Rui Li via zhz)
+
 Release 2.9.0 - UNRELEASED
 
   INCOMPATIBLE CHANGES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockRecoveryWorker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockRecoveryWorker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockRecoveryWorker.java
index 45ea711..d39d050 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockRecoveryWorker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockRecoveryWorker.java
@@ -34,6 +34,7 @@ import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringBlo
 import org.apache.hadoop.hdfs.server.protocol.BlockRecoveryCommand.RecoveringStripedBlock;
 import org.apache.hadoop.hdfs.server.protocol.InterDatanodeProtocol;
 import org.apache.hadoop.hdfs.server.protocol.ReplicaRecoveryInfo;
+import org.apache.hadoop.hdfs.util.StripedBlockUtil;
 import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.util.Daemon;
 import org.slf4j.Logger;
@@ -513,24 +514,15 @@ public class BlockRecoveryWorker {
      */
     @VisibleForTesting
     long getSafeLength(Map<Long, BlockRecord> syncBlocks) {
-      final int cellSize = ecPolicy.getCellSize();
       final int dataBlkNum = ecPolicy.getNumDataUnits();
       Preconditions.checkArgument(syncBlocks.size() >= dataBlkNum);
-      final int stripeSize = dataBlkNum * cellSize;
       long[] blockLengths = new long[syncBlocks.size()];
       int i = 0;
       for (BlockRecord r : syncBlocks.values()) {
         ReplicaRecoveryInfo rInfo = r.getReplicaRecoveryInfo();
         blockLengths[i++] = rInfo.getNumBytes();
       }
-      Arrays.sort(blockLengths);
-      // full stripe is a stripe has at least dataBlkNum full cells.
-      // lastFullStripeIdx is the index of the last full stripe.
-      int lastFullStripeIdx =
-          (int) (blockLengths[blockLengths.length - dataBlkNum] / cellSize);
-      return lastFullStripeIdx * stripeSize; // return the safeLength
-      // TODO: Include lastFullStripeIdx+1 stripe in safeLength, if there exists
-      // such a stripe (and it must be partial).
+      return StripedBlockUtil.getSafeLength(ecPolicy, blockLengths);
     }
 
     private void checkLocations(int locationCount)

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLeaseRecoveryStriped.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLeaseRecoveryStriped.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLeaseRecoveryStriped.java
index bb4e929..87c3b4c 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLeaseRecoveryStriped.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLeaseRecoveryStriped.java
@@ -27,7 +27,9 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
+import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
 import org.apache.hadoop.hdfs.server.datanode.DataNode;
+import org.apache.hadoop.hdfs.util.StripedBlockUtil;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.test.GenericTestUtils;
@@ -45,12 +47,16 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Random;
+import java.util.concurrent.ThreadLocalRandom;
 import java.util.concurrent.TimeoutException;
 
 public class TestLeaseRecoveryStriped {
   public static final Log LOG = LogFactory
       .getLog(TestLeaseRecoveryStriped.class);
 
+  private static final ErasureCodingPolicy ecPolicy =
+      StripedFileTestUtil.TEST_EC_POLICY;
   private static final int NUM_DATA_BLOCKS = StripedFileTestUtil.NUM_DATA_BLOCKS;
   private static final int NUM_PARITY_BLOCKS = StripedFileTestUtil.NUM_PARITY_BLOCKS;
   private static final int CELL_SIZE = StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
@@ -90,7 +96,7 @@ public class TestLeaseRecoveryStriped {
     cluster.waitActive();
     dfs = cluster.getFileSystem();
     dfs.mkdirs(dir);
-    dfs.setErasureCodingPolicy(dir, null);
+    dfs.setErasureCodingPolicy(dir, ecPolicy);
   }
 
   @After
@@ -100,26 +106,38 @@ public class TestLeaseRecoveryStriped {
     }
   }
 
-  public static final int[][][] BLOCK_LENGTHS_SUITE = {
-      { { 11 * CELL_SIZE, 10 * CELL_SIZE, 9 * CELL_SIZE, 8 * CELL_SIZE,
-          7 * CELL_SIZE, 6 * CELL_SIZE, 5 * CELL_SIZE, 4 * CELL_SIZE,
-          3 * CELL_SIZE }, { 36 * CELL_SIZE } },
-
-      { { 3 * CELL_SIZE, 4 * CELL_SIZE, 5 * CELL_SIZE, 6 * CELL_SIZE,
-          7 * CELL_SIZE, 8 * CELL_SIZE, 9 * CELL_SIZE, 10 * CELL_SIZE,
-          11 * CELL_SIZE }, { 36 * CELL_SIZE } },
-
-      { { 11 * CELL_SIZE, 7 * CELL_SIZE, 6 * CELL_SIZE, 5 * CELL_SIZE,
-          4 * CELL_SIZE, 2 * CELL_SIZE, 9 * CELL_SIZE, 10 * CELL_SIZE,
-          11 * CELL_SIZE }, { 36 * CELL_SIZE } },
+  private static int[][][] getBlockLengthsSuite() {
+    final int groups = 4;
+    final int minNumCell = 3;
+    final int maxNumCell = 11;
+    final int minNumDelta = -4;
+    final int maxNumDelta = 2;
+    int delta = 0;
+    int[][][] blkLenSuite = new int[groups][][];
+    Random random = ThreadLocalRandom.current();
+    for (int i = 0; i < blkLenSuite.length; i++) {
+      if (i == blkLenSuite.length - 1) {
+        delta = bytesPerChecksum;
+      }
+      int[][] suite = new int[2][];
+      int[] lens = new int[NUM_DATA_BLOCKS + NUM_PARITY_BLOCKS];
+      long[] lenInLong = new long[lens.length];
+      for (int j = 0; j < lens.length; j++) {
+        int numCell = random.nextInt(maxNumCell - minNumCell + 1) + minNumCell;
+        int numDelta = j < NUM_DATA_BLOCKS ?
+            random.nextInt(maxNumDelta - minNumDelta + 1) + minNumDelta : 0;
+        lens[j] = CELL_SIZE * numCell + delta * numDelta;
+        lenInLong[j] = lens[j];
+      }
+      suite[0] = lens;
+      suite[1] = new int[]{
+          (int) StripedBlockUtil.getSafeLength(ecPolicy, lenInLong)};
+      blkLenSuite[i] = suite;
+    }
+    return blkLenSuite;
+  }
 
-      { { 8 * CELL_SIZE + bytesPerChecksum,
-          7 * CELL_SIZE + bytesPerChecksum * 2,
-          6 * CELL_SIZE + bytesPerChecksum * 2,
-          5 * CELL_SIZE - bytesPerChecksum * 3,
-          4 * CELL_SIZE - bytesPerChecksum * 4,
-          3 * CELL_SIZE - bytesPerChecksum * 4, 9 * CELL_SIZE, 10 * CELL_SIZE,
-          11 * CELL_SIZE }, { 36 * CELL_SIZE } }, };
+  private static final int[][][] BLOCK_LENGTHS_SUITE = getBlockLengthsSuite();
 
   @Test
   public void testLeaseRecovery() throws Exception {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlockQueues.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlockQueues.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlockQueues.java
index 3ad45df..b228d09 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlockQueues.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestUnderReplicatedBlockQueues.java
@@ -111,37 +111,36 @@ public class TestUnderReplicatedBlockQueues {
     int groupSize = dataBlkNum + parityBlkNum;
     long numBytes = ecPolicy.getCellSize() * dataBlkNum;
     UnderReplicatedBlocks queues = new UnderReplicatedBlocks();
-
-    // add a striped block which been left NUM_DATA_BLOCKS internal blocks
-    BlockInfo block1 = genStripedBlockInfo(-100, numBytes);
-    assertAdded(queues, block1, dataBlkNum, 0, groupSize);
-    assertEquals(1, queues.getUnderReplicatedBlockCount());
-    assertEquals(1, queues.size());
-    assertInLevel(queues, block1, UnderReplicatedBlocks.QUEUE_HIGHEST_PRIORITY);
-
-    // add a striped block which been left NUM_DATA_BLOCKS+1 internal blocks
-    BlockInfo block2 = genStripedBlockInfo(-200, numBytes);
-    assertAdded(queues, block2, dataBlkNum + 1, 0, groupSize);
-    assertEquals(2, queues.getUnderReplicatedBlockCount());
-    assertEquals(2, queues.size());
-    assertInLevel(queues, block2,
-        UnderReplicatedBlocks.QUEUE_VERY_UNDER_REPLICATED);
-
-    // add a striped block which been left NUM_DATA_BLOCKS+2 internal blocks
-    BlockInfo block3 = genStripedBlockInfo(-300, numBytes);
-    assertAdded(queues, block3, dataBlkNum + 2, 0, groupSize);
-    assertEquals(3, queues.getUnderReplicatedBlockCount());
-    assertEquals(3, queues.size());
-    assertInLevel(queues, block3,
-        UnderReplicatedBlocks.QUEUE_UNDER_REPLICATED);
+    int numUR = 0;
+    int numCorrupt = 0;
+
+    // add under replicated blocks
+    for (int i = 0; dataBlkNum + i < groupSize; i++) {
+      BlockInfo block = genStripedBlockInfo(-100 - 100 * i, numBytes);
+      assertAdded(queues, block, dataBlkNum + i, 0, groupSize);
+      numUR++;
+      assertEquals(numUR, queues.getUnderReplicatedBlockCount());
+      assertEquals(numUR + numCorrupt, queues.size());
+      if (i == 0) {
+        assertInLevel(queues, block,
+            UnderReplicatedBlocks.QUEUE_HIGHEST_PRIORITY);
+      } else if (i * 3 < parityBlkNum + 1) {
+        assertInLevel(queues, block,
+            UnderReplicatedBlocks.QUEUE_VERY_UNDER_REPLICATED);
+      } else {
+        assertInLevel(queues, block,
+            UnderReplicatedBlocks.QUEUE_UNDER_REPLICATED);
+      }
+    }
 
     // add a corrupted block
-    BlockInfo block_corrupt = genStripedBlockInfo(-400, numBytes);
-    assertEquals(0, queues.getCorruptBlockSize());
+    BlockInfo block_corrupt = genStripedBlockInfo(-10, numBytes);
+    assertEquals(numCorrupt, queues.getCorruptBlockSize());
     assertAdded(queues, block_corrupt, dataBlkNum - 1, 0, groupSize);
-    assertEquals(4, queues.size());
-    assertEquals(3, queues.getUnderReplicatedBlockCount());
-    assertEquals(1, queues.getCorruptBlockSize());
+    numCorrupt++;
+    assertEquals(numUR + numCorrupt, queues.size());
+    assertEquals(numUR, queues.getUnderReplicatedBlockCount());
+    assertEquals(numCorrupt, queues.getCorruptBlockSize());
     assertInLevel(queues, block_corrupt,
         UnderReplicatedBlocks.QUEUE_WITH_CORRUPT_BLOCKS);
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockRecovery.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockRecovery.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockRecovery.java
index 190f881..ef4b2c6 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockRecovery.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestBlockRecovery.java
@@ -61,6 +61,7 @@ import org.apache.hadoop.hdfs.DFSTestUtil;
 import org.apache.hadoop.hdfs.DistributedFileSystem;
 import org.apache.hadoop.hdfs.HdfsConfiguration;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.hdfs.StripedFileTestUtil;
 import org.apache.hadoop.hdfs.protocol.DatanodeID;
 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
 import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
@@ -98,8 +99,6 @@ import org.mockito.stubbing.Answer;
 
 import com.google.common.base.Supplier;
 
-import static org.apache.hadoop.hdfs.TestLeaseRecoveryStriped.BLOCK_LENGTHS_SUITE;
-
 /**
  * This tests if sync all replicas in block recovery works correctly
  */
@@ -124,6 +123,30 @@ public class TestBlockRecovery {
   private final static long REPLICA_LEN2 = 5000L;
   private final static ExtendedBlock block = new ExtendedBlock(POOL_ID,
       BLOCK_ID, BLOCK_LEN, GEN_STAMP);
+
+  private static final int CELL_SIZE =
+      StripedFileTestUtil.BLOCK_STRIPED_CELL_SIZE;
+  private static final int bytesPerChecksum = 512;
+  private static final int[][][] BLOCK_LENGTHS_SUITE = {
+      { { 11 * CELL_SIZE, 10 * CELL_SIZE, 9 * CELL_SIZE, 8 * CELL_SIZE,
+          7 * CELL_SIZE, 6 * CELL_SIZE, 5 * CELL_SIZE, 4 * CELL_SIZE,
+          3 * CELL_SIZE }, { 36 * CELL_SIZE } },
+
+      { { 3 * CELL_SIZE, 4 * CELL_SIZE, 5 * CELL_SIZE, 6 * CELL_SIZE,
+          7 * CELL_SIZE, 8 * CELL_SIZE, 9 * CELL_SIZE, 10 * CELL_SIZE,
+          11 * CELL_SIZE }, { 36 * CELL_SIZE } },
+
+      { { 11 * CELL_SIZE, 7 * CELL_SIZE, 6 * CELL_SIZE, 5 * CELL_SIZE,
+          4 * CELL_SIZE, 2 * CELL_SIZE, 9 * CELL_SIZE, 10 * CELL_SIZE,
+          11 * CELL_SIZE }, { 36 * CELL_SIZE } },
+
+      { { 8 * CELL_SIZE + bytesPerChecksum,
+          7 * CELL_SIZE + bytesPerChecksum * 2,
+          6 * CELL_SIZE + bytesPerChecksum * 2,
+          5 * CELL_SIZE - bytesPerChecksum * 3,
+          4 * CELL_SIZE - bytesPerChecksum * 4,
+          3 * CELL_SIZE - bytesPerChecksum * 4, 9 * CELL_SIZE, 10 * CELL_SIZE,
+          11 * CELL_SIZE }, { 36 * CELL_SIZE } }, };
   
   static {
     GenericTestUtils.setLogLevel(FSNamesystem.LOG, Level.ALL);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddOverReplicatedStripedBlocks.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddOverReplicatedStripedBlocks.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddOverReplicatedStripedBlocks.java
index 71590b7..eba6b87 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddOverReplicatedStripedBlocks.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddOverReplicatedStripedBlocks.java
@@ -104,11 +104,11 @@ public class TestAddOverReplicatedStripedBlocks {
     cluster.triggerBlockReports();
 
     // let a internal block be over replicated with 2 redundant blocks.
-    blk.setBlockId(groupId + 2);
+    blk.setBlockId(groupId);
     cluster.injectBlocks(numDNs - 3, Arrays.asList(blk), bpid);
     cluster.injectBlocks(numDNs - 2, Arrays.asList(blk), bpid);
     // let a internal block be over replicated with 1 redundant block.
-    blk.setBlockId(groupId + 6);
+    blk.setBlockId(groupId + DATA_BLK_NUM);
     cluster.injectBlocks(numDNs - 1, Arrays.asList(blk), bpid);
 
     // update blocksMap
@@ -143,10 +143,9 @@ public class TestAddOverReplicatedStripedBlocks {
     cluster.triggerBlockReports();
     List<DatanodeInfo> infos = Arrays.asList(bg.getLocations());
 
-    // let a internal block be over replicated with 2 redundant blocks.
-    // Therefor number of internal blocks is over GROUP_SIZE. (5 data blocks +
-    // 3 parity blocks  + 2 redundant blocks > GROUP_SIZE)
-    blk.setBlockId(groupId + 2);
+    // let a internal block be over replicated with (numDNs - GROUP_SIZE + 1)
+    // redundant blocks. Therefor number of internal blocks is over GROUP_SIZE.
+    blk.setBlockId(groupId);
     List<DataNode> dataNodeList = cluster.getDataNodes();
     for (int i = 0; i < numDNs; i++) {
       if (!infos.contains(dataNodeList.get(i).getDatanodeId())) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddStripedBlocks.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddStripedBlocks.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddStripedBlocks.java
index 7ca1a53..b206f83 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddStripedBlocks.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestAddStripedBlocks.java
@@ -454,7 +454,7 @@ public class TestAddStripedBlocks {
     reports = DFSTestUtil.makeReportForReceivedBlock(reported,
         ReceivedDeletedBlockInfo.BlockStatus.RECEIVED_BLOCK, storage);
     ns.processIncrementalBlockReport(
-        cluster.getDataNodes().get(5).getDatanodeId(), reports[0]);
+        cluster.getDataNodes().get(0).getDatanodeId(), reports[0]);
     BlockManagerTestUtil.updateState(ns.getBlockManager());
     Assert.assertEquals(1, ns.getCorruptReplicaBlocks());
     Assert.assertEquals(3, bm.getCorruptReplicas(stored).size());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSEditLogLoader.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSEditLogLoader.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSEditLogLoader.java
index 47c3ace..b0e5704 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSEditLogLoader.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSEditLogLoader.java
@@ -75,7 +75,7 @@ public class TestFSEditLogLoader {
   private static final int NUM_DATA_NODES = 0;
 
   private static final ErasureCodingPolicy testECPolicy
-      = ErasureCodingPolicyManager.getSystemDefaultPolicy();
+      = StripedFileTestUtil.TEST_EC_POLICY;
   
   @Test
   public void testDisplayRecentEditLogOpCodes() throws IOException {
@@ -454,7 +454,8 @@ public class TestFSEditLogLoader {
 
       //set the storage policy of the directory
       fs.mkdir(new Path(testDir), new FsPermission("755"));
-      fs.getClient().getNamenode().setErasureCodingPolicy(testDir, null);
+      fs.getClient().getNamenode().setErasureCodingPolicy(
+          testDir, testECPolicy);
 
       // Create a file with striped block
       Path p = new Path(testFilePath);
@@ -526,7 +527,8 @@ public class TestFSEditLogLoader {
 
       //set the storage policy of the directory
       fs.mkdir(new Path(testDir), new FsPermission("755"));
-      fs.getClient().getNamenode().setErasureCodingPolicy(testDir, null);
+      fs.getClient().getNamenode().setErasureCodingPolicy(
+          testDir, testECPolicy);
 
       //create a file with striped blocks
       Path p = new Path(testFilePath);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
index 8e39bca..645f6fa 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSImage.java
@@ -143,7 +143,7 @@ public class TestFSImage {
   private void testSaveAndLoadStripedINodeFile(FSNamesystem fsn, Configuration conf,
                                                boolean isUC) throws IOException{
     // contruct a INode with StripedBlock for saving and loading
-    fsn.setErasureCodingPolicy("/", null, false);
+    fsn.setErasureCodingPolicy("/", testECPolicy, false);
     long id = 123456789;
     byte[] name = "testSaveAndLoadInodeFile_testfile".getBytes();
     PermissionStatus permissionStatus = new PermissionStatus("testuser_a",
@@ -439,8 +439,8 @@ public class TestFSImage {
    */
   @Test
   public void testSupportBlockGroup() throws IOException {
-    final short GROUP_SIZE = (short) (StripedFileTestUtil.NUM_DATA_BLOCKS
-        + StripedFileTestUtil.NUM_PARITY_BLOCKS);
+    final short GROUP_SIZE = (short) (testECPolicy.getNumDataUnits() +
+        testECPolicy.getNumParityUnits());
     final int BLOCK_SIZE = 8 * 1024 * 1024;
     Configuration conf = new HdfsConfiguration();
     conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
@@ -450,7 +450,7 @@ public class TestFSImage {
           .build();
       cluster.waitActive();
       DistributedFileSystem fs = cluster.getFileSystem();
-      fs.getClient().getNamenode().setErasureCodingPolicy("/", null);
+      fs.getClient().getNamenode().setErasureCodingPolicy("/", testECPolicy);
       Path file = new Path("/striped");
       FSDataOutputStream out = fs.create(file);
       byte[] bytes = DFSTestUtil.generateSequentialBytes(0, BLOCK_SIZE);
@@ -472,10 +472,14 @@ public class TestFSImage {
       BlockInfo[] blks = inode.getBlocks();
       assertEquals(1, blks.length);
       assertTrue(blks[0].isStriped());
-      assertEquals(StripedFileTestUtil.NUM_DATA_BLOCKS, ((BlockInfoStriped)blks[0]).getDataBlockNum());
-      assertEquals(StripedFileTestUtil.NUM_PARITY_BLOCKS, ((BlockInfoStriped)blks[0]).getParityBlockNum());
+      assertEquals(testECPolicy.getNumDataUnits(),
+          ((BlockInfoStriped) blks[0]).getDataBlockNum());
+      assertEquals(testECPolicy.getNumParityUnits(),
+          ((BlockInfoStriped) blks[0]).getParityBlockNum());
     } finally {
-      cluster.shutdown();
+      if (cluster != null) {
+        cluster.shutdown();
+      }
     }
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java
index b54f585..1818db8 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFsck.java
@@ -76,6 +76,7 @@ import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.hdfs.protocol.Block;
 import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
+import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy;
 import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
 import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
 import org.apache.hadoop.hdfs.protocol.LocatedBlock;
@@ -654,8 +655,11 @@ public class TestFsck {
         setNumFiles(4).build();
     Configuration conf = new HdfsConfiguration();
     conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, 10000L);
-    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(10)
-        .build();
+    ErasureCodingPolicy ecPolicy =
+        ErasureCodingPolicyManager.getSystemDefaultPolicy();
+    int numAllUnits = ecPolicy.getNumDataUnits() + ecPolicy.getNumParityUnits();
+    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(
+        numAllUnits + 1).build();
     FileSystem fs = null;
     try {
       String topDir = "/myDir";
@@ -666,7 +670,8 @@ public class TestFsck {
       fs = cluster.getFileSystem();
       util.createFiles(fs, topDir);
       // set topDir to EC when it has replicated files
-      cluster.getFileSystem().getClient().setErasureCodingPolicy(topDir, null);
+      cluster.getFileSystem().getClient().setErasureCodingPolicy(
+          topDir, ecPolicy);
 
       // create a new file under topDir
       DFSTestUtil.createFile(fs, new Path(topDir, "ecFile"), 1024, (short) 1, 0L);
@@ -687,16 +692,16 @@ public class TestFsck {
           "-blocks", "-openforwrite");
       assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
       assertTrue(outStr.contains("OPENFORWRITE"));
-      assertTrue(outStr.contains("Live_repl=9"));
-      assertTrue(outStr.contains("Expected_repl=9"));
+      assertTrue(outStr.contains("Live_repl=" + numAllUnits));
+      assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
 
       // Use -openforwrite option to list open files
       outStr = runFsck(conf, 0, true, openFile.toString(), "-files", "-blocks",
           "-locations", "-openforwrite", "-replicaDetails");
       assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
       assertTrue(outStr.contains("OPENFORWRITE"));
-      assertTrue(outStr.contains("Live_repl=9"));
-      assertTrue(outStr.contains("Expected_repl=9"));
+      assertTrue(outStr.contains("Live_repl=" + numAllUnits));
+      assertTrue(outStr.contains("Expected_repl=" + numAllUnits));
       assertTrue(outStr.contains("Under Construction Block:"));
 
       // Close the file
@@ -708,8 +713,8 @@ public class TestFsck {
       assertTrue(outStr.contains(NamenodeFsck.HEALTHY_STATUS));
       assertFalse(outStr.contains("OPENFORWRITE"));
       assertFalse(outStr.contains("Under Construction Block:"));
-      assertFalse(outStr.contains("Expected_repl=9"));
-      assertTrue(outStr.contains("Live_repl=9"));
+      assertFalse(outStr.contains("Expected_repl=" + numAllUnits));
+      assertTrue(outStr.contains("Live_repl=" + numAllUnits));
       util.cleanup(fs, topDir);
     } finally {
       if (fs != null) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestReconstructStripedBlocks.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestReconstructStripedBlocks.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestReconstructStripedBlocks.java
index 6ed982f..0bbc220 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestReconstructStripedBlocks.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestReconstructStripedBlocks.java
@@ -77,13 +77,10 @@ public class TestReconstructStripedBlocks {
   }
 
   @Test
-  public void testMissingStripedBlockWithBusyNode1() throws Exception {
-    doTestMissingStripedBlock(2, 1);
-  }
-
-  @Test
-  public void testMissingStripedBlockWithBusyNode2() throws Exception {
-    doTestMissingStripedBlock(3, 1);
+  public void testMissingStripedBlockWithBusyNode() throws Exception {
+    for (int i = 1; i <= NUM_PARITY_BLOCKS; i++) {
+      doTestMissingStripedBlock(i, 1);
+    }
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/def754ec/hadoop-hdfs-project/hadoop-hdfs/src/test/resources/testErasureCodingConf.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/resources/testErasureCodingConf.xml b/hadoop-hdfs-project/hadoop-hdfs/src/test/resources/testErasureCodingConf.xml
index e72d862..fd7cf9d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/resources/testErasureCodingConf.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/resources/testErasureCodingConf.xml
@@ -153,7 +153,7 @@
       <comparators>
         <comparator>
           <type>SubstringComparator</type>
-          <expected-output>ErasureCodingPolicy=[Name=RS-6-3-64k</expected-output>
+          <expected-output>ErasureCodingPolicy=[Name=</expected-output>
         </comparator>
       </comparators>
     </test>
@@ -292,7 +292,7 @@
       <comparators>
         <comparator>
           <type>SubstringComparator</type>
-          <expected-output>Policy 'invalidpolicy' does not match any of the supported policies. Please select any one of [RS-6-3-64k]</expected-output>
+          <expected-output>Policy 'invalidpolicy' does not match any of the supported policies. Please select any one of [</expected-output>
         </comparator>
       </comparators>
     </test>


[10/50] [abbrv] hadoop git commit: HDFS-9711. Integrate CSRF prevention filter in WebHDFS. Contributed by Chris Nauroth.

Posted by ji...@apache.org.
HDFS-9711. Integrate CSRF prevention filter in WebHDFS. Contributed by Chris Nauroth.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/5d1889a6
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/5d1889a6
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/5d1889a6

Branch: refs/heads/HDFS-7240
Commit: 5d1889a66d91608d34ca9411fb6e9161e637e9d3
Parents: e78d8e6
Author: cnauroth <cn...@apache.org>
Authored: Thu Feb 18 10:07:28 2016 -0800
Committer: cnauroth <cn...@apache.org>
Committed: Thu Feb 18 10:07:28 2016 -0800

----------------------------------------------------------------------
 .../security/http/RestCsrfPreventionFilter.java | 168 +++++++++++++++++--
 .../hdfs/client/HdfsClientConfigKeys.java       |  12 ++
 .../hadoop/hdfs/web/WebHdfsFileSystem.java      |  59 +++++++
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |   2 +
 .../server/datanode/web/DatanodeHttpServer.java | 114 ++++++++++++-
 .../web/PortUnificationServerHandler.java       |  18 +-
 .../web/RestCsrfPreventionFilterHandler.java    | 137 +++++++++++++++
 .../server/namenode/NameNodeHttpServer.java     |  15 +-
 .../src/main/resources/hdfs-default.xml         |  52 ++++++
 .../src/main/webapps/hdfs/explorer.html         |   1 +
 .../src/main/webapps/static/rest-csrf.js        |  91 ++++++++++
 .../hadoop-hdfs/src/site/markdown/WebHDFS.md    |  36 ++++
 ...TestWebHdfsWithRestCsrfPreventionFilter.java | 166 ++++++++++++++++++
 13 files changed, 851 insertions(+), 20 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java
index 4f7f5bb..c0f7e39 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/http/RestCsrfPreventionFilter.java
@@ -18,7 +18,9 @@
 package org.apache.hadoop.security.http;
 
 import java.io.IOException;
+import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.Set;
@@ -32,6 +34,13 @@ import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 /**
  * This filter provides protection against cross site request forgery (CSRF)
  * attacks for REST APIs. Enabling this filter on an endpoint results in the
@@ -39,7 +48,13 @@ import javax.servlet.http.HttpServletResponse;
  * with every request. In the absense of this header the filter will reject the
  * attempt as a bad request.
  */
+@InterfaceAudience.Public
+@InterfaceStability.Evolving
 public class RestCsrfPreventionFilter implements Filter {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(RestCsrfPreventionFilter.class);
+
   public static final String HEADER_USER_AGENT = "User-Agent";
   public static final String BROWSER_USER_AGENT_PARAM =
       "browser-useragents-regex";
@@ -72,6 +87,9 @@ public class RestCsrfPreventionFilter implements Filter {
       agents = BROWSER_USER_AGENTS_DEFAULT;
     }
     parseBrowserUserAgents(agents);
+    LOG.info("Adding cross-site request forgery (CSRF) protection, "
+        + "headerName = {}, methodsToIgnore = {}, browserUserAgents = {}",
+        headerName, methodsToIgnore, browserUserAgents);
   }
 
   void parseBrowserUserAgents(String userAgents) {
@@ -118,22 +136,152 @@ public class RestCsrfPreventionFilter implements Filter {
     return false;
   }
 
-  @Override
-  public void doFilter(ServletRequest request, ServletResponse response,
-      FilterChain chain) throws IOException, ServletException {
-    HttpServletRequest httpRequest = (HttpServletRequest)request;
-    if (!isBrowser(httpRequest.getHeader(HEADER_USER_AGENT)) ||
-        methodsToIgnore.contains(httpRequest.getMethod()) ||
-        httpRequest.getHeader(headerName) != null) {
-      chain.doFilter(request, response);
+  /**
+   * Defines the minimal API requirements for the filter to execute its
+   * filtering logic.  This interface exists to facilitate integration in
+   * components that do not run within a servlet container and therefore cannot
+   * rely on a servlet container to dispatch to the {@link #doFilter} method.
+   * Applications that do run inside a servlet container will not need to write
+   * code that uses this interface.  Instead, they can use typical servlet
+   * container configuration mechanisms to insert the filter.
+   */
+  public interface HttpInteraction {
+
+    /**
+     * Returns the value of a header.
+     *
+     * @param header name of header
+     * @return value of header
+     */
+    String getHeader(String header);
+
+    /**
+     * Returns the method.
+     *
+     * @return method
+     */
+    String getMethod();
+
+    /**
+     * Called by the filter after it decides that the request may proceed.
+     *
+     * @throws IOException if there is an I/O error
+     * @throws ServletException if the implementation relies on the servlet API
+     *     and a servlet API call has failed
+     */
+    void proceed() throws IOException, ServletException;
+
+    /**
+     * Called by the filter after it decides that the request is a potential
+     * CSRF attack and therefore must be rejected.
+     *
+     * @param code status code to send
+     * @param message response message
+     * @throws IOException if there is an I/O error
+     */
+    void sendError(int code, String message) throws IOException;
+  }
+
+  /**
+   * Handles an {@link HttpInteraction} by applying the filtering logic.
+   *
+   * @param httpInteraction caller's HTTP interaction
+   * @throws IOException if there is an I/O error
+   * @throws ServletException if the implementation relies on the servlet API
+   *     and a servlet API call has failed
+   */
+  public void handleHttpInteraction(HttpInteraction httpInteraction)
+      throws IOException, ServletException {
+    if (!isBrowser(httpInteraction.getHeader(HEADER_USER_AGENT)) ||
+        methodsToIgnore.contains(httpInteraction.getMethod()) ||
+        httpInteraction.getHeader(headerName) != null) {
+      httpInteraction.proceed();
     } else {
-      ((HttpServletResponse)response).sendError(
-          HttpServletResponse.SC_BAD_REQUEST,
+      httpInteraction.sendError(HttpServletResponse.SC_BAD_REQUEST,
           "Missing Required Header for CSRF Vulnerability Protection");
     }
   }
 
   @Override
+  public void doFilter(ServletRequest request, ServletResponse response,
+      final FilterChain chain) throws IOException, ServletException {
+    final HttpServletRequest httpRequest = (HttpServletRequest)request;
+    final HttpServletResponse httpResponse = (HttpServletResponse)response;
+    handleHttpInteraction(new ServletFilterHttpInteraction(httpRequest,
+        httpResponse, chain));
+  }
+
+  @Override
   public void destroy() {
   }
+
+  /**
+   * Constructs a mapping of configuration properties to be used for filter
+   * initialization.  The mapping includes all properties that start with the
+   * specified configuration prefix.  Property names in the mapping are trimmed
+   * to remove the configuration prefix.
+   *
+   * @param conf configuration to read
+   * @param confPrefix configuration prefix
+   * @return mapping of configuration properties to be used for filter
+   *     initialization
+   */
+  public static Map<String, String> getFilterParams(Configuration conf,
+      String confPrefix) {
+    Map<String, String> filterConfigMap = new HashMap<>();
+    for (Map.Entry<String, String> entry : conf) {
+      String name = entry.getKey();
+      if (name.startsWith(confPrefix)) {
+        String value = conf.get(name);
+        name = name.substring(confPrefix.length());
+        filterConfigMap.put(name, value);
+      }
+    }
+    return filterConfigMap;
+  }
+
+  /**
+   * {@link HttpInteraction} implementation for use in the servlet filter.
+   */
+  private static final class ServletFilterHttpInteraction
+      implements HttpInteraction {
+
+    private final FilterChain chain;
+    private final HttpServletRequest httpRequest;
+    private final HttpServletResponse httpResponse;
+
+    /**
+     * Creates a new ServletFilterHttpInteraction.
+     *
+     * @param httpRequest request to process
+     * @param httpResponse response to process
+     * @param chain filter chain to forward to if HTTP interaction is allowed
+     */
+    public ServletFilterHttpInteraction(HttpServletRequest httpRequest,
+        HttpServletResponse httpResponse, FilterChain chain) {
+      this.httpRequest = httpRequest;
+      this.httpResponse = httpResponse;
+      this.chain = chain;
+    }
+
+    @Override
+    public String getHeader(String header) {
+      return httpRequest.getHeader(header);
+    }
+
+    @Override
+    public String getMethod() {
+      return httpRequest.getMethod();
+    }
+
+    @Override
+    public void proceed() throws IOException, ServletException {
+      chain.doFilter(httpRequest, httpResponse);
+    }
+
+    @Override
+    public void sendError(int code, String message) throws IOException {
+      httpResponse.sendError(code, message);
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java
index 775907e..ce0f3e4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java
@@ -41,6 +41,18 @@ public interface HdfsClientConfigKeys {
   String DFS_WEBHDFS_OAUTH_ENABLED_KEY = "dfs.webhdfs.oauth2.enabled";
   boolean DFS_WEBHDFS_OAUTH_ENABLED_DEFAULT = false;
 
+  String DFS_WEBHDFS_REST_CSRF_ENABLED_KEY = "dfs.webhdfs.rest-csrf.enabled";
+  boolean DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT = false;
+  String DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY =
+      "dfs.webhdfs.rest-csrf.custom-header";
+  String DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT = "X-XSRF-HEADER";
+  String DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY =
+      "dfs.webhdfs.rest-csrf.methods-to-ignore";
+  String DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT =
+      "GET,OPTIONS,HEAD,TRACE";
+  String DFS_WEBHDFS_REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY =
+      "dfs.webhdfs.rest-csrf.browser-useragents-regex";
+
   String OAUTH_CLIENT_ID_KEY = "dfs.webhdfs.oauth2.client.id";
   String OAUTH_REFRESH_URL_KEY = "dfs.webhdfs.oauth2.refresh.url";
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
index 82cf655..3527c27 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
@@ -18,6 +18,13 @@
 
 package org.apache.hadoop.hdfs.web;
 
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY;
+
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.EOFException;
@@ -33,8 +40,10 @@ import java.net.URL;
 import java.security.PrivilegedExceptionAction;
 import java.util.ArrayList;
 import java.util.EnumSet;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.StringTokenizer;
 
 import javax.ws.rs.core.HttpHeaders;
@@ -129,6 +138,8 @@ public class WebHdfsFileSystem extends FileSystem
   private InetSocketAddress nnAddrs[];
   private int currentNNAddrIndex;
   private boolean disallowFallbackToInsecureCluster;
+  private String restCsrfCustomHeader;
+  private Set<String> restCsrfMethodsToIgnore;
   private static final ObjectReader READER =
       new ObjectMapper().reader(Map.class);
 
@@ -227,9 +238,52 @@ public class WebHdfsFileSystem extends FileSystem
     this.disallowFallbackToInsecureCluster = !conf.getBoolean(
         CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
         CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
+    this.initializeRestCsrf(conf);
     this.delegationToken = null;
   }
 
+  /**
+   * Initializes client-side handling of cross-site request forgery (CSRF)
+   * protection by figuring out the custom HTTP headers that need to be sent in
+   * requests and which HTTP methods are ignored because they do not require
+   * CSRF protection.
+   *
+   * @param conf configuration to read
+   */
+  private void initializeRestCsrf(Configuration conf) {
+    if (conf.getBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY,
+        DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT)) {
+      this.restCsrfCustomHeader = conf.getTrimmed(
+          DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_KEY,
+          DFS_WEBHDFS_REST_CSRF_CUSTOM_HEADER_DEFAULT);
+      this.restCsrfMethodsToIgnore = new HashSet<>();
+      this.restCsrfMethodsToIgnore.addAll(getTrimmedStringList(conf,
+          DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_KEY,
+          DFS_WEBHDFS_REST_CSRF_METHODS_TO_IGNORE_DEFAULT));
+    } else {
+      this.restCsrfCustomHeader = null;
+      this.restCsrfMethodsToIgnore = null;
+    }
+  }
+
+  /**
+   * Returns a list of strings from a comma-delimited configuration value.
+   *
+   * @param conf configuration to check
+   * @param name configuration property name
+   * @param defaultValue default value if no value found for name
+   * @return list of strings from comma-delimited configuration value, or an
+   *     empty list if not found
+   */
+  private static List<String> getTrimmedStringList(Configuration conf,
+      String name, String defaultValue) {
+    String valueString = conf.get(name, defaultValue);
+    if (valueString == null) {
+      return new ArrayList<>();
+    }
+    return new ArrayList<>(StringUtils.getTrimmedStringCollection(valueString));
+  }
+
   @Override
   public URI getCanonicalUri() {
     return super.getCanonicalUri();
@@ -601,6 +655,11 @@ public class WebHdfsFileSystem extends FileSystem
       final boolean doOutput = op.getDoOutput();
       conn.setRequestMethod(op.getType().toString());
       conn.setInstanceFollowRedirects(false);
+      if (restCsrfCustomHeader != null &&
+          !restCsrfMethodsToIgnore.contains(op.getType().name())) {
+        // The value of the header is unimportant.  Only its presence matters.
+        conn.setRequestProperty(restCsrfCustomHeader, "\"\"");
+      }
       switch (op.getType()) {
       // if not sending a message body for a POST or PUT operation, need
       // to ensure the server/proxy knows this

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 61a783d..2948a94 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1041,6 +1041,8 @@ Release 2.8.0 - UNRELEASED
 
     HDFS-9244. Support nested encryption zones. (zhz)
 
+    HDFS-9711. Integrate CSRF prevention filter in WebHDFS. (cnauroth)
+
   IMPROVEMENTS
 
     HDFS-9257. improve error message for "Absolute path required" in INode.java

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
index fc24fae..f9bdbf6 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/DatanodeHttpServer.java
@@ -17,6 +17,15 @@
  */
 package org.apache.hadoop.hdfs.server.datanode.web;
 
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
+
+import java.util.Enumeration;
+import java.util.Map;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.ChannelFactory;
 import io.netty.channel.ChannelFuture;
@@ -46,6 +55,7 @@ import org.apache.hadoop.http.HttpConfig;
 import org.apache.hadoop.http.HttpServer2;
 import org.apache.hadoop.net.NetUtils;
 import org.apache.hadoop.security.authorize.AccessControlList;
+import org.apache.hadoop.security.http.RestCsrfPreventionFilter;
 import org.apache.hadoop.security.ssl.SSLFactory;
 
 import java.io.Closeable;
@@ -73,6 +83,7 @@ public class DatanodeHttpServer implements Closeable {
   private final ServerBootstrap httpsServer;
   private final Configuration conf;
   private final Configuration confForCreate;
+  private final RestCsrfPreventionFilter restCsrfPreventionFilter;
   private InetSocketAddress httpAddress;
   private InetSocketAddress httpsAddress;
   static final Log LOG = LogFactory.getLog(DatanodeHttpServer.class);
@@ -81,6 +92,7 @@ public class DatanodeHttpServer implements Closeable {
       final DataNode datanode,
       final ServerSocketChannel externalHttpChannel)
     throws IOException {
+    this.restCsrfPreventionFilter = createRestCsrfPreventionFilter(conf);
     this.conf = conf;
 
     Configuration confForInfoServer = new Configuration(conf);
@@ -117,7 +129,7 @@ public class DatanodeHttpServer implements Closeable {
         @Override
         protected void initChannel(SocketChannel ch) throws Exception {
           ch.pipeline().addLast(new PortUnificationServerHandler(jettyAddr,
-              conf, confForCreate));
+              conf, confForCreate, restCsrfPreventionFilter));
         }
       });
 
@@ -165,11 +177,16 @@ public class DatanodeHttpServer implements Closeable {
           protected void initChannel(SocketChannel ch) throws Exception {
             ChannelPipeline p = ch.pipeline();
             p.addLast(
-              new SslHandler(sslFactory.createSSLEngine()),
-              new HttpRequestDecoder(),
-              new HttpResponseEncoder(),
-              new ChunkedWriteHandler(),
-              new URLDispatcher(jettyAddr, conf, confForCreate));
+                new SslHandler(sslFactory.createSSLEngine()),
+                new HttpRequestDecoder(),
+                new HttpResponseEncoder());
+            if (restCsrfPreventionFilter != null) {
+              p.addLast(new RestCsrfPreventionFilterHandler(
+                  restCsrfPreventionFilter));
+            }
+            p.addLast(
+                new ChunkedWriteHandler(),
+                new URLDispatcher(jettyAddr, conf, confForCreate));
           }
         });
     } else {
@@ -252,4 +269,87 @@ public class DatanodeHttpServer implements Closeable {
     InetSocketAddress inetSocker = NetUtils.createSocketAddr(addr);
     return inetSocker.getHostString();
   }
-}
\ No newline at end of file
+
+  /**
+   * Creates the {@link RestCsrfPreventionFilter} for the DataNode.  Since the
+   * DataNode HTTP server is not implemented in terms of the servlet API, it
+   * takes some extra effort to obtain an instance of the filter.  This method
+   * takes care of configuration and implementing just enough of the servlet API
+   * and related interfaces so that the DataNode can get a fully initialized
+   * instance of the filter.
+   *
+   * @param conf configuration to read
+   * @return initialized filter, or null if CSRF protection not enabled
+   */
+  private static RestCsrfPreventionFilter createRestCsrfPreventionFilter(
+      Configuration conf) {
+    if (!conf.getBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY,
+        DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT)) {
+      return null;
+    }
+    String restCsrfClassName = RestCsrfPreventionFilter.class.getName();
+    Map<String, String> restCsrfParams = RestCsrfPreventionFilter
+        .getFilterParams(conf, "dfs.webhdfs.rest-csrf.");
+    RestCsrfPreventionFilter filter = new RestCsrfPreventionFilter();
+    try {
+      filter.init(new MapBasedFilterConfig(restCsrfClassName, restCsrfParams));
+    } catch (ServletException e) {
+      throw new IllegalStateException(
+          "Failed to initialize RestCsrfPreventionFilter.", e);
+    }
+    return filter;
+  }
+
+  /**
+   * A minimal {@link FilterConfig} implementation backed by a {@link Map}.
+   */
+  private static final class MapBasedFilterConfig implements FilterConfig {
+
+    private final String filterName;
+    private final Map<String, String> parameters;
+
+    /**
+     * Creates a new MapBasedFilterConfig.
+     *
+     * @param filterName filter name
+     * @param parameters mapping of filter initialization parameters
+     */
+    public MapBasedFilterConfig(String filterName,
+        Map<String, String> parameters) {
+      this.filterName = filterName;
+      this.parameters = parameters;
+    }
+
+    @Override
+    public String getFilterName() {
+      return this.filterName;
+    }
+
+    @Override
+    public String getInitParameter(String name) {
+      return this.parameters.get(name);
+    }
+
+    @Override
+    public Enumeration<String> getInitParameterNames() {
+      throw this.notImplemented();
+    }
+
+    @Override
+    public ServletContext getServletContext() {
+      throw this.notImplemented();
+    }
+
+    /**
+     * Creates an exception indicating that an interface method is not
+     * implemented.  These should never be seen in practice, because it is only
+     * used for methods that are not called by {@link RestCsrfPreventionFilter}.
+     *
+     * @return exception indicating method not implemented
+     */
+    private UnsupportedOperationException notImplemented() {
+      return new UnsupportedOperationException(this.getClass().getSimpleName()
+          + " does not implement this method.");
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
index 7ebc070..ff10c6d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/PortUnificationServerHandler.java
@@ -23,6 +23,7 @@ import java.util.List;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hdfs.server.datanode.web.dtp.DtpHttp2Handler;
+import org.apache.hadoop.security.http.RestCsrfPreventionFilter;
 
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufUtil;
@@ -51,19 +52,32 @@ public class PortUnificationServerHandler extends ByteToMessageDecoder {
 
   private final Configuration confForCreate;
 
+  private final RestCsrfPreventionFilter restCsrfPreventionFilter;
+
   public PortUnificationServerHandler(InetSocketAddress proxyHost,
-      Configuration conf, Configuration confForCreate) {
+      Configuration conf, Configuration confForCreate,
+      RestCsrfPreventionFilter restCsrfPreventionFilter) {
     this.proxyHost = proxyHost;
     this.conf = conf;
     this.confForCreate = confForCreate;
+    this.restCsrfPreventionFilter = restCsrfPreventionFilter;
   }
 
   private void configureHttp1(ChannelHandlerContext ctx) {
-    ctx.pipeline().addLast(new HttpServerCodec(), new ChunkedWriteHandler(),
+    ctx.pipeline().addLast(new HttpServerCodec());
+    if (this.restCsrfPreventionFilter != null) {
+      ctx.pipeline().addLast(new RestCsrfPreventionFilterHandler(
+          this.restCsrfPreventionFilter));
+    }
+    ctx.pipeline().addLast(new ChunkedWriteHandler(),
         new URLDispatcher(proxyHost, conf, confForCreate));
   }
 
   private void configureHttp2(ChannelHandlerContext ctx) {
+    if (this.restCsrfPreventionFilter != null) {
+      ctx.pipeline().addLast(new RestCsrfPreventionFilterHandler(
+          this.restCsrfPreventionFilter));
+    }
     ctx.pipeline().addLast(new DtpHttp2Handler());
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/RestCsrfPreventionFilterHandler.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/RestCsrfPreventionFilterHandler.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/RestCsrfPreventionFilterHandler.java
new file mode 100644
index 0000000..f2f0533
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/web/RestCsrfPreventionFilterHandler.java
@@ -0,0 +1,137 @@
+/**
+ * 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.hdfs.server.datanode.web;
+
+import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
+import static io.netty.handler.codec.http.HttpHeaderValues.CLOSE;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.util.ReferenceCountUtil;
+
+import org.apache.commons.logging.Log;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.security.http.RestCsrfPreventionFilter;
+import org.apache.hadoop.security.http.RestCsrfPreventionFilter.HttpInteraction;
+
+/**
+ * Netty handler that integrates with the {@link RestCsrfPreventionFilter}.  If
+ * the filter determines that the request is allowed, then this handler forwards
+ * the request to the next handler in the Netty pipeline.  Otherwise, this
+ * handler drops the request and immediately sends an HTTP 400 response.
+ */
+@InterfaceAudience.Private
+final class RestCsrfPreventionFilterHandler
+    extends SimpleChannelInboundHandler<HttpRequest> {
+
+  private static final Log LOG = DatanodeHttpServer.LOG;
+
+  private final RestCsrfPreventionFilter restCsrfPreventionFilter;
+
+  /**
+   * Creates a new RestCsrfPreventionFilterHandler.  There will be a new
+   * instance created for each new Netty channel/pipeline serving a new request.
+   * To prevent the cost of repeated initialization of the filter, this
+   * constructor requires the caller to pass in a pre-built, fully initialized
+   * filter instance.  The filter is stateless after initialization, so it can
+   * be shared across multiple Netty channels/pipelines.
+   *
+   * @param restCsrfPreventionFilter initialized filter
+   */
+  public RestCsrfPreventionFilterHandler(
+      RestCsrfPreventionFilter restCsrfPreventionFilter) {
+    this.restCsrfPreventionFilter = restCsrfPreventionFilter;
+  }
+
+  @Override
+  protected void channelRead0(final ChannelHandlerContext ctx,
+      final HttpRequest req) throws Exception {
+    restCsrfPreventionFilter.handleHttpInteraction(new NettyHttpInteraction(
+        ctx, req));
+  }
+
+  @Override
+  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+    LOG.error("Exception in " + this.getClass().getSimpleName(), cause);
+    sendResponseAndClose(ctx,
+        new DefaultHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
+  }
+
+  /**
+   * Finish handling this pipeline by writing a response with the
+   * "Connection: close" header, flushing, and scheduling a close of the
+   * connection.
+   *
+   * @param ctx context to receive the response
+   * @param resp response to send
+   */
+  private static void sendResponseAndClose(ChannelHandlerContext ctx,
+      DefaultHttpResponse resp) {
+    resp.headers().set(CONNECTION, CLOSE);
+    ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
+  }
+
+  /**
+   * {@link HttpInteraction} implementation for use in a Netty pipeline.
+   */
+  private static final class NettyHttpInteraction implements HttpInteraction {
+
+    private final ChannelHandlerContext ctx;
+    private final HttpRequest req;
+
+    /**
+     * Creates a new NettyHttpInteraction.
+     *
+     * @param ctx context to receive the response
+     * @param req request to process
+     */
+    public NettyHttpInteraction(ChannelHandlerContext ctx, HttpRequest req) {
+      this.ctx = ctx;
+      this.req = req;
+    }
+
+    @Override
+    public String getHeader(String header) {
+      return req.headers().get(header);
+    }
+
+    @Override
+    public String getMethod() {
+      return req.method().name();
+    }
+
+    @Override
+    public void proceed() {
+      ReferenceCountUtil.retain(req);
+      ctx.fireChannelRead(req);
+    }
+
+    @Override
+    public void sendError(int code, String message) {
+      HttpResponseStatus status = new HttpResponseStatus(code, message);
+      sendResponseAndClose(ctx, new DefaultHttpResponse(HTTP_1_1, status));
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeHttpServer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeHttpServer.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeHttpServer.java
index 55cf00f..84229e7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeHttpServer.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeHttpServer.java
@@ -17,6 +17,8 @@
  */
 package org.apache.hadoop.hdfs.server.namenode;
 
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
 
 import java.io.IOException;
 import java.net.InetSocketAddress;
@@ -45,6 +47,7 @@ import org.apache.hadoop.http.HttpServer2;
 import org.apache.hadoop.net.NetUtils;
 import org.apache.hadoop.security.SecurityUtil;
 import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.security.http.RestCsrfPreventionFilter;
 
 /**
  * Encapsulates the HTTP server started by the NameNode. 
@@ -90,6 +93,16 @@ public class NameNodeHttpServer {
     HttpServer2.LOG.info("Added filter '" + name + "' (class=" + className
         + ")");
 
+    // add REST CSRF prevention filter
+    if (conf.getBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY,
+        DFS_WEBHDFS_REST_CSRF_ENABLED_DEFAULT)) {
+      Map<String, String> restCsrfParams = RestCsrfPreventionFilter
+          .getFilterParams(conf, "dfs.webhdfs.rest-csrf.");
+      String restCsrfClassName = RestCsrfPreventionFilter.class.getName();
+      HttpServer2.defineFilter(httpServer.getWebAppContext(), restCsrfClassName,
+          restCsrfClassName, restCsrfParams, new String[] {pathSpec});
+    }
+
     // add webhdfs packages
     httpServer.addJerseyResourcePackage(NamenodeWebHdfsMethods.class
         .getPackage().getName() + ";" + Param.class.getPackage().getName(),
@@ -297,4 +310,4 @@ public class NameNodeHttpServer {
   public static HAServiceProtocol.HAServiceState getNameNodeStateFromContext(ServletContext context) {
     return getNameNodeFromContext(context).getServiceState();
   }
-}
\ No newline at end of file
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
index 4889bc3..0f5130a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/resources/hdfs-default.xml
@@ -2762,4 +2762,56 @@
   </description>
 </property>
 
+<property>
+  <name>dfs.webhdfs.rest-csrf.enabled</name>
+  <value>false</value>
+  <description>
+    If true, then enables WebHDFS protection against cross-site request forgery
+    (CSRF).  The WebHDFS client also uses this property to determine whether or
+    not it needs to send the custom CSRF prevention header in its HTTP requests.
+  </description>
+</property>
+
+<property>
+  <name>dfs.webhdfs.rest-csrf.custom-header</name>
+  <value>X-XSRF-HEADER</value>
+  <description>
+    The name of a custom header that HTTP requests must send when protection
+    against cross-site request forgery (CSRF) is enabled for WebHDFS by setting
+    dfs.webhdfs.rest-csrf.enabled to true.  The WebHDFS client also uses this
+    property to determine whether or not it needs to send the custom CSRF
+    prevention header in its HTTP requests.
+  </description>
+</property>
+
+<property>
+  <name>dfs.webhdfs.rest-csrf.methods-to-ignore</name>
+  <value>GET,OPTIONS,HEAD,TRACE</value>
+  <description>
+    A comma-separated list of HTTP methods that do not require HTTP requests to
+    include a custom header when protection against cross-site request forgery
+    (CSRF) is enabled for WebHDFS by setting dfs.webhdfs.rest-csrf.enabled to
+    true.  The WebHDFS client also uses this property to determine whether or
+    not it needs to send the custom CSRF prevention header in its HTTP requests.
+  </description>
+</property>
+
+<property>
+  <name>dfs.webhdfs.rest-csrf.browser-useragents-regex</name>
+  <value>^Mozilla.*,^Opera.*</value>
+  <description>
+    A comma-separated list of regular expressions used to match against an HTTP
+    request's User-Agent header when protection against cross-site request
+    forgery (CSRF) is enabled for WebHDFS by setting
+    dfs.webhdfs.reset-csrf.enabled to true.  If the incoming User-Agent matches
+    any of these regular expressions, then the request is considered to be sent
+    by a browser, and therefore CSRF prevention is enforced.  If the request's
+    User-Agent does not match any of these regular expressions, then the request
+    is considered to be sent by something other than a browser, such as scripted
+    automation.  In this case, CSRF is not a potential attack vector, so
+    the prevention is not enforced.  This helps achieve backwards-compatibility
+    with existing automation that has not been updated to send the CSRF
+    prevention header.
+  </description>
+</property>
 </configuration>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
index b68cac2..e66e1e7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/explorer.html
@@ -269,6 +269,7 @@
     </script><script type="text/javascript" src="/static/dust-helpers-1.1.1.min.js">
     </script><script type="text/javascript" src="/static/dfs-dust.js">
     </script><script type="text/javascript" src="/static/json-bignum.js">
+    </script><script type="text/javascript" src="/static/rest-csrf.js">
     </script><script type="text/javascript" src="explorer.js">
     </script><script type="text/javascript" src="/static/moment.min.js">
     </script>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/static/rest-csrf.js
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/static/rest-csrf.js b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/static/rest-csrf.js
new file mode 100644
index 0000000..973a8e8
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/static/rest-csrf.js
@@ -0,0 +1,91 @@
+/**
+ * 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.
+ */
+
+"use strict";
+
+// Initializes client-side handling of cross-site request forgery (CSRF)
+// protection by figuring out the custom HTTP headers that need to be sent in
+// requests and which HTTP methods are ignored because they do not require CSRF
+// protection.
+(function() {
+  var restCsrfCustomHeader = null;
+  var restCsrfMethodsToIgnore = null;
+
+  $.ajax({'url': '/conf', 'dataType': 'xml', 'async': false}).done(
+    function(data) {
+      function getBooleanValue(element) {
+        return ($(element).find('value').text().trim().toLowerCase() === 'true')
+      }
+
+      function getTrimmedStringValue(element) {
+        return $(element).find('value').text().trim();
+      }
+
+      function getTrimmedStringArrayValue(element) {
+        var str = $(element).find('value').text().trim();
+        var array = [];
+        if (str) {
+          var splitStr = str.split(',');
+          for (var i = 0; i < splitStr.length; i++) {
+            array.push(splitStr[i].trim());
+          }
+        }
+        return array;
+      }
+
+      // Get all relevant configuration properties.
+      var $xml = $(data);
+      var csrfEnabled = false;
+      var header = null;
+      var methods = [];
+      $xml.find('property').each(function(idx, element) {
+        var name = $(element).find('name').text();
+        if (name === 'dfs.webhdfs.rest-csrf.enabled') {
+          csrfEnabled = getBooleanValue(element);
+        } else if (name === 'dfs.webhdfs.rest-csrf.custom-header') {
+          header = getTrimmedStringValue(element);
+        } else if (name === 'dfs.webhdfs.rest-csrf.methods-to-ignore') {
+          methods = getTrimmedStringArrayValue(element);
+        }
+      });
+
+      // If enabled, set up all subsequent AJAX calls with a pre-send callback
+      // that adds the custom headers if necessary.
+      if (csrfEnabled) {
+        restCsrfCustomHeader = header;
+        restCsrfMethodsToIgnore = {};
+        methods.map(function(method) { restCsrfMethodsToIgnore[method] = true; });
+        $.ajaxSetup({
+          beforeSend: addRestCsrfCustomHeader
+        });
+      }
+    });
+
+  // Adds custom headers to request if necessary.  This is done only for WebHDFS
+  // URLs, and only if it's not an ignored method.
+  function addRestCsrfCustomHeader(xhr, settings) {
+    if (settings.url == null || !settings.url.startsWith('/webhdfs/')) {
+      return;
+    }
+    var method = settings.type;
+    if (restCsrfCustomHeader != null && !restCsrfMethodsToIgnore[method]) {
+      // The value of the header is unimportant.  Only its presence matters.
+      xhr.setRequestHeader(restCsrfCustomHeader, '""');
+    }
+  }
+})();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/WebHDFS.md
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/WebHDFS.md b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/WebHDFS.md
index 2b7a493..473ad27 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/WebHDFS.md
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/WebHDFS.md
@@ -23,6 +23,7 @@ WebHDFS REST API
         * [HDFS Configuration Options](#HDFS_Configuration_Options)
     * [Authentication](#Authentication)
     * [Proxy Users](#Proxy_Users)
+    * [Cross-Site Request Forgery Prevention](#Cross-Site_Request_Forgery_Prevention)
     * [File and Directory Operations](#File_and_Directory_Operations)
         * [Create and Write to a File](#Create_and_Write_to_a_File)
         * [Append to a File](#Append_to_a_File)
@@ -263,6 +264,41 @@ When the proxy user feature is enabled, a proxy user *P* may submit a request on
 
         curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?delegation=<TOKEN>&op=..."
 
+Cross-Site Request Forgery Prevention
+-------------------------------------
+
+WebHDFS supports an optional, configurable mechanism for cross-site request
+forgery (CSRF) prevention.  When enabled, WebHDFS HTTP requests to the NameNode
+or DataNode must include a custom HTTP header.  Configuration properties allow
+adjusting which specific HTTP methods are protected and the name of the HTTP
+header.  The value sent in the header is not relevant.  Only the presence of a
+header by that name is required.
+
+Enabling CSRF prevention also sets up the `WebHdfsFileSystem` class to send the
+required header.  This ensures that CLI commands like
+[`hdfs dfs`](./HDFSCommands.html#dfs) and
+[`hadoop distcp`](../../hadoop-distcp/DistCp.html) continue to work correctly
+when used with `webhdfs:` URIs.
+
+Enabling CSRF prevention also sets up the NameNode web UI to send the required
+header.  After enabling CSRF prevention and restarting the NameNode, existing
+users of the NameNode web UI need to refresh the browser to reload the page and
+find the new configuration.
+
+The following properties control CSRF prevention.
+
+| Property | Description | Default Value |
+|:---- |:---- |:----
+| `dfs.webhdfs.rest-csrf.enabled` | If true, then enables WebHDFS protection against cross-site request forgery (CSRF).  The WebHDFS client also uses this property to determine whether or not it needs to send the custom CSRF prevention header in its HTTP requests. | `false` |
+| `dfs.webhdfs.rest-csrf.custom-header` | The name of a custom header that HTTP requests must send when protection against cross-site request forgery (CSRF) is enabled for WebHDFS by setting dfs.webhdfs.rest-csrf.enabled to true.  The WebHDFS client also uses this property to determine whether or not it needs to send the custom CSRF prevention header in its HTTP requests. | `X-XSRF-HEADER` |
+| `dfs.webhdfs.rest-csrf.methods-to-ignore` | A comma-separated list of HTTP methods that do not require HTTP requests to include a custom header when protection against cross-site request forgery (CSRF) is enabled for WebHDFS by setting dfs.webhdfs.rest-csrf.enabled to true.  The WebHDFS client also uses this property to determine whether or not it needs to send the custom CSRF prevention header in its HTTP requests. | `GET,OPTIONS,HEAD,TRACE` |
+| `dfs.webhdfs.rest-csrf.browser-useragents-regex` | A comma-separated list of regular expressions used to match against an HTTP request's User-Agent header when protection against cross-site request forgery (CSRF) is enabled for WebHDFS by setting dfs.webhdfs.reset-csrf.enabled to true.  If the incoming User-Agent matches any of these regular expressions, then the request is considered to be sent by a browser, and therefore CSRF prevention is enforced.  If the request's User-Agent does not match any of these regular expressions, then the request is considered to be sent by something other than a browser, such as scripted automation.  In this case, CSRF is not a potential attack vector, so the prevention is not enforced.  This helps achieve backwards-compatibility with existing automation that has not been updated to send the CSRF prevention header. | `^Mozilla.*,^Opera.*` |
+
+The following is an example `curl` call that uses the `-H` option to include the
+custom header in the request.
+
+        curl -i -L -X PUT -H 'X-XSRF-HEADER: ""' 'http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=CREATE'
+
 File and Directory Operations
 -----------------------------
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/5d1889a6/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/web/TestWebHdfsWithRestCsrfPreventionFilter.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/web/TestWebHdfsWithRestCsrfPreventionFilter.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/web/TestWebHdfsWithRestCsrfPreventionFilter.java
new file mode 100644
index 0000000..d5f4a05
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/web/TestWebHdfsWithRestCsrfPreventionFilter.java
@@ -0,0 +1,166 @@
+/**
+ * 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.hdfs.web;
+
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_WEBHDFS_REST_CSRF_ENABLED_KEY;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.util.Arrays;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.DFSTestUtil;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.io.IOUtils;
+import org.apache.hadoop.net.NetUtils;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
+
+/**
+ * Tests use of the cross-site-request forgery (CSRF) prevention filter with
+ * WebHDFS.  This is a parameterized test that covers various combinations of
+ * CSRF protection enabled or disabled at the NameNode, the DataNode and the
+ * WebHDFS client.  If the server is configured with CSRF prevention, but the
+ * client is not, then protected operations are expected to fail.
+ */
+@RunWith(Parameterized.class)
+public class TestWebHdfsWithRestCsrfPreventionFilter {
+
+  private static final Path FILE = new Path("/file");
+
+  private final boolean nnRestCsrf;
+  private final boolean dnRestCsrf;
+  private final boolean clientRestCsrf;
+
+  private MiniDFSCluster cluster;
+  private FileSystem fs, webhdfs;
+
+  @Rule
+  public ExpectedException exception = ExpectedException.none();
+
+  public TestWebHdfsWithRestCsrfPreventionFilter(boolean nnRestCsrf,
+      boolean dnRestCsrf, boolean clientRestCsrf) {
+    this.nnRestCsrf = nnRestCsrf;
+    this.dnRestCsrf = dnRestCsrf;
+    this.clientRestCsrf = clientRestCsrf;
+  }
+
+  @Parameters
+  public static Iterable<Object[]> data() {
+    return Arrays.asList(new Object[][] {
+        { false, false, false },
+        { true, true, true },
+        { true, true, false },
+        { true, false, true },
+        { true, false, false },
+        { false, true, true },
+        { false, true, false },
+        { false, false, true }});
+  }
+
+  @Before
+  public void before() throws Exception {
+    Configuration nnConf = new Configuration();
+    nnConf.setBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY, nnRestCsrf);
+    // Set configuration to treat anything as a browser, so that CSRF prevention
+    // checks actually get enforced.
+    nnConf.set(DFS_WEBHDFS_REST_CSRF_BROWSER_USERAGENTS_REGEX_KEY, ".*");
+    cluster = new MiniDFSCluster.Builder(nnConf).numDataNodes(0).build();
+
+    Configuration dnConf = new Configuration(nnConf);
+    dnConf.setBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY, dnRestCsrf);
+    cluster.startDataNodes(dnConf, 1, true, null, null, null, null, false);
+
+    cluster.waitActive();
+    fs = cluster.getFileSystem();
+
+    Configuration clientConf = new Configuration();
+    clientConf.setBoolean(DFS_WEBHDFS_REST_CSRF_ENABLED_KEY, clientRestCsrf);
+    InetSocketAddress addr = cluster.getNameNode().getHttpAddress();
+    webhdfs = FileSystem.get(URI.create("webhdfs://" +
+        NetUtils.getHostPortString(addr)), clientConf);
+  }
+
+  @After
+  public void after() {
+    IOUtils.closeStream(webhdfs);
+    IOUtils.closeStream(fs);
+    if (cluster != null) {
+      cluster.shutdown();
+    }
+  }
+
+  @Test
+  public void testCreate() throws Exception {
+    // create is a HTTP PUT that redirects from NameNode to DataNode, so we
+    // expect CSRF prevention on either server to block an unconfigured client.
+    if ((nnRestCsrf || dnRestCsrf) && !clientRestCsrf) {
+      expectException();
+    }
+    assertTrue(webhdfs.createNewFile(FILE));
+  }
+
+  @Test
+  public void testDelete() throws Exception {
+    DFSTestUtil.createFile(fs, FILE, 1024, (short)1, 0L);
+    // delete is an HTTP DELETE that executes solely within the NameNode as a
+    // metadata operation, so we expect CSRF prevention configured on the
+    // NameNode to block an unconfigured client.
+    if (nnRestCsrf && !clientRestCsrf) {
+      expectException();
+    }
+    assertTrue(webhdfs.delete(FILE, false));
+  }
+
+  @Test
+  public void testGetFileStatus() throws Exception {
+    // getFileStatus is an HTTP GET, not subject to CSRF prevention, so we
+    // expect it to succeed always, regardless of CSRF configuration.
+    assertNotNull(webhdfs.getFileStatus(new Path("/")));
+  }
+
+  @Test
+  public void testTruncate() throws Exception {
+    DFSTestUtil.createFile(fs, FILE, 1024, (short)1, 0L);
+    // truncate is an HTTP POST that executes solely within the NameNode as a
+    // metadata operation, so we expect CSRF prevention configured on the
+    // NameNode to block an unconfigured client.
+    if (nnRestCsrf && !clientRestCsrf) {
+      expectException();
+    }
+    assertTrue(webhdfs.truncate(FILE, 0L));
+  }
+
+  private void expectException() {
+    exception.expect(IOException.class);
+    exception.expectMessage("Missing Required Header");
+  }
+}


[48/50] [abbrv] hadoop git commit: HDFS-9844. Correct path creation in getTrashRoot to handle root dir.

Posted by ji...@apache.org.
HDFS-9844. Correct path creation in getTrashRoot to handle root dir.

Change-Id: I5afe6c7176063892e3e632698c849bd9f4b92906


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/647a35e9
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/647a35e9
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/647a35e9

Branch: refs/heads/HDFS-7240
Commit: 647a35e996d33d8df898891760305222446b68f5
Parents: d284e18
Author: Zhe Zhang <zh...@apache.org>
Authored: Tue Feb 23 13:29:39 2016 -0800
Committer: Zhe Zhang <zh...@apache.org>
Committed: Tue Feb 23 13:29:39 2016 -0800

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DistributedFileSystem.java |  2 +-
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt           |  2 ++
 .../org/apache/hadoop/hdfs/TestEncryptionZones.java   | 14 ++++++++++++++
 3 files changed, 17 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/647a35e9/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
index 69f3871..d6eb9e5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DistributedFileSystem.java
@@ -2355,7 +2355,7 @@ public class DistributedFileSystem extends FileSystem {
       EncryptionZone ez = dfs.getEZForPath(parentSrc);
       if ((ez != null)) {
         return this.makeQualified(
-            new Path(ez.getPath() + "/" + FileSystem.TRASH_PREFIX +
+            new Path(ez.getPath(), FileSystem.TRASH_PREFIX +
                 dfs.ugi.getShortUserName()));
       }
     } catch (IOException e) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/647a35e9/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index 526ddff..83eacc3 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -1954,6 +1954,8 @@ Release 2.8.0 - UNRELEASED
     HDFS-9084. Pagination, sorting and filtering of files/directories in the
     HDFS Web UI. (Ravi Prakash via ozawa)
 
+    HDFS-9844. Correct path creation in getTrashRoot to handle root dir. (zhz)
+
   OPTIMIZATIONS
 
     HDFS-8026. Trace FSOutputSummer#writeChecksumChunks rather than

http://git-wip-us.apache.org/repos/asf/hadoop/blob/647a35e9/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java
index 42cb661..82a646f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestEncryptionZones.java
@@ -1428,6 +1428,20 @@ public class TestEncryptionZones {
     verifyShellDeleteWithTrash(shell, topEZ);
   }
 
+  @Test(timeout = 120000)
+  public void testRootDirEZTrash() throws Exception {
+    final HdfsAdmin dfsAdmin =
+        new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
+    dfsAdmin.createEncryptionZone(new Path("/"), TEST_KEY);
+    final Path encFile = new Path("/encFile");
+    final int len = 8192;
+    DFSTestUtil.createFile(fs, encFile, len, (short) 1, 0xFEED);
+    Configuration clientConf = new Configuration(conf);
+    clientConf.setLong(FS_TRASH_INTERVAL_KEY, 1);
+    FsShell shell = new FsShell(clientConf);
+    verifyShellDeleteWithTrash(shell, encFile);
+  }
+
   private void verifyShellDeleteWithTrash(FsShell shell, Path path)
       throws Exception{
     try {


[36/50] [abbrv] hadoop git commit: HDFS-8578. On upgrade, Datanode should process all storage/data dirs in parallel. Contributed by vinayakumarb and szetszwo

Posted by ji...@apache.org.
HDFS-8578. On upgrade, Datanode should process all storage/data dirs in parallel.  Contributed by vinayakumarb and szetszwo


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/66289a3b
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/66289a3b
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/66289a3b

Branch: refs/heads/HDFS-7240
Commit: 66289a3bf403f307844ea0b6ceed35b603d12c0b
Parents: a2fdfff
Author: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Authored: Mon Feb 22 15:01:15 2016 -0800
Committer: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Committed: Mon Feb 22 15:01:15 2016 -0800

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt     |   3 +
 .../org/apache/hadoop/hdfs/DFSConfigKeys.java   |   3 +
 .../server/datanode/BlockPoolSliceStorage.java  |  56 ++++---
 .../hdfs/server/datanode/DataStorage.java       | 146 +++++++++++++++----
 4 files changed, 160 insertions(+), 48 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/66289a3b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
index c39bcee..256df39 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
+++ b/hadoop-hdfs-project/hadoop-hdfs/CHANGES.txt
@@ -2840,6 +2840,9 @@ Release 2.7.3 - UNRELEASED
     HDFS-4946. Allow preferLocalNode in BlockPlacementPolicyDefault to be
     configurable (James Kinley and Nathan Roberts via kihwal)
 
+    HDFS-8578. On upgrade, Datanode should process all storage/data dirs in
+    parallel.  (vinayakumarb and szetszwo via szetszwo)
+
   OPTIMIZATIONS
 
   BUG FIXES

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66289a3b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
index 39e4fe4..a055e2b 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/DFSConfigKeys.java
@@ -836,6 +836,9 @@ public class DFSConfigKeys extends CommonConfigurationKeys {
     "dfs.datanode.slow.io.warning.threshold.ms";
   public static final long DFS_DATANODE_SLOW_IO_WARNING_THRESHOLD_DEFAULT = 300;
 
+  // Number of parallel threads to load multiple datanode volumes
+  public static final String DFS_DATANODE_PARALLEL_VOLUME_LOAD_THREADS_NUM_KEY =
+      "dfs.datanode.parallel.volumes.load.threads.num";
   public static final String DFS_DATANODE_BLOCK_ID_LAYOUT_UPGRADE_THREADS_KEY =
       "dfs.datanode.block.id.layout.upgrade.threads";
   public static final int DFS_DATANODE_BLOCK_ID_LAYOUT_UPGRADE_THREADS = 12;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66289a3b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java
index acf10f1..90a4669 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockPoolSliceStorage.java
@@ -27,6 +27,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Properties;
 import java.util.Set;
+import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -145,7 +146,8 @@ public class BlockPoolSliceStorage extends Storage {
    * @throws IOException
    */
   private StorageDirectory loadStorageDirectory(NamespaceInfo nsInfo,
-      File dataDir, StartupOption startOpt, Configuration conf)
+      File dataDir, StartupOption startOpt,
+      List<Callable<StorageDirectory>> callables, Configuration conf)
           throws IOException {
     StorageDirectory sd = new StorageDirectory(dataDir, null, true);
     try {
@@ -172,19 +174,17 @@ public class BlockPoolSliceStorage extends Storage {
       // Each storage directory is treated individually.
       // During startup some of them can upgrade or roll back
       // while others could be up-to-date for the regular startup.
-      if (doTransition(sd, nsInfo, startOpt, conf)) {
-        return sd;
-      }
+      if (!doTransition(sd, nsInfo, startOpt, callables, conf)) {
 
-      if (getCTime() != nsInfo.getCTime()) {
-        throw new IOException("Datanode CTime (=" + getCTime()
-            + ") is not equal to namenode CTime (=" + nsInfo.getCTime() + ")");
+        // 3. Check CTime and update successfully loaded storage.
+        if (getCTime() != nsInfo.getCTime()) {
+          throw new IOException("Datanode CTime (=" + getCTime()
+              + ") is not equal to namenode CTime (=" + nsInfo.getCTime() + ")");
+        }
+        setServiceLayoutVersion(getServiceLayoutVersion());
+        writeProperties(sd);
       }
 
-      // 3. Update successfully loaded storage.
-      setServiceLayoutVersion(getServiceLayoutVersion());
-      writeProperties(sd);
-
       return sd;
     } catch (IOException ioe) {
       sd.unlock();
@@ -208,7 +208,8 @@ public class BlockPoolSliceStorage extends Storage {
    */
   List<StorageDirectory> loadBpStorageDirectories(NamespaceInfo nsInfo,
       Collection<File> dataDirs, StartupOption startOpt,
-      Configuration conf) throws IOException {
+      List<Callable<StorageDirectory>> callables, Configuration conf)
+          throws IOException {
     List<StorageDirectory> succeedDirs = Lists.newArrayList();
     try {
       for (File dataDir : dataDirs) {
@@ -218,7 +219,7 @@ public class BlockPoolSliceStorage extends Storage {
                   "attempt to load an used block storage: " + dataDir);
         }
         final StorageDirectory sd = loadStorageDirectory(
-            nsInfo, dataDir, startOpt, conf);
+            nsInfo, dataDir, startOpt, callables, conf);
         succeedDirs.add(sd);
       }
     } catch (IOException e) {
@@ -242,11 +243,12 @@ public class BlockPoolSliceStorage extends Storage {
    * @throws IOException on error
    */
   List<StorageDirectory> recoverTransitionRead(NamespaceInfo nsInfo,
-      Collection<File> dataDirs, StartupOption startOpt, Configuration conf)
+      Collection<File> dataDirs, StartupOption startOpt,
+      List<Callable<StorageDirectory>> callables, Configuration conf)
           throws IOException {
     LOG.info("Analyzing storage directories for bpid " + nsInfo.getBlockPoolID());
     final List<StorageDirectory> loaded = loadBpStorageDirectories(
-        nsInfo, dataDirs, startOpt, conf);
+        nsInfo, dataDirs, startOpt, callables, conf);
     for (StorageDirectory sd : loaded) {
       addStorageDir(sd);
     }
@@ -353,7 +355,8 @@ public class BlockPoolSliceStorage extends Storage {
    * @return true if the new properties has been written.
    */
   private boolean doTransition(StorageDirectory sd, NamespaceInfo nsInfo,
-      StartupOption startOpt, Configuration conf) throws IOException {
+      StartupOption startOpt, List<Callable<StorageDirectory>> callables,
+      Configuration conf) throws IOException {
     if (startOpt == StartupOption.ROLLBACK && sd.getPreviousDir().exists()) {
       Preconditions.checkState(!getTrashRootDir(sd).exists(),
           sd.getPreviousDir() + " and " + getTrashRootDir(sd) + " should not " +
@@ -395,7 +398,7 @@ public class BlockPoolSliceStorage extends Storage {
     }
     if (this.layoutVersion > HdfsServerConstants.DATANODE_LAYOUT_VERSION
         || this.cTime < nsInfo.getCTime()) {
-      doUpgrade(sd, nsInfo, conf); // upgrade
+      doUpgrade(sd, nsInfo, callables, conf); // upgrade
       return true;
     }
     // layoutVersion == LAYOUT_VERSION && this.cTime > nsInfo.cTime
@@ -425,7 +428,9 @@ public class BlockPoolSliceStorage extends Storage {
    * @throws IOException on error
    */
   private void doUpgrade(final StorageDirectory bpSd,
-      final NamespaceInfo nsInfo, final Configuration conf) throws IOException {
+      final NamespaceInfo nsInfo,
+      final List<Callable<StorageDirectory>> callables,
+      final Configuration conf) throws IOException {
     // Upgrading is applicable only to release with federation or after
     if (!DataNodeLayoutVersion.supports(
         LayoutVersion.Feature.FEDERATION, layoutVersion)) {
@@ -463,10 +468,21 @@ public class BlockPoolSliceStorage extends Storage {
     rename(bpCurDir, bpTmpDir);
     
     final String name = "block pool " + blockpoolID + " at " + bpSd.getRoot();
-    doUgrade(name, bpSd, nsInfo, bpPrevDir, bpTmpDir, bpCurDir, oldLV, conf);
+    if (callables == null) {
+      doUpgrade(name, bpSd, nsInfo, bpPrevDir, bpTmpDir, bpCurDir, oldLV, conf);
+    } else {
+      callables.add(new Callable<StorageDirectory>() {
+        @Override
+        public StorageDirectory call() throws Exception {
+          doUpgrade(name, bpSd, nsInfo, bpPrevDir, bpTmpDir, bpCurDir, oldLV,
+              conf);
+          return bpSd;
+        }
+      });
+    }
   }
 
-  private void doUgrade(String name, final StorageDirectory bpSd,
+  private void doUpgrade(String name, final StorageDirectory bpSd,
       NamespaceInfo nsInfo, final File bpPrevDir, final File bpTmpDir,
       final File bpCurDir, final int oldLV, Configuration conf)
           throws IOException {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66289a3b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
index 7903194..6697054 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataStorage.java
@@ -37,10 +37,12 @@ import java.util.Set;
 import java.util.TreeMap;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 
+import org.apache.hadoop.HadoopIllegalArgumentException;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.classification.InterfaceStability;
 import org.apache.hadoop.conf.Configuration;
@@ -51,6 +53,7 @@ import org.apache.hadoop.fs.LocalFileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.permission.FsPermission;
 import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.DFSUtilClient;
 import org.apache.hadoop.hdfs.HdfsConfiguration;
 import org.apache.hadoop.hdfs.protocol.Block;
 import org.apache.hadoop.hdfs.protocol.LayoutVersion;
@@ -260,8 +263,8 @@ public class DataStorage extends Storage {
   }
 
   private StorageDirectory loadStorageDirectory(DataNode datanode,
-      NamespaceInfo nsInfo, File dataDir, StartupOption startOpt)
-          throws IOException {
+      NamespaceInfo nsInfo, File dataDir, StartupOption startOpt,
+      List<Callable<StorageDirectory>> callables) throws IOException {
     StorageDirectory sd = new StorageDirectory(dataDir, null, false);
     try {
       StorageState curState = sd.analyzeStorage(startOpt, this);
@@ -287,13 +290,12 @@ public class DataStorage extends Storage {
       // Each storage directory is treated individually.
       // During startup some of them can upgrade or roll back
       // while others could be up-to-date for the regular startup.
-      if (doTransition(sd, nsInfo, startOpt, datanode.getConf())) {
-        return sd;
-      }
+      if (!doTransition(sd, nsInfo, startOpt, callables, datanode.getConf())) {
 
-      // 3. Update successfully loaded storage.
-      setServiceLayoutVersion(getServiceLayoutVersion());
-      writeProperties(sd);
+        // 3. Update successfully loaded storage.
+        setServiceLayoutVersion(getServiceLayoutVersion());
+        writeProperties(sd);
+      }
 
       return sd;
     } catch (IOException ioe) {
@@ -325,7 +327,7 @@ public class DataStorage extends Storage {
     }
 
     StorageDirectory sd = loadStorageDirectory(
-        datanode, nsInfos.get(0), volume, StartupOption.HOTSWAP);
+        datanode, nsInfos.get(0), volume, StartupOption.HOTSWAP, null);
     VolumeBuilder builder =
         new VolumeBuilder(this, sd);
     for (NamespaceInfo nsInfo : nsInfos) {
@@ -336,12 +338,35 @@ public class DataStorage extends Storage {
 
       final BlockPoolSliceStorage bpStorage = getBlockPoolSliceStorage(nsInfo);
       final List<StorageDirectory> dirs = bpStorage.loadBpStorageDirectories(
-          nsInfo, bpDataDirs, StartupOption.HOTSWAP, datanode.getConf());
+          nsInfo, bpDataDirs, StartupOption.HOTSWAP, null, datanode.getConf());
       builder.addBpStorageDirectories(nsInfo.getBlockPoolID(), dirs);
     }
     return builder;
   }
 
+  static int getParallelVolumeLoadThreadsNum(int dataDirs, Configuration conf) {
+    final String key
+        = DFSConfigKeys.DFS_DATANODE_PARALLEL_VOLUME_LOAD_THREADS_NUM_KEY;
+    final int n = conf.getInt(key, dataDirs);
+    if (n < 1) {
+      throw new HadoopIllegalArgumentException(key + " = " + n + " < 1");
+    }
+    final int min = Math.min(n, dataDirs);
+    LOG.info("Using " + min + " threads to upgrade data directories ("
+        + key + "=" + n + ", dataDirs=" + dataDirs + ")");
+    return min;
+  }
+
+  static class UpgradeTask {
+    private final StorageLocation dataDir;
+    private final Future<StorageDirectory> future;
+
+    UpgradeTask(StorageLocation dataDir, Future<StorageDirectory> future) {
+      this.dataDir = dataDir;
+      this.future = future;
+    }
+  }
+
   /**
    * Add a list of volumes to be managed by DataStorage. If the volume is empty,
    * format it, otherwise recover it from previous transitions if required.
@@ -356,32 +381,62 @@ public class DataStorage extends Storage {
   synchronized List<StorageDirectory> addStorageLocations(DataNode datanode,
       NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
       StartupOption startOpt) throws IOException {
-    final List<StorageLocation> successLocations = loadDataStorage(
-        datanode, nsInfo, dataDirs, startOpt);
-    return loadBlockPoolSliceStorage(
-        datanode, nsInfo, successLocations, startOpt);
+    final int numThreads = getParallelVolumeLoadThreadsNum(
+        dataDirs.size(), datanode.getConf());
+    final ExecutorService executor = Executors.newFixedThreadPool(numThreads);
+    try {
+      final List<StorageLocation> successLocations = loadDataStorage(
+          datanode, nsInfo, dataDirs, startOpt, executor);
+      return loadBlockPoolSliceStorage(
+          datanode, nsInfo, successLocations, startOpt, executor);
+    } finally {
+      executor.shutdown();
+    }
   }
 
   private List<StorageLocation> loadDataStorage(DataNode datanode,
       NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
-      StartupOption startOpt) throws IOException {
+      StartupOption startOpt, ExecutorService executor) throws IOException {
     final List<StorageLocation> success = Lists.newArrayList();
+    final List<UpgradeTask> tasks = Lists.newArrayList();
     for (StorageLocation dataDir : dataDirs) {
       File root = dataDir.getFile();
       if (!containsStorageDir(root)) {
         try {
           // It first ensures the datanode level format is completed.
+          final List<Callable<StorageDirectory>> callables
+              = Lists.newArrayList();
           final StorageDirectory sd = loadStorageDirectory(
-              datanode, nsInfo, root, startOpt);
-          addStorageDir(sd);
+              datanode, nsInfo, root, startOpt, callables);
+          if (callables.isEmpty()) {
+            addStorageDir(sd);
+            success.add(dataDir);
+          } else {
+            for(Callable<StorageDirectory> c : callables) {
+              tasks.add(new UpgradeTask(dataDir, executor.submit(c)));
+            }
+          }
         } catch (IOException e) {
           LOG.warn("Failed to add storage directory " + dataDir, e);
-          continue;
         }
       } else {
         LOG.info("Storage directory " + dataDir + " has already been used.");
+        success.add(dataDir);
+      }
+    }
+
+    if (!tasks.isEmpty()) {
+      LOG.info("loadDataStorage: " + tasks.size() + " upgrade tasks");
+      for(UpgradeTask t : tasks) {
+        try {
+          addStorageDir(t.future.get());
+          success.add(t.dataDir);
+        } catch (ExecutionException e) {
+          LOG.warn("Failed to upgrade storage directory " + t.dataDir, e);
+        } catch (InterruptedException e) {
+          throw DFSUtilClient.toInterruptedIOException("Task interrupted", e);
+        }
       }
-      success.add(dataDir);
     }
 
     return success;
@@ -389,10 +444,11 @@ public class DataStorage extends Storage {
 
   private List<StorageDirectory> loadBlockPoolSliceStorage(DataNode datanode,
       NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
-      StartupOption startOpt) throws IOException {
+      StartupOption startOpt, ExecutorService executor) throws IOException {
     final String bpid = nsInfo.getBlockPoolID();
     final BlockPoolSliceStorage bpStorage = getBlockPoolSliceStorage(nsInfo);
     final List<StorageDirectory> success = Lists.newArrayList();
+    final List<UpgradeTask> tasks = Lists.newArrayList();
     for (StorageLocation dataDir : dataDirs) {
       final File curDir = new File(dataDir.getFile(), STORAGE_DIR_CURRENT);
       List<File> bpDataDirs = new ArrayList<File>();
@@ -400,10 +456,17 @@ public class DataStorage extends Storage {
       try {
         makeBlockPoolDataDir(bpDataDirs, null);
 
+        final List<Callable<StorageDirectory>> callables = Lists.newArrayList();
         final List<StorageDirectory> dirs = bpStorage.recoverTransitionRead(
-            nsInfo, bpDataDirs, startOpt, datanode.getConf());
-        for(StorageDirectory sd : dirs) {
-          success.add(sd);
+            nsInfo, bpDataDirs, startOpt, callables, datanode.getConf());
+        if (callables.isEmpty()) {
+          for(StorageDirectory sd : dirs) {
+            success.add(sd);
+          }
+        } else {
+          for(Callable<StorageDirectory> c : callables) {
+            tasks.add(new UpgradeTask(dataDir, executor.submit(c)));
+          }
         }
       } catch (IOException e) {
         LOG.warn("Failed to add storage directory " + dataDir
@@ -411,6 +474,20 @@ public class DataStorage extends Storage {
       }
     }
 
+    if (!tasks.isEmpty()) {
+      LOG.info("loadBlockPoolSliceStorage: " + tasks.size() + " upgrade tasks");
+      for(UpgradeTask t : tasks) {
+        try {
+          success.add(t.future.get());
+        } catch (ExecutionException e) {
+          LOG.warn("Failed to upgrade storage directory " + t.dataDir
+              + " for block pool " + bpid, e);
+        } catch (InterruptedException e) {
+          throw DFSUtilClient.toInterruptedIOException("Task interrupted", e);
+        }
+      }
+    }
+
     return success;
   }
 
@@ -655,7 +732,8 @@ public class DataStorage extends Storage {
    * @return true if the new properties has been written.
    */
   private boolean doTransition(StorageDirectory sd, NamespaceInfo nsInfo,
-      StartupOption startOpt, Configuration conf) throws IOException {
+      StartupOption startOpt, List<Callable<StorageDirectory>> callables,
+      Configuration conf) throws IOException {
     if (startOpt == StartupOption.ROLLBACK) {
       doRollback(sd, nsInfo); // rollback if applicable
     }
@@ -697,7 +775,7 @@ public class DataStorage extends Storage {
         // simply update the properties.
         upgradeProperties(sd);
       } else {
-        doUpgradePreFederation(sd, nsInfo, conf);
+        doUpgradePreFederation(sd, nsInfo, callables, conf);
       }
       return true; // doUgrade already has written properties
     }
@@ -734,7 +812,9 @@ public class DataStorage extends Storage {
    * @param sd  storage directory
    */
   void doUpgradePreFederation(final StorageDirectory sd,
-      final NamespaceInfo nsInfo, final Configuration conf) throws IOException {
+      final NamespaceInfo nsInfo,
+      final List<Callable<StorageDirectory>> callables,
+      final Configuration conf) throws IOException {
     final int oldLV = getLayoutVersion();
     LOG.info("Upgrading storage directory " + sd.getRoot()
              + ".\n   old LV = " + oldLV
@@ -767,10 +847,20 @@ public class DataStorage extends Storage {
     bpStorage.format(curDir, nsInfo);
 
     final File toDir = new File(curBpDir, STORAGE_DIR_CURRENT);
-    doUgrade(sd, nsInfo, prevDir, tmpDir, bbwDir, toDir, oldLV, conf);
+    if (callables == null) {
+      doUpgrade(sd, nsInfo, prevDir, tmpDir, bbwDir, toDir, oldLV, conf);
+    } else {
+      callables.add(new Callable<StorageDirectory>() {
+        @Override
+        public StorageDirectory call() throws Exception {
+          doUpgrade(sd, nsInfo, prevDir, tmpDir, bbwDir, toDir, oldLV, conf);
+          return sd;
+        }
+      });
+    }
   }
 
-  private void doUgrade(final StorageDirectory sd,
+  private void doUpgrade(final StorageDirectory sd,
       final NamespaceInfo nsInfo, final File prevDir,
       final File tmpDir, final File bbwDir, final File toDir, final int oldLV,
       Configuration conf) throws IOException {


[34/50] [abbrv] hadoop git commit: HADOOP-11613. Remove commons-httpclient dependency from hadoop-azure. Contributed by Masatake Iwasaki.

Posted by ji...@apache.org.
HADOOP-11613. Remove commons-httpclient dependency from hadoop-azure. Contributed by Masatake Iwasaki.


Project: http://git-wip-us.apache.org/repos/asf/hadoop/repo
Commit: http://git-wip-us.apache.org/repos/asf/hadoop/commit/d4f5fc23
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/d4f5fc23
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/d4f5fc23

Branch: refs/heads/HDFS-7240
Commit: d4f5fc23b208635e8f9a14c375d4101141aefa4a
Parents: a63301a
Author: cnauroth <cn...@apache.org>
Authored: Mon Feb 22 13:39:38 2016 -0800
Committer: cnauroth <cn...@apache.org>
Committed: Mon Feb 22 13:39:38 2016 -0800

----------------------------------------------------------------------
 hadoop-common-project/hadoop-common/CHANGES.txt |  3 ++
 .../hadoop/fs/azure/MockStorageInterface.java   | 33 +++++++-------------
 2 files changed, 15 insertions(+), 21 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/d4f5fc23/hadoop-common-project/hadoop-common/CHANGES.txt
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/CHANGES.txt b/hadoop-common-project/hadoop-common/CHANGES.txt
index e53c001..ff56c63 100644
--- a/hadoop-common-project/hadoop-common/CHANGES.txt
+++ b/hadoop-common-project/hadoop-common/CHANGES.txt
@@ -1137,6 +1137,9 @@ Release 2.8.0 - UNRELEASED
     HADOOP-12828. Print user when services are started.
     (Wei-Chiu Chuang via Yongjun Zhang) 
 
+    HADOOP-11613. Remove commons-httpclient dependency from hadoop-azure.
+    (Masatake Iwasaki via cnauroth) 
+
   OPTIMIZATIONS
 
     HADOOP-11785. Reduce the number of listStatus operation in distcp

http://git-wip-us.apache.org/repos/asf/hadoop/blob/d4f5fc23/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java b/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java
index 2bb2a9a..4fda017 100644
--- a/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java
+++ b/hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java
@@ -33,9 +33,10 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.TimeZone;
 import java.util.List;
-import org.apache.commons.httpclient.URIException;
-import org.apache.commons.httpclient.util.URIUtil;
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.net.URLCodec;
 import org.apache.commons.lang.NotImplementedException;
+import org.apache.http.client.utils.URIBuilder;
 
 import com.microsoft.azure.storage.AccessCondition;
 import com.microsoft.azure.storage.CloudStorageAccount;
@@ -68,6 +69,7 @@ public class MockStorageInterface extends StorageInterface {
   private final ArrayList<PreExistingContainer> preExistingContainers =
       new ArrayList<MockStorageInterface.PreExistingContainer>();
   private String baseUriString;
+  private static final URLCodec codec = new URLCodec();
 
   public InMemoryBlockBlobStore getBackingStore() {
     return backingStore;
@@ -126,22 +128,17 @@ public class MockStorageInterface extends StorageInterface {
    */
   private static String convertUriToDecodedString(URI uri) {
     try {
-      String result = URIUtil.decode(uri.toString());
-      return result;
-    } catch (URIException e) {
+      return codec.decode(uri.toString());
+    } catch (DecoderException e) {
       throw new AssertionError("Failed to decode URI: " + uri.toString());
     }
   }
 
   private static URI convertKeyToEncodedUri(String key) {
     try {
-      String encodedKey = URIUtil.encodePath(key);
-      URI uri = new URI(encodedKey);
-      return uri;
+      return new URIBuilder().setPath(key).build();
     } catch (URISyntaxException e) {
       throw new AssertionError("Failed to encode key: " + key);
-    } catch (URIException e) {
-      throw new AssertionError("Failed to encode key: " + key);
     }
   }
 
@@ -149,11 +146,8 @@ public class MockStorageInterface extends StorageInterface {
   public CloudBlobContainerWrapper getContainerReference(String name)
       throws URISyntaxException, StorageException {
     String fullUri;
-    try {
-      fullUri = baseUriString + "/" + URIUtil.encodePath(name);
-    } catch (URIException e) {
-      throw new RuntimeException("problem encoding fullUri", e);
-    }
+    URIBuilder builder = new URIBuilder(baseUriString);
+    fullUri = builder.setPath(builder.getPath() + "/" + name).toString();
 
     MockCloudBlobContainerWrapper container = new MockCloudBlobContainerWrapper(
         fullUri, name);
@@ -243,8 +237,6 @@ public class MockStorageInterface extends StorageInterface {
     // helper to create full URIs for directory and blob.
     // use withTrailingSlash=true to get a good path for a directory.
     private String fullUriString(String relativePath, boolean withTrailingSlash) {
-      String fullUri;
-
       String baseUri = this.baseUri;
       if (!baseUri.endsWith("/")) {
         baseUri += "/";
@@ -255,12 +247,11 @@ public class MockStorageInterface extends StorageInterface {
       }
 
       try {
-        fullUri = baseUri + URIUtil.encodePath(relativePath);
-      } catch (URIException e) {
+        URIBuilder builder = new URIBuilder(baseUri);
+        return builder.setPath(builder.getPath() + relativePath).toString();
+      } catch (URISyntaxException e) {
         throw new RuntimeException("problem encoding fullUri", e);
       }
-
-      return fullUri;
     }
   }