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 in...@apache.org on 2017/04/17 17:57:58 UTC

[01/50] [abbrv] hadoop git commit: HDFS-11551. Handle SlowDiskReport from DataNode at the NameNode. Contributed by Hanisha Koneru.

Repository: hadoop
Updated Branches:
  refs/heads/HDFS-10467 6c399a88e -> 0e4661f7f


HDFS-11551. Handle SlowDiskReport from DataNode at the NameNode. Contributed by Hanisha Koneru.


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

Branch: refs/heads/HDFS-10467
Commit: af40cfa1cb96a3f70eae867576090421df1abfeb
Parents: 20e57a9
Author: Hanisha Koneru <ha...@apache.org>
Authored: Thu Mar 30 22:41:26 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:19 2017 -0700

----------------------------------------------------------------------
 .../hdfs/server/protocol/SlowDiskReports.java   |  28 +-
 .../server/blockmanagement/DatanodeManager.java |  34 +-
 .../server/blockmanagement/SlowDiskTracker.java | 291 ++++++++++++
 .../datanode/metrics/DataNodeDiskMetrics.java   |  35 +-
 .../blockmanagement/TestSlowDiskTracker.java    | 448 +++++++++++++++++++
 5 files changed, 812 insertions(+), 24 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/af40cfa1/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/SlowDiskReports.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/SlowDiskReports.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/SlowDiskReports.java
index ef4d09e..8095c2a 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/SlowDiskReports.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/SlowDiskReports.java
@@ -48,7 +48,7 @@ public final class SlowDiskReports {
   private final Map<String, Map<DiskOp, Double>> slowDisks;
 
   /**
-   * An object representing a SlowPeerReports with no entries. Should
+   * An object representing a SlowDiskReports with no entries. Should
    * be used instead of null or creating new objects when there are
    * no slow peers to report.
    */
@@ -119,8 +119,28 @@ public final class SlowDiskReports {
    * Lists the types of operations on which disk latencies are measured.
    */
   public enum DiskOp {
-    METADATA,
-    READ,
-    WRITE
+    METADATA("MetadataOp"),
+    READ("ReadIO"),
+    WRITE("WriteIO");
+
+    private final String value;
+
+    DiskOp(final String v) {
+      this.value = v;
+    }
+
+    @Override
+    public String toString() {
+      return value;
+    }
+
+    public static DiskOp fromValue(final String value) {
+      for (DiskOp as : DiskOp.values()) {
+        if (as.value.equals(value)) {
+          return as;
+        }
+      }
+      return null;
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/af40cfa1/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 e22b7af..18135a8 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
@@ -38,6 +38,7 @@ import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
 import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor.BlockTargetPair;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor.CachedBlocksList;
+import org.apache.hadoop.hdfs.server.common.Util;
 import org.apache.hadoop.hdfs.server.namenode.CachedBlock;
 import org.apache.hadoop.hdfs.server.namenode.NameNode;
 import org.apache.hadoop.hdfs.server.namenode.Namesystem;
@@ -180,9 +181,15 @@ public class DatanodeManager {
    * True if we should process latency metrics from downstream peers.
    */
   private final boolean dataNodePeerStatsEnabled;
+  /**
+   *  True if we should process latency metrics from individual DN disks.
+   */
+  private final boolean dataNodeDiskStatsEnabled;
 
   @Nullable
   private final SlowPeerTracker slowPeerTracker;
+  @Nullable
+  private final SlowDiskTracker slowDiskTracker;
   
   /**
    * The minimum time between resending caching directives to Datanodes,
@@ -208,9 +215,16 @@ public class DatanodeManager {
     this.dataNodePeerStatsEnabled = conf.getBoolean(
         DFSConfigKeys.DFS_DATANODE_PEER_STATS_ENABLED_KEY,
         DFSConfigKeys.DFS_DATANODE_PEER_STATS_ENABLED_DEFAULT);
+    this.dataNodeDiskStatsEnabled = Util.isDiskStatsEnabled(conf.getDouble(
+        DFSConfigKeys.DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_KEY,
+        DFSConfigKeys.DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_DEFAULT));
 
+    final Timer timer = new Timer();
     this.slowPeerTracker = dataNodePeerStatsEnabled ?
-        new SlowPeerTracker(conf, new Timer()) : null;
+        new SlowPeerTracker(conf, timer) : null;
+
+    this.slowDiskTracker = dataNodeDiskStatsEnabled ?
+        new SlowDiskTracker(conf, timer) : null;
 
     this.defaultXferPort = NetUtils.createSocketAddr(
           conf.getTrimmed(DFSConfigKeys.DFS_DATANODE_ADDRESS_KEY,
@@ -1664,6 +1678,16 @@ public class DatanodeManager {
       }
     }
 
+    if (slowDiskTracker != null) {
+      if (!slowDisks.getSlowDisks().isEmpty()) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("DataNode " + nodeReg + " reported slow disks: " +
+              slowDisks.getSlowDisks());
+        }
+        slowDiskTracker.addSlowDiskReport(nodeReg.getIpcAddr(false), slowDisks);
+      }
+    }
+
     if (!cmds.isEmpty()) {
       return cmds.toArray(new DatanodeCommand[cmds.size()]);
     }
@@ -1875,5 +1899,13 @@ public class DatanodeManager {
   public String getSlowPeersReport() {
     return slowPeerTracker != null ? slowPeerTracker.getJson() : null;
   }
+
+  /**
+   * Use only for testing.
+   */
+  @VisibleForTesting
+  public SlowDiskTracker getSlowDiskTracker() {
+    return slowDiskTracker;
+  }
 }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/af40cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
new file mode 100644
index 0000000..25920a2
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
@@ -0,0 +1,291 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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 com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.primitives.Doubles;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.server.protocol.SlowDiskReports;
+import org.apache.hadoop.hdfs.server.protocol.SlowDiskReports.DiskOp;
+import org.apache.hadoop.util.Timer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.PriorityQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This class aggregates information from {@link SlowDiskReports} received via
+ * heartbeats.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Unstable
+public class SlowDiskTracker {
+  public static final Logger LOG =
+      LoggerFactory.getLogger(SlowPeerTracker.class);
+
+  /**
+   * Time duration after which a report is considered stale. This is
+   * set to DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY * 3 i.e.
+   * maintained for at least two successive reports.
+   */
+  private long reportValidityMs;
+
+  /**
+   * Timer object for querying the current time. Separated out for
+   * unit testing.
+   */
+  private final Timer timer;
+
+  /**
+   * Number of disks to include in JSON report per operation. We will return
+   * disks with the highest latency.
+   */
+  private static final int MAX_DISKS_TO_REPORT = 5;
+  private static final String DATANODE_DISK_SEPARATOR = ":";
+  private final long reportGenerationIntervalMs;
+
+  private volatile long lastUpdateTime;
+  private AtomicBoolean isUpdateInProgress = new AtomicBoolean(false);
+
+  /**
+   * Information about disks that have been reported as being slow.
+   * It is map of (Slow Disk ID) -> (DiskLatency). The DiskLatency contains
+   * the disk ID, the latencies reported and the timestamp when the report
+   * was received.
+   */
+  private final Map<String, DiskLatency> diskIDLatencyMap;
+
+  /**
+   * Map of slow disk -> diskOperations it has been reported slow in.
+   */
+  private volatile ArrayList<DiskLatency> slowDisksReport =
+      Lists.newArrayList();
+  private volatile ArrayList<DiskLatency> oldSlowDisksCheck;
+
+  public SlowDiskTracker(Configuration conf, Timer timer) {
+    this.timer = timer;
+    this.lastUpdateTime = timer.monotonicNow();
+    this.diskIDLatencyMap = new ConcurrentHashMap<>();
+    this.reportGenerationIntervalMs = conf.getTimeDuration(
+        DFSConfigKeys.DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY,
+        DFSConfigKeys.DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_DEFAULT,
+        TimeUnit.MILLISECONDS);
+    this.reportValidityMs = reportGenerationIntervalMs * 3;
+  }
+
+  @VisibleForTesting
+  public static String getSlowDiskIDForReport(String datanodeID,
+      String slowDisk) {
+    return datanodeID + DATANODE_DISK_SEPARATOR + slowDisk;
+  }
+
+  public void addSlowDiskReport(String dataNodeID,
+      SlowDiskReports dnSlowDiskReport) {
+    Map<String, Map<DiskOp, Double>> slowDisks =
+        dnSlowDiskReport.getSlowDisks();
+
+    long now = timer.monotonicNow();
+
+    for (Map.Entry<String, Map<DiskOp, Double>> slowDiskEntry :
+        slowDisks.entrySet()) {
+
+      String diskID = getSlowDiskIDForReport(dataNodeID,
+          slowDiskEntry.getKey());
+
+      Map<DiskOp, Double> latencies = slowDiskEntry.getValue();
+
+      DiskLatency diskLatency = new DiskLatency(diskID, latencies, now);
+      diskIDLatencyMap.put(diskID, diskLatency);
+    }
+
+    checkAndUpdateReportIfNecessary();
+  }
+
+  private void checkAndUpdateReportIfNecessary() {
+    // Check if it is time for update
+    long now = timer.monotonicNow();
+    if (now - lastUpdateTime > reportGenerationIntervalMs) {
+      updateSlowDiskReportAsync(now);
+    }
+  }
+
+  @VisibleForTesting
+  public void updateSlowDiskReportAsync(long now) {
+    if (isUpdateInProgress.compareAndSet(false, true)) {
+      lastUpdateTime = now;
+      new Thread(new Runnable() {
+        @Override
+        public void run() {
+          slowDisksReport = getSlowDisks(diskIDLatencyMap,
+              MAX_DISKS_TO_REPORT, now);
+
+          cleanUpOldReports(now);
+
+          isUpdateInProgress.set(false);
+        }
+      }).start();
+    }
+  }
+
+  /**
+   * This structure is a thin wrapper over disk latencies.
+   */
+  public static class DiskLatency {
+    @JsonProperty("SlowDiskID")
+    final private String slowDiskID;
+    @JsonProperty("Latencies")
+    final private Map<DiskOp, Double> latencyMap;
+    @JsonIgnore
+    private long timestamp;
+
+    /**
+     * Constructor needed by Jackson for Object mapping.
+     */
+    public DiskLatency(
+        @JsonProperty("SlowDiskID") String slowDiskID,
+        @JsonProperty("Latencies") Map<DiskOp, Double> latencyMap) {
+      this.slowDiskID = slowDiskID;
+      this.latencyMap = latencyMap;
+    }
+
+    public DiskLatency(String slowDiskID, Map<DiskOp, Double> latencyMap,
+        long timestamp) {
+      this.slowDiskID = slowDiskID;
+      this.latencyMap = latencyMap;
+      this.timestamp = timestamp;
+    }
+
+    String getSlowDiskID() {
+      return this.slowDiskID;
+    }
+
+    double getMaxLatency() {
+      double maxLatency = 0;
+      for (double latency : latencyMap.values()) {
+        if (latency > maxLatency) {
+          maxLatency = latency;
+        }
+      }
+      return maxLatency;
+    }
+
+    Double getLatency(DiskOp op) {
+      return this.latencyMap.get(op);
+    }
+  }
+
+  /**
+   * Retrieve a list of stop low disks i.e disks with the highest max latencies.
+   * @param numDisks number of disks to return. This is to limit the size of
+   *                 the generated JSON.
+   */
+  private ArrayList<DiskLatency> getSlowDisks(
+      Map<String, DiskLatency> reports, int numDisks, long now) {
+    if (reports.isEmpty()) {
+      return new ArrayList(ImmutableList.of());
+    }
+
+    final PriorityQueue<DiskLatency> topNReports = new PriorityQueue<>(
+        reports.size(),
+        new Comparator<DiskLatency>() {
+          @Override
+          public int compare(DiskLatency o1, DiskLatency o2) {
+            return Doubles.compare(
+                o1.getMaxLatency(), o2.getMaxLatency());
+          }
+        });
+
+    ArrayList<DiskLatency> oldSlowDiskIDs = Lists.newArrayList();
+
+    for (Map.Entry<String, DiskLatency> entry : reports.entrySet()) {
+      DiskLatency diskLatency = entry.getValue();
+      if (now - diskLatency.timestamp < reportValidityMs) {
+        if (topNReports.size() < numDisks) {
+          topNReports.add(diskLatency);
+        } else if (topNReports.peek().getMaxLatency() <
+            diskLatency.getMaxLatency()) {
+          topNReports.poll();
+          topNReports.add(diskLatency);
+        }
+      } else {
+        oldSlowDiskIDs.add(diskLatency);
+      }
+    }
+
+    oldSlowDisksCheck = oldSlowDiskIDs;
+
+    return Lists.newArrayList(topNReports);
+  }
+
+  /**
+   * Retrieve all valid reports as a JSON string.
+   * @return serialized representation of valid reports. null if
+   *         serialization failed.
+   */
+  public String getSlowDiskReportAsJsonString() {
+    ObjectMapper objectMapper = new ObjectMapper();
+    try {
+      return objectMapper.writeValueAsString(slowDisksReport);
+    } catch (JsonProcessingException e) {
+      // Failed to serialize. Don't log the exception call stack.
+      LOG.debug("Failed to serialize statistics" + e);
+      return null;
+    }
+  }
+
+  private void cleanUpOldReports(long now) {
+    if (oldSlowDisksCheck != null) {
+      for (DiskLatency oldDiskLatency : oldSlowDisksCheck) {
+        diskIDLatencyMap.remove(oldDiskLatency.getSlowDiskID(), oldDiskLatency);
+      }
+    }
+    // Replace oldSlowDiskIDsCheck with an empty ArrayList
+    oldSlowDisksCheck = null;
+  }
+
+  @VisibleForTesting
+  ArrayList<DiskLatency> getSlowDisksReport() {
+    return this.slowDisksReport;
+  }
+
+  @VisibleForTesting
+  long getReportValidityMs() {
+    return reportValidityMs;
+  }
+
+  @VisibleForTesting
+  void setReportValidityMs(long reportValidityMs) {
+    this.reportValidityMs = reportValidityMs;
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/af40cfa1/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodeDiskMetrics.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodeDiskMetrics.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodeDiskMetrics.java
index 2602b01..f2954e8 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodeDiskMetrics.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/metrics/DataNodeDiskMetrics.java
@@ -20,7 +20,6 @@ package org.apache.hadoop.hdfs.server.datanode.metrics;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.classification.InterfaceStability;
 import org.apache.hadoop.hdfs.server.datanode.DataNode;
@@ -33,9 +32,9 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
-import java.util.Set;
 
 /**
  * This class detects and maintains DataNode disk outliers and their
@@ -122,43 +121,41 @@ public class DataNodeDiskMetrics {
 
   private void detectAndUpdateDiskOutliers(Map<String, Double> metadataOpStats,
       Map<String, Double> readIoStats, Map<String, Double> writeIoStats) {
-    Set<String> diskOutliersSet = Sets.newHashSet();
+    Map<String, Map<DiskOp, Double>> diskStats = Maps.newHashMap();
 
     // Get MetadataOp Outliers
     Map<String, Double> metadataOpOutliers = slowDiskDetector
         .getOutliers(metadataOpStats);
-    if (!metadataOpOutliers.isEmpty()) {
-      diskOutliersSet.addAll(metadataOpOutliers.keySet());
+    for (Map.Entry<String, Double> entry : metadataOpOutliers.entrySet()) {
+      addDiskStat(diskStats, entry.getKey(), DiskOp.METADATA, entry.getValue());
     }
 
     // Get ReadIo Outliers
     Map<String, Double> readIoOutliers = slowDiskDetector
         .getOutliers(readIoStats);
-    if (!readIoOutliers.isEmpty()) {
-      diskOutliersSet.addAll(readIoOutliers.keySet());
+    for (Map.Entry<String, Double> entry : readIoOutliers.entrySet()) {
+      addDiskStat(diskStats, entry.getKey(), DiskOp.READ, entry.getValue());
     }
 
     // Get WriteIo Outliers
     Map<String, Double> writeIoOutliers = slowDiskDetector
         .getOutliers(writeIoStats);
-    if (!readIoOutliers.isEmpty()) {
-      diskOutliersSet.addAll(writeIoOutliers.keySet());
-    }
-
-    Map<String, Map<DiskOp, Double>> diskStats =
-        Maps.newHashMap();
-    for (String disk : diskOutliersSet) {
-      Map<DiskOp, Double> diskStat = Maps.newHashMap();
-      diskStat.put(DiskOp.METADATA, metadataOpStats.get(disk));
-      diskStat.put(DiskOp.READ, readIoStats.get(disk));
-      diskStat.put(DiskOp.WRITE, writeIoStats.get(disk));
-      diskStats.put(disk, diskStat);
+    for (Map.Entry<String, Double> entry : writeIoOutliers.entrySet()) {
+      addDiskStat(diskStats, entry.getKey(), DiskOp.WRITE, entry.getValue());
     }
 
     diskOutliersStats = diskStats;
     LOG.debug("Updated disk outliers.");
   }
 
+  private void addDiskStat(Map<String, Map<DiskOp, Double>> diskStats,
+      String disk, DiskOp diskOp, double latency) {
+    if (!diskStats.containsKey(disk)) {
+      diskStats.put(disk, new HashMap<>());
+    }
+    diskStats.get(disk).put(diskOp, latency);
+  }
+
   public Map<String, Map<DiskOp, Double>> getDiskOutliersStats() {
     return diskOutliersStats;
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/af40cfa1/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
new file mode 100644
index 0000000..e96b96a
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
@@ -0,0 +1,448 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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 static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableMap;
+import org.apache.hadoop.conf.Configuration;
+import static org.apache.hadoop.hdfs.DFSConfigKeys
+    .DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_KEY;
+import static org.apache.hadoop.hdfs.DFSConfigKeys
+    .DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY;
+import org.apache.hadoop.hdfs.HdfsConfiguration;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.hdfs.server.datanode.DataNode;
+import org.apache.hadoop.hdfs.server.namenode.NameNode;
+import org.apache.hadoop.hdfs.server.protocol.SlowDiskReports;
+import org.apache.hadoop.hdfs.server.protocol.SlowDiskReports.DiskOp;
+import org.apache.hadoop.hdfs.server.blockmanagement.SlowDiskTracker
+    .DiskLatency;
+import org.apache.hadoop.test.GenericTestUtils;
+import org.apache.hadoop.util.FakeTimer;
+
+import com.google.common.base.Supplier;
+import com.google.common.collect.Maps;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Tests for {@link SlowDiskTracker}.
+ */
+public class TestSlowDiskTracker {
+  public static final Logger LOG = LoggerFactory.getLogger(
+      TestSlowDiskTracker.class);
+
+  /**
+   * Set a timeout for every test case.
+   */
+  @Rule
+  public Timeout testTimeout = new Timeout(300_000);
+
+  private static Configuration conf;
+  private SlowDiskTracker tracker;
+  private FakeTimer timer;
+  private long reportValidityMs;
+  private static final long OUTLIERS_REPORT_INTERVAL = 1000;
+
+  static {
+    conf = new HdfsConfiguration();
+    conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1L);
+    conf.setDouble(DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_KEY, 1.0);
+    conf.setTimeDuration(DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY,
+        OUTLIERS_REPORT_INTERVAL, TimeUnit.MILLISECONDS);
+  }
+  @Before
+  public void setup() {
+    timer = new FakeTimer();
+    tracker = new SlowDiskTracker(conf, timer);
+    reportValidityMs = tracker.getReportValidityMs();
+  }
+
+  @Test
+  public void testDataNodeHeartbeatSlowDiskReport() throws Exception {
+    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2)
+        .build();
+    try {
+      DataNode dn1 = cluster.getDataNodes().get(0);
+      DataNode dn2 = cluster.getDataNodes().get(1);
+      NameNode nn = cluster.getNameNode(0);
+
+      DatanodeManager datanodeManager = nn.getNamesystem().getBlockManager()
+          .getDatanodeManager();
+      SlowDiskTracker slowDiskTracker = datanodeManager.getSlowDiskTracker();
+      slowDiskTracker.setReportValidityMs(OUTLIERS_REPORT_INTERVAL * 100);
+
+      dn1.getDiskMetrics().addSlowDiskForTesting("disk1", ImmutableMap.of(
+          DiskOp.WRITE, 1.3));
+      dn1.getDiskMetrics().addSlowDiskForTesting("disk2", ImmutableMap.of(
+          DiskOp.READ, 1.6, DiskOp.WRITE, 1.1));
+      dn2.getDiskMetrics().addSlowDiskForTesting("disk1", ImmutableMap.of(
+          DiskOp.METADATA, 0.8));
+      dn2.getDiskMetrics().addSlowDiskForTesting("disk2", ImmutableMap.of(
+          DiskOp.WRITE, 1.3));
+
+      String dn1ID = dn1.getDatanodeId().getIpcAddr(false);
+      String dn2ID = dn2.getDatanodeId().getIpcAddr(false);
+
+      // Advance the timer and wait for NN to receive reports from DataNodes.
+      Thread.sleep(OUTLIERS_REPORT_INTERVAL);
+
+      // Wait for NN to receive reports from all DNs
+      GenericTestUtils.waitFor(new Supplier<Boolean>() {
+        @Override
+        public Boolean get() {
+          return (slowDiskTracker.getSlowDisksReport().size() == 4);
+        }
+      }, 1000, 100000);
+
+      Map<String, DiskLatency> slowDisksReport = getSlowDisksReportForTesting(
+          slowDiskTracker);
+
+      assertThat(slowDisksReport.size(), is(4));
+      assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk1")
+          .getLatency(DiskOp.WRITE) - 1.3) < 0.0000001);
+      assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk2")
+          .getLatency(DiskOp.READ) - 1.6) < 0.0000001);
+      assertTrue(Math.abs(slowDisksReport.get(dn1ID + ":disk2")
+          .getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
+      assertTrue(Math.abs(slowDisksReport.get(dn2ID + ":disk1")
+          .getLatency(DiskOp.METADATA) - 0.8) < 0.0000001);
+      assertTrue(Math.abs(slowDisksReport.get(dn2ID + ":disk2")
+          .getLatency(DiskOp.WRITE) - 1.3) < 0.0000001);
+
+      // Test the slow disk report JSON string
+      ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
+          slowDiskTracker.getSlowDiskReportAsJsonString());
+
+      assertThat(jsonReport.size(), is(4));
+      assertTrue(isDiskInReports(jsonReport, dn1ID, "disk1", DiskOp.WRITE, 1.3));
+      assertTrue(isDiskInReports(jsonReport, dn1ID, "disk2", DiskOp.READ, 1.6));
+      assertTrue(isDiskInReports(jsonReport, dn1ID, "disk2", DiskOp.WRITE, 1.1));
+      assertTrue(isDiskInReports(jsonReport, dn2ID, "disk1", DiskOp.METADATA,
+          0.8));
+      assertTrue(isDiskInReports(jsonReport, dn2ID, "disk2", DiskOp.WRITE, 1.3));
+    } finally {
+      cluster.shutdown();
+    }
+  }
+
+  /**
+   * Edge case, there are no reports to retrieve.
+   */
+  @Test
+  public void testEmptyReports() {
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+    assertTrue(getSlowDisksReportForTesting(tracker).isEmpty());
+  }
+
+  @Test
+  public void testReportsAreRetrieved() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
+    addSlowDiskForTesting("dn1", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.3));
+    addSlowDiskForTesting("dn2", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.1));
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return !tracker.getSlowDisksReport().isEmpty();
+      }
+    }, 500, 5000);
+
+    Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
+
+    assertThat(reports.size(), is(3));
+    assertTrue(Math.abs(reports.get("dn1:disk1")
+        .getLatency(DiskOp.METADATA) - 1.1) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn1:disk1")
+        .getLatency(DiskOp.READ) - 1.8) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn1:disk2")
+        .getLatency(DiskOp.READ) - 1.3) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn2:disk2")
+        .getLatency(DiskOp.READ) - 1.1) < 0.0000001);
+  }
+
+  /**
+   * Test that when all reports are expired, we get back nothing.
+   */
+  @Test
+  public void testAllReportsAreExpired() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
+    addSlowDiskForTesting("dn1", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.3));
+    addSlowDiskForTesting("dn2", "disk2",
+        ImmutableMap.of(DiskOp.WRITE, 1.1));
+
+    // No reports should expire after 1ms.
+    timer.advance(1);
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return !tracker.getSlowDisksReport().isEmpty();
+      }
+    }, 500, 5000);
+
+    Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
+
+    assertThat(reports.size(), is(3));
+    assertTrue(Math.abs(reports.get("dn1:disk1")
+        .getLatency(DiskOp.METADATA) - 1.1) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn1:disk1")
+        .getLatency(DiskOp.READ) - 1.8) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn1:disk2")
+        .getLatency(DiskOp.READ) - 1.3) < 0.0000001);
+    assertTrue(Math.abs(reports.get("dn2:disk2")
+        .getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
+
+    // All reports should expire after REPORT_VALIDITY_MS.
+    timer.advance(reportValidityMs);
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return tracker.getSlowDisksReport().isEmpty();
+      }
+    }, 500, 3000);
+
+    reports = getSlowDisksReportForTesting(tracker);
+
+    assertThat(reports.size(), is(0));
+  }
+
+  /**
+   * Test the case when a subset of reports has expired.
+   * Ensure that we only get back non-expired reports.
+   */
+  @Test
+  public void testSomeReportsAreExpired() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
+    addSlowDiskForTesting("dn1", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.3));
+    timer.advance(reportValidityMs);
+    addSlowDiskForTesting("dn2", "disk2",
+        ImmutableMap.of(DiskOp.WRITE, 1.1));
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return !tracker.getSlowDisksReport().isEmpty();
+      }
+    }, 500, 5000);
+
+    Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
+
+    assertThat(reports.size(), is(1));
+    assertTrue(Math.abs(reports.get("dn2:disk2")
+        .getLatency(DiskOp.WRITE) - 1.1) < 0.0000001);
+  }
+
+  /**
+   * Test the case when an expired report is replaced by a valid one.
+   */
+  @Test
+  public void testReplacement() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
+    timer.advance(reportValidityMs);
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.READ, 1.4));
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return !tracker.getSlowDisksReport().isEmpty();
+      }
+    }, 500, 5000);
+
+    Map<String, DiskLatency> reports = getSlowDisksReportForTesting(tracker);
+
+    assertThat(reports.size(), is(1));
+    assertTrue(reports.get("dn1:disk1").getLatency(DiskOp.METADATA) == null);
+    assertTrue(Math.abs(reports.get("dn1:disk1")
+        .getLatency(DiskOp.READ) - 1.4) < 0.0000001);
+  }
+
+  @Test
+  public void testGetJson() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.METADATA, 1.1, DiskOp.READ, 1.8));
+    addSlowDiskForTesting("dn1", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.3));
+    addSlowDiskForTesting("dn2", "disk2",
+        ImmutableMap.of(DiskOp.WRITE, 1.1));
+    addSlowDiskForTesting("dn3", "disk1",
+        ImmutableMap.of(DiskOp.WRITE, 1.1));
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return tracker.getSlowDiskReportAsJsonString() != null;
+      }
+    }, 500, 5000);
+
+    ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
+        tracker.getSlowDiskReportAsJsonString());
+
+    // And ensure its contents are what we expect.
+    assertThat(jsonReport.size(), is(4));
+    assertTrue(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.METADATA,
+        1.1));
+    assertTrue(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.READ, 1.8));
+    assertTrue(isDiskInReports(jsonReport, "dn1", "disk2", DiskOp.READ, 1.3));
+    assertTrue(isDiskInReports(jsonReport, "dn2", "disk2", DiskOp.WRITE, 1.1));
+    assertTrue(isDiskInReports(jsonReport, "dn3", "disk1", DiskOp.WRITE, 1.1));
+  }
+
+  @Test
+  public void testGetJsonSizeIsLimited() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.READ, 1.1));
+    addSlowDiskForTesting("dn1", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.2));
+    addSlowDiskForTesting("dn1", "disk3",
+        ImmutableMap.of(DiskOp.READ, 1.3));
+    addSlowDiskForTesting("dn2", "disk1",
+        ImmutableMap.of(DiskOp.READ, 1.4));
+    addSlowDiskForTesting("dn2", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.5));
+    addSlowDiskForTesting("dn3", "disk1",
+        ImmutableMap.of(DiskOp.WRITE, 1.6));
+    addSlowDiskForTesting("dn3", "disk2",
+        ImmutableMap.of(DiskOp.READ, 1.7));
+    addSlowDiskForTesting("dn3", "disk3",
+        ImmutableMap.of(DiskOp.READ, 1.2));
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return tracker.getSlowDiskReportAsJsonString() != null;
+      }
+    }, 500, 5000);
+
+    ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
+        tracker.getSlowDiskReportAsJsonString());
+
+    // Ensure that only the top 5 highest latencies are in the report.
+    assertThat(jsonReport.size(), is(5));
+    assertTrue(isDiskInReports(jsonReport, "dn3", "disk2", DiskOp.READ, 1.7));
+    assertTrue(isDiskInReports(jsonReport, "dn3", "disk1", DiskOp.WRITE, 1.6));
+    assertTrue(isDiskInReports(jsonReport, "dn2", "disk2", DiskOp.READ, 1.5));
+    assertTrue(isDiskInReports(jsonReport, "dn2", "disk1", DiskOp.READ, 1.4));
+    assertTrue(isDiskInReports(jsonReport, "dn1", "disk3", DiskOp.READ, 1.3));
+
+    // Remaining nodes should be in the list.
+    assertFalse(isDiskInReports(jsonReport, "dn1", "disk1", DiskOp.READ, 1.1));
+    assertFalse(isDiskInReports(jsonReport, "dn1", "disk2", DiskOp.READ, 1.2));
+    assertFalse(isDiskInReports(jsonReport, "dn3", "disk3", DiskOp.READ, 1.2));
+  }
+
+  @Test
+  public void testEmptyReport() throws Exception {
+    addSlowDiskForTesting("dn1", "disk1",
+        ImmutableMap.of(DiskOp.READ, 1.1));
+    timer.advance(reportValidityMs);
+
+    tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+
+    GenericTestUtils.waitFor(new Supplier<Boolean>() {
+      @Override
+      public Boolean get() {
+        return tracker.getSlowDiskReportAsJsonString() != null;
+      }
+    }, 500, 5000);
+
+    ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
+        tracker.getSlowDiskReportAsJsonString());
+
+    assertTrue(jsonReport.isEmpty());
+  }
+
+  private boolean isDiskInReports(ArrayList<DiskLatency> reports,
+      String dataNodeID, String disk, DiskOp diskOp, double latency) {
+    String diskID = SlowDiskTracker.getSlowDiskIDForReport(dataNodeID, disk);
+    for (DiskLatency diskLatency : reports) {
+      if (diskLatency.getSlowDiskID().equals(diskID)) {
+        if (diskLatency.getLatency(diskOp) == null) {
+          return false;
+        }
+        if (Math.abs(diskLatency.getLatency(diskOp) - latency) < 0.0000001) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+
+  private ArrayList<DiskLatency> getAndDeserializeJson(
+      final String json) throws IOException {
+    return (new ObjectMapper()).readValue(json,
+        new TypeReference<ArrayList<DiskLatency>>() {});
+  }
+
+  private void addSlowDiskForTesting(String dnID, String disk,
+      Map<DiskOp, Double> latencies) {
+    Map<String, Map<DiskOp, Double>> slowDisk = Maps.newHashMap();
+    slowDisk.put(disk, latencies);
+    SlowDiskReports slowDiskReport = SlowDiskReports.create(slowDisk);
+    tracker.addSlowDiskReport(dnID, slowDiskReport);
+  }
+
+  Map<String, DiskLatency> getSlowDisksReportForTesting(
+      SlowDiskTracker slowDiskTracker) {
+    Map<String, DiskLatency> slowDisksMap = Maps.newHashMap();
+    for (DiskLatency diskLatency : slowDiskTracker.getSlowDisksReport()) {
+      slowDisksMap.put(diskLatency.getSlowDiskID(), diskLatency);
+    }
+    return slowDisksMap;
+  }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[45/50] [abbrv] hadoop git commit: HDFS-11131. TestThrottledAsyncChecker#testCancellation is flaky.

Posted by in...@apache.org.
HDFS-11131. TestThrottledAsyncChecker#testCancellation is flaky.


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

Branch: refs/heads/HDFS-10467
Commit: 6ae4d414f321efa0edcf69abb649cb6dbfe8f3eb
Parents: a8d602e
Author: Arpit Agarwal <ar...@apache.org>
Authored: Wed Apr 5 16:01:54 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../datanode/checker/ThrottledAsyncChecker.java |  25 ++--
 .../checker/TestThrottledAsyncChecker.java      | 118 ++++++-------------
 2 files changed, 43 insertions(+), 100 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/6ae4d414/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/ThrottledAsyncChecker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/ThrottledAsyncChecker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/ThrottledAsyncChecker.java
index 7584d97..b71c015 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/ThrottledAsyncChecker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/ThrottledAsyncChecker.java
@@ -187,28 +187,21 @@ public class ThrottledAsyncChecker<K, V> implements AsyncChecker<K, V> {
 
   /**
    * {@inheritDoc}.
+   *
+   * The results of in-progress checks are not useful during shutdown,
+   * so we optimize for faster shutdown by interrupt all actively
+   * executing checks.
    */
   @Override
   public void shutdownAndWait(long timeout, TimeUnit timeUnit)
       throws InterruptedException {
-    // Try orderly shutdown.
-    executorService.shutdown();
-
-    if (!executorService.awaitTermination(timeout, timeUnit)) {
-      // Interrupt executing tasks and wait again.
-      executorService.shutdownNow();
-      executorService.awaitTermination(timeout, timeUnit);
-    }
     if (scheduledExecutorService != null) {
-      // Try orderly shutdown
-      scheduledExecutorService.shutdown();
-
-      if (!scheduledExecutorService.awaitTermination(timeout, timeUnit)) {
-        // Interrupt executing tasks and wait again.
-        scheduledExecutorService.shutdownNow();
-        scheduledExecutorService.awaitTermination(timeout, timeUnit);
-      }
+      scheduledExecutorService.shutdownNow();
+      scheduledExecutorService.awaitTermination(timeout, timeUnit);
     }
+
+    executorService.shutdownNow();
+    executorService.awaitTermination(timeout, timeUnit);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/6ae4d414/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestThrottledAsyncChecker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestThrottledAsyncChecker.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestThrottledAsyncChecker.java
index 00b1af2..4ed6371 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestThrottledAsyncChecker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/checker/TestThrottledAsyncChecker.java
@@ -20,8 +20,6 @@ package org.apache.hadoop.hdfs.server.datanode.checker;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Supplier;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.util.FakeTimer;
@@ -29,12 +27,9 @@ import org.junit.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.annotation.Nonnull;
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 
 import static org.junit.Assert.assertFalse;
@@ -94,34 +89,8 @@ public class TestThrottledAsyncChecker {
   }
 
   @Test (timeout=60000)
-  public void testCancellation() throws Exception {
-    LatchedCheckable target = new LatchedCheckable();
-    final FakeTimer timer = new FakeTimer();
-    final LatchedCallback callback = new LatchedCallback(target);
-    ThrottledAsyncChecker<Boolean, Boolean> checker =
-        new ThrottledAsyncChecker<>(timer, MIN_ERROR_CHECK_GAP, 0,
-            getExecutorService());
-
-    Optional<ListenableFuture<Boolean>> olf =
-        checker.schedule(target, true);
-    if (olf.isPresent()) {
-      Futures.addCallback(olf.get(), callback);
-    }
-
-    // Request immediate cancellation.
-    checker.shutdownAndWait(0, TimeUnit.MILLISECONDS);
-    try {
-      assertFalse(olf.get().get());
-      fail("Failed to get expected InterruptedException");
-    } catch (ExecutionException ee) {
-      assertTrue(ee.getCause() instanceof InterruptedException);
-    }
-    callback.failureLatch.await();
-  }
-
-  @Test (timeout=60000)
   public void testConcurrentChecks() throws Exception {
-    LatchedCheckable target = new LatchedCheckable();
+    final StalledCheckable target = new StalledCheckable();
     final FakeTimer timer = new FakeTimer();
     ThrottledAsyncChecker<Boolean, Boolean> checker =
         new ThrottledAsyncChecker<>(timer, MIN_ERROR_CHECK_GAP, 0,
@@ -136,25 +105,6 @@ public class TestThrottledAsyncChecker {
     // for the first caller.
     assertTrue(olf1.isPresent());
     assertFalse(olf2.isPresent());
-
-    // Unblock the latch and wait for it to finish execution.
-    target.latch.countDown();
-    olf1.get().get();
-
-    GenericTestUtils.waitFor(new Supplier<Boolean>() {
-      @Override
-      public Boolean get() {
-        // We should get an absent Optional.
-        // This can take a short while until the internal callback in
-        // ThrottledAsyncChecker is scheduled for execution.
-        // Also this should not trigger a new check operation as the timer
-        // was not advanced. If it does trigger a new check then the test
-        // will fail with a timeout.
-        final Optional<ListenableFuture<Boolean>> olf3 =
-            checker.schedule(target, true);
-        return !olf3.isPresent();
-      }
-    }, 100, 10000);
   }
 
   /**
@@ -191,6 +141,32 @@ public class TestThrottledAsyncChecker {
       }
     }, 100, 10000);
   }
+
+  /**
+   * Ensure that an exception thrown by the check routine is
+   * propagated.
+   *
+   * @throws Exception
+   */
+  @Test(timeout=60000)
+  public void testExceptionIsPropagated() throws Exception {
+    final ThrowingCheckable target = new ThrowingCheckable();
+    final FakeTimer timer = new FakeTimer();
+    ThrottledAsyncChecker<Boolean, Boolean> checker =
+        new ThrottledAsyncChecker<>(timer, MIN_ERROR_CHECK_GAP, 0,
+            getExecutorService());
+
+    final Optional<ListenableFuture<Boolean>> olf =
+        checker.schedule(target, true);
+    assertTrue(olf.isPresent());
+    try {
+      olf.get().get();
+      fail("Failed to get expected ExecutionException");
+    } catch(ExecutionException ee) {
+      assertTrue(ee.getCause() instanceof DummyException);
+    }
+  }
+
   /**
    * Ensure that the exception from a failed check is cached
    * and returned without re-running the check when the minimum
@@ -245,6 +221,9 @@ public class TestThrottledAsyncChecker {
     }
   }
 
+  /**
+   * A Checkable that throws an exception when checked.
+   */
   private static class ThrowingCheckable
       extends TestCheckableBase {
     @Override
@@ -258,43 +237,14 @@ public class TestThrottledAsyncChecker {
   }
 
   /**
-   * A checkable that hangs until signaled.
+   * A checkable that hangs forever when checked.
    */
-  private static class LatchedCheckable
+  private static class StalledCheckable
       implements Checkable<Boolean, Boolean> {
-    private final CountDownLatch latch = new CountDownLatch(1);
-
     @Override
     public Boolean check(Boolean ignored) throws InterruptedException {
-      LOG.info("LatchedCheckable {} waiting.", this);
-      latch.await();
-      return true;  // Unreachable.
-    }
-  }
-
-  /**
-   * A {@link FutureCallback} that counts its invocations.
-   */
-  private static final class LatchedCallback
-      implements FutureCallback<Boolean> {
-    private final CountDownLatch successLatch = new CountDownLatch(1);
-    private final CountDownLatch failureLatch = new CountDownLatch(1);
-    private final Checkable target;
-
-    private LatchedCallback(Checkable target) {
-      this.target = target;
-    }
-
-    @Override
-    public void onSuccess(@Nonnull Boolean result) {
-      LOG.info("onSuccess callback invoked for {}", target);
-      successLatch.countDown();
-    }
-
-    @Override
-    public void onFailure(@Nonnull Throwable t) {
-      LOG.info("onFailure callback invoked for {} with exception", target, t);
-      failureLatch.countDown();
+      Thread.sleep(Long.MAX_VALUE);
+      return false; // Unreachable.
     }
   }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[31/50] [abbrv] hadoop git commit: HDFS-11538. Move ClientProtocol HA proxies into hadoop-hdfs-client. Contributed by Huafeng Wang.

Posted by in...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
deleted file mode 100644
index 2f6c9bc..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/**
- * 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
- * <p>
- * http://www.apache.org/licenses/LICENSE-2.0
- * <p>
- * 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.namenode.ha;
-
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CompletionService;
-import java.util.concurrent.ExecutorCompletionService;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.ipc.RemoteException;
-import org.apache.hadoop.ipc.StandbyException;
-
-import com.google.common.annotations.VisibleForTesting;
-import org.apache.hadoop.io.retry.MultiException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A FailoverProxyProvider implementation that technically does not "failover"
- * per-se. It constructs a wrapper proxy that sends the request to ALL
- * underlying proxies simultaneously. It assumes the in an HA setup, there will
- * be only one Active, and the active should respond faster than any configured
- * standbys. Once it receive a response from any one of the configred proxies,
- * outstanding requests to other proxies are immediately cancelled.
- */
-public class RequestHedgingProxyProvider<T> extends
-        ConfiguredFailoverProxyProvider<T> {
-
-  public static final Logger LOG =
-      LoggerFactory.getLogger(RequestHedgingProxyProvider.class);
-
-  class RequestHedgingInvocationHandler implements InvocationHandler {
-
-    final Map<String, ProxyInfo<T>> targetProxies;
-
-    public RequestHedgingInvocationHandler(
-            Map<String, ProxyInfo<T>> targetProxies) {
-      this.targetProxies = new HashMap<>(targetProxies);
-    }
-
-    /**
-     * Creates a Executor and invokes all proxies concurrently. This
-     * implementation assumes that Clients have configured proper socket
-     * timeouts, else the call can block forever.
-     *
-     * @param proxy
-     * @param method
-     * @param args
-     * @return
-     * @throws Throwable
-     */
-    @Override
-    public Object
-    invoke(Object proxy, final Method method, final Object[] args)
-            throws Throwable {
-      Map<Future<Object>, ProxyInfo<T>> proxyMap = new HashMap<>();
-      int numAttempts = 0;
-
-      ExecutorService executor = null;
-      CompletionService<Object> completionService;
-      try {
-        // Optimization : if only 2 proxies are configured and one had failed
-        // over, then we dont need to create a threadpool etc.
-        targetProxies.remove(toIgnore);
-        if (targetProxies.size() == 1) {
-          ProxyInfo<T> proxyInfo = targetProxies.values().iterator().next();
-          Object retVal = method.invoke(proxyInfo.proxy, args);
-          successfulProxy = proxyInfo;
-          return retVal;
-        }
-        executor = Executors.newFixedThreadPool(proxies.size());
-        completionService = new ExecutorCompletionService<>(executor);
-        for (final Map.Entry<String, ProxyInfo<T>> pEntry :
-                targetProxies.entrySet()) {
-          Callable<Object> c = new Callable<Object>() {
-            @Override
-            public Object call() throws Exception {
-              LOG.trace("Invoking method {} on proxy {}", method,
-                  pEntry.getValue().proxyInfo);
-              return method.invoke(pEntry.getValue().proxy, args);
-            }
-          };
-          proxyMap.put(completionService.submit(c), pEntry.getValue());
-          numAttempts++;
-        }
-
-        Map<String, Exception> badResults = new HashMap<>();
-        while (numAttempts > 0) {
-          Future<Object> callResultFuture = completionService.take();
-          Object retVal;
-          try {
-            retVal = callResultFuture.get();
-            successfulProxy = proxyMap.get(callResultFuture);
-            LOG.debug("Invocation successful on [{}]",
-                successfulProxy.proxyInfo);
-            return retVal;
-          } catch (Exception ex) {
-            ProxyInfo<T> tProxyInfo = proxyMap.get(callResultFuture);
-            logProxyException(ex, tProxyInfo.proxyInfo);
-            badResults.put(tProxyInfo.proxyInfo, unwrapException(ex));
-            LOG.trace("Unsuccessful invocation on [{}]", tProxyInfo.proxyInfo);
-            numAttempts--;
-          }
-        }
-
-        // At this point we should have All bad results (Exceptions)
-        // Or should have returned with successful result.
-        if (badResults.size() == 1) {
-          throw badResults.values().iterator().next();
-        } else {
-          throw new MultiException(badResults);
-        }
-      } finally {
-        if (executor != null) {
-          LOG.trace("Shutting down threadpool executor");
-          executor.shutdownNow();
-        }
-      }
-    }
-  }
-
-
-  private volatile ProxyInfo<T> successfulProxy = null;
-  private volatile String toIgnore = null;
-
-  public RequestHedgingProxyProvider(
-          Configuration conf, URI uri, Class<T> xface) {
-    this(conf, uri, xface, new DefaultProxyFactory<T>());
-  }
-
-  @VisibleForTesting
-  RequestHedgingProxyProvider(Configuration conf, URI uri,
-                              Class<T> xface, ProxyFactory<T> factory) {
-    super(conf, uri, xface, factory);
-  }
-
-  @SuppressWarnings("unchecked")
-  @Override
-  public synchronized ProxyInfo<T> getProxy() {
-    if (successfulProxy != null) {
-      return successfulProxy;
-    }
-    Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>();
-    StringBuilder combinedInfo = new StringBuilder("[");
-    for (int i = 0; i < proxies.size(); i++) {
-      ProxyInfo<T> pInfo = super.getProxy();
-      incrementProxyIndex();
-      targetProxyInfos.put(pInfo.proxyInfo, pInfo);
-      combinedInfo.append(pInfo.proxyInfo).append(',');
-    }
-    combinedInfo.append(']');
-    T wrappedProxy = (T) Proxy.newProxyInstance(
-            RequestHedgingInvocationHandler.class.getClassLoader(),
-            new Class<?>[]{xface},
-            new RequestHedgingInvocationHandler(targetProxyInfos));
-    return new ProxyInfo<T>(wrappedProxy, combinedInfo.toString());
-  }
-
-  @Override
-  public synchronized void performFailover(T currentProxy) {
-    toIgnore = successfulProxy.proxyInfo;
-    successfulProxy = null;
-  }
-
-  /**
-   * Check the exception returned by the proxy log a warning message if it's
-   * not a StandbyException (expected exception).
-   * @param ex Exception to evaluate.
-   * @param proxyInfo Information of the proxy reporting the exception.
-   */
-  private void logProxyException(Exception ex, String proxyInfo) {
-    if (isStandbyException(ex)) {
-      LOG.debug("Invocation returned standby exception on [{}]", proxyInfo);
-    } else {
-      LOG.warn("Invocation returned exception on [{}]", proxyInfo);
-    }
-  }
-
-  /**
-   * Check if the returned exception is caused by an standby namenode.
-   * @param ex Exception to check.
-   * @return If the exception is caused by an standby namenode.
-   */
-  private boolean isStandbyException(Exception ex) {
-    Exception exception = unwrapException(ex);
-    if (exception instanceof RemoteException) {
-      return ((RemoteException) exception).unwrapRemoteException()
-          instanceof StandbyException;
-    }
-    return false;
-  }
-
-  /**
-   * Unwraps the exception. <p>
-   * Example:
-   * <blockquote><pre>
-   * if ex is
-   * ExecutionException(InvocationTargetExeption(SomeException))
-   * returns SomeException
-   * </pre></blockquote>
-   *
-   * @return unwrapped exception
-   */
-  private Exception unwrapException(Exception ex) {
-    if (ex != null) {
-      Throwable cause = ex.getCause();
-      if (cause instanceof Exception) {
-        Throwable innerCause = cause.getCause();
-        if (innerCause instanceof Exception) {
-          return (Exception) innerCause;
-        }
-        return (Exception) cause;
-      }
-    }
-    return ex;
-  }
-}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientFailover.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientFailover.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientFailover.java
index 7e8621b..6265f44 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientFailover.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSClientFailover.java
@@ -42,10 +42,10 @@ import org.apache.hadoop.fs.FileContext;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
-import org.apache.hadoop.hdfs.server.namenode.NameNode;
 import org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider;
 import org.apache.hadoop.hdfs.server.namenode.ha.HATestUtil;
 import org.apache.hadoop.hdfs.server.namenode.ha.IPFailoverProxyProvider;
+import org.apache.hadoop.hdfs.server.namenode.ha.HAProxyFactory;
 import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.io.retry.FailoverProxyProvider;
@@ -333,7 +333,7 @@ public class TestDFSClientFailover {
     private Class<T> xface;
     private T proxy;
     public DummyLegacyFailoverProxyProvider(Configuration conf, URI uri,
-        Class<T> xface) {
+        Class<T> xface, HAProxyFactory<T> proxyFactory) {
       try {
         this.proxy = NameNodeProxies.createNonHAProxy(conf,
             DFSUtilClient.getNNAddress(uri), xface,

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUtil.java
index 7257bbd..14ad6dd 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUtil.java
@@ -513,7 +513,7 @@ public class TestDFSUtil {
         NS2_NN2_HOST);
     
     Map<String, Map<String, InetSocketAddress>> map =
-      DFSUtil.getHaNnRpcAddresses(conf);
+        DFSUtilClient.getHaNnRpcAddresses(conf);
 
     assertTrue(HAUtil.isHAEnabled(conf, "ns1"));
     assertTrue(HAUtil.isHAEnabled(conf, "ns2"));

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java
index 632bbf6..ca44c79 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestDelegationTokensWithHA.java
@@ -292,7 +292,7 @@ public class TestDelegationTokensWithHA {
       nn0.getNameNodeAddress().getPort()));
     nnAddrs.add(new InetSocketAddress("localhost",
       nn1.getNameNodeAddress().getPort()));
-    HAUtil.cloneDelegationTokenForLogicalUri(ugi, haUri, nnAddrs);
+    HAUtilClient.cloneDelegationTokenForLogicalUri(ugi, haUri, nnAddrs);
     
     Collection<Token<? extends TokenIdentifier>> tokens = ugi.getTokens();
     assertEquals(3, tokens.size());
@@ -321,7 +321,7 @@ public class TestDelegationTokensWithHA {
     }
     
     // reclone the tokens, and see if they match now
-    HAUtil.cloneDelegationTokenForLogicalUri(ugi, haUri, nnAddrs);
+    HAUtilClient.cloneDelegationTokenForLogicalUri(ugi, haUri, nnAddrs);
     for (InetSocketAddress addr : nnAddrs) {
       Text ipcDtService = SecurityUtil.buildTokenService(addr);
       Token<DelegationTokenIdentifier> token2 =

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
deleted file mode 100644
index 37532d5..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
+++ /dev/null
@@ -1,470 +0,0 @@
-/**
- * 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.namenode.ha;
-
-import java.io.EOFException;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.ConnectException;
-import java.net.InetSocketAddress;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Iterator;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hdfs.DFSConfigKeys;
-import org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider.ProxyFactory;
-import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
-import org.apache.hadoop.io.retry.MultiException;
-import org.apache.hadoop.ipc.RemoteException;
-import org.apache.hadoop.ipc.StandbyException;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.test.GenericTestUtils;
-import org.apache.hadoop.util.Time;
-import org.apache.log4j.Level;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Matchers;
-import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import com.google.common.collect.Lists;
-
-public class TestRequestHedgingProxyProvider {
-
-  private Configuration conf;
-  private URI nnUri;
-  private String ns;
-
-  @BeforeClass
-  public static void setupClass() throws Exception {
-    GenericTestUtils.setLogLevel(RequestHedgingProxyProvider.LOG, Level.TRACE);
-  }
-
-  @Before
-  public void setup() throws URISyntaxException {
-    ns = "mycluster-" + Time.monotonicNow();
-    nnUri = new URI("hdfs://" + ns);
-    conf = new Configuration();
-    conf.set(DFSConfigKeys.DFS_NAMESERVICES, ns);
-    conf.set(
-        DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + ns, "nn1,nn2");
-    conf.set(
-        DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn1",
-        "machine1.foo.bar:9820");
-    conf.set(
-        DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn2",
-        "machine2.foo.bar:9820");
-  }
-
-  @Test
-  public void testHedgingWhenOneFails() throws Exception {
-    final NamenodeProtocols goodMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        Thread.sleep(1000);
-        return new long[]{1};
-      }
-    });
-    final NamenodeProtocols badMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri, NamenodeProtocols.class,
-            createFactory(badMock, goodMock));
-    long[] stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Mockito.verify(badMock).getStats();
-    Mockito.verify(goodMock).getStats();
-  }
-
-  @Test
-  public void testHedgingWhenOneIsSlow() throws Exception {
-    final NamenodeProtocols goodMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        Thread.sleep(1000);
-        return new long[]{1};
-      }
-    });
-    final NamenodeProtocols badMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri, NamenodeProtocols.class,
-            createFactory(goodMock, badMock));
-    long[] stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(1, stats[0]);
-    Mockito.verify(badMock).getStats();
-    Mockito.verify(goodMock).getStats();
-  }
-
-  @Test
-  public void testHedgingWhenBothFail() throws Exception {
-    NamenodeProtocols badMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
-    NamenodeProtocols worseMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(worseMock.getStats()).thenThrow(
-            new IOException("Worse mock !!"));
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri, NamenodeProtocols.class,
-            createFactory(badMock, worseMock));
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since both namenodes throw IOException !!");
-    } catch (Exception e) {
-      Assert.assertTrue(e instanceof MultiException);
-    }
-    Mockito.verify(badMock).getStats();
-    Mockito.verify(worseMock).getStats();
-  }
-
-  @Test
-  public void testPerformFailover() throws Exception {
-    final AtomicInteger counter = new AtomicInteger(0);
-    final int[] isGood = {1};
-    final NamenodeProtocols goodMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        counter.incrementAndGet();
-        if (isGood[0] == 1) {
-          Thread.sleep(1000);
-          return new long[]{1};
-        }
-        throw new IOException("Was Good mock !!");
-      }
-    });
-    final NamenodeProtocols badMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(badMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        counter.incrementAndGet();
-        if (isGood[0] == 2) {
-          Thread.sleep(1000);
-          return new long[]{2};
-        }
-        throw new IOException("Bad mock !!");
-      }
-    });
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-            new RequestHedgingProxyProvider<>(conf, nnUri, NamenodeProtocols.class,
-                    createFactory(goodMock, badMock));
-    long[] stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(1, stats[0]);
-    Assert.assertEquals(2, counter.get());
-    Mockito.verify(badMock).getStats();
-    Mockito.verify(goodMock).getStats();
-
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(1, stats[0]);
-    // Ensure only the previous successful one is invoked
-    Mockito.verifyNoMoreInteractions(badMock);
-    Assert.assertEquals(3, counter.get());
-
-    // Flip to standby.. so now this should fail
-    isGood[0] = 2;
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since previously successful proxy now fails ");
-    } catch (Exception ex) {
-      Assert.assertTrue(ex instanceof IOException);
-    }
-
-    Assert.assertEquals(4, counter.get());
-
-    provider.performFailover(provider.getProxy().proxy);
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(2, stats[0]);
-
-    // Counter should update only once
-    Assert.assertEquals(5, counter.get());
-
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(2, stats[0]);
-
-    // Counter updates only once now
-    Assert.assertEquals(6, counter.get());
-
-    // Flip back to old active.. so now this should fail
-    isGood[0] = 1;
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since previously successful proxy now fails ");
-    } catch (Exception ex) {
-      Assert.assertTrue(ex instanceof IOException);
-    }
-
-    Assert.assertEquals(7, counter.get());
-
-    provider.performFailover(provider.getProxy().proxy);
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    // Ensure correct proxy was called
-    Assert.assertEquals(1, stats[0]);
-  }
-
-  @Test
-  public void testPerformFailoverWith3Proxies() throws Exception {
-    conf.set(DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + ns,
-            "nn1,nn2,nn3");
-    conf.set(DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn3",
-            "machine3.foo.bar:9820");
-
-    final AtomicInteger counter = new AtomicInteger(0);
-    final int[] isGood = {1};
-    final NamenodeProtocols goodMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        counter.incrementAndGet();
-        if (isGood[0] == 1) {
-          Thread.sleep(1000);
-          return new long[]{1};
-        }
-        throw new IOException("Was Good mock !!");
-      }
-    });
-    final NamenodeProtocols badMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(badMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        counter.incrementAndGet();
-        if (isGood[0] == 2) {
-          Thread.sleep(1000);
-          return new long[]{2};
-        }
-        throw new IOException("Bad mock !!");
-      }
-    });
-    final NamenodeProtocols worseMock = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(worseMock.getStats()).thenAnswer(new Answer<long[]>() {
-      @Override
-      public long[] answer(InvocationOnMock invocation) throws Throwable {
-        counter.incrementAndGet();
-        if (isGood[0] == 3) {
-          Thread.sleep(1000);
-          return new long[]{3};
-        }
-        throw new IOException("Worse mock !!");
-      }
-    });
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-            new RequestHedgingProxyProvider<>(conf, nnUri, NamenodeProtocols.class,
-                    createFactory(goodMock, badMock, worseMock));
-    long[] stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(1, stats[0]);
-    Assert.assertEquals(3, counter.get());
-    Mockito.verify(badMock).getStats();
-    Mockito.verify(goodMock).getStats();
-    Mockito.verify(worseMock).getStats();
-
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(1, stats[0]);
-    // Ensure only the previous successful one is invoked
-    Mockito.verifyNoMoreInteractions(badMock);
-    Mockito.verifyNoMoreInteractions(worseMock);
-    Assert.assertEquals(4, counter.get());
-
-    // Flip to standby.. so now this should fail
-    isGood[0] = 2;
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since previously successful proxy now fails ");
-    } catch (Exception ex) {
-      Assert.assertTrue(ex instanceof IOException);
-    }
-
-    Assert.assertEquals(5, counter.get());
-
-    provider.performFailover(provider.getProxy().proxy);
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(2, stats[0]);
-
-    // Counter updates twice since both proxies are tried on failure
-    Assert.assertEquals(7, counter.get());
-
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(2, stats[0]);
-
-    // Counter updates only once now
-    Assert.assertEquals(8, counter.get());
-
-    // Flip to Other standby.. so now this should fail
-    isGood[0] = 3;
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since previously successful proxy now fails ");
-    } catch (Exception ex) {
-      Assert.assertTrue(ex instanceof IOException);
-    }
-
-    // Counter should ipdate only 1 time
-    Assert.assertEquals(9, counter.get());
-
-    provider.performFailover(provider.getProxy().proxy);
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-
-    // Ensure correct proxy was called
-    Assert.assertEquals(3, stats[0]);
-
-    // Counter updates twice since both proxies are tried on failure
-    Assert.assertEquals(11, counter.get());
-
-    stats = provider.getProxy().proxy.getStats();
-    Assert.assertTrue(stats.length == 1);
-    Assert.assertEquals(3, stats[0]);
-
-    // Counter updates only once now
-    Assert.assertEquals(12, counter.get());
-  }
-
-  @Test
-  public void testHedgingWhenFileNotFoundException() throws Exception {
-    NamenodeProtocols active = Mockito.mock(NamenodeProtocols.class);
-    Mockito
-        .when(active.getBlockLocations(Matchers.anyString(),
-            Matchers.anyLong(), Matchers.anyLong()))
-        .thenThrow(new RemoteException("java.io.FileNotFoundException",
-            "File does not exist!"));
-
-    NamenodeProtocols standby = Mockito.mock(NamenodeProtocols.class);
-    Mockito
-        .when(standby.getBlockLocations(Matchers.anyString(),
-            Matchers.anyLong(), Matchers.anyLong()))
-        .thenThrow(
-            new RemoteException("org.apache.hadoop.ipc.StandbyException",
-            "Standby NameNode"));
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri,
-            NamenodeProtocols.class, createFactory(active, standby));
-    try {
-      provider.getProxy().proxy.getBlockLocations("/tmp/test.file", 0L, 20L);
-      Assert.fail("Should fail since the active namenode throws"
-          + " FileNotFoundException!");
-    } catch (MultiException me) {
-      for (Exception ex : me.getExceptions().values()) {
-        Exception rEx = ((RemoteException) ex).unwrapRemoteException();
-        if (rEx instanceof StandbyException) {
-          continue;
-        }
-        Assert.assertTrue(rEx instanceof FileNotFoundException);
-      }
-    }
-    Mockito.verify(active).getBlockLocations(Matchers.anyString(),
-        Matchers.anyLong(), Matchers.anyLong());
-    Mockito.verify(standby).getBlockLocations(Matchers.anyString(),
-        Matchers.anyLong(), Matchers.anyLong());
-  }
-
-  @Test
-  public void testHedgingWhenConnectException() throws Exception {
-    NamenodeProtocols active = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(active.getStats()).thenThrow(new ConnectException());
-
-    NamenodeProtocols standby = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(standby.getStats())
-        .thenThrow(
-            new RemoteException("org.apache.hadoop.ipc.StandbyException",
-            "Standby NameNode"));
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri,
-            NamenodeProtocols.class, createFactory(active, standby));
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since the active namenode throws"
-          + " ConnectException!");
-    } catch (MultiException me) {
-      for (Exception ex : me.getExceptions().values()) {
-        if (ex instanceof RemoteException) {
-          Exception rEx = ((RemoteException) ex)
-              .unwrapRemoteException();
-          Assert.assertTrue("Unexpected RemoteException: " + rEx.getMessage(),
-              rEx instanceof StandbyException);
-        } else {
-          Assert.assertTrue(ex instanceof ConnectException);
-        }
-      }
-    }
-    Mockito.verify(active).getStats();
-    Mockito.verify(standby).getStats();
-  }
-
-  @Test
-  public void testHedgingWhenConnectAndEOFException() throws Exception {
-    NamenodeProtocols active = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(active.getStats()).thenThrow(new EOFException());
-
-    NamenodeProtocols standby = Mockito.mock(NamenodeProtocols.class);
-    Mockito.when(standby.getStats()).thenThrow(new ConnectException());
-
-    RequestHedgingProxyProvider<NamenodeProtocols> provider =
-        new RequestHedgingProxyProvider<>(conf, nnUri,
-            NamenodeProtocols.class, createFactory(active, standby));
-    try {
-      provider.getProxy().proxy.getStats();
-      Assert.fail("Should fail since both active and standby namenodes throw"
-          + " Exceptions!");
-    } catch (MultiException me) {
-      for (Exception ex : me.getExceptions().values()) {
-        if (!(ex instanceof ConnectException) &&
-            !(ex instanceof EOFException)) {
-          Assert.fail("Unexpected Exception " + ex.getMessage());
-        }
-      }
-    }
-    Mockito.verify(active).getStats();
-    Mockito.verify(standby).getStats();
-  }
-
-  private ProxyFactory<NamenodeProtocols> createFactory(
-      NamenodeProtocols... protos) {
-    final Iterator<NamenodeProtocols> iterator =
-        Lists.newArrayList(protos).iterator();
-    return new ProxyFactory<NamenodeProtocols>() {
-      @Override
-      public NamenodeProtocols createProxy(Configuration conf,
-          InetSocketAddress nnAddr, Class<NamenodeProtocols> xface,
-          UserGroupInformation ugi, boolean withRetries,
-          AtomicBoolean fallbackToSimpleAuth) throws IOException {
-        return iterator.next();
-      }
-    };
-  }
-}


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[34/50] [abbrv] hadoop git commit: YARN-6437. TestSignalContainer#testSignalRequestDeliveryToNM fails intermittently (Jason Lowe via Varun Saxena)

Posted by in...@apache.org.
YARN-6437. TestSignalContainer#testSignalRequestDeliveryToNM fails intermittently (Jason Lowe via Varun Saxena)


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

Branch: refs/heads/HDFS-10467
Commit: 04ef448c270016920d71f589a0591628d267ab05
Parents: 5528527
Author: Varun Saxena <va...@apache.org>
Authored: Thu Apr 6 01:20:41 2017 +0530
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../server/resourcemanager/TestSignalContainer.java    | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/04ef448c/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestSignalContainer.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/TestSignalContainer.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestSignalContainer.java
index 692924c..2688987 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestSignalContainer.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestSignalContainer.java
@@ -69,18 +69,17 @@ public class TestSignalContainer {
 
     //kick the scheduler
     nm1.nodeHeartbeat(true);
-    List<Container> conts = null;
-    int contReceived = 0;
+    List<Container> conts = new ArrayList<>(request);
     int waitCount = 0;
-    while (contReceived < request && waitCount++ < 200) {
-      LOG.info("Got " + contReceived + " containers. Waiting to get "
+    while (conts.size() < request && waitCount++ < 200) {
+      LOG.info("Got " + conts.size() + " containers. Waiting to get "
            + request);
       Thread.sleep(100);
-      conts = am.allocate(new ArrayList<ResourceRequest>(),
+      List<Container> allocation = am.allocate(new ArrayList<ResourceRequest>(),
           new ArrayList<ContainerId>()).getAllocatedContainers();
-      contReceived += conts.size();
+      conts.addAll(allocation);
     }
-    Assert.assertEquals(request, contReceived);
+    Assert.assertEquals(request, conts.size());
 
     for(Container container : conts) {
       rm.signalToContainer(container.getId(),


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[18/50] [abbrv] hadoop git commit: HADOOP-14272. Azure: WasbRemoteCallHelper should use String equals for comparison. Contributed by Santhosh G Nayak

Posted by in...@apache.org.
HADOOP-14272. Azure: WasbRemoteCallHelper should use String equals for comparison. Contributed by Santhosh G Nayak


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

Branch: refs/heads/HDFS-10467
Commit: c5e97cfe656815bd5be50e19b8eec60f4dc6eaa9
Parents: 53a513f
Author: Mingliang Liu <li...@apache.org>
Authored: Tue Apr 4 11:03:59 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java     | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/c5e97cfe/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java
index 09ea084..b43e5ae 100644
--- a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java
+++ b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/WasbRemoteCallHelper.java
@@ -88,7 +88,8 @@ class WasbRemoteCallHelper {
       }
 
       Header contentTypeHeader = response.getFirstHeader("Content-Type");
-      if (contentTypeHeader == null || contentTypeHeader.getValue() != APPLICATION_JSON) {
+      if (contentTypeHeader == null
+          || !APPLICATION_JSON.equals(contentTypeHeader.getValue())) {
         throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" +
             "Content-Type mismatch: expected: " + APPLICATION_JSON +
             ", got " + ((contentTypeHeader!=null) ? contentTypeHeader.getValue() : "NULL")


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[40/50] [abbrv] hadoop git commit: HDFS-11608. HDFS write crashed with block size greater than 2 GB. Contributed by Xiaobing Zhou.

Posted by in...@apache.org.
HDFS-11608. HDFS write crashed with block size greater than 2 GB. Contributed by Xiaobing Zhou.


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

Branch: refs/heads/HDFS-10467
Commit: 60c3edad54703b8cfb4c03e297494750e226af3b
Parents: 7c477f2
Author: Xiaoyu Yao <xy...@apache.org>
Authored: Thu Apr 6 16:11:55 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSOutputStream.java |  39 +++++-
 .../protocol/datatransfer/PacketReceiver.java   |   2 +-
 .../apache/hadoop/hdfs/TestDFSOutputStream.java | 126 +++++++++++++++++++
 3 files changed, 164 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/60c3edad/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
index e4929e1..9a52fbe 100755
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSOutputStream.java
@@ -50,6 +50,7 @@ import org.apache.hadoop.hdfs.protocol.QuotaByStorageTypeExceededException;
 import org.apache.hadoop.hdfs.protocol.SnapshotAccessControlException;
 import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
 import org.apache.hadoop.hdfs.protocol.datatransfer.PacketHeader;
+import org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver;
 import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
 import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
 import org.apache.hadoop.hdfs.server.namenode.NotReplicatedYetException;
@@ -122,6 +123,7 @@ public class DFSOutputStream extends FSOutputSummer
   private final EnumSet<AddBlockFlag> addBlockFlags;
   protected final AtomicReference<CachingStrategy> cachingStrategy;
   private FileEncryptionInfo fileEncryptionInfo;
+  private int writePacketSize;
 
   /** Use {@link ByteArrayManager} to create buffer for non-heartbeat packets.*/
   protected DFSPacket createPacket(int packetSize, int chunksPerPkt,
@@ -202,6 +204,8 @@ public class DFSOutputStream extends FSOutputSummer
           +"{}", src);
     }
 
+    initWritePacketSize();
+
     this.bytesPerChecksum = checksum.getBytesPerChecksum();
     if (bytesPerChecksum <= 0) {
       throw new HadoopIllegalArgumentException(
@@ -216,6 +220,21 @@ public class DFSOutputStream extends FSOutputSummer
     this.byteArrayManager = dfsClient.getClientContext().getByteArrayManager();
   }
 
+  /**
+   * Ensures the configured writePacketSize never exceeds
+   * PacketReceiver.MAX_PACKET_SIZE.
+   */
+  private void initWritePacketSize() {
+    writePacketSize = dfsClient.getConf().getWritePacketSize();
+    if (writePacketSize > PacketReceiver.MAX_PACKET_SIZE) {
+      LOG.warn(
+          "Configured write packet exceeds {} bytes as max,"
+              + " using {} bytes.",
+          PacketReceiver.MAX_PACKET_SIZE, PacketReceiver.MAX_PACKET_SIZE);
+      writePacketSize = PacketReceiver.MAX_PACKET_SIZE;
+    }
+  }
+
   /** Construct a new output stream for creating a file. */
   protected DFSOutputStream(DFSClient dfsClient, String src,
       HdfsFileStatus stat, EnumSet<CreateFlag> flag, Progressable progress,
@@ -489,13 +508,29 @@ public class DFSOutputStream extends FSOutputSummer
     }
 
     if (!getStreamer().getAppendChunk()) {
-      int psize = Math.min((int)(blockSize- getStreamer().getBytesCurBlock()),
-          dfsClient.getConf().getWritePacketSize());
+      final int psize = (int) Math
+          .min(blockSize - getStreamer().getBytesCurBlock(), writePacketSize);
       computePacketChunkSize(psize, bytesPerChecksum);
     }
   }
 
   /**
+   * Used in test only.
+   */
+  @VisibleForTesting
+  void setAppendChunk(final boolean appendChunk) {
+    getStreamer().setAppendChunk(appendChunk);
+  }
+
+  /**
+   * Used in test only.
+   */
+  @VisibleForTesting
+  void setBytesCurBlock(final long bytesCurBlock) {
+    getStreamer().setBytesCurBlock(bytesCurBlock);
+  }
+
+  /**
    * if encountering a block boundary, send an empty packet to
    * indicate the end of block and reset bytesCurBlock.
    *

http://git-wip-us.apache.org/repos/asf/hadoop/blob/60c3edad/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketReceiver.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketReceiver.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketReceiver.java
index 93e9217..6b717ec 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketReceiver.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketReceiver.java
@@ -45,7 +45,7 @@ public class PacketReceiver implements Closeable {
    * The max size of any single packet. This prevents OOMEs when
    * invalid data is sent.
    */
-  private static final int MAX_PACKET_SIZE = 16 * 1024 * 1024;
+  public static final int MAX_PACKET_SIZE = 16 * 1024 * 1024;
 
   static final Logger LOG = LoggerFactory.getLogger(PacketReceiver.class);
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/60c3edad/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSOutputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSOutputStream.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSOutputStream.java
index 9ec01b6..52e3bb4 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSOutputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSOutputStream.java
@@ -18,8 +18,10 @@
 package org.apache.hadoop.hdfs;
 
 import java.io.DataOutputStream;
+import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.EnumSet;
@@ -41,10 +43,13 @@ import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
 import org.apache.hadoop.hdfs.protocol.HdfsConstants;
 import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
 import org.apache.hadoop.hdfs.protocol.datatransfer.BlockConstructionStage;
+import org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver;
 import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
 import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
 import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
+import org.apache.hadoop.test.GenericTestUtils;
+import org.apache.hadoop.test.PathUtils;
 import org.apache.htrace.core.SpanId;
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -64,6 +69,9 @@ import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;
+
 public class TestDFSOutputStream {
   static MiniDFSCluster cluster;
 
@@ -133,6 +141,124 @@ public class TestDFSOutputStream {
     Assert.assertTrue((Integer) field.get(dos) + 257 < packetSize);
   }
 
+  /**
+   * This tests preventing overflows of package size and bodySize.
+   * <p>
+   * See also https://issues.apache.org/jira/browse/HDFS-11608.
+   * </p>
+   * @throws IOException
+   * @throws SecurityException
+   * @throws NoSuchFieldException
+   * @throws InvocationTargetException
+   * @throws IllegalArgumentException
+   * @throws IllegalAccessException
+   * @throws NoSuchMethodException
+   */
+  @Test(timeout=60000)
+  public void testPreventOverflow() throws IOException, NoSuchFieldException,
+      SecurityException, IllegalAccessException, IllegalArgumentException,
+      InvocationTargetException, NoSuchMethodException {
+
+    final int defaultWritePacketSize = DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
+    int configuredWritePacketSize = defaultWritePacketSize;
+    int finalWritePacketSize = defaultWritePacketSize;
+
+    /* test default WritePacketSize, e.g. 64*1024 */
+    runAdjustChunkBoundary(configuredWritePacketSize, finalWritePacketSize);
+
+    /* test large WritePacketSize, e.g. 1G */
+    configuredWritePacketSize = 1000 * 1024 * 1024;
+    finalWritePacketSize = PacketReceiver.MAX_PACKET_SIZE;
+    runAdjustChunkBoundary(configuredWritePacketSize, finalWritePacketSize);
+  }
+
+  /**
+   * @configuredWritePacketSize the configured WritePacketSize.
+   * @finalWritePacketSize the final WritePacketSize picked by
+   *                       {@link DFSOutputStream#adjustChunkBoundary}
+   */
+  private void runAdjustChunkBoundary(
+      final int configuredWritePacketSize,
+      final int finalWritePacketSize) throws IOException, NoSuchFieldException,
+      SecurityException, IllegalAccessException, IllegalArgumentException,
+      InvocationTargetException, NoSuchMethodException {
+
+    final boolean appendChunk = false;
+    final long blockSize = 3221225500L;
+    final long bytesCurBlock = 1073741824L;
+    final int bytesPerChecksum = 512;
+    final int checksumSize = 4;
+    final int chunkSize = bytesPerChecksum + checksumSize;
+    final int packateMaxHeaderLength = 33;
+
+    MiniDFSCluster dfsCluster = null;
+    final File baseDir = new File(PathUtils.getTestDir(getClass()),
+        GenericTestUtils.getMethodName());
+
+    try {
+      final Configuration dfsConf = new Configuration();
+      dfsConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR,
+          baseDir.getAbsolutePath());
+      dfsConf.setInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
+          configuredWritePacketSize);
+      dfsCluster = new MiniDFSCluster.Builder(dfsConf).numDataNodes(1).build();
+      dfsCluster.waitActive();
+
+      final FSDataOutputStream os = dfsCluster.getFileSystem()
+          .create(new Path(baseDir.getAbsolutePath(), "testPreventOverflow"));
+      final DFSOutputStream dos = (DFSOutputStream) Whitebox
+          .getInternalState(os, "wrappedStream");
+
+      /* set appendChunk */
+      final Method setAppendChunkMethod = dos.getClass()
+          .getDeclaredMethod("setAppendChunk", boolean.class);
+      setAppendChunkMethod.setAccessible(true);
+      setAppendChunkMethod.invoke(dos, appendChunk);
+
+      /* set bytesCurBlock */
+      final Method setBytesCurBlockMethod = dos.getClass()
+          .getDeclaredMethod("setBytesCurBlock", long.class);
+      setBytesCurBlockMethod.setAccessible(true);
+      setBytesCurBlockMethod.invoke(dos, bytesCurBlock);
+
+      /* set blockSize */
+      final Field blockSizeField = dos.getClass().getDeclaredField("blockSize");
+      blockSizeField.setAccessible(true);
+      blockSizeField.setLong(dos, blockSize);
+
+      /* call adjustChunkBoundary */
+      final Method method = dos.getClass()
+          .getDeclaredMethod("adjustChunkBoundary");
+      method.setAccessible(true);
+      method.invoke(dos);
+
+      /* get and verify writePacketSize */
+      final Field writePacketSizeField = dos.getClass()
+          .getDeclaredField("writePacketSize");
+      writePacketSizeField.setAccessible(true);
+      Assert.assertEquals(writePacketSizeField.getInt(dos),
+          finalWritePacketSize);
+
+      /* get and verify chunksPerPacket */
+      final Field chunksPerPacketField = dos.getClass()
+          .getDeclaredField("chunksPerPacket");
+      chunksPerPacketField.setAccessible(true);
+      Assert.assertEquals(chunksPerPacketField.getInt(dos),
+          (finalWritePacketSize - packateMaxHeaderLength) / chunkSize);
+
+      /* get and verify packetSize */
+      final Field packetSizeField = dos.getClass()
+          .getDeclaredField("packetSize");
+      packetSizeField.setAccessible(true);
+      Assert.assertEquals(packetSizeField.getInt(dos),
+          chunksPerPacketField.getInt(dos) * chunkSize);
+    } finally {
+      if (dfsCluster != null) {
+        dfsCluster.shutdown();
+      }
+    }
+  }
+
   @Test
   public void testCongestionBackoff() throws IOException {
     DfsClientConf dfsClientConf = mock(DfsClientConf.class);


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[02/50] [abbrv] hadoop git commit: HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen, Rosie Li.

Posted by in...@apache.org.
HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen, Rosie Li.


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

Branch: refs/heads/HDFS-10467
Commit: 20e57a9afbd71c50699864c1dc2a7620b448c924
Parents: 0ca98cb
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Thu Mar 30 17:01:15 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:19 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSTestUtil.java     |  22 +-
 .../org/apache/hadoop/tools/CopyListing.java    |  37 +-
 .../hadoop/tools/CopyListingFileStatus.java     |  87 ++++-
 .../java/org/apache/hadoop/tools/DistCp.java    |  52 +++
 .../apache/hadoop/tools/DistCpOptionSwitch.java |  10 +
 .../org/apache/hadoop/tools/DistCpOptions.java  |  22 +-
 .../org/apache/hadoop/tools/OptionsParser.java  |  36 +-
 .../apache/hadoop/tools/SimpleCopyListing.java  |  83 +++--
 .../hadoop/tools/mapred/CopyCommitter.java      | 174 ++++++++-
 .../apache/hadoop/tools/mapred/CopyMapper.java  |  40 +-
 .../tools/mapred/RetriableFileCopyCommand.java  |  26 +-
 .../tools/mapred/UniformSizeInputFormat.java    |   5 +-
 .../apache/hadoop/tools/util/DistCpUtils.java   | 111 +++++-
 .../src/site/markdown/DistCp.md.vm              |   1 +
 .../apache/hadoop/tools/TestDistCpSystem.java   | 368 +++++++++++++++++--
 .../apache/hadoop/tools/TestOptionsParser.java  |   2 +-
 .../hadoop/tools/mapred/TestCopyCommitter.java  |   5 +-
 17 files changed, 971 insertions(+), 110 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
index 1329195..9b782f3 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
@@ -862,7 +862,27 @@ public class DFSTestUtil {
       out.write(toAppend);
     }
   }
-  
+
+  /**
+   * Append specified length of bytes to a given file, starting with new block.
+   * @param fs The file system
+   * @param p Path of the file to append
+   * @param length Length of bytes to append to the file
+   * @throws IOException
+   */
+  public static void appendFileNewBlock(DistributedFileSystem fs,
+      Path p, int length) throws IOException {
+    assert fs.exists(p);
+    assert length >= 0;
+    byte[] toAppend = new byte[length];
+    Random random = new Random();
+    random.nextBytes(toAppend);
+    try (FSDataOutputStream out = fs.append(p,
+        EnumSet.of(CreateFlag.APPEND, CreateFlag.NEW_BLOCK), 4096, null)) {
+      out.write(toAppend);
+    }
+  }
+
   /**
    * @return url content as string (UTF-8 encoding assumed)
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
index 481aa61..9ebf9d2 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
@@ -145,12 +145,22 @@ public abstract class CopyListing extends Configured {
     Configuration config = getConf();
     FileSystem fs = pathToListFile.getFileSystem(config);
 
-    Path sortedList = DistCpUtils.sortListing(fs, config, pathToListFile);
+    final boolean splitLargeFile = options.splitLargeFile();
+
+    // When splitLargeFile is enabled, we don't randomize the copylist
+    // earlier, so we don't do the sorting here. For a file that has
+    // multiple entries due to split, we check here that their
+    // <chunkOffset, chunkLength> is continuous.
+    //
+    Path checkPath = splitLargeFile?
+        pathToListFile : DistCpUtils.sortListing(fs, config, pathToListFile);
 
     SequenceFile.Reader reader = new SequenceFile.Reader(
-                          config, SequenceFile.Reader.file(sortedList));
+                          config, SequenceFile.Reader.file(checkPath));
     try {
       Text lastKey = new Text("*"); //source relative path can never hold *
+      long lastChunkOffset = -1;
+      long lastChunkLength = -1;
       CopyListingFileStatus lastFileStatus = new CopyListingFileStatus();
 
       Text currentKey = new Text();
@@ -161,8 +171,21 @@ public abstract class CopyListing extends Configured {
         if (currentKey.equals(lastKey)) {
           CopyListingFileStatus currentFileStatus = new CopyListingFileStatus();
           reader.getCurrentValue(currentFileStatus);
-          throw new DuplicateFileException("File " + lastFileStatus.getPath() + " and " +
-              currentFileStatus.getPath() + " would cause duplicates. Aborting");
+          if (!splitLargeFile) {
+            throw new DuplicateFileException("File " + lastFileStatus.getPath()
+                + " and " + currentFileStatus.getPath()
+                + " would cause duplicates. Aborting");
+          } else {
+            if (lastChunkOffset + lastChunkLength !=
+                currentFileStatus.getChunkOffset()) {
+              throw new InvalidInputException("File " + lastFileStatus.getPath()
+                  + " " + lastChunkOffset + "," + lastChunkLength
+                  + " and " + currentFileStatus.getPath()
+                  + " " + currentFileStatus.getChunkOffset() + ","
+                  + currentFileStatus.getChunkLength()
+                  + " are not continuous. Aborting");
+            }
+          }
         }
         reader.getCurrentValue(lastFileStatus);
         if (options.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
@@ -181,8 +204,12 @@ public abstract class CopyListing extends Configured {
             xAttrSupportCheckFsSet.add(lastFsUri);
           }
         }
-        lastKey.set(currentKey);
 
+        lastKey.set(currentKey);
+        if (splitLargeFile) {
+          lastChunkOffset = lastFileStatus.getChunkOffset();
+          lastChunkLength = lastFileStatus.getChunkLength();
+        }
         if (options.shouldUseDiff() && LOG.isDebugEnabled()) {
           LOG.debug("Copy list entry " + idx + ": " +
                   lastFileStatus.getPath().toUri().getPath());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
index 00d4b32..29c59ac 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
@@ -74,6 +74,14 @@ public final class CopyListingFileStatus implements Writable {
   private List<AclEntry> aclEntries;
   private Map<String, byte[]> xAttrs;
 
+  // <chunkOffset, chunkLength> represents the offset and length of a file
+  // chunk in number of bytes.
+  // used when splitting a large file to chunks to copy in parallel.
+  // If a file is not large enough to split, chunkOffset would be 0 and
+  // chunkLength would be the length of the file.
+  private long chunkOffset = 0;
+  private long chunkLength = Long.MAX_VALUE;
+
   /**
    * Default constructor.
    */
@@ -96,11 +104,32 @@ public final class CopyListingFileStatus implements Writable {
         fileStatus.getPath());
   }
 
+  public CopyListingFileStatus(FileStatus fileStatus,
+      long chunkOffset, long chunkLength) {
+    this(fileStatus.getLen(), fileStatus.isDirectory(),
+        fileStatus.getReplication(), fileStatus.getBlockSize(),
+        fileStatus.getModificationTime(), fileStatus.getAccessTime(),
+        fileStatus.getPermission(), fileStatus.getOwner(),
+        fileStatus.getGroup(),
+        fileStatus.getPath());
+    this.chunkOffset = chunkOffset;
+    this.chunkLength = chunkLength;
+  }
+
   @SuppressWarnings("checkstyle:parameternumber")
   public CopyListingFileStatus(long length, boolean isdir,
       int blockReplication, long blocksize, long modificationTime,
       long accessTime, FsPermission permission, String owner, String group,
       Path path) {
+    this(length, isdir, blockReplication, blocksize, modificationTime,
+        accessTime, permission, owner, group, path, 0, Long.MAX_VALUE);
+  }
+
+  @SuppressWarnings("checkstyle:parameternumber")
+  public CopyListingFileStatus(long length, boolean isdir,
+      int blockReplication, long blocksize, long modificationTime,
+      long accessTime, FsPermission permission, String owner, String group,
+      Path path, long chunkOffset, long chunkLength) {
     this.length = length;
     this.isdir = isdir;
     this.blockReplication = (short)blockReplication;
@@ -117,6 +146,23 @@ public final class CopyListingFileStatus implements Writable {
     this.owner = (owner == null) ? "" : owner;
     this.group = (group == null) ? "" : group;
     this.path = path;
+    this.chunkOffset = chunkOffset;
+    this.chunkLength = chunkLength;
+  }
+
+  public CopyListingFileStatus(CopyListingFileStatus other) {
+    this.length = other.length;
+    this.isdir = other.isdir;
+    this.blockReplication = other.blockReplication;
+    this.blocksize = other.blocksize;
+    this.modificationTime = other.modificationTime;
+    this.accessTime = other.accessTime;
+    this.permission = other.permission;
+    this.owner = other.owner;
+    this.group = other.group;
+    this.path = new Path(other.path.toUri());
+    this.chunkOffset = other.chunkOffset;
+    this.chunkLength = other.chunkLength;
   }
 
   public Path getPath() {
@@ -200,6 +246,31 @@ public final class CopyListingFileStatus implements Writable {
     this.xAttrs = xAttrs;
   }
 
+  public long getChunkOffset() {
+    return chunkOffset;
+  }
+
+  public void setChunkOffset(long offset) {
+    this.chunkOffset = offset;
+  }
+
+  public long getChunkLength() {
+    return chunkLength;
+  }
+
+  public void setChunkLength(long chunkLength) {
+    this.chunkLength = chunkLength;
+  }
+
+  public boolean isSplit() {
+    return getChunkLength() != Long.MAX_VALUE &&
+        getChunkLength() != getLen();
+  }
+
+  public long getSizeToCopy() {
+    return isSplit()? getChunkLength() : getLen();
+  }
+
   @Override
   public void write(DataOutput out) throws IOException {
     Text.writeString(out, getPath().toString(), Text.DEFAULT_MAX_LEN);
@@ -244,6 +315,9 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       out.writeInt(NO_XATTRS);
     }
+
+    out.writeLong(chunkOffset);
+    out.writeLong(chunkLength);
   }
 
   @Override
@@ -292,6 +366,9 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       xAttrs = null;
     }
+
+    chunkOffset = in.readLong();
+    chunkLength = in.readLong();
   }
 
   @Override
@@ -317,8 +394,14 @@ public final class CopyListingFileStatus implements Writable {
   public String toString() {
     StringBuilder sb = new StringBuilder(super.toString());
     sb.append('{');
-    sb.append("aclEntries = " + aclEntries);
-    sb.append(", xAttrs = " + xAttrs);
+    sb.append(this.getPath().toString());
+    sb.append(" length = ").append(this.getLen());
+    sb.append(" aclEntries = ").append(aclEntries);
+    sb.append(", xAttrs = ").append(xAttrs);
+    if (isSplit()) {
+      sb.append(", chunkOffset = ").append(this.getChunkOffset());
+      sb.append(", chunkLength = ").append(this.getChunkLength());
+    }
     sb.append('}');
     return sb.toString();
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
index ab58e9c..8c2fa24 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.mapreduce.Cluster;
 import org.apache.hadoop.mapreduce.Job;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobSubmissionFiles;
+import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.CopyListing.*;
 import org.apache.hadoop.tools.mapred.CopyMapper;
 import org.apache.hadoop.tools.mapred.CopyOutputFormat;
@@ -134,6 +135,7 @@ public class DistCp extends Configured implements Tool {
     
     try {
       inputOptions = (OptionsParser.parse(argv));
+      setOptionsForSplitLargeFile();
       setTargetPathExists();
       LOG.info("Input Options: " + inputOptions);
     } catch (Throwable e) {
@@ -235,6 +237,56 @@ public class DistCp extends Configured implements Tool {
     getConf().setBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, 
         targetExists);
   }
+
+  /**
+   * Check if concat is supported by fs.
+   * Throws UnsupportedOperationException if not.
+   */
+  private void checkConcatSupport(FileSystem fs) {
+    try {
+      Path[] src = null;
+      Path tgt = null;
+      fs.concat(tgt, src);
+    } catch (UnsupportedOperationException use) {
+      throw new UnsupportedOperationException(
+          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() +
+          " is not supported since the target file system doesn't" +
+          " support concat.", use);
+    } catch (Exception e) {
+      // Ignore other exception
+    }
+  }
+
+  /**
+   * Set up needed options for splitting large files.
+   */
+  private void setOptionsForSplitLargeFile() throws IOException {
+    if (!inputOptions.splitLargeFile()) {
+      return;
+    }
+    Path target = inputOptions.getTargetPath();
+    FileSystem targetFS = target.getFileSystem(getConf());
+    checkConcatSupport(targetFS);
+
+    LOG.info("Enabling preserving blocksize since "
+        + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " is passed.");
+    inputOptions.preserve(FileAttribute.BLOCKSIZE);
+
+    LOG.info("Set " +
+        DistCpOptionSwitch.APPEND.getSwitch()
+        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
+        + " is passed.");
+    inputOptions.setAppend(false);
+
+    LOG.info("Set " +
+        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES
+        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
+        + " is passed.");
+    getConf().setBoolean(
+        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES, false);
+  }
+
+
   /**
    * Create Job object for submitting it, with all the configuration
    *

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
index fb47d76..ced9b54 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
@@ -169,6 +169,16 @@ public enum DistCpOptionSwitch {
       new Option("sizelimit", true, "(Deprecated!) Limit number of files " +
               "copied to <= n bytes")),
 
+  BLOCKS_PER_CHUNK("",
+      new Option("blocksperchunk", true, "If set to a positive value, files"
+          + "with more blocks than this value will be split into chunks of "
+          + "<blocksperchunk> blocks to be transferred in parallel, and "
+          + "reassembled on the destination. By default, <blocksperchunk> is "
+          + "0 and the files will be transmitted in their entirety without "
+          + "splitting. This switch is only applicable when the source file "
+          + "system implements getBlockLocations method and the target file "
+          + "system implements concat method")),
+
   /**
    * Specify bandwidth per map in MB, accepts bandwidth as a fraction
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/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 8c37ff3..9822d83 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
@@ -97,7 +97,11 @@ public class DistCpOptions {
   // targetPathExist is a derived field, it's initialized in the
   // beginning of distcp.
   private boolean targetPathExists = true;
-  
+
+  // Size of chunk in number of blocks when splitting large file into chunks
+  // to copy in parallel. Default is 0 and file are not splitted.
+  private int blocksPerChunk = 0;
+
   public static enum FileAttribute{
     REPLICATION, BLOCKSIZE, USER, GROUP, PERMISSION, CHECKSUMTYPE, ACL, XATTR, TIMES;
 
@@ -166,6 +170,7 @@ public class DistCpOptions {
       this.targetPath = that.getTargetPath();
       this.targetPathExists = that.getTargetPathExists();
       this.filtersFile = that.getFiltersFile();
+      this.blocksPerChunk = that.blocksPerChunk;
     }
   }
 
@@ -578,6 +583,18 @@ public class DistCpOptions {
     this.filtersFile = filtersFilename;
   }
 
+  public final void setBlocksPerChunk(int csize) {
+    this.blocksPerChunk = csize;
+  }
+
+  public final int getBlocksPerChunk() {
+    return blocksPerChunk;
+  }
+
+  public final boolean splitLargeFile() {
+    return blocksPerChunk > 0;
+  }
+
   void validate() {
     if ((useDiff || useRdiff) && deleteMissing) {
       // -delete and -diff/-rdiff are mutually exclusive. For backward
@@ -669,6 +686,8 @@ public class DistCpOptions {
       DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.FILTERS,
           filtersFile);
     }
+    DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.BLOCKS_PER_CHUNK,
+        String.valueOf(blocksPerChunk));
   }
 
   /**
@@ -704,6 +723,7 @@ public class DistCpOptions {
         ", targetPath=" + targetPath +
         ", targetPathExists=" + targetPathExists +
         ", filtersFile='" + filtersFile + '\'' +
+        ", blocksPerChunk=" + blocksPerChunk +
         '}';
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
index d0f82ca..8881264 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
@@ -172,11 +172,44 @@ public class OptionsParser {
           DistCpOptionSwitch.FILTERS.getSwitch()));
     }
 
+    parseBlocksPerChunk(command, option);
+
     option.validate();
 
     return option;
   }
 
+
+  /**
+   * A helper method to parse chunk size in number of blocks.
+   * Used when breaking large file into chunks to copy in parallel.
+   *
+   * @param command command line arguments
+   */
+  private static void parseBlocksPerChunk(CommandLine command,
+      DistCpOptions option) {
+    boolean hasOption =
+        command.hasOption(DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch());
+    LOG.info("parseChunkSize: " +
+        DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " " + hasOption);
+    if (hasOption) {
+      String chunkSizeString = getVal(command,
+          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch().trim());
+      try {
+        int csize = Integer.parseInt(chunkSizeString);
+        if (csize < 0) {
+          csize = 0;
+        }
+        LOG.info("Set distcp blocksPerChunk to " + csize);
+        option.setBlocksPerChunk(csize);
+      }
+      catch (NumberFormatException e) {
+        throw new IllegalArgumentException("blocksPerChunk is invalid: "
+            + chunkSizeString, e);
+      }
+    }
+  }
+
   /**
    * parseSizeLimit is a helper method for parsing the deprecated
    * argument SIZE_LIMIT.
@@ -211,8 +244,7 @@ public class OptionsParser {
                               DistCpOptionSwitch.FILE_LIMIT.getSwitch().trim());
       try {
         Integer.parseInt(fileLimitString);
-      }
-      catch (NumberFormatException e) {
+      } catch (NumberFormatException e) {
         throw new IllegalArgumentException("File-limit is invalid: "
                                             + fileLimitString, e);
       }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
index 105e4f2..af91347 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
@@ -19,6 +19,7 @@
 package org.apache.hadoop.tools;
 
 import com.google.common.collect.Lists;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.Path;
@@ -47,6 +48,7 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Random;
+import java.util.LinkedList;
 
 import static org.apache.hadoop.tools.DistCpConstants
         .HDFS_RESERVED_RAW_DIRECTORY_NAME;
@@ -240,10 +242,10 @@ public class SimpleCopyListing extends CopyListing {
     final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
     final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
     final boolean preserveRawXAttrs = options.shouldPreserveRawXattrs();
-    CopyListingFileStatus fileCopyListingStatus =
+    LinkedList<CopyListingFileStatus> fileCopyListingStatus =
         DistCpUtils.toCopyListingFileStatus(sourceFS, fileStatus,
-            preserveAcls, preserveXAttrs, preserveRawXAttrs);
-
+            preserveAcls, preserveXAttrs, preserveRawXAttrs,
+            options.getBlocksPerChunk());
     writeToFileListingRoot(fileListWriter, fileCopyListingStatus,
         sourceRoot, options);
   }
@@ -348,9 +350,10 @@ public class SimpleCopyListing extends CopyListing {
         FileStatus[] sourceFiles = sourceFS.listStatus(path);
         boolean explore = (sourceFiles != null && sourceFiles.length > 0);
         if (!explore || rootStatus.isDirectory()) {
-          CopyListingFileStatus rootCopyListingStatus =
-            DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
-                preserveAcls, preserveXAttrs, preserveRawXAttrs);
+          LinkedList<CopyListingFileStatus> rootCopyListingStatus =
+              DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
+                  preserveAcls, preserveXAttrs, preserveRawXAttrs,
+                  options.getBlocksPerChunk());
           writeToFileListingRoot(fileListWriter, rootCopyListingStatus,
               sourcePathRoot, options);
         }
@@ -360,20 +363,20 @@ public class SimpleCopyListing extends CopyListing {
             if (LOG.isDebugEnabled()) {
               LOG.debug("Recording source-path: " + sourceStatus.getPath() + " for copy.");
             }
-            CopyListingFileStatus sourceCopyListingStatus =
-              DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
-                  preserveAcls && sourceStatus.isDirectory(),
-                  preserveXAttrs && sourceStatus.isDirectory(),
-                  preserveRawXAttrs && sourceStatus.isDirectory());
-            if (randomizeFileListing) {
-              addToFileListing(statusList,
-                  new FileStatusInfo(sourceCopyListingStatus, sourcePathRoot),
-                  fileListWriter);
-            } else {
-              writeToFileListing(fileListWriter, sourceCopyListingStatus,
-                  sourcePathRoot);
+            LinkedList<CopyListingFileStatus> sourceCopyListingStatus =
+                DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
+                    preserveAcls && sourceStatus.isDirectory(),
+                    preserveXAttrs && sourceStatus.isDirectory(),
+                    preserveRawXAttrs && sourceStatus.isDirectory(),
+                    options.getBlocksPerChunk());
+            for (CopyListingFileStatus fs : sourceCopyListingStatus) {
+              if (randomizeFileListing) {
+                addToFileListing(statusList,
+                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
+              } else {
+                writeToFileListing(fileListWriter, fs, sourcePathRoot);
+              }
             }
-
             if (sourceStatus.isDirectory()) {
               if (LOG.isDebugEnabled()) {
                 LOG.debug("Adding source dir for traverse: " + sourceStatus.getPath());
@@ -641,18 +644,20 @@ public class SimpleCopyListing extends CopyListing {
             LOG.debug("Recording source-path: " + child.getPath() + " for copy.");
           }
           if (workResult.getSuccess()) {
-            CopyListingFileStatus childCopyListingStatus =
+            LinkedList<CopyListingFileStatus> childCopyListingStatus =
               DistCpUtils.toCopyListingFileStatus(sourceFS, child,
                 preserveAcls && child.isDirectory(),
                 preserveXAttrs && child.isDirectory(),
-                preserveRawXattrs && child.isDirectory());
-            if (randomizeFileListing) {
-              addToFileListing(fileStatuses,
-                  new FileStatusInfo(childCopyListingStatus, sourcePathRoot),
-                  fileListWriter);
-            } else {
-              writeToFileListing(fileListWriter, childCopyListingStatus,
-                  sourcePathRoot);
+                preserveRawXattrs && child.isDirectory(),
+                options.getBlocksPerChunk());
+
+            for (CopyListingFileStatus fs : childCopyListingStatus) {
+              if (randomizeFileListing) {
+                addToFileListing(fileStatuses,
+                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
+              } else {
+                writeToFileListing(fileListWriter, fs, sourcePathRoot);
+              }
             }
           }
           if (retry < maxRetries) {
@@ -675,19 +680,21 @@ public class SimpleCopyListing extends CopyListing {
   }
 
   private void writeToFileListingRoot(SequenceFile.Writer fileListWriter,
-      CopyListingFileStatus fileStatus, Path sourcePathRoot,
+      LinkedList<CopyListingFileStatus> fileStatus, Path sourcePathRoot,
       DistCpOptions options) throws IOException {
     boolean syncOrOverwrite = options.shouldSyncFolder() ||
         options.shouldOverwrite();
-    if (fileStatus.getPath().equals(sourcePathRoot) && 
-        fileStatus.isDirectory() && syncOrOverwrite) {
-      // Skip the root-paths when syncOrOverwrite
-      if (LOG.isDebugEnabled()) {
-        LOG.debug("Skip " + fileStatus.getPath());
-      }      
-      return;
+    for (CopyListingFileStatus fs : fileStatus) {
+      if (fs.getPath().equals(sourcePathRoot) &&
+          fs.isDirectory() && syncOrOverwrite) {
+        // Skip the root-paths when syncOrOverwrite
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Skip " + fs.getPath());
+        }
+        return;
+      }
+      writeToFileListing(fileListWriter, fs, sourcePathRoot);
     }
-    writeToFileListing(fileListWriter, fileStatus, sourcePathRoot);
   }
 
   private void writeToFileListing(SequenceFile.Writer fileListWriter,
@@ -707,7 +714,7 @@ public class SimpleCopyListing extends CopyListing {
     fileListWriter.sync();
 
     if (!fileStatus.isDirectory()) {
-      totalBytesToCopy += fileStatus.getLen();
+      totalBytesToCopy += fileStatus.getSizeToCopy();
     } else {
       totalDirs++;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
index 75cefb4..6ddaab9 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
@@ -27,6 +27,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
+import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobStatus;
 import org.apache.hadoop.mapreduce.TaskAttemptContext;
@@ -34,14 +35,17 @@ import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
 import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.CopyListingFileStatus;
 import org.apache.hadoop.tools.DistCpConstants;
+import org.apache.hadoop.tools.DistCpOptionSwitch;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.GlobbedCopyListing;
 import org.apache.hadoop.tools.util.DistCpUtils;
 
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.EnumSet;
+import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -63,7 +67,8 @@ public class CopyCommitter extends FileOutputCommitter {
   private boolean syncFolder = false;
   private boolean overwrite = false;
   private boolean targetPathExists = true;
-  
+  private boolean ignoreFailures = false;
+
   /**
    * Create a output committer
    *
@@ -82,8 +87,13 @@ public class CopyCommitter extends FileOutputCommitter {
     Configuration conf = jobContext.getConfiguration();
     syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false);
     overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false);
-    targetPathExists = conf.getBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
-    
+    targetPathExists = conf.getBoolean(
+        DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
+    ignoreFailures = conf.getBoolean(
+        DistCpOptionSwitch.IGNORE_FAILURES.getConfigLabel(), false);
+
+    concatFileChunks(conf);
+
     super.commitJob(jobContext);
 
     cleanupTempFiles(jobContext);
@@ -169,9 +179,112 @@ public class CopyCommitter extends FileOutputCommitter {
     }
   }
 
+  private boolean isFileNotFoundException(IOException e) {
+    if (e instanceof FileNotFoundException) {
+      return true;
+    }
+
+    if (e instanceof RemoteException) {
+      return ((RemoteException)e).unwrapRemoteException()
+          instanceof FileNotFoundException;
+    }
+
+    return false;
+  }
+
+  /**
+   * Concat chunk files for the same file into one.
+   * Iterate through copy listing, identify chunk files for the same file,
+   * concat them into one.
+   */
+  private void concatFileChunks(Configuration conf) throws IOException {
+
+    LOG.info("concat file chunks ...");
+
+    String spath = conf.get(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH);
+    if (spath == null || spath.isEmpty()) {
+      return;
+    }
+    Path sourceListing = new Path(spath);
+    SequenceFile.Reader sourceReader = new SequenceFile.Reader(conf,
+                                      SequenceFile.Reader.file(sourceListing));
+    Path targetRoot =
+        new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
+
+    try {
+      CopyListingFileStatus srcFileStatus = new CopyListingFileStatus();
+      Text srcRelPath = new Text();
+      CopyListingFileStatus lastFileStatus = null;
+      LinkedList<Path> allChunkPaths = new LinkedList<Path>();
+
+      // Iterate over every source path that was copied.
+      while (sourceReader.next(srcRelPath, srcFileStatus)) {
+        if (srcFileStatus.isDirectory()) {
+          continue;
+        }
+        Path targetFile = new Path(targetRoot.toString() + "/" + srcRelPath);
+        Path targetFileChunkPath =
+            DistCpUtils.getSplitChunkPath(targetFile, srcFileStatus);
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("  add " + targetFileChunkPath + " to concat.");
+        }
+        allChunkPaths.add(targetFileChunkPath);
+        if (srcFileStatus.getChunkOffset() + srcFileStatus.getChunkLength()
+            == srcFileStatus.getLen()) {
+          // This is the last chunk of the splits, consolidate allChunkPaths
+          try {
+            concatFileChunks(conf, targetFile, allChunkPaths);
+          } catch (IOException e) {
+            // If the concat failed because a chunk file doesn't exist,
+            // then we assume that the CopyMapper has skipped copying this
+            // file, and we ignore the exception here.
+            // If a chunk file should have been created but it was not, then
+            // the CopyMapper would have failed.
+            if (!isFileNotFoundException(e)) {
+              String emsg = "Failed to concat chunk files for " + targetFile;
+              if (!ignoreFailures) {
+                throw new IOException(emsg, e);
+              } else {
+                LOG.warn(emsg, e);
+              }
+            }
+          }
+          allChunkPaths.clear();
+          lastFileStatus = null;
+        } else {
+          if (lastFileStatus == null) {
+            lastFileStatus = new CopyListingFileStatus(srcFileStatus);
+          } else {
+            // Two neighboring chunks have to be consecutive ones for the same
+            // file, for them to be merged
+            if (!srcFileStatus.getPath().equals(lastFileStatus.getPath()) ||
+                srcFileStatus.getChunkOffset() !=
+                (lastFileStatus.getChunkOffset() +
+                lastFileStatus.getChunkLength())) {
+              String emsg = "Inconsistent sequence file: current " +
+                  "chunk file " + srcFileStatus + " doesnt match prior " +
+                  "entry " + lastFileStatus;
+              if (!ignoreFailures) {
+                throw new IOException(emsg);
+              } else {
+                LOG.warn(emsg + ", skipping concat this set.");
+              }
+            } else {
+              lastFileStatus.setChunkOffset(srcFileStatus.getChunkOffset());
+              lastFileStatus.setChunkLength(srcFileStatus.getChunkLength());
+            }
+          }
+        }
+      }
+    } finally {
+      IOUtils.closeStream(sourceReader);
+    }
+  }
+
   // This method changes the target-directories' file-attributes (owner,
   // user/group permissions, etc.) based on the corresponding source directories.
-  private void preserveFileAttributesForDirectories(Configuration conf) throws IOException {
+  private void preserveFileAttributesForDirectories(Configuration conf)
+      throws IOException {
     String attrSymbols = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS);
     final boolean syncOrOverwrite = syncFolder || overwrite;
 
@@ -325,4 +438,57 @@ public class CopyCommitter extends FileOutputCommitter {
         ", Unable to move to " + finalDir);
     }
   }
+
+  /**
+   * Concat the passed chunk files into one and rename it the targetFile.
+   */
+  private void concatFileChunks(Configuration conf, Path targetFile,
+      LinkedList<Path> allChunkPaths) throws IOException {
+    if (allChunkPaths.size() == 1) {
+      return;
+    }
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat " + targetFile + " allChunkSize+ "
+          + allChunkPaths.size());
+    }
+    FileSystem dstfs = targetFile.getFileSystem(conf);
+
+    Path firstChunkFile = allChunkPaths.removeFirst();
+    Path[] restChunkFiles = new Path[allChunkPaths.size()];
+    allChunkPaths.toArray(restChunkFiles);
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat: firstchunk: " + dstfs.getFileStatus(firstChunkFile));
+      int i = 0;
+      for (Path f : restChunkFiles) {
+        LOG.debug("concat: other chunk: " + i + ": " + dstfs.getFileStatus(f));
+        ++i;
+      }
+    }
+    dstfs.concat(firstChunkFile, restChunkFiles);
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat: result: " + dstfs.getFileStatus(firstChunkFile));
+    }
+    rename(dstfs, firstChunkFile, targetFile);
+  }
+
+  /**
+   * Rename tmp to dst on destFileSys.
+   * @param destFileSys the file ssystem
+   * @param tmp the source path
+   * @param dst the destination path
+   * @throws IOException if renaming failed
+   */
+  private static void rename(FileSystem destFileSys, Path tmp, Path dst)
+      throws IOException {
+    try {
+      if (destFileSys.exists(dst)) {
+        destFileSys.delete(dst, true);
+      }
+      destFileSys.rename(tmp, dst);
+    } catch (IOException ioe) {
+      throw new IOException("Fail to rename tmp file (=" + tmp
+          + ") to destination file (=" + dst + ")", ioe);
+    }
+  }
+
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
index e1873f1..d6b3ba8 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
@@ -156,10 +156,12 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         sourceFS = sourcePath.getFileSystem(conf);
         final boolean preserveXAttrs =
             fileAttributes.contains(FileAttribute.XATTR);
-        sourceCurrStatus = DistCpUtils.toCopyListingFileStatus(sourceFS,
-          sourceFS.getFileStatus(sourcePath),
-          fileAttributes.contains(FileAttribute.ACL), 
-          preserveXAttrs, preserveRawXattrs);
+        sourceCurrStatus = DistCpUtils.toCopyListingFileStatusHelper(sourceFS,
+            sourceFS.getFileStatus(sourcePath),
+            fileAttributes.contains(FileAttribute.ACL),
+            preserveXAttrs, preserveRawXattrs,
+            sourceFileStatus.getChunkOffset(),
+            sourceFileStatus.getChunkLength());
       } catch (FileNotFoundException e) {
         throw new IOException(new RetriableFileCopyCommand.CopyReadException(e));
       }
@@ -173,7 +175,8 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
           LOG.debug("Path could not be found: " + target, ignore);
       }
 
-      if (targetStatus != null && (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
+      if (targetStatus != null &&
+          (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
         throw new IOException("Can't replace " + target + ". Target is " +
             getFileType(targetStatus) + ", Source is " + getFileType(sourceCurrStatus));
       }
@@ -183,19 +186,28 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         return;
       }
 
-      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target, targetStatus);
+      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target,
+          targetStatus);
+
+      Path tmpTarget = target;
       if (action == FileAction.SKIP) {
         LOG.info("Skipping copy of " + sourceCurrStatus.getPath()
                  + " to " + target);
         updateSkipCounters(context, sourceCurrStatus);
         context.write(null, new Text("SKIP: " + sourceCurrStatus.getPath()));
+
       } else {
-        copyFileWithRetry(description, sourceCurrStatus, target, context,
+        if (sourceCurrStatus.isSplit()) {
+          tmpTarget = DistCpUtils.getSplitChunkPath(target, sourceCurrStatus);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("copying " + sourceCurrStatus + " " + tmpTarget);
+        }
+        copyFileWithRetry(description, sourceCurrStatus, tmpTarget, context,
             action, fileAttributes);
       }
-
-      DistCpUtils.preserve(target.getFileSystem(conf), target, sourceCurrStatus,
-          fileAttributes, preserveRawXattrs);
+      DistCpUtils.preserve(target.getFileSystem(conf), tmpTarget,
+          sourceCurrStatus, fileAttributes, preserveRawXattrs);
     } catch (IOException exception) {
       handleFailures(exception, sourceFileStatus, target, context);
     }
@@ -261,8 +273,12 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
   private void handleFailures(IOException exception,
       CopyListingFileStatus sourceFileStatus, Path target, Context context)
       throws IOException, InterruptedException {
-    LOG.error("Failure in copying " + sourceFileStatus.getPath() + " to " +
-                target, exception);
+    LOG.error("Failure in copying " + sourceFileStatus.getPath() +
+        (sourceFileStatus.isSplit()? ","
+            + " offset=" + sourceFileStatus.getChunkOffset()
+            + " chunkLength=" + sourceFileStatus.getChunkLength()
+            : "") +
+        " to " + target, exception);
 
     if (ignoreFailures &&
         ExceptionUtils.indexOfType(exception, CopyReadException.class) != -1) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
index 06acd78..2c17fef 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
@@ -118,17 +118,21 @@ public class RetriableFileCopyCommand extends RetriableCommand {
           .contains(FileAttribute.CHECKSUMTYPE) ? sourceFS
           .getFileChecksum(sourcePath) : null;
 
-      final long offset = action == FileAction.APPEND ? targetFS.getFileStatus(
-          target).getLen() : 0;
+      long offset = (action == FileAction.APPEND) ?
+          targetFS.getFileStatus(target).getLen() : source.getChunkOffset();
       long bytesRead = copyToFile(targetPath, targetFS, source,
           offset, context, fileAttributes, sourceChecksum);
 
-      compareFileLengths(source, targetPath, configuration, bytesRead
-          + offset);
+      if (!source.isSplit()) {
+        compareFileLengths(source, targetPath, configuration, bytesRead
+            + offset);
+      }
       //At this point, src&dest lengths are same. if length==0, we skip checksum
       if ((bytesRead != 0) && (!skipCrc)) {
-        compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
-            targetFS, targetPath);
+        if (!source.isSplit()) {
+          compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
+              targetFS, targetPath);
+        }
       }
       // it's not append case, thus we first write to a temporary file, rename
       // it to the target path.
@@ -249,16 +253,26 @@ public class RetriableFileCopyCommand extends RetriableCommand {
     ThrottledInputStream inStream = null;
     long totalBytesRead = 0;
 
+    long chunkLength = source2.getChunkLength();
+    boolean finished = false;
     try {
       inStream = getInputStream(source, context.getConfiguration());
       int bytesRead = readBytes(inStream, buf, sourceOffset);
       while (bytesRead >= 0) {
+        if (chunkLength > 0 &&
+            (totalBytesRead + bytesRead) >= chunkLength) {
+          bytesRead = (int)(chunkLength - totalBytesRead);
+          finished = true;
+        }
         totalBytesRead += bytesRead;
         if (action == FileAction.APPEND) {
           sourceOffset += bytesRead;
         }
         outStream.write(buf, 0, bytesRead);
         updateContextStatus(totalBytesRead, context, source2);
+        if (finished) {
+          break;
+        }
         bytesRead = readBytes(inStream, buf, sourceOffset);
       }
       outStream.close();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
index 3e86d09..d1c18ea 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
@@ -99,7 +99,8 @@ public class UniformSizeInputFormat
       while (reader.next(srcRelPath, srcFileStatus)) {
         // If adding the current file would cause the bytes per map to exceed
         // limit. Add the current file to new split
-        if (currentSplitSize + srcFileStatus.getLen() > nBytesPerSplit && lastPosition != 0) {
+        if (currentSplitSize + srcFileStatus.getChunkLength() > nBytesPerSplit
+            && lastPosition != 0) {
           FileSplit split = new FileSplit(listingFilePath, lastSplitStart,
               lastPosition - lastSplitStart, null);
           if (LOG.isDebugEnabled()) {
@@ -109,7 +110,7 @@ public class UniformSizeInputFormat
           lastSplitStart = lastPosition;
           currentSplitSize = 0;
         }
-        currentSplitSize += srcFileStatus.getLen();
+        currentSplitSize += srcFileStatus.getChunkLength();
         lastPosition = reader.getPosition();
       }
       if (lastPosition > lastSplitStart) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
index 76bc4c5..e315b84 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
@@ -19,9 +19,11 @@
 package org.apache.hadoop.tools.util;
 
 import com.google.common.collect.Maps;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.FileChecksum;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
@@ -30,6 +32,7 @@ import org.apache.hadoop.fs.XAttr;
 import org.apache.hadoop.fs.permission.AclEntry;
 import org.apache.hadoop.fs.permission.AclUtil;
 import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.mapreduce.InputFormat;
@@ -44,6 +47,7 @@ import org.apache.hadoop.util.StringUtils;
 import java.io.IOException;
 import java.text.DecimalFormat;
 import java.util.EnumSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -116,7 +120,7 @@ public class DistCpUtils {
    * @return Class implementing the strategy specified in options.
    */
   public static Class<? extends InputFormat> getStrategy(Configuration conf,
-                                                                 DistCpOptions options) {
+      DistCpOptions options) {
     String confLabel = "distcp."
         + StringUtils.toLowerCase(options.getCopyStrategy())
         + ".strategy" + ".impl";
@@ -298,6 +302,86 @@ public class DistCpUtils {
   }
 
   /**
+   * Converts FileStatus to a list of CopyListingFileStatus.
+   * The resulted list contains either one CopyListingFileStatus per chunk of
+   * file-blocks (if file-size exceeds blockSize * blocksPerChunk, and there
+   * are more blocks in the file than blocksperChunk), or a single
+   * CopyListingFileStatus for the entire file (if file-size is too small to
+   * split).
+   * If preserving ACLs, populates the CopyListingFileStatus with the ACLs.
+   * If preserving XAttrs, populates the CopyListingFileStatus with the XAttrs.
+   *
+   * @param fileSystem FileSystem containing the file
+   * @param fileStatus FileStatus of file
+   * @param preserveAcls boolean true if preserving ACLs
+   * @param preserveXAttrs boolean true if preserving XAttrs
+   * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
+   * @param blocksPerChunk size of chunks when copying chunks in parallel
+   * @return list of CopyListingFileStatus
+   * @throws IOException if there is an I/O error
+   */
+  public static LinkedList<CopyListingFileStatus> toCopyListingFileStatus(
+      FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls,
+      boolean preserveXAttrs, boolean preserveRawXAttrs, int blocksPerChunk)
+          throws IOException {
+    LinkedList<CopyListingFileStatus> copyListingFileStatus =
+        new LinkedList<CopyListingFileStatus>();
+
+    final CopyListingFileStatus clfs = toCopyListingFileStatusHelper(
+        fileSystem, fileStatus, preserveAcls,
+        preserveXAttrs, preserveRawXAttrs,
+        0, fileStatus.getLen());
+    final long blockSize = fileStatus.getBlockSize();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("toCopyListing: " + fileStatus + " chunkSize: "
+          + blocksPerChunk + " isDFS: " +
+          (fileSystem instanceof DistributedFileSystem));
+    }
+    if ((blocksPerChunk > 0) &&
+        !fileStatus.isDirectory() &&
+        (fileStatus.getLen() > blockSize * blocksPerChunk)) {
+      // split only when the file size is larger than the intended chunk size
+      final BlockLocation[] blockLocations;
+      blockLocations = fileSystem.getFileBlockLocations(fileStatus, 0,
+            fileStatus.getLen());
+
+      int numBlocks = blockLocations.length;
+      long curPos = 0;
+      if (numBlocks <= blocksPerChunk) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("  add file " + clfs);
+        }
+        copyListingFileStatus.add(clfs);
+      } else {
+        int i = 0;
+        while (i < numBlocks) {
+          long curLength = 0;
+          for (int j = 0; j < blocksPerChunk && i < numBlocks; ++j, ++i) {
+            curLength += blockLocations[i].getLength();
+          }
+          if (curLength > 0) {
+            CopyListingFileStatus clfs1 = new CopyListingFileStatus(clfs);
+            clfs1.setChunkOffset(curPos);
+            clfs1.setChunkLength(curLength);
+            if (LOG.isDebugEnabled()) {
+              LOG.debug("  add file chunk " + clfs1);
+            }
+            copyListingFileStatus.add(clfs1);
+            curPos += curLength;
+          }
+        }
+      }
+    } else {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("  add file/dir " + clfs);
+      }
+      copyListingFileStatus.add(clfs);
+    }
+
+    return copyListingFileStatus;
+  }
+
+  /**
    * Converts a FileStatus to a CopyListingFileStatus.  If preserving ACLs,
    * populates the CopyListingFileStatus with the ACLs. If preserving XAttrs,
    * populates the CopyListingFileStatus with the XAttrs.
@@ -307,13 +391,17 @@ public class DistCpUtils {
    * @param preserveAcls boolean true if preserving ACLs
    * @param preserveXAttrs boolean true if preserving XAttrs
    * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
+   * @param chunkOffset chunk offset in bytes
+   * @param chunkLength chunk length in bytes
+   * @return CopyListingFileStatus
    * @throws IOException if there is an I/O error
    */
-  public static CopyListingFileStatus toCopyListingFileStatus(
+  public static CopyListingFileStatus toCopyListingFileStatusHelper(
       FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls, 
-      boolean preserveXAttrs, boolean preserveRawXAttrs) throws IOException {
+      boolean preserveXAttrs, boolean preserveRawXAttrs,
+      long chunkOffset, long chunkLength) throws IOException {
     CopyListingFileStatus copyListingFileStatus =
-      new CopyListingFileStatus(fileStatus);
+        new CopyListingFileStatus(fileStatus, chunkOffset, chunkLength);
     if (preserveAcls) {
       FsPermission perm = fileStatus.getPermission();
       if (perm.getAclBit()) {
@@ -470,4 +558,19 @@ public class DistCpUtils {
     return (sourceChecksum == null || targetChecksum == null ||
             sourceChecksum.equals(targetChecksum));
   }
+
+  /*
+   * Return the Path for a given chunk.
+   * Used when splitting large file into chunks to copy in parallel.
+   * @param targetFile path to target file
+   * @param srcFileStatus source file status in copy listing
+   * @return path to the chunk specified by the parameters to store
+   * in target cluster temporarily
+   */
+  public static Path getSplitChunkPath(Path targetFile,
+      CopyListingFileStatus srcFileStatus) {
+    return new Path(targetFile.toString()
+        + ".____distcpSplit____" + srcFileStatus.getChunkOffset()
+        + "." + srcFileStatus.getChunkLength());
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
index 41a6e94..a77deb2 100644
--- a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
+++ b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
@@ -237,6 +237,7 @@ Flag              | Description                          | Notes
 `-rdiff <newSnapshot> <oldSnapshot>` | Use snapshot diff report between given two snapshots to identify what has been changed on the target since the snapshot `<oldSnapshot>` was created on the target, and apply the diff reversely to the target, and copy modified files from the source's `<oldSnapshot>`, to make the target the same as `<oldSnapshot>`. | This option is valid only with `-update` option and the following conditions should be satisfied. <ol><li>Both the source and the target FileSystem must be DistributedFileSystem. The source and the target can be two different clusters/paths, or they can be exactly the same cluster/path. In the latter case, modified files are copied from target's `<oldSnapshot>` to target's current state).</li>  <li> Two snapshots `<newSnapshot>` and `<oldSnapshot>` have been created on the target FS, and `<oldSnapshot>` is older than `<newSnapshot>`. No change has been made on target since `<newSnapshot>` was created on the target. </li> <li> The sour
 ce has the same snapshot `<oldSnapshot>`, which has the same content as the `<oldSnapshot>` on the target. All the files/directories in the target's `<oldSnapshot>` are the same with source's `<oldSnapshot>`.</li> </ol> |
 `-numListstatusThreads` | Number of threads to use for building file listing | At most 40 threads.
 `-skipcrccheck` | Whether to skip CRC checks between source and target paths. |
+`-blocksperchunk <blocksperchunk>` | Number of blocks per chunk. When specified, split files into chunks to copy in parallel | If set to a positive value, files with more blocks than this value will be split into chunks of `<blocksperchunk>` blocks to be transferred in parallel, and reassembled on the destination. By default, `<blocksperchunk>` is 0 and the files will be transmitted in their entirety without splitting. This switch is only applicable when the source file system implements getBlockLocations method and the target file system implements concat method. |
 
 Architecture of DistCp
 ----------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
index e3018a0..b2266b3 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
@@ -23,17 +23,27 @@ import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
+import java.io.PrintStream;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Random;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.FsShell;
 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.MiniDFSCluster;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.util.ToolRunner;
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -47,11 +57,15 @@ import org.junit.rules.Timeout;
  */
 
 public class TestDistCpSystem {
+  private static final Log LOG =
+      LogFactory.getLog(TestDistCpSystem.class);
+
   @Rule
   public Timeout globalTimeout = new Timeout(30000);
 
   private static final String SRCDAT = "srcdat";
   private static final String DSTDAT = "dstdat";
+  private static final long BLOCK_SIZE = 1024;
 
   private static MiniDFSCluster cluster;
   private static Configuration conf;
@@ -63,27 +77,76 @@ public class TestDistCpSystem {
       this.path = path;
       this.isDir = isDir;
     }
-    String getPath() { return path; }
-    boolean isDirectory() { return isDir; }
+
+    String getPath() {
+      return path;
+    }
+
+    boolean isDirectory() {
+      return isDir;
+    }
+  }
+
+  @BeforeClass
+  public static void beforeClass() throws IOException {
+    conf = new Configuration();
+    conf.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, BLOCK_SIZE);
+    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
+    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
+    cluster.waitActive();
+  }
+
+  @AfterClass
+  public static void afterClass() throws IOException {
+    if (cluster != null) {
+      cluster.shutdown();
+    }
+  }
+
+  static String execCmd(FsShell shell, String... args) throws Exception {
+    ByteArrayOutputStream baout = new ByteArrayOutputStream();
+    PrintStream out = new PrintStream(baout, true);
+    PrintStream old = System.out;
+    System.setOut(out);
+    shell.run(args);
+    out.close();
+    System.setOut(old);
+    return baout.toString();
   }
   
-  private void createFiles(FileSystem fs, String topdir,
-      FileEntry[] entries) throws IOException {
+  private void createFiles(DistributedFileSystem fs, String topdir,
+      FileEntry[] entries, long chunkSize) throws IOException {
+    long seed = System.currentTimeMillis();
+    Random rand = new Random(seed);
+    short replicationFactor = 2;
     for (FileEntry entry : entries) {
-      Path newpath = new Path(topdir + "/" + entry.getPath());
+      Path newPath = new Path(topdir + "/" + entry.getPath());
       if (entry.isDirectory()) {
-        fs.mkdirs(newpath);
+        fs.mkdirs(newPath);
       } else {
-        OutputStream out = fs.create(newpath);
-        try {
-          out.write((topdir + "/" + entry).getBytes());
-          out.write("\n".getBytes());
-        } finally {
-          out.close();
+        long fileSize = BLOCK_SIZE *100;
+        int bufSize = 128;
+        if (chunkSize == -1) {
+          DFSTestUtil.createFile(fs, newPath, bufSize,
+              fileSize, BLOCK_SIZE, replicationFactor, seed);
+        } else {
+          // Create a variable length block file, by creating
+          // one block of half block size at the chunk boundary
+          long seg1 = chunkSize * BLOCK_SIZE - BLOCK_SIZE / 2;
+          long seg2 = fileSize - seg1;
+          DFSTestUtil.createFile(fs, newPath, bufSize,
+              seg1, BLOCK_SIZE, replicationFactor, seed);
+          DFSTestUtil.appendFileNewBlock(fs, newPath, (int)seg2);
         }
       }
+      seed = System.currentTimeMillis() + rand.nextLong();
     }
   }
+
+  private void createFiles(DistributedFileSystem fs, String topdir,
+      FileEntry[] entries) throws IOException {
+    createFiles(fs, topdir, entries, -1);
+  }
    
   private static FileStatus[] getFileStatus(FileSystem fs,
       String topdir, FileEntry[] files) throws IOException {
@@ -104,18 +167,19 @@ public class TestDistCpSystem {
   }
 
   private void testPreserveUserHelper(String testRoot,
-                                      FileEntry[] srcEntries,
-                                      FileEntry[] dstEntries,
-                                      boolean createSrcDir,
-                                      boolean createTgtDir,
-                                      boolean update) throws Exception {
+      FileEntry[] srcEntries,
+      FileEntry[] dstEntries,
+      boolean createSrcDir,
+      boolean createTgtDir,
+      boolean update) throws Exception {
     final String testSrcRel = SRCDAT;
     final String testSrc = testRoot + "/" + testSrcRel;
     final String testDstRel = DSTDAT;
     final String testDst = testRoot + "/" + testDstRel;
 
     String nnUri = FileSystem.getDefaultUri(conf).toString();
-    FileSystem fs = FileSystem.get(URI.create(nnUri), conf);
+    DistributedFileSystem fs = (DistributedFileSystem)
+        FileSystem.get(URI.create(nnUri), conf);
     fs.mkdirs(new Path(testRoot));
     if (createSrcDir) {
       fs.mkdirs(new Path(testSrc));
@@ -129,8 +193,8 @@ public class TestDistCpSystem {
     for(int i = 0; i < srcEntries.length; i++) {
       fs.setOwner(srcstats[i].getPath(), "u" + i, null);
     }
-    String[] args = update? new String[]{"-pu", "-update", nnUri+testSrc,
-        nnUri+testDst} : new String[]{"-pu", nnUri+testSrc, nnUri+testDst};
+    String[] args = update? new String[]{"-pub", "-update", nnUri+testSrc,
+        nnUri+testDst} : new String[]{"-pub", nnUri+testSrc, nnUri+testDst};
 
     ToolRunner.run(conf, new DistCp(), args);
 
@@ -145,20 +209,263 @@ public class TestDistCpSystem {
     deldir(fs, testRoot);
   }
 
-  @BeforeClass
-  public static void beforeClass() throws IOException {
-    conf = new Configuration();
-    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
-    cluster.waitActive();
+  private void compareFiles(FileSystem fs, FileStatus srcStat,
+      FileStatus dstStat) throws Exception {
+    LOG.info("Comparing " + srcStat + " and " + dstStat);
+    assertEquals(srcStat.isDirectory(), dstStat.isDirectory());
+    assertEquals(srcStat.getReplication(), dstStat.getReplication());
+    assertEquals("File POSIX permission should match",
+        srcStat.getPermission(), dstStat.getPermission());
+    assertEquals("File user ownership should match",
+        srcStat.getOwner(), dstStat.getOwner());
+    assertEquals("File group ownership should match",
+        srcStat.getGroup(), dstStat.getGroup());
+    // TODO; check ACL attributes
+
+    if (srcStat.isDirectory()) {
+      return;
+    }
+
+    assertEquals("File length should match (" + srcStat.getPath() + ")",
+        srcStat.getLen(), dstStat.getLen());
+
+    FSDataInputStream srcIn = fs.open(srcStat.getPath());
+    FSDataInputStream dstIn = fs.open(dstStat.getPath());
+    try {
+      byte[] readSrc = new byte[(int)
+                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
+      byte[] readDst = new byte[(int)
+                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
+
+      int srcBytesRead = 0, tgtBytesRead = 0;
+      int srcIdx = 0, tgtIdx = 0;
+      long totalComparedBytes = 0;
+      while (true) {
+        if (srcBytesRead == 0) {
+          srcBytesRead = srcIn.read(readSrc);
+          srcIdx = 0;
+        }
+        if (tgtBytesRead == 0) {
+          tgtBytesRead = dstIn.read(readDst);
+          tgtIdx = 0;
+        }
+        if (srcBytesRead == 0 || tgtBytesRead == 0) {
+          LOG.info("______ compared src and dst files for "
+              + totalComparedBytes + " bytes, content match.");
+          if (srcBytesRead != tgtBytesRead) {
+            Assert.fail("Read mismatching size, compared "
+                + totalComparedBytes + " bytes between src and dst file "
+                + srcStat + " and " + dstStat);
+          }
+          if (totalComparedBytes != srcStat.getLen()) {
+            Assert.fail("Only read/compared " + totalComparedBytes +
+                " bytes between src and dst file " + srcStat +
+                " and " + dstStat);
+          } else {
+            // success
+            break;
+          }
+        }
+        for (; srcIdx < srcBytesRead && tgtIdx < tgtBytesRead;
+            ++srcIdx, ++tgtIdx) {
+          if (readSrc[srcIdx] != readDst[tgtIdx]) {
+            Assert.fail("src and dst file does not match at "
+                + totalComparedBytes + " between "
+                + srcStat + " and " + dstStat);
+          }
+          ++totalComparedBytes;
+        }
+        LOG.info("______ compared src and dst files for "
+            + totalComparedBytes + " bytes, content match. FileLength: "
+            + srcStat.getLen());
+        if (totalComparedBytes == srcStat.getLen()) {
+          LOG.info("______ Final:" + srcIdx + " "
+              + srcBytesRead + " " + tgtIdx + " " + tgtBytesRead);
+          break;
+        }
+        if (srcIdx == srcBytesRead) {
+          srcBytesRead = 0;
+        }
+        if (tgtIdx == tgtBytesRead) {
+          tgtBytesRead = 0;
+        }
+      }
+    } finally {
+      if (srcIn != null) {
+        srcIn.close();
+      }
+      if (dstIn != null) {
+        dstIn.close();
+      }
+    }
   }
 
-  @AfterClass
-  public static void afterClass() throws IOException {
-    if (cluster != null) {
-      cluster.shutdown();
+  // WC: needed because the current distcp does not create target dirs
+  private void createDestDir(FileSystem fs, String testDst,
+      FileStatus[] srcStats, FileEntry[] srcFiles) throws IOException {
+    fs.mkdirs(new Path(testDst));
+
+    for (int i=0; i<srcStats.length; i++) {
+      FileStatus srcStat = srcStats[i];
+      if (srcStat.isDirectory()) {
+        Path dstPath = new Path(testDst, srcFiles[i].getPath());
+        fs.mkdirs(dstPath);
+        fs.setOwner(dstPath, srcStat.getOwner(), srcStat.getGroup());
+      }
+    }
+  }
+
+  private void copyAndVerify(final DistributedFileSystem fs,
+      final FileEntry[] srcFiles, final FileStatus[] srcStats,
+      final String testDst,
+      final String[] args) throws Exception {
+    final String testRoot = "/testdir";
+    FsShell shell = new FsShell(fs.getConf());
+
+    LOG.info("ls before distcp");
+    LOG.info(execCmd(shell, "-lsr", testRoot));
+
+    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
+    ToolRunner.run(conf, new DistCp(), args);
+
+    LOG.info("ls after distcp");
+    LOG.info(execCmd(shell, "-lsr", testRoot));
+
+    FileStatus[] dstStat = getFileStatus(fs, testDst, srcFiles);
+    for (int i=0; i< dstStat.length; i++) {
+      compareFiles(fs, srcStats[i], dstStat[i]);
     }
   }
 
+  private void chunkCopy(FileEntry[] srcFiles) throws Exception {
+    final String testRoot = "/testdir";
+    final String testSrcRel = SRCDAT;
+    final String testSrc = testRoot + "/" + testSrcRel;
+    final String testDstRel = DSTDAT;
+    final String testDst = testRoot + "/" + testDstRel;
+    long chunkSize = 8;
+
+    String nnUri = FileSystem.getDefaultUri(conf).toString();
+    DistributedFileSystem fs = (DistributedFileSystem)
+        FileSystem.get(URI.create(nnUri), conf);
+
+    createFiles(fs, testRoot, srcFiles, chunkSize);
+
+    FileStatus[] srcStats = getFileStatus(fs, testRoot, srcFiles);
+    for (int i = 0; i < srcFiles.length; i++) {
+      fs.setOwner(srcStats[i].getPath(), "u" + i,  "g" + i);
+    }
+    // get file status after updating owners
+    srcStats = getFileStatus(fs, testRoot, srcFiles);
+
+    createDestDir(fs, testDst, srcStats, srcFiles);
+
+    String[] args = new String[] {"-pugp", "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc, nnUri + testDst};
+
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+    // Do it again
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+
+    // modify last file and rerun distcp with -update option
+    LOG.info("Modify a file and copy again");
+    for(int i=srcFiles.length-1; i >=0; --i) {
+      if (!srcFiles[i].isDirectory()) {
+        LOG.info("Modifying " + srcStats[i].getPath());
+        DFSTestUtil.appendFileNewBlock(fs, srcStats[i].getPath(),
+            (int)BLOCK_SIZE * 3);
+        break;
+      }
+    }
+    // get file status after modifying file
+    srcStats = getFileStatus(fs, testRoot, srcFiles);
+
+    args = new String[] {"-pugp", "-update", "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc, nnUri + testDst + "/" + testSrcRel};
+
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+
+    deldir(fs, testRoot);
+  }
+
+  @Test
+  public void testRecursiveChunkCopy() throws Exception {
+    FileEntry[] srcFiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file0", false),
+        new FileEntry(SRCDAT + "/dir1", true),
+        new FileEntry(SRCDAT + "/dir2", true),
+        new FileEntry(SRCDAT + "/dir1/file1", false)
+    };
+    chunkCopy(srcFiles);
+  }
+
+  @Test
+  public void testChunkCopyOneFile() throws Exception {
+    FileEntry[] srcFiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file0", false)
+    };
+    chunkCopy(srcFiles);
+  }
+
+  @Test
+  public void testDistcpLargeFile() throws Exception {
+    FileEntry[] srcfiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file", false)
+    };
+
+    final String testRoot = "/testdir";
+    final String testSrcRel = SRCDAT;
+    final String testSrc = testRoot + "/" + testSrcRel;
+    final String testDstRel = DSTDAT;
+    final String testDst = testRoot + "/" + testDstRel;
+
+    String nnUri = FileSystem.getDefaultUri(conf).toString();
+    DistributedFileSystem fs =
+        (DistributedFileSystem) FileSystem.get(URI.create(nnUri), conf);
+    fs.mkdirs(new Path(testRoot));
+    fs.mkdirs(new Path(testSrc));
+    fs.mkdirs(new Path(testDst));
+    long chunkSize = 6;
+    createFiles(fs, testRoot, srcfiles, chunkSize);
+
+    String srcFileName = testRoot + Path.SEPARATOR + srcfiles[1].getPath();
+    Path srcfile = new Path(srcFileName);
+
+    if(!cluster.getFileSystem().exists(srcfile)){
+      throw new Exception("src not exist");
+    }
+
+    final long srcLen = fs.getFileStatus(srcfile).getLen();
+
+    FileStatus[] srcstats = getFileStatus(fs, testRoot, srcfiles);
+    for (int i = 0; i < srcfiles.length; i++) {
+      fs.setOwner(srcstats[i].getPath(), "u" + i, null);
+    }
+    String[] args = new String[] {
+        "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc,
+        nnUri + testDst
+    };
+
+    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
+    ToolRunner.run(conf, new DistCp(), args);
+
+    String realTgtPath = testDst;
+    FileStatus[] dststat = getFileStatus(fs, realTgtPath, srcfiles);
+    assertEquals("File length should match", srcLen,
+        dststat[dststat.length - 1].getLen());
+
+    this.compareFiles(fs,  srcstats[srcstats.length-1],
+        dststat[dststat.length-1]);
+    deldir(fs, testRoot);
+  }
+
   @Test
   public void testPreserveUseNonEmptyDir() throws Exception {
     String testRoot = "/testdir." + getMethodName();
@@ -180,7 +487,6 @@ public class TestDistCpSystem {
     testPreserveUserHelper(testRoot, srcfiles, dstfiles, false, false, false);
   }
 
-
   @Test
   public void testPreserveUserEmptyDir() throws Exception {
     String testRoot = "/testdir." + getMethodName();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/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 efe4627..f94ba97 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
@@ -394,7 +394,7 @@ public class TestOptionsParser {
         + "copyStrategy='uniformsize', preserveStatus=[], "
         + "preserveRawXattrs=false, atomicWorkPath=null, logPath=null, "
         + "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, "
-        + "targetPathExists=true, filtersFile='null'}";
+        + "targetPathExists=true, filtersFile='null', blocksPerChunk=0}";
     String optionString = option.toString();
     Assert.assertEquals(val, optionString);
     Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),

http://git-wip-us.apache.org/repos/asf/hadoop/blob/20e57a9a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
index 2e9a350..2452d6f 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
@@ -81,6 +81,10 @@ public class TestCopyCommitter {
   @Before
   public void createMetaFolder() {
     config.set(DistCpConstants.CONF_LABEL_META_FOLDER, "/meta");
+    // Unset listing file path since the config is shared by
+    // multiple tests, and some test doesn't set it, such as
+    // testNoCommitAction, but the distcp code will check it.
+    config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, "");
     Path meta = new Path("/meta");
     try {
       cluster.getFileSystem().mkdirs(meta);
@@ -326,7 +330,6 @@ public class TestCopyCommitter {
       committer.commitJob(jobContext);
       Assert.assertFalse(fs.exists(new Path(workPath)));
       Assert.assertTrue(fs.exists(new Path(finalPath)));
-
     } catch (IOException e) {
       LOG.error("Exception encountered while testing for preserve status", e);
       Assert.fail("Atomic commit failure");


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[23/50] [abbrv] hadoop git commit: YARN-6004. Refactor TestResourceLocalizationService#testDownloadingResourcesOnContainer so that it is less than 150 lines. (Chris Trezzo via mingma)

Posted by in...@apache.org.
YARN-6004. Refactor TestResourceLocalizationService#testDownloadingResourcesOnContainer so that it is less than 150 lines. (Chris Trezzo via mingma)


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

Branch: refs/heads/HDFS-10467
Commit: bf4ed74f2f361015bac26fa874db18b09a2d1000
Parents: bb8a925
Author: Ming Ma <mi...@apache.org>
Authored: Tue Apr 4 17:56:21 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../TestResourceLocalizationService.java        | 376 +++++++++++--------
 1 file changed, 212 insertions(+), 164 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/bf4ed74f/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.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/localizer/TestResourceLocalizationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
index 41cccc1..932e94f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
@@ -1124,7 +1124,6 @@ public class TestResourceLocalizationService {
   }
 
   @Test(timeout = 20000)
-  @SuppressWarnings("unchecked")
   public void testDownloadingResourcesOnContainerKill() throws Exception {
     List<Path> localDirs = new ArrayList<Path>();
     String[] sDirs = new String[1];
@@ -1132,13 +1131,6 @@ public class TestResourceLocalizationService {
     sDirs[0] = localDirs.get(0).toString();
 
     conf.setStrings(YarnConfiguration.NM_LOCAL_DIRS, sDirs);
-    DrainDispatcher dispatcher = new DrainDispatcher();
-    dispatcher.init(conf);
-    dispatcher.start();
-    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
-    dispatcher.register(ApplicationEventType.class, applicationBus);
-    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
-    dispatcher.register(ContainerEventType.class, containerBus);
 
     DummyExecutor exec = new DummyExecutor();
     LocalDirsHandlerService dirsHandler = new LocalDirsHandlerService();
@@ -1149,6 +1141,7 @@ public class TestResourceLocalizationService {
     delService.init(new Configuration());
     delService.start();
 
+    DrainDispatcher dispatcher = getDispatcher(conf);
     ResourceLocalizationService rawService = new ResourceLocalizationService(
         dispatcher, exec, delService, dirsHandler, nmContext);
     ResourceLocalizationService spyService = spy(rawService);
@@ -1191,180 +1184,235 @@ public class TestResourceLocalizationService {
       spyService.init(conf);
       spyService.start();
 
-      final Application app = mock(Application.class);
-      final ApplicationId appId =
-          BuilderUtils.newApplicationId(314159265358979L, 3);
-      String user = "user0";
-      when(app.getUser()).thenReturn(user);
-      when(app.getAppId()).thenReturn(appId);
-      spyService.handle(new ApplicationLocalizationEvent(
-          LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
-      ArgumentMatcher<ApplicationEvent> matchesAppInit =
+      doLocalization(spyService, dispatcher, exec, delService);
+
+    } finally {
+      spyService.stop();
+      dispatcher.stop();
+      delService.stop();
+    }
+  }
+
+  private DrainDispatcher getDispatcher(Configuration config) {
+    DrainDispatcher dispatcher = new DrainDispatcher();
+    dispatcher.init(config);
+    dispatcher.start();
+    return dispatcher;
+  }
+
+  @SuppressWarnings("unchecked")
+  private EventHandler<ApplicationEvent> getApplicationBus(
+      DrainDispatcher dispatcher) {
+    EventHandler<ApplicationEvent> applicationBus = mock(EventHandler.class);
+    dispatcher.register(ApplicationEventType.class, applicationBus);
+    return applicationBus;
+  }
+
+  @SuppressWarnings("unchecked")
+  private EventHandler<ContainerEvent> getContainerBus(
+      DrainDispatcher dispatcher) {
+    EventHandler<ContainerEvent> containerBus = mock(EventHandler.class);
+    dispatcher.register(ContainerEventType.class, containerBus);
+    return containerBus;
+  }
+
+  private void initApp(ResourceLocalizationService spyService,
+      EventHandler<ApplicationEvent> applicationBus, Application app,
+      ApplicationId appId, DrainDispatcher dispatcher) {
+    spyService.handle(new ApplicationLocalizationEvent(
+        LocalizationEventType.INIT_APPLICATION_RESOURCES, app));
+    ArgumentMatcher<ApplicationEvent> matchesAppInit =
         new ArgumentMatcher<ApplicationEvent>() {
           @Override
           public boolean matches(Object o) {
             ApplicationEvent evt = (ApplicationEvent) o;
             return evt.getType() == ApplicationEventType.APPLICATION_INITED
-              && appId == evt.getApplicationID();
+                && appId == evt.getApplicationID();
           }
         };
-      dispatcher.await();
-      verify(applicationBus).handle(argThat(matchesAppInit));
-
-      // Initialize localizer.
-      Random r = new Random();
-      long seed = r.nextLong();
-      System.out.println("SEED: " + seed);
-      r.setSeed(seed);
-      final Container c1 = getMockContainer(appId, 42, "user0");
-      final Container c2 = getMockContainer(appId, 43, "user0");
-      FSDataOutputStream out =
-        new FSDataOutputStream(new DataOutputBuffer(), null);
-      doReturn(out).when(spylfs).createInternal(isA(Path.class),
-          isA(EnumSet.class), isA(FsPermission.class), anyInt(), anyShort(),
-          anyLong(), isA(Progressable.class), isA(ChecksumOpt.class),
-          anyBoolean());
-      final LocalResource resource1 = getPrivateMockedResource(r);
-      LocalResource resource2 = null;
-      do {
-        resource2 = getPrivateMockedResource(r);
-      } while (resource2 == null || resource2.equals(resource1));
-      LocalResource resource3 = null;
-      do {
-        resource3 = getPrivateMockedResource(r);
-      } while (resource3 == null || resource3.equals(resource1)
-          || resource3.equals(resource2));
+    dispatcher.await();
+    verify(applicationBus).handle(argThat(matchesAppInit));
+  }
 
-      // Send localization requests for container c1 and c2.
-      final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
-      final LocalResourceRequest req2 = new LocalResourceRequest(resource2);
-      final LocalResourceRequest req3 = new LocalResourceRequest(resource3);
-      Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
+  private void doLocalization(ResourceLocalizationService spyService,
+      DrainDispatcher dispatcher, DummyExecutor exec,
+      DeletionService delService)
+      throws IOException, URISyntaxException, InterruptedException {
+    final Application app = mock(Application.class);
+    final ApplicationId appId =
+        BuilderUtils.newApplicationId(314159265358979L, 3);
+    String user = "user0";
+    when(app.getUser()).thenReturn(user);
+    when(app.getAppId()).thenReturn(appId);
+    List<LocalResource> resources = initializeLocalizer(appId);
+    LocalResource resource1 = resources.get(0);
+    LocalResource resource2 = resources.get(1);
+    LocalResource resource3 = resources.get(2);
+    final Container c1 = getMockContainer(appId, 42, "user0");
+    final Container c2 = getMockContainer(appId, 43, "user0");
+
+    EventHandler<ApplicationEvent> applicationBus =
+        getApplicationBus(dispatcher);
+    EventHandler<ContainerEvent> containerBus = getContainerBus(dispatcher);
+    initApp(spyService, applicationBus, app, appId, dispatcher);
+
+    // Send localization requests for container c1 and c2.
+    final LocalResourceRequest req1 = new LocalResourceRequest(resource1);
+    final LocalResourceRequest req2 = new LocalResourceRequest(resource2);
+    final LocalResourceRequest req3 = new LocalResourceRequest(resource3);
+    Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs =
         new HashMap<LocalResourceVisibility,
-                    Collection<LocalResourceRequest>>();
-      List<LocalResourceRequest> privateResourceList =
-          new ArrayList<LocalResourceRequest>();
-      privateResourceList.add(req1);
-      privateResourceList.add(req2);
-      privateResourceList.add(req3);
-      rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
-      spyService.handle(new ContainerLocalizationRequestEvent(c1, rsrcs));
-
-      final LocalResourceRequest req1_1 = new LocalResourceRequest(resource2);
-      Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs1 =
+            Collection<LocalResourceRequest>>();
+    List<LocalResourceRequest> privateResourceList =
+        new ArrayList<LocalResourceRequest>();
+    privateResourceList.add(req1);
+    privateResourceList.add(req2);
+    privateResourceList.add(req3);
+    rsrcs.put(LocalResourceVisibility.PRIVATE, privateResourceList);
+    spyService.handle(new ContainerLocalizationRequestEvent(c1, rsrcs));
+
+    final LocalResourceRequest req11 = new LocalResourceRequest(resource2);
+    Map<LocalResourceVisibility, Collection<LocalResourceRequest>> rsrcs1 =
         new HashMap<LocalResourceVisibility,
-                    Collection<LocalResourceRequest>>();
-      List<LocalResourceRequest> privateResourceList1 =
-          new ArrayList<LocalResourceRequest>();
-      privateResourceList1.add(req1_1);
-      rsrcs1.put(LocalResourceVisibility.PRIVATE, privateResourceList1);
-      spyService.handle(new ContainerLocalizationRequestEvent(c2, rsrcs1));
-
-      dispatcher.await();
-      // Wait for localizers of both container c1 and c2 to begin.
-      exec.waitForLocalizers(2);
-      LocalizerRunner locC1 =
-          spyService.getLocalizerRunner(c1.getContainerId().toString());
-      final String containerIdStr = c1.getContainerId().toString();
-      // Heartbeats from container localizer
-      LocalResourceStatus rsrc1success = mock(LocalResourceStatus.class);
-      LocalResourceStatus rsrc2pending = mock(LocalResourceStatus.class);
-      LocalizerStatus stat = mock(LocalizerStatus.class);
-      when(stat.getLocalizerId()).thenReturn(containerIdStr);
-      when(rsrc1success.getResource()).thenReturn(resource1);
-      when(rsrc2pending.getResource()).thenReturn(resource2);
-      when(rsrc1success.getLocalSize()).thenReturn(4344L);
-      URL locPath = getPath("/some/path");
-      when(rsrc1success.getLocalPath()).thenReturn(locPath);
-      when(rsrc1success.getStatus()).
-          thenReturn(ResourceStatusType.FETCH_SUCCESS);
-      when(rsrc2pending.getStatus()).
-          thenReturn(ResourceStatusType.FETCH_PENDING);
-
-      when(stat.getResources())
-        .thenReturn(Collections.<LocalResourceStatus>emptyList())
-        .thenReturn(Collections.singletonList(rsrc1success))
-        .thenReturn(Collections.singletonList(rsrc2pending))
-        .thenReturn(Collections.singletonList(rsrc2pending))
-        .thenReturn(Collections.<LocalResourceStatus>emptyList());
-
-      // First heartbeat which schedules first resource.
-      LocalizerHeartbeatResponse response = spyService.heartbeat(stat);
-      assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
-
-      // Second heartbeat which reports first resource as success.
-      // Second resource is scheduled.
-      response = spyService.heartbeat(stat);
-      assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
-      final String locPath1 = response.getResourceSpecs().get(0).
-          getDestinationDirectory().getFile();
-
-      // Third heartbeat which reports second resource as pending.
-      // Third resource is scheduled.
-      response = spyService.heartbeat(stat);
-      assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
-      final String locPath2 = response.getResourceSpecs().get(0).
-          getDestinationDirectory().getFile();
-
-      // Container c1 is killed which leads to cleanup
-      spyService.handle(new ContainerLocalizationCleanupEvent(c1, rsrcs));
-
-      // This heartbeat will indicate to container localizer to die as localizer
-      // runner has stopped.
-      response = spyService.heartbeat(stat);
-      assertEquals(LocalizerAction.DIE, response.getLocalizerAction());
-
-      exec.setStopLocalization();
-      dispatcher.await();
-      // verify container notification
-      ArgumentMatcher<ContainerEvent> successContainerLoc =
+            Collection<LocalResourceRequest>>();
+    List<LocalResourceRequest> privateResourceList1 =
+        new ArrayList<LocalResourceRequest>();
+    privateResourceList1.add(req11);
+    rsrcs1.put(LocalResourceVisibility.PRIVATE, privateResourceList1);
+    spyService.handle(new ContainerLocalizationRequestEvent(c2, rsrcs1));
+
+    dispatcher.await();
+    // Wait for localizers of both container c1 and c2 to begin.
+    exec.waitForLocalizers(2);
+    LocalizerRunner locC1 =
+        spyService.getLocalizerRunner(c1.getContainerId().toString());
+
+    LocalizerStatus stat = mockLocalizerStatus(c1, resource1, resource2);
+
+    // First heartbeat which schedules first resource.
+    LocalizerHeartbeatResponse response = spyService.heartbeat(stat);
+    assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
+
+    // Second heartbeat which reports first resource as success.
+    // Second resource is scheduled.
+    response = spyService.heartbeat(stat);
+    assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
+    final String locPath1 =
+        response.getResourceSpecs().get(0).getDestinationDirectory().getFile();
+
+    // Third heartbeat which reports second resource as pending.
+    // Third resource is scheduled.
+    response = spyService.heartbeat(stat);
+    assertEquals(LocalizerAction.LIVE, response.getLocalizerAction());
+    final String locPath2 =
+        response.getResourceSpecs().get(0).getDestinationDirectory().getFile();
+
+    // Container c1 is killed which leads to cleanup
+    spyService.handle(new ContainerLocalizationCleanupEvent(c1, rsrcs));
+
+    // This heartbeat will indicate to container localizer to die as localizer
+    // runner has stopped.
+    response = spyService.heartbeat(stat);
+    assertEquals(LocalizerAction.DIE, response.getLocalizerAction());
+
+    exec.setStopLocalization();
+    dispatcher.await();
+    // verify container notification
+    ArgumentMatcher<ContainerEvent> successContainerLoc =
         new ArgumentMatcher<ContainerEvent>() {
           @Override
           public boolean matches(Object o) {
             ContainerEvent evt = (ContainerEvent) o;
             return evt.getType() == ContainerEventType.RESOURCE_LOCALIZED
-              && c1.getContainerId() == evt.getContainerID();
+                && c1.getContainerId() == evt.getContainerID();
           }
         };
-      // Only one resource gets localized for container c1.
-      verify(containerBus).handle(argThat(successContainerLoc));
-
-      Set<Path> paths =
-          Sets.newHashSet(new Path(locPath1), new Path(locPath1 + "_tmp"),
-              new Path(locPath2), new Path(locPath2 + "_tmp"));
-      // Wait for localizer runner thread for container c1 to finish.
-      while (locC1.getState() != Thread.State.TERMINATED) {
-        Thread.sleep(50);
-      }
-      // Verify if downloading resources were submitted for deletion.
-      verify(delService).delete(eq(user),
-          (Path) eq(null), argThat(new DownloadingPathsMatcher(paths)));
-
-      LocalResourcesTracker tracker = spyService.getLocalResourcesTracker(
-          LocalResourceVisibility.PRIVATE, "user0", appId);
-      // Container c1 was killed but this resource was localized before kill
-      // hence its not removed despite ref cnt being 0.
-      LocalizedResource rsrc1 = tracker.getLocalizedResource(req1);
-      assertNotNull(rsrc1);
-      assertEquals(rsrc1.getState(), ResourceState.LOCALIZED);
-      assertEquals(rsrc1.getRefCount(), 0);
-
-      // Container c1 was killed but this resource is referenced by container c2
-      // as well hence its ref cnt is 1.
-      LocalizedResource rsrc2 = tracker.getLocalizedResource(req2);
-      assertNotNull(rsrc2);
-      assertEquals(rsrc2.getState(), ResourceState.DOWNLOADING);
-      assertEquals(rsrc2.getRefCount(), 1);
-
-      // As container c1 was killed and this resource was not referenced by any
-      // other container, hence its removed.
-      LocalizedResource rsrc3 = tracker.getLocalizedResource(req3);
-      assertNull(rsrc3);
-    } finally {
-      spyService.stop();
-      dispatcher.stop();
-      delService.stop();
+    // Only one resource gets localized for container c1.
+    verify(containerBus).handle(argThat(successContainerLoc));
+
+    Set<Path> paths =
+        Sets.newHashSet(new Path(locPath1), new Path(locPath1 + "_tmp"),
+            new Path(locPath2), new Path(locPath2 + "_tmp"));
+    // Wait for localizer runner thread for container c1 to finish.
+    while (locC1.getState() != Thread.State.TERMINATED) {
+      Thread.sleep(50);
     }
+    // Verify if downloading resources were submitted for deletion.
+    verify(delService).delete(eq(user), (Path) eq(null),
+        argThat(new DownloadingPathsMatcher(paths)));
+
+    LocalResourcesTracker tracker = spyService.getLocalResourcesTracker(
+        LocalResourceVisibility.PRIVATE, "user0", appId);
+    // Container c1 was killed but this resource was localized before kill
+    // hence its not removed despite ref cnt being 0.
+    LocalizedResource rsrc1 = tracker.getLocalizedResource(req1);
+    assertNotNull(rsrc1);
+    assertEquals(rsrc1.getState(), ResourceState.LOCALIZED);
+    assertEquals(rsrc1.getRefCount(), 0);
+
+    // Container c1 was killed but this resource is referenced by container c2
+    // as well hence its ref cnt is 1.
+    LocalizedResource rsrc2 = tracker.getLocalizedResource(req2);
+    assertNotNull(rsrc2);
+    assertEquals(rsrc2.getState(), ResourceState.DOWNLOADING);
+    assertEquals(rsrc2.getRefCount(), 1);
+
+    // As container c1 was killed and this resource was not referenced by any
+    // other container, hence its removed.
+    LocalizedResource rsrc3 = tracker.getLocalizedResource(req3);
+    assertNull(rsrc3);
+  }
+
+  private LocalizerStatus mockLocalizerStatus(Container c1,
+      LocalResource resource1, LocalResource resource2) {
+    final String containerIdStr = c1.getContainerId().toString();
+    // Heartbeats from container localizer
+    LocalResourceStatus rsrc1success = mock(LocalResourceStatus.class);
+    LocalResourceStatus rsrc2pending = mock(LocalResourceStatus.class);
+    LocalizerStatus stat = mock(LocalizerStatus.class);
+    when(stat.getLocalizerId()).thenReturn(containerIdStr);
+    when(rsrc1success.getResource()).thenReturn(resource1);
+    when(rsrc2pending.getResource()).thenReturn(resource2);
+    when(rsrc1success.getLocalSize()).thenReturn(4344L);
+    URL locPath = getPath("/some/path");
+    when(rsrc1success.getLocalPath()).thenReturn(locPath);
+    when(rsrc1success.getStatus()).thenReturn(ResourceStatusType.FETCH_SUCCESS);
+    when(rsrc2pending.getStatus()).thenReturn(ResourceStatusType.FETCH_PENDING);
+
+    when(stat.getResources())
+        .thenReturn(Collections.<LocalResourceStatus> emptyList())
+        .thenReturn(Collections.singletonList(rsrc1success))
+        .thenReturn(Collections.singletonList(rsrc2pending))
+        .thenReturn(Collections.singletonList(rsrc2pending))
+        .thenReturn(Collections.<LocalResourceStatus> emptyList());
+    return stat;
+  }
+
+  @SuppressWarnings("unchecked")
+  private List<LocalResource> initializeLocalizer(ApplicationId appId)
+      throws IOException {
+    // Initialize localizer.
+    Random r = new Random();
+    long seed = r.nextLong();
+    System.out.println("SEED: " + seed);
+    r.setSeed(seed);
+    FSDataOutputStream out =
+        new FSDataOutputStream(new DataOutputBuffer(), null);
+    doReturn(out).when(spylfs).createInternal(isA(Path.class),
+        isA(EnumSet.class), isA(FsPermission.class), anyInt(), anyShort(),
+        anyLong(), isA(Progressable.class), isA(ChecksumOpt.class),
+        anyBoolean());
+    final LocalResource resource1 = getPrivateMockedResource(r);
+    LocalResource resource2 = null;
+    do {
+      resource2 = getPrivateMockedResource(r);
+    } while (resource2 == null || resource2.equals(resource1));
+    LocalResource resource3 = null;
+    do {
+      resource3 = getPrivateMockedResource(r);
+    } while (resource3 == null || resource3.equals(resource1)
+        || resource3.equals(resource2));
+    return Arrays.asList(resource1, resource2, resource3);
   }
 
   @Test


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[25/50] [abbrv] hadoop git commit: HDFS-11598. Improve -setrep for Erasure Coded files. Contributed by Yiqun Lin.

Posted by in...@apache.org.
HDFS-11598. Improve -setrep for Erasure Coded files. Contributed by Yiqun Lin.


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

Branch: refs/heads/HDFS-10467
Commit: b4d65779841d824d0bff5f106b2888e8d4dbe8a8
Parents: 285478a
Author: Wei-Chiu Chuang <we...@apache.org>
Authored: Mon Apr 3 07:57:28 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../apache/hadoop/fs/shell/SetReplication.java  | 17 ++++++--
 .../hadoop/hdfs/TestSetrepIncreasing.java       | 44 ++++++++++++++++++++
 2 files changed, 57 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/b4d65779/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/SetReplication.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/SetReplication.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/SetReplication.java
index 2231c58..16e6e92 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/SetReplication.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/SetReplication.java
@@ -85,11 +85,20 @@ class SetReplication extends FsCommand {
     }
     
     if (item.stat.isFile()) {
-      if (!item.fs.setReplication(item.path, newRep)) {
-        throw new IOException("Could not set replication for: " + item);
+      // Do the checking if the file is erasure coded since
+      // replication factor for an EC file is meaningless.
+      if (!item.stat.isErasureCoded()) {
+        if (!item.fs.setReplication(item.path, newRep)) {
+          throw new IOException("Could not set replication for: " + item);
+        }
+        out.println("Replication " + newRep + " set: " + item);
+        if (waitOpt) {
+          waitList.add(item);
+        }
+      } else {
+        out.println("Did not set replication for: " + item
+            + ", because it's an erasure coded file.");
       }
-      out.println("Replication " + newRep + " set: " + item);
-      if (waitOpt) waitList.add(item);
     } 
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b4d65779/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetrepIncreasing.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetrepIncreasing.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetrepIncreasing.java
index fee30b5..50d7b27 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetrepIncreasing.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSetrepIncreasing.java
@@ -20,7 +20,9 @@ package org.apache.hadoop.hdfs;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.PrintStream;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.BlockLocation;
@@ -28,6 +30,7 @@ import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.FsShell;
 import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.protocol.ClientProtocol;
 import org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset;
 import org.junit.Test;
 
@@ -102,4 +105,45 @@ public class TestSetrepIncreasing {
       cluster.shutdown();
     }
  }
+
+  @Test
+  public void testSetRepOnECFile() throws Exception {
+    ClientProtocol client;
+    Configuration conf = new HdfsConfiguration();
+    conf.set(DFSConfigKeys.DFS_NAMENODE_EC_POLICIES_ENABLED_KEY,
+        StripedFileTestUtil.getDefaultECPolicy().getName());
+    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1)
+        .build();
+    cluster.waitActive();
+    client = NameNodeProxies.createProxy(conf,
+        cluster.getFileSystem(0).getUri(), ClientProtocol.class).getProxy();
+    client.setErasureCodingPolicy("/",
+        StripedFileTestUtil.getDefaultECPolicy().getName());
+
+    FileSystem dfs = cluster.getFileSystem();
+    try {
+      Path d = new Path("/tmp");
+      dfs.mkdirs(d);
+      Path f = new Path(d, "foo");
+      dfs.createNewFile(f);
+      FileStatus file = dfs.getFileStatus(f);
+      assertTrue(file.isErasureCoded());
+
+      ByteArrayOutputStream out = new ByteArrayOutputStream();
+      System.setOut(new PrintStream(out));
+      String[] args = {"-setrep", "2", "" + f};
+      FsShell shell = new FsShell();
+      shell.setConf(conf);
+      assertEquals(0, shell.run(args));
+      assertTrue(
+          out.toString().contains("Did not set replication for: /tmp/foo"));
+
+      // verify the replication factor of the EC file
+      file = dfs.getFileStatus(f);
+      assertEquals(1, file.getReplication());
+    } finally {
+      dfs.close();
+      cluster.shutdown();
+    }
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[12/50] [abbrv] hadoop git commit: YARN-6377. NMTimelinePublisher#serviceStop does not stop timeline clients (Haibo Chen via Varun Saxena)

Posted by in...@apache.org.
YARN-6377. NMTimelinePublisher#serviceStop does not stop timeline clients (Haibo Chen via Varun Saxena)


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

Branch: refs/heads/HDFS-10467
Commit: 51456bf8ebf3e46604ddb0461a186eb82d4fd3a5
Parents: 2882013
Author: Varun Saxena <va...@apache.org>
Authored: Sun Apr 2 04:54:12 2017 +0530
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../nodemanager/timelineservice/NMTimelinePublisher.java  |  8 ++++++++
 .../timelineservice/TestNMTimelinePublisher.java          | 10 +++++++++-
 2 files changed, 17 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/51456bf8/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/NMTimelinePublisher.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/timelineservice/NMTimelinePublisher.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/NMTimelinePublisher.java
index ce2c656..8aaae79 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/NMTimelinePublisher.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/NMTimelinePublisher.java
@@ -101,6 +101,14 @@ public class NMTimelinePublisher extends CompositeService {
     this.nodeId = context.getNodeId();
   }
 
+  @Override
+  protected void serviceStop() throws Exception {
+    for(ApplicationId app : appToClientMap.keySet()) {
+      stopTimelineClient(app);
+    }
+    super.serviceStop();
+  }
+
   @VisibleForTesting
   Map<ApplicationId, TimelineV2Client> getAppToClientMap() {
     return appToClientMap;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/51456bf8/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.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/timelineservice/TestNMTimelinePublisher.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.java
index e116122..0b8eaa9 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/timelineservice/TestNMTimelinePublisher.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.yarn.api.records.NodeId;
 import org.apache.hadoop.yarn.api.records.timelineservice.TimelineEntity;
 import org.apache.hadoop.yarn.api.records.timelineservice.TimelineMetric;
 import org.apache.hadoop.yarn.client.api.impl.TimelineV2ClientImpl;
+import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.Container;
@@ -53,14 +54,21 @@ public class TestNMTimelinePublisher {
     final DummyTimelineClient timelineClient = new DummyTimelineClient(null);
     when(context.getNodeId()).thenReturn(NodeId.newInstance("localhost", 0));
     when(context.getHttpPort()).thenReturn(0);
+
+    Configuration conf = new Configuration();
+    conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
+    conf.setFloat(YarnConfiguration.TIMELINE_SERVICE_VERSION, 2.0f);
+
     NMTimelinePublisher publisher = new NMTimelinePublisher(context) {
       public void createTimelineClient(ApplicationId appId) {
         if (!getAppToClientMap().containsKey(appId)) {
+          timelineClient.init(getConfig());
+          timelineClient.start();
           getAppToClientMap().put(appId, timelineClient);
         }
       }
     };
-    publisher.init(new Configuration());
+    publisher.init(conf);
     publisher.start();
     ApplicationId appId = ApplicationId.newInstance(0, 1);
     publisher.createTimelineClient(appId);


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[17/50] [abbrv] hadoop git commit: HADOOP-14104. Client should always ask namenode for kms provider path. Contributed by Rushabh S Shah.

Posted by in...@apache.org.
HADOOP-14104. Client should always ask namenode for kms provider path. Contributed by Rushabh S Shah.


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

Branch: refs/heads/HDFS-10467
Commit: b8a0b18f10018fab7e16ac31f4ff76ec544be33e
Parents: 0edd758
Author: Andrew Wang <wa...@apache.org>
Authored: Tue Apr 4 13:38:25 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../java/org/apache/hadoop/fs/FileSystem.java   |   3 +-
 .../org/apache/hadoop/fs/FsServerDefaults.java  |  13 +-
 .../org/apache/hadoop/fs/ftp/FtpConfigKeys.java |   4 +-
 .../apache/hadoop/fs/local/LocalConfigKeys.java |   5 +-
 .../java/org/apache/hadoop/util/KMSUtil.java    |  20 +-
 .../src/main/resources/core-default.xml         |   2 +
 .../java/org/apache/hadoop/hdfs/DFSClient.java  |  78 ++++++-
 .../hadoop/hdfs/DistributedFileSystem.java      |  13 +-
 .../apache/hadoop/hdfs/KeyProviderCache.java    |  17 +-
 .../hadoop/hdfs/protocolPB/PBHelperClient.java  |   4 +-
 .../src/main/proto/hdfs.proto                   |   1 +
 .../hdfs/server/namenode/FSNamesystem.java      |   8 +-
 .../src/site/markdown/TransparentEncryption.md  |   1 +
 .../apache/hadoop/hdfs/TestEncryptionZones.java | 205 +++++++++++++++++++
 .../hadoop/hdfs/TestKeyProviderCache.java       |  21 +-
 .../hadoop/hdfs/protocolPB/TestPBHelper.java    |  31 +++
 16 files changed, 386 insertions(+), 40 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/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 c3282e5..8f3f40d 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
@@ -874,7 +874,8 @@ public abstract class FileSystem extends Configured implements Closeable {
         config.getInt(IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT),
         false,
         FS_TRASH_INTERVAL_DEFAULT,
-        DataChecksum.Type.CRC32);
+        DataChecksum.Type.CRC32,
+        "");
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsServerDefaults.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsServerDefaults.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsServerDefaults.java
index c1b9071..469243c 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsServerDefaults.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FsServerDefaults.java
@@ -54,6 +54,7 @@ public class FsServerDefaults implements Writable {
   private boolean encryptDataTransfer;
   private long trashInterval;
   private DataChecksum.Type checksumType;
+  private String keyProviderUri;
 
   public FsServerDefaults() {
   }
@@ -61,7 +62,8 @@ public class FsServerDefaults implements Writable {
   public FsServerDefaults(long blockSize, int bytesPerChecksum,
       int writePacketSize, short replication, int fileBufferSize,
       boolean encryptDataTransfer, long trashInterval,
-      DataChecksum.Type checksumType) {
+      DataChecksum.Type checksumType,
+      String keyProviderUri) {
     this.blockSize = blockSize;
     this.bytesPerChecksum = bytesPerChecksum;
     this.writePacketSize = writePacketSize;
@@ -70,6 +72,7 @@ public class FsServerDefaults implements Writable {
     this.encryptDataTransfer = encryptDataTransfer;
     this.trashInterval = trashInterval;
     this.checksumType = checksumType;
+    this.keyProviderUri = keyProviderUri;
   }
 
   public long getBlockSize() {
@@ -104,6 +107,14 @@ public class FsServerDefaults implements Writable {
     return checksumType;
   }
 
+  /* null means old style namenode.
+   * "" (empty string) means namenode is upgraded but EZ is not supported.
+   * some string means that value is the key provider.
+   */
+  public String getKeyProviderUri() {
+    return keyProviderUri;
+  }
+
   // /////////////////////////////////////////
   // Writable
   // /////////////////////////////////////////

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ftp/FtpConfigKeys.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ftp/FtpConfigKeys.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ftp/FtpConfigKeys.java
index 2313a14..e59efa5 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ftp/FtpConfigKeys.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ftp/FtpConfigKeys.java
@@ -54,6 +54,7 @@ public class FtpConfigKeys extends CommonConfigurationKeys {
   public static final long    FS_TRASH_INTERVAL_DEFAULT = 0;
   public static final DataChecksum.Type CHECKSUM_TYPE_DEFAULT =
       DataChecksum.Type.CRC32;
+  public static final String KEY_PROVIDER_URI_DEFAULT = "";
   
   protected static FsServerDefaults getServerDefaults() throws IOException {
     return new FsServerDefaults(
@@ -64,7 +65,8 @@ public class FtpConfigKeys extends CommonConfigurationKeys {
         STREAM_BUFFER_SIZE_DEFAULT,
         ENCRYPT_DATA_TRANSFER_DEFAULT,
         FS_TRASH_INTERVAL_DEFAULT,
-        CHECKSUM_TYPE_DEFAULT);
+        CHECKSUM_TYPE_DEFAULT,
+        KEY_PROVIDER_URI_DEFAULT);
   }
 }
   

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/local/LocalConfigKeys.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/local/LocalConfigKeys.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/local/LocalConfigKeys.java
index d1ebca2..0b9e7455 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/local/LocalConfigKeys.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/local/LocalConfigKeys.java
@@ -54,6 +54,8 @@ public class LocalConfigKeys extends CommonConfigurationKeys {
   public static final long FS_TRASH_INTERVAL_DEFAULT = 0;
   public static final DataChecksum.Type CHECKSUM_TYPE_DEFAULT =
       DataChecksum.Type.CRC32;
+  public static final String KEY_PROVIDER_URI_DEFAULT = "";
+
   public static FsServerDefaults getServerDefaults() throws IOException {
     return new FsServerDefaults(
         BLOCK_SIZE_DEFAULT,
@@ -63,7 +65,8 @@ public class LocalConfigKeys extends CommonConfigurationKeys {
         STREAM_BUFFER_SIZE_DEFAULT,
         ENCRYPT_DATA_TRANSFER_DEFAULT,
         FS_TRASH_INTERVAL_DEFAULT,
-        CHECKSUM_TYPE_DEFAULT);
+        CHECKSUM_TYPE_DEFAULT,
+        KEY_PROVIDER_URI_DEFAULT);
   }
 }
   

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/KMSUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/KMSUtil.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/KMSUtil.java
index bd6b460..5f783a9 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/KMSUtil.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/KMSUtil.java
@@ -26,7 +26,6 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.net.URI;
-import java.net.URISyntaxException;
 
 /**
  * Utils for KMS.
@@ -51,21 +50,20 @@ public final class KMSUtil {
   public static KeyProvider createKeyProvider(final Configuration conf,
       final String configKeyName) throws IOException {
     LOG.debug("Creating key provider with config key {}", configKeyName);
-    final String providerUriStr = conf.getTrimmed(configKeyName, "");
+    final String providerUriStr = conf.getTrimmed(configKeyName);
     // No provider set in conf
-    if (providerUriStr.isEmpty()) {
+    if (providerUriStr == null || providerUriStr.isEmpty()) {
       return null;
     }
-    final URI providerUri;
-    try {
-      providerUri = new URI(providerUriStr);
-    } catch (URISyntaxException e) {
-      throw new IOException(e);
-    }
+    return createKeyProviderFromUri(conf, URI.create(providerUriStr));
+  }
+
+  public static KeyProvider createKeyProviderFromUri(final Configuration conf,
+      final URI providerUri) throws IOException {
     KeyProvider keyProvider = KeyProviderFactory.get(providerUri, conf);
     if (keyProvider == null) {
-      throw new IOException("Could not instantiate KeyProvider from " +
-          configKeyName + " setting of '" + providerUriStr + "'");
+      throw new IOException("Could not instantiate KeyProvider for uri: " +
+          providerUri);
     }
     if (keyProvider.isTransient()) {
       throw new IOException("KeyProvider " + keyProvider.toString()

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/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 f742ba8..b8f9904 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
@@ -2202,6 +2202,8 @@
   <description>
     The KeyProvider to use when managing zone keys, and interacting with
     encryption keys when reading and writing to an encryption zone.
+    For hdfs clients, the provider path will be same as namenode's
+    provider path.
   </description>
 </property>
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
index aaf8bdd..5bc38e8 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSClient.java
@@ -67,6 +67,7 @@ import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
 import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion;
 import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.CacheFlag;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
 import org.apache.hadoop.fs.ContentSummary;
 import org.apache.hadoop.fs.CreateFlag;
 import org.apache.hadoop.fs.FileAlreadyExistsException;
@@ -160,6 +161,7 @@ import org.apache.hadoop.ipc.RpcNoSuchMethodException;
 import org.apache.hadoop.net.DNS;
 import org.apache.hadoop.net.NetUtils;
 import org.apache.hadoop.security.AccessControlException;
+import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.SecretManager.InvalidToken;
 import org.apache.hadoop.security.token.Token;
@@ -197,6 +199,7 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
   public static final Logger LOG = LoggerFactory.getLogger(DFSClient.class);
   // 1 hour
   public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L;
+  private static final String DFS_KMS_PREFIX = "dfs-kms-";
 
   private final Configuration conf;
   private final Tracer tracer;
@@ -214,7 +217,7 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
   final SocketFactory socketFactory;
   final ReplaceDatanodeOnFailure dtpReplaceDatanodeOnFailure;
   private final FileSystem.Statistics stats;
-  private final String authority;
+  private final URI namenodeUri;
   private final Random r = new Random();
   private SocketAddress[] localInterfaceAddrs;
   private DataEncryptionKey encryptionKey;
@@ -228,6 +231,7 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
   private static ThreadPoolExecutor HEDGED_READ_THREAD_POOL;
   private static volatile ThreadPoolExecutor STRIPED_READ_THREAD_POOL;
   private final int smallBufferSize;
+  private URI keyProviderUri = null;
 
   public DfsClientConf getConf() {
     return dfsClientConf;
@@ -298,7 +302,7 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
 
     this.ugi = UserGroupInformation.getCurrentUser();
 
-    this.authority = nameNodeUri == null? "null": nameNodeUri.getAuthority();
+    this.namenodeUri = nameNodeUri;
     this.clientName = "DFSClient_" + dfsClientConf.getTaskId() + "_" +
         ThreadLocalRandom.current().nextInt()  + "_" +
         Thread.currentThread().getId();
@@ -454,7 +458,8 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
    *  be returned until all output streams are closed.
    */
   public LeaseRenewer getLeaseRenewer() {
-    return LeaseRenewer.getInstance(authority, ugi, this);
+    return LeaseRenewer.getInstance(
+        namenodeUri != null ? namenodeUri.getAuthority() : "null", ugi, this);
   }
 
   /** Get a lease and start automatic renewal */
@@ -2851,8 +2856,66 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
     return HEDGED_READ_METRIC;
   }
 
-  public KeyProvider getKeyProvider() {
-    return clientContext.getKeyProviderCache().get(conf);
+  /**
+   * Returns a key to map namenode uri to key provider uri.
+   * Tasks will lookup this key to find key Provider.
+   */
+  public Text getKeyProviderMapKey() {
+    return new Text(DFS_KMS_PREFIX + namenodeUri.getScheme()
+        +"://" + namenodeUri.getAuthority());
+  }
+
+  /**
+   * The key provider uri is searched in the following order.
+   * 1. If there is a mapping in Credential's secrets map for namenode uri.
+   * 2. From namenode getServerDefaults rpc.
+   * 3. Finally fallback to local conf.
+   * @return keyProviderUri if found from either of above 3 cases,
+   * null otherwise
+   * @throws IOException
+   */
+  URI getKeyProviderUri() throws IOException {
+    if (keyProviderUri != null) {
+      return keyProviderUri;
+    }
+
+    // Lookup the secret in credentials object for namenodeuri.
+    Credentials credentials = ugi.getCredentials();
+    byte[] keyProviderUriBytes = credentials.getSecretKey(getKeyProviderMapKey());
+    if(keyProviderUriBytes != null) {
+      keyProviderUri =
+          URI.create(DFSUtilClient.bytes2String(keyProviderUriBytes));
+      return keyProviderUri;
+    }
+
+    // Query the namenode for the key provider uri.
+    FsServerDefaults serverDefaults = getServerDefaults();
+    if (serverDefaults.getKeyProviderUri() != null) {
+      if (!serverDefaults.getKeyProviderUri().isEmpty()) {
+        keyProviderUri = URI.create(serverDefaults.getKeyProviderUri());
+      }
+      return keyProviderUri;
+    }
+
+    // Last thing is to trust its own conf to be backwards compatible.
+    String keyProviderUriStr = conf.getTrimmed(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH);
+    if (keyProviderUriStr != null && !keyProviderUriStr.isEmpty()) {
+      keyProviderUri = URI.create(keyProviderUriStr);
+    }
+    return keyProviderUri;
+  }
+
+  public KeyProvider getKeyProvider() throws IOException {
+    return clientContext.getKeyProviderCache().get(conf, getKeyProviderUri());
+  }
+
+  /*
+   * Should be used only for testing.
+   */
+  @VisibleForTesting
+  public void setKeyProviderUri(URI providerUri) {
+    this.keyProviderUri = providerUri;
   }
 
   @VisibleForTesting
@@ -2862,11 +2925,10 @@ public class DFSClient implements java.io.Closeable, RemotePeerFactory,
 
   /**
    * Probe for encryption enabled on this filesystem.
-   * See {@link DFSUtilClient#isHDFSEncryptionEnabled(Configuration)}
    * @return true if encryption is enabled
    */
-  public boolean isHDFSEncryptionEnabled() {
-    return DFSUtilClient.isHDFSEncryptionEnabled(this.conf);
+  public boolean isHDFSEncryptionEnabled() throws IOException{
+    return getKeyProviderUri() != null;
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/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 5cd956c..2336fab 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
@@ -2409,12 +2409,15 @@ public class DistributedFileSystem extends FileSystem {
   public Token<?>[] addDelegationTokens(
       final String renewer, Credentials credentials) throws IOException {
     Token<?>[] tokens = super.addDelegationTokens(renewer, credentials);
-    if (dfs.isHDFSEncryptionEnabled()) {
+    URI keyProviderUri = dfs.getKeyProviderUri();
+    if (keyProviderUri != null) {
       KeyProviderDelegationTokenExtension keyProviderDelegationTokenExtension =
           KeyProviderDelegationTokenExtension.
               createKeyProviderDelegationTokenExtension(dfs.getKeyProvider());
       Token<?>[] kpTokens = keyProviderDelegationTokenExtension.
           addDelegationTokens(renewer, credentials);
+      credentials.addSecretKey(dfs.getKeyProviderMapKey(),
+          DFSUtilClient.string2Bytes(keyProviderUri.toString()));
       if (tokens != null && kpTokens != null) {
         Token<?>[] all = new Token<?>[tokens.length + kpTokens.length];
         System.arraycopy(tokens, 0, all, 0, tokens.length);
@@ -2551,7 +2554,13 @@ public class DistributedFileSystem extends FileSystem {
    */
   @Override
   public Path getTrashRoot(Path path) {
-    if ((path == null) || !dfs.isHDFSEncryptionEnabled()) {
+    try {
+      if ((path == null) || !dfs.isHDFSEncryptionEnabled()) {
+        return super.getTrashRoot(path);
+      }
+    } catch (IOException ioe) {
+      DFSClient.LOG.warn("Exception while checking whether encryption zone is "
+          + "supported", ioe);
       return super.getTrashRoot(path);
     }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/KeyProviderCache.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/KeyProviderCache.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/KeyProviderCache.java
index 3491010..17d20fe 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/KeyProviderCache.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/KeyProviderCache.java
@@ -26,6 +26,7 @@ import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.crypto.key.KeyProvider;
 import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.util.KMSUtil;
 
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.cache.Cache;
@@ -66,29 +67,29 @@ public class KeyProviderCache {
         .build();
   }
 
-  public KeyProvider get(final Configuration conf) {
-    URI kpURI = createKeyProviderURI(conf);
-    if (kpURI == null) {
+  public KeyProvider get(final Configuration conf,
+      final URI serverProviderUri) {
+    if (serverProviderUri == null) {
       return null;
     }
     try {
-      return cache.get(kpURI, new Callable<KeyProvider>() {
+      return cache.get(serverProviderUri, new Callable<KeyProvider>() {
         @Override
         public KeyProvider call() throws Exception {
-          return DFSUtilClient.createKeyProvider(conf);
+          return KMSUtil.createKeyProviderFromUri(conf, serverProviderUri);
         }
       });
     } catch (Exception e) {
-      LOG.error("Could not create KeyProvider for DFSClient !!", e.getCause());
+      LOG.error("Could not create KeyProvider for DFSClient !!", e);
       return null;
     }
   }
 
   private URI createKeyProviderURI(Configuration conf) {
     final String providerUriStr = conf.getTrimmed(
-        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH, "");
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH);
     // No provider set in conf
-    if (providerUriStr.isEmpty()) {
+    if (providerUriStr == null || providerUriStr.isEmpty()) {
       LOG.error("Could not find uri with key ["
           + CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH
           + "] to create a keyProvider !!");

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java
index b4fa926..125b53f 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java
@@ -1758,7 +1758,8 @@ public class PBHelperClient {
         fs.getFileBufferSize(),
         fs.getEncryptDataTransfer(),
         fs.getTrashInterval(),
-        convert(fs.getChecksumType()));
+        convert(fs.getChecksumType()),
+        fs.hasKeyProviderUri() ? fs.getKeyProviderUri() : null);
   }
 
   public static List<CryptoProtocolVersionProto> convert(
@@ -1932,6 +1933,7 @@ public class PBHelperClient {
         .setEncryptDataTransfer(fs.getEncryptDataTransfer())
         .setTrashInterval(fs.getTrashInterval())
         .setChecksumType(convert(fs.getChecksumType()))
+        .setKeyProviderUri(fs.getKeyProviderUri())
         .build();
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto
index 7824fd1..9e03b29 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto
@@ -420,6 +420,7 @@ message FsServerDefaultsProto {
   optional bool encryptDataTransfer = 6 [default = false];
   optional uint64 trashInterval = 7 [default = 0];
   optional ChecksumTypeProto checksumType = 8 [default = CHECKSUM_CRC32];
+  optional string keyProviderUri = 9;
 }
 
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/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 f405cc0..2a7c75b 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
@@ -148,6 +148,7 @@ import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
 import org.apache.hadoop.hdfs.AddBlockFlag;
 import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedListEntries;
 import org.apache.hadoop.fs.CacheFlag;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
 import org.apache.hadoop.fs.ContentSummary;
 import org.apache.hadoop.fs.CreateFlag;
 import org.apache.hadoop.fs.FileEncryptionInfo;
@@ -778,8 +779,11 @@ public class FSNamesystem implements Namesystem, FSNamesystemMBean,
           conf.getInt(IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT),
           conf.getBoolean(DFS_ENCRYPT_DATA_TRANSFER_KEY, DFS_ENCRYPT_DATA_TRANSFER_DEFAULT),
           conf.getLong(FS_TRASH_INTERVAL_KEY, FS_TRASH_INTERVAL_DEFAULT),
-          checksumType);
-      
+          checksumType,
+          conf.getTrimmed(
+          CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
+          ""));
+
       this.maxFsObjects = conf.getLong(DFS_NAMENODE_MAX_OBJECTS_KEY, 
                                        DFS_NAMENODE_MAX_OBJECTS_DEFAULT);
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/TransparentEncryption.md
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/TransparentEncryption.md b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/TransparentEncryption.md
index 089d7b4..3f9fbf0 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/TransparentEncryption.md
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/TransparentEncryption.md
@@ -97,6 +97,7 @@ Once a KMS has been set up and the NameNode and HDFS clients have been correctly
 #### hadoop.security.key.provider.path
 
 The KeyProvider to use when interacting with encryption keys used when reading and writing to an encryption zone.
+HDFS clients will use the provider path returned from Namenode via getServerDefaults. If namenode doesn't support returning key provider uri then client's conf will be used.
 
 ### <a name="Selecting_an_encryption_algorithm_and_codec"></a>Selecting an encryption algorithm and codec
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/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 6417078..61cc433 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
@@ -56,6 +56,7 @@ import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.FileSystemTestHelper;
 import org.apache.hadoop.fs.FileSystemTestWrapper;
+import org.apache.hadoop.fs.FsServerDefaults;
 import org.apache.hadoop.fs.FsShell;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.fs.RemoteIterator;
@@ -83,6 +84,7 @@ import org.apache.hadoop.security.AccessControlException;
 import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
+import org.apache.hadoop.util.DataChecksum;
 import org.apache.hadoop.util.ToolRunner;
 import org.apache.hadoop.crypto.key.KeyProviderDelegationTokenExtension.DelegationTokenExtension;
 import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.CryptoExtension;
@@ -105,8 +107,21 @@ import static org.mockito.Matchers.anyShort;
 import static org.mockito.Mockito.withSettings;
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyString;
+import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_DEFAULT;
 import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_TRASH_INTERVAL_KEY;
+import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT;
+import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_KEY;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_DEFAULT;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_KEY;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_DEFAULT;
+import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_KEY;
 import static org.apache.hadoop.hdfs.DFSTestUtil.verifyFilesEqual;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
+import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;
 import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
 import static org.apache.hadoop.test.MetricsAsserts.assertGauge;
 import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
@@ -1668,4 +1683,194 @@ public class TestEncryptionZones {
       }
     }
   }
+
+  /** This test tests that client will first lookup secrets map
+   * for key provider uri from {@link Credentials} in
+   * {@link UserGroupInformation}
+   * @throws Exception
+   */
+  @Test
+  public void testProviderUriInCredentials() throws Exception {
+    String dummyKeyProvider = "dummy://foo:bar@test_provider1";
+    DFSClient client = cluster.getFileSystem().getClient();
+    Credentials credentials = new Credentials();
+    // Key provider uri should be in the secret map of credentials object with
+    // namenode uri as key
+    Text lookUpKey = client.getKeyProviderMapKey();
+    credentials.addSecretKey(lookUpKey,
+        DFSUtilClient.string2Bytes(dummyKeyProvider));
+    client.ugi.addCredentials(credentials);
+    client.setKeyProviderUri(null);
+    Assert.assertEquals("Client Key provider is different from provider in "
+        + "credentials map", dummyKeyProvider,
+        client.getKeyProviderUri().toString());
+  }
+
+
+ /**
+  * Testing the fallback behavior of keyProviderUri.
+  * This test tests first the key provider uri is used from conf
+  * and then used from serverDefaults.
+  * @throws IOException
+  */
+  @Test
+  public void testKeyProviderFallBackBehavior() throws IOException {
+    Configuration clusterConf = cluster.getConfiguration(0);
+    String dummyKeyProviderUri1 = "dummy://foo:bar@test_provider1";
+    // set the key provider uri in conf.
+    clusterConf.set(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
+        dummyKeyProviderUri1);
+    DFSClient mockClient = Mockito.spy(cluster.getFileSystem().getClient());
+    mockClient.setKeyProviderUri(null);
+    // Namenode returning null as keyProviderUri in FSServerDefaults.
+    FsServerDefaults serverDefaultsWithKeyProviderNull =
+        getTestServerDefaults(null);
+    Mockito.doReturn(serverDefaultsWithKeyProviderNull)
+        .when(mockClient).getServerDefaults();
+    Assert.assertEquals(
+        "Key provider uri from client doesn't match with uri from conf",
+        dummyKeyProviderUri1, mockClient.getKeyProviderUri().toString());
+    Mockito.verify(mockClient, Mockito.times(1)).getServerDefaults();
+
+    String dummyKeyProviderUri2 = "dummy://foo:bar@test_provider2";
+    mockClient.setKeyProviderUri(null);
+    FsServerDefaults serverDefaultsWithDummyKeyProvider =
+        getTestServerDefaults(dummyKeyProviderUri2);
+    // Namenode returning dummyKeyProvider2 in serverDefaults.
+    Mockito.doReturn(serverDefaultsWithDummyKeyProvider)
+    .when(mockClient).getServerDefaults();
+    Assert.assertEquals(
+        "Key provider uri from client doesn't match with uri from namenode",
+        dummyKeyProviderUri2, mockClient.getKeyProviderUri().toString());
+    Mockito.verify(mockClient, Mockito.times(2)).getServerDefaults();
+  }
+
+  /**
+   * This test makes sure the client gets the key provider uri from namenode
+   * instead of its own conf.
+   * This test assumes both the namenode and client are upgraded.
+   * @throws Exception
+   */
+  @Test
+  public void testDifferentKMSProviderOnUpgradedNamenode() throws Exception {
+    Configuration clusterConf = cluster.getConfiguration(0);
+    URI namenodeKeyProviderUri = URI.create(getKeyProviderURI());
+    Assert.assertEquals("Key Provider for client and namenode are different",
+        namenodeKeyProviderUri, cluster.getFileSystem().getClient()
+        .getKeyProviderUri());
+
+    // Unset the provider path in conf
+    clusterConf.unset(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH);
+    // Nullify the cached value for key provider uri on client
+    cluster.getFileSystem().getClient().setKeyProviderUri(null);
+    // Even after unsetting the local conf, the client key provider should be
+    // the same as namenode's provider.
+    Assert.assertEquals("Key Provider for client and namenode are different",
+        namenodeKeyProviderUri, cluster.getFileSystem().getClient()
+        .getKeyProviderUri());
+
+    // Set the provider path to some dummy scheme.
+    clusterConf.set(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
+        "dummy://foo:bar@test_provider1");
+    // Nullify the cached value for key provider uri on client
+    cluster.getFileSystem().getClient().setKeyProviderUri(null);
+    // Even after pointing the conf to some dummy provider, the client key
+    // provider should be the same as namenode's provider.
+    Assert.assertEquals("Key Provider for client and namenode are different",
+        namenodeKeyProviderUri, cluster.getFileSystem().getClient()
+        .getKeyProviderUri());
+  }
+
+  /**
+   * This test makes sure the client trusts its local conf
+   * This test assumes the client is upgraded but the namenode is not.
+   * @throws Exception
+   */
+  @Test
+  public void testDifferentKMSProviderOnUnUpgradedNamenode()
+      throws Exception {
+    Configuration clusterConf = cluster.getConfiguration(0);
+    URI namenodeKeyProviderUri = URI.create(getKeyProviderURI());
+    URI clientKeyProviderUri =
+        cluster.getFileSystem().getClient().getKeyProviderUri();
+    Assert.assertNotNull(clientKeyProviderUri);
+    // Since the client and the namenode share the same conf, they will have
+    // identical key provider.
+    Assert.assertEquals("Key Provider for client and namenode are different",
+        namenodeKeyProviderUri, clientKeyProviderUri);
+
+    String dummyKeyProviderUri = "dummy://foo:bar@test_provider";
+    // Unset the provider path in conf.
+    clusterConf.set(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
+        dummyKeyProviderUri);
+    FsServerDefaults spyServerDefaults = getTestServerDefaults(null);
+    // Creating a fake serverdefaults so that we can simulate namenode not
+    // being upgraded.
+    DFSClient spyClient = Mockito.spy(cluster.getFileSystem().getClient());
+    // Clear the cache value of keyProviderUri on client side.
+    spyClient.setKeyProviderUri(null);
+    Mockito.doReturn(spyServerDefaults).when(spyClient).getServerDefaults();
+
+    // Since FsServerDefaults#keyProviderUri is null, the client
+    // will fallback to local conf which is null.
+    clientKeyProviderUri = spyClient.getKeyProviderUri();
+    Assert.assertEquals("Client keyProvider should be " + dummyKeyProviderUri,
+        dummyKeyProviderUri, clientKeyProviderUri.toString());
+    Mockito.verify(spyClient, Mockito.times(1)).getServerDefaults();
+  }
+
+  // Given a provider uri return serverdefaults.
+  // provider uri == null means the namenode does not support returning
+  // provider uri in FSServerDefaults object.
+  private FsServerDefaults getTestServerDefaults(String providerPath) {
+    FsServerDefaults serverDefaults = new FsServerDefaults(
+        conf.getLongBytes(DFS_BLOCK_SIZE_KEY, DFS_BLOCK_SIZE_DEFAULT),
+        conf.getInt(DFS_BYTES_PER_CHECKSUM_KEY, DFS_BYTES_PER_CHECKSUM_DEFAULT),
+        conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
+        DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT),
+        (short) conf.getInt(DFS_REPLICATION_KEY, DFS_REPLICATION_DEFAULT),
+        conf.getInt(IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT),
+        conf.getBoolean(
+        DFS_ENCRYPT_DATA_TRANSFER_KEY, DFS_ENCRYPT_DATA_TRANSFER_DEFAULT),
+        conf.getLong(FS_TRASH_INTERVAL_KEY, FS_TRASH_INTERVAL_DEFAULT),
+        DataChecksum.Type.valueOf(DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT),
+        providerPath);
+    return serverDefaults;
+  }
+
+  /**
+   * This test performs encrypted read/write and picks up the key provider uri
+   * from the credentials and not the conf.
+   * @throws Exception
+   */
+  @Test
+  public void testEncryptedReadWriteUsingDiffKeyProvider() throws Exception {
+    final HdfsAdmin dfsAdmin =
+        new HdfsAdmin(FileSystem.getDefaultUri(conf), conf);
+    Configuration clusterConf = cluster.getConfiguration(0);
+    clusterConf.unset(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH);
+    DFSClient client = cluster.getFileSystem().getClient();
+    Credentials credentials = new Credentials();
+    Text lookUpKey = client.getKeyProviderMapKey();
+    credentials.addSecretKey(lookUpKey,
+        DFSUtilClient.string2Bytes(getKeyProviderURI()));
+    client.ugi.addCredentials(credentials);
+    // Create a base file for comparison
+    final Path baseFile = new Path("/base");
+    final int len = 8192;
+    DFSTestUtil.createFile(fs, baseFile, len, (short) 1, 0xFEED);
+    // Create the first enc file
+    final Path zone = new Path("/zone");
+    fs.mkdirs(zone);
+    dfsAdmin.createEncryptionZone(zone, TEST_KEY, NO_TRASH);
+    final Path encFile1 = new Path(zone, "myfile");
+    DFSTestUtil.createFile(fs, encFile1, len, (short) 1, 0xFEED);
+    // Read them back in and compare byte-by-byte
+    verifyFilesEqual(fs, baseFile, encFile1, len);
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestKeyProviderCache.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestKeyProviderCache.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestKeyProviderCache.java
index 0868b54..9fc6b38 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestKeyProviderCache.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestKeyProviderCache.java
@@ -96,29 +96,42 @@ public class TestKeyProviderCache {
     Configuration conf = new Configuration();
     conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
         "dummy://foo:bar@test_provider1");
-    KeyProvider keyProvider1 = kpCache.get(conf);
+    KeyProvider keyProvider1 = kpCache.get(conf,
+        getKeyProviderUriFromConf(conf));
     Assert.assertNotNull("Returned Key Provider is null !!", keyProvider1);
 
     conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
         "dummy://foo:bar@test_provider1");
-    KeyProvider keyProvider2 = kpCache.get(conf);
+    KeyProvider keyProvider2 = kpCache.get(conf,
+        getKeyProviderUriFromConf(conf));
 
     Assert.assertTrue("Different KeyProviders returned !!",
         keyProvider1 == keyProvider2);
 
     conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
         "dummy://test_provider3");
-    KeyProvider keyProvider3 = kpCache.get(conf);
+    KeyProvider keyProvider3 = kpCache.get(conf,
+        getKeyProviderUriFromConf(conf));
 
     Assert.assertFalse("Same KeyProviders returned !!",
         keyProvider1 == keyProvider3);
 
     conf.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH,
         "dummy://hello:there@test_provider1");
-    KeyProvider keyProvider4 = kpCache.get(conf);
+    KeyProvider keyProvider4 = kpCache.get(conf,
+        getKeyProviderUriFromConf(conf));
 
     Assert.assertFalse("Same KeyProviders returned !!",
         keyProvider1 == keyProvider4);
 
   }
+
+  private URI getKeyProviderUriFromConf(Configuration conf) {
+    String providerUriStr = conf.get(
+        CommonConfigurationKeysPublic.HADOOP_SECURITY_KEY_PROVIDER_PATH);
+    if (providerUriStr == null || providerUriStr.isEmpty()) {
+      return null;
+    }
+    return URI.create(providerUriStr);
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b8a0b18f/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java
index 314ecf6..d0363c5 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java
@@ -35,9 +35,12 @@ import org.apache.hadoop.fs.permission.AclEntryScope;
 import org.apache.hadoop.fs.permission.AclEntryType;
 import org.apache.hadoop.fs.permission.AclStatus;
 import org.apache.hadoop.fs.permission.FsAction;
+import org.apache.hadoop.fs.FsServerDefaults;
 import org.apache.hadoop.fs.StorageType;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
 import org.apache.hadoop.hdfs.DFSTestUtil;
 import org.apache.hadoop.hdfs.StripedFileTestUtil;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.hdfs.protocol.Block;
 import org.apache.hadoop.hdfs.protocol.BlockType;
 import org.apache.hadoop.hdfs.protocol.DatanodeID;
@@ -868,5 +871,33 @@ public class TestPBHelper {
     }
   }
 
+  /**
+   * Test case for old namenode where the namenode doesn't support returning
+   * keyProviderUri.
+   */
+  @Test
+  public void testFSServerDefaultsHelper() {
+    HdfsProtos.FsServerDefaultsProto.Builder b =
+        HdfsProtos.FsServerDefaultsProto
+        .newBuilder();
+    b.setBlockSize(DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
+    b.setBytesPerChecksum(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT);
+    b.setWritePacketSize(
+        HdfsClientConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);
+    b.setReplication(DFSConfigKeys.DFS_REPLICATION_DEFAULT);
+    b.setFileBufferSize(DFSConfigKeys.IO_FILE_BUFFER_SIZE_DEFAULT);
+    b.setEncryptDataTransfer(DFSConfigKeys.DFS_ENCRYPT_DATA_TRANSFER_DEFAULT);
+    b.setTrashInterval(DFSConfigKeys.FS_TRASH_INTERVAL_DEFAULT);
+    b.setChecksumType(HdfsProtos.ChecksumTypeProto.valueOf(
+        DataChecksum.Type.valueOf(DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT).id));
+    HdfsProtos.FsServerDefaultsProto proto = b.build();
+
+    Assert.assertFalse("KeyProvider uri is not supported",
+        proto.hasKeyProviderUri());
+    FsServerDefaults fsServerDefaults = PBHelperClient.convert(proto);
+    Assert.assertNotNull("FsServerDefaults is null", fsServerDefaults);
+    Assert.assertNull("KeyProviderUri should be null",
+        fsServerDefaults.getKeyProviderUri());
+  }
 
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[21/50] [abbrv] hadoop git commit: YARN-6436. TestSchedulingPolicy#testParseSchedulingPolicy timeout is too low. (Eric Badger via kasha)

Posted by in...@apache.org.
YARN-6436. TestSchedulingPolicy#testParseSchedulingPolicy timeout is too low. (Eric Badger via kasha)


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

Branch: refs/heads/HDFS-10467
Commit: bb8a92504e3f70cb463b6efe18760dada93bfa08
Parents: f9544fa
Author: Karthik Kambatla <ka...@cloudera.com>
Authored: Tue Apr 4 17:08:26 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../server/resourcemanager/scheduler/fair/TestSchedulingPolicy.java | 1 -
 1 file changed, 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/bb8a9250/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestSchedulingPolicy.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/TestSchedulingPolicy.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/TestSchedulingPolicy.java
index 8dccf6e..d84f0cf 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/TestSchedulingPolicy.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/TestSchedulingPolicy.java
@@ -55,7 +55,6 @@ public class TestSchedulingPolicy {
     conf = new FairSchedulerConfiguration();
   }
 
-  @Test(timeout = 1000)
   public void testParseSchedulingPolicy()
       throws AllocationConfigurationException {
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[39/50] [abbrv] hadoop git commit: YARN-6288. Exceptions during aggregated log writes are mishandled. Contributed by Akira Ajisaka

Posted by in...@apache.org.
YARN-6288. Exceptions during aggregated log writes are mishandled. Contributed by Akira Ajisaka


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

Branch: refs/heads/HDFS-10467
Commit: 8c11900e83e29c05caa9daa804d59c8fa4619e37
Parents: 52c0ac5
Author: Jason Lowe <jl...@yahoo-inc.com>
Authored: Thu Apr 6 16:24:36 2017 -0500
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../hadoop/yarn/client/cli/TestLogsCLI.java     |  58 ++++-----
 .../logaggregation/AggregatedLogFormat.java     |  30 +++--
 .../logaggregation/TestAggregatedLogFormat.java | 123 ++++++++++---------
 .../logaggregation/TestAggregatedLogsBlock.java |  25 ++--
 .../logaggregation/TestContainerLogsUtils.java  |  15 +--
 .../logaggregation/AppLogAggregatorImpl.java    |  70 +++++------
 .../TestAppLogAggregatorImpl.java               |   8 +-
 7 files changed, 169 insertions(+), 160 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java
index 05993d5..37c859c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/cli/TestLogsCLI.java
@@ -1345,18 +1345,18 @@ public class TestLogsCLI {
     Path path =
         new Path(appDir, LogAggregationUtils.getNodeString(nodeId)
             + System.currentTimeMillis());
-    AggregatedLogFormat.LogWriter writer =
-        new AggregatedLogFormat.LogWriter(configuration, path, ugi);
-    writer.writeApplicationOwner(ugi.getUserName());
-
-    Map<ApplicationAccessType, String> appAcls =
-        new HashMap<ApplicationAccessType, String>();
-    appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
-    writer.writeApplicationACLs(appAcls);
-    writer.append(new AggregatedLogFormat.LogKey(containerId),
-      new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
-        UserGroupInformation.getCurrentUser().getShortUserName()));
-    writer.close();
+    try (AggregatedLogFormat.LogWriter writer =
+             new AggregatedLogFormat.LogWriter()) {
+      writer.initialize(configuration, path, ugi);
+      writer.writeApplicationOwner(ugi.getUserName());
+
+      Map<ApplicationAccessType, String> appAcls = new HashMap<>();
+      appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
+      writer.writeApplicationACLs(appAcls);
+      writer.append(new AggregatedLogFormat.LogKey(containerId),
+          new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
+              UserGroupInformation.getCurrentUser().getShortUserName()));
+    }
   }
 
   private static void uploadEmptyContainerLogIntoRemoteDir(UserGroupInformation ugi,
@@ -1365,23 +1365,23 @@ public class TestLogsCLI {
     Path path =
         new Path(appDir, LogAggregationUtils.getNodeString(nodeId)
             + System.currentTimeMillis());
-    AggregatedLogFormat.LogWriter writer =
-        new AggregatedLogFormat.LogWriter(configuration, path, ugi);
-    writer.writeApplicationOwner(ugi.getUserName());
-
-    Map<ApplicationAccessType, String> appAcls =
-        new HashMap<ApplicationAccessType, String>();
-    appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
-    writer.writeApplicationACLs(appAcls);
-    DataOutputStream out = writer.getWriter().prepareAppendKey(-1);
-    new AggregatedLogFormat.LogKey(containerId).write(out);
-    out.close();
-    out = writer.getWriter().prepareAppendValue(-1);
-    new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
-      UserGroupInformation.getCurrentUser().getShortUserName()).write(out,
-      new HashSet<File>());
-    out.close();
-    writer.close();
+    try (AggregatedLogFormat.LogWriter writer =
+             new AggregatedLogFormat.LogWriter()) {
+      writer.initialize(configuration, path, ugi);
+      writer.writeApplicationOwner(ugi.getUserName());
+
+      Map<ApplicationAccessType, String> appAcls = new HashMap<>();
+      appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
+      writer.writeApplicationACLs(appAcls);
+      DataOutputStream out = writer.getWriter().prepareAppendKey(-1);
+      new AggregatedLogFormat.LogKey(containerId).write(out);
+      out.close();
+      out = writer.getWriter().prepareAppendValue(-1);
+      new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
+          UserGroupInformation.getCurrentUser().getShortUserName()).write(out,
+              new HashSet<>());
+      out.close();
+    }
   }
 
   private YarnClient createMockYarnClient(YarnApplicationState appState,

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
index 1b46007..8d86967 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java
@@ -446,14 +446,23 @@ public class AggregatedLogFormat {
    * The writer that writes out the aggregated logs.
    */
   @Private
-  public static class LogWriter {
+  public static class LogWriter implements AutoCloseable {
 
-    private final FSDataOutputStream fsDataOStream;
-    private final TFile.Writer writer;
+    private FSDataOutputStream fsDataOStream;
+    private TFile.Writer writer;
     private FileContext fc;
 
-    public LogWriter(final Configuration conf, final Path remoteAppLogFile,
-        UserGroupInformation userUgi) throws IOException {
+    /**
+     * Initialize the LogWriter.
+     * Must be called just after the instance is created.
+     * @param conf Configuration
+     * @param remoteAppLogFile remote log file path
+     * @param userUgi Ugi of the user
+     * @throws IOException Failed to initialize
+     */
+    public void initialize(final Configuration conf,
+                           final Path remoteAppLogFile,
+                           UserGroupInformation userUgi) throws IOException {
       try {
         this.fsDataOStream =
             userUgi.doAs(new PrivilegedExceptionAction<FSDataOutputStream>() {
@@ -530,11 +539,14 @@ public class AggregatedLogFormat {
       }
     }
 
+    @Override
     public void close() {
-      try {
-        this.writer.close();
-      } catch (IOException e) {
-        LOG.warn("Exception closing writer", e);
+      if (writer != null) {
+        try {
+          writer.close();
+        } catch (IOException e) {
+          LOG.warn("Exception closing writer", e);
+        }
       }
       IOUtils.closeStream(fsDataOStream);
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
index 8cbec10..efbaa4c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogFormat.java
@@ -140,44 +140,44 @@ public class TestAggregatedLogFormat {
     final int ch = filler;
 
     UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
-    LogWriter logWriter = new LogWriter(new Configuration(), remoteAppLogFile,
-        ugi);
+    try (LogWriter logWriter = new LogWriter()) {
+      logWriter.initialize(new Configuration(), remoteAppLogFile, ugi);
 
-    LogKey logKey = new LogKey(testContainerId);
-    LogValue logValue =
-        spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
-            testContainerId, ugi.getShortUserName()));
+      LogKey logKey = new LogKey(testContainerId);
+      LogValue logValue =
+          spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
+              testContainerId, ugi.getShortUserName()));
 
-    final CountDownLatch latch = new CountDownLatch(1);
+      final CountDownLatch latch = new CountDownLatch(1);
 
-    Thread t = new Thread() {
-      public void run() {
-        try {
-          for(int i=0; i < length/3; i++) {
+      Thread t = new Thread() {
+        public void run() {
+          try {
+            for (int i = 0; i < length / 3; i++) {
               osw.write(ch);
-          }
+            }
 
-          latch.countDown();
+            latch.countDown();
 
-          for(int i=0; i < (2*length)/3; i++) {
-            osw.write(ch);
+            for (int i = 0; i < (2 * length) / 3; i++) {
+              osw.write(ch);
+            }
+            osw.close();
+          } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
           }
-          osw.close();
-        } catch (IOException e) {
-          // TODO Auto-generated catch block
-          e.printStackTrace();
         }
-      }
-    };
-    t.start();
+      };
+      t.start();
 
-    //Wait till the osw is partially written
-    //aggregation starts once the ows has completed 1/3rd of its work
-    latch.await();
+      //Wait till the osw is partially written
+      //aggregation starts once the ows has completed 1/3rd of its work
+      latch.await();
 
-    //Aggregate The Logs
-    logWriter.append(logKey, logValue);
-    logWriter.close();
+      //Aggregate The Logs
+      logWriter.append(logKey, logValue);
+    }
   }
 
   @Test
@@ -216,22 +216,23 @@ public class TestAggregatedLogFormat {
     writeSrcFile(srcFilePath, "stdout", numChars);
 
     UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
-    LogWriter logWriter = new LogWriter(conf, remoteAppLogFile, ugi);
-
-    LogKey logKey = new LogKey(testContainerId);
-    LogValue logValue =
-        new LogValue(Collections.singletonList(srcFileRoot.toString()),
-            testContainerId, ugi.getShortUserName());
-
-    // When we try to open FileInputStream for stderr, it will throw out an IOException.
-    // Skip the log aggregation for stderr.
-    LogValue spyLogValue = spy(logValue);
-    File errorFile = new File((new Path(srcFilePath, "stderr")).toString());
-    doThrow(new IOException("Mock can not open FileInputStream")).when(
-      spyLogValue).secureOpenFile(errorFile);
-
-    logWriter.append(logKey, spyLogValue);
-    logWriter.close();
+    try (LogWriter logWriter = new LogWriter()) {
+      logWriter.initialize(conf, remoteAppLogFile, ugi);
+
+      LogKey logKey = new LogKey(testContainerId);
+      LogValue logValue =
+          new LogValue(Collections.singletonList(srcFileRoot.toString()),
+              testContainerId, ugi.getShortUserName());
+
+      // When we try to open FileInputStream for stderr, it will throw out an
+      // IOException. Skip the log aggregation for stderr.
+      LogValue spyLogValue = spy(logValue);
+      File errorFile = new File((new Path(srcFilePath, "stderr")).toString());
+      doThrow(new IOException("Mock can not open FileInputStream")).when(
+          spyLogValue).secureOpenFile(errorFile);
+
+      logWriter.append(logKey, spyLogValue);
+    }
 
     // make sure permission are correct on the file
     FileStatus fsStatus =  fs.getFileStatus(remoteAppLogFile);
@@ -311,24 +312,24 @@ public class TestAggregatedLogFormat {
 
     UserGroupInformation ugi =
         UserGroupInformation.getCurrentUser();
-    LogWriter logWriter = new LogWriter(conf, remoteAppLogFile, ugi);
+    try (LogWriter logWriter = new LogWriter()) {
+      logWriter.initialize(conf, remoteAppLogFile, ugi);
+
+      LogKey logKey = new LogKey(testContainerId1);
+      String randomUser = "randomUser";
+      LogValue logValue =
+          spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
+              testContainerId1, randomUser));
+
+      // It is trying simulate a situation where first log file is owned by
+      // different user (probably symlink) and second one by the user itself.
+      // The first file should not be aggregated. Because this log file has
+      // the invalid user name.
+      when(logValue.getUser()).thenReturn(randomUser).thenReturn(
+          ugi.getShortUserName());
+      logWriter.append(logKey, logValue);
+    }
 
-    LogKey logKey = new LogKey(testContainerId1);
-    String randomUser = "randomUser";
-    LogValue logValue =
-        spy(new LogValue(Collections.singletonList(srcFileRoot.toString()),
-            testContainerId1, randomUser));
-    
-    // It is trying simulate a situation where first log file is owned by
-    // different user (probably symlink) and second one by the user itself.
-    // The first file should not be aggregated. Because this log file has the invalid
-    // user name.
-    when(logValue.getUser()).thenReturn(randomUser).thenReturn(
-        ugi.getShortUserName());
-    logWriter.append(logKey, logValue);
-
-    logWriter.close();
-    
     BufferedReader in =
         new BufferedReader(new FileReader(new File(remoteAppLogFile
             .toUri().getRawPath())));

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogsBlock.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogsBlock.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogsBlock.java
index 594f186..1e71b3c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogsBlock.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestAggregatedLogsBlock.java
@@ -295,17 +295,20 @@ public class TestAggregatedLogsBlock {
     List<String> rootLogDirs = Arrays.asList("target/logs/logs");
     UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
 
-    AggregatedLogFormat.LogWriter writer = new AggregatedLogFormat.LogWriter(
-        configuration, new Path(path), ugi);
-    writer.writeApplicationOwner(ugi.getUserName());
-
-    Map<ApplicationAccessType, String> appAcls = new HashMap<ApplicationAccessType, String>();
-    appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
-    writer.writeApplicationACLs(appAcls);
-
-    writer.append(new AggregatedLogFormat.LogKey("container_0_0001_01_000001"),
-        new AggregatedLogFormat.LogValue(rootLogDirs, containerId,UserGroupInformation.getCurrentUser().getShortUserName()));
-    writer.close();
+    try (AggregatedLogFormat.LogWriter writer =
+             new AggregatedLogFormat.LogWriter()) {
+      writer.initialize(configuration, new Path(path), ugi);
+      writer.writeApplicationOwner(ugi.getUserName());
+
+      Map<ApplicationAccessType, String> appAcls = new HashMap<>();
+      appAcls.put(ApplicationAccessType.VIEW_APP, ugi.getUserName());
+      writer.writeApplicationACLs(appAcls);
+
+      writer.append(
+          new AggregatedLogFormat.LogKey("container_0_0001_01_000001"),
+          new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
+              UserGroupInformation.getCurrentUser().getShortUserName()));
+    }
   }
 
   private void writeLogs(String dirName) throws Exception {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestContainerLogsUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestContainerLogsUtils.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestContainerLogsUtils.java
index c6841c9..8b665e0 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestContainerLogsUtils.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/logaggregation/TestContainerLogsUtils.java
@@ -110,13 +110,14 @@ public final class TestContainerLogsUtils {
       ContainerId containerId, Path appDir, FileSystem fs) throws IOException {
     Path path =
         new Path(appDir, LogAggregationUtils.getNodeString(nodeId));
-    AggregatedLogFormat.LogWriter writer =
-        new AggregatedLogFormat.LogWriter(configuration, path, ugi);
-    writer.writeApplicationOwner(ugi.getUserName());
+    try (AggregatedLogFormat.LogWriter writer =
+        new AggregatedLogFormat.LogWriter()) {
+      writer.initialize(configuration, path, ugi);
+      writer.writeApplicationOwner(ugi.getUserName());
 
-    writer.append(new AggregatedLogFormat.LogKey(containerId),
-        new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
-        ugi.getShortUserName()));
-    writer.close();
+      writer.append(new AggregatedLogFormat.LogKey(containerId),
+          new AggregatedLogFormat.LogValue(rootLogDirs, containerId,
+              ugi.getShortUserName()));
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.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/logaggregation/AppLogAggregatorImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
index d70acc9..f465534 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/AppLogAggregatorImpl.java
@@ -295,18 +295,18 @@ public class AppLogAggregatorImpl implements AppLogAggregator {
       }
     }
 
-    LogWriter writer = null;
+    if (pendingContainerInThisCycle.isEmpty()) {
+      sendLogAggregationReport(true, "", appFinished);
+      return;
+    }
+
+    logAggregationTimes++;
     String diagnosticMessage = "";
     boolean logAggregationSucceedInThisCycle = true;
-    try {
-      if (pendingContainerInThisCycle.isEmpty()) {
-        return;
-      }
-
-      logAggregationTimes++;
-
+    try (LogWriter writer = createLogWriter()) {
       try {
-        writer = createLogWriter();
+        writer.initialize(this.conf, this.remoteNodeTmpLogFileForApp,
+            this.userUgi);
         // Write ACLs once when the writer is created.
         writer.writeApplicationACLs(appAcls);
         writer.writeApplicationOwner(this.userUgi.getShortUserName());
@@ -351,11 +351,6 @@ public class AppLogAggregatorImpl implements AppLogAggregator {
         cleanupOldLogTimes++;
       }
 
-      if (writer != null) {
-        writer.close();
-        writer = null;
-      }
-
       long currentTime = System.currentTimeMillis();
       final Path renamedPath = this.rollingMonitorInterval <= 0
               ? remoteNodeLogFileForApp : new Path(
@@ -396,34 +391,37 @@ public class AppLogAggregatorImpl implements AppLogAggregator {
         logAggregationSucceedInThisCycle = false;
       }
     } finally {
-      LogAggregationStatus logAggregationStatus =
-          logAggregationSucceedInThisCycle
-              ? LogAggregationStatus.RUNNING
-              : LogAggregationStatus.RUNNING_WITH_FAILURE;
-      sendLogAggregationReport(logAggregationStatus, diagnosticMessage);
-      if (appFinished) {
-        // If the app is finished, one extra final report with log aggregation
-        // status SUCCEEDED/FAILED will be sent to RM to inform the RM
-        // that the log aggregation in this NM is completed.
-        LogAggregationStatus finalLogAggregationStatus =
-            renameTemporaryLogFileFailed || !logAggregationSucceedInThisCycle
-                ? LogAggregationStatus.FAILED
-                : LogAggregationStatus.SUCCEEDED;
-        sendLogAggregationReport(finalLogAggregationStatus, "");
-      }
-
-      if (writer != null) {
-        writer.close();
-      }
+      sendLogAggregationReport(logAggregationSucceedInThisCycle,
+          diagnosticMessage, appFinished);
     }
   }
 
-  protected LogWriter createLogWriter() throws IOException {
-    return new LogWriter(this.conf, this.remoteNodeTmpLogFileForApp,
-        this.userUgi);
+  @VisibleForTesting
+  protected LogWriter createLogWriter() {
+    return new LogWriter();
   }
 
   private void sendLogAggregationReport(
+      boolean logAggregationSucceedInThisCycle, String diagnosticMessage,
+      boolean appFinished) {
+    LogAggregationStatus logAggregationStatus =
+        logAggregationSucceedInThisCycle
+            ? LogAggregationStatus.RUNNING
+            : LogAggregationStatus.RUNNING_WITH_FAILURE;
+    sendLogAggregationReportInternal(logAggregationStatus, diagnosticMessage);
+    if (appFinished) {
+      // If the app is finished, one extra final report with log aggregation
+      // status SUCCEEDED/FAILED will be sent to RM to inform the RM
+      // that the log aggregation in this NM is completed.
+      LogAggregationStatus finalLogAggregationStatus =
+          renameTemporaryLogFileFailed || !logAggregationSucceedInThisCycle
+              ? LogAggregationStatus.FAILED
+              : LogAggregationStatus.SUCCEEDED;
+      sendLogAggregationReportInternal(finalLogAggregationStatus, "");
+    }
+  }
+
+  private void sendLogAggregationReportInternal(
       LogAggregationStatus logAggregationStatus, String diagnosticMessage) {
     LogAggregationReport report =
         Records.newRecord(LogAggregationReport.class);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c11900e/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestAppLogAggregatorImpl.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/logaggregation/TestAppLogAggregatorImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestAppLogAggregatorImpl.java
index 17d527a..097146b 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestAppLogAggregatorImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/logaggregation/TestAppLogAggregatorImpl.java
@@ -416,8 +416,7 @@ public class TestAppLogAggregatorImpl {
           logAggregationContext, context, lfs, -1, recoveredLogInitedTime);
       this.applicationId = appId;
       this.deletionService = deletionService;
-
-      this.logWriter = getSpiedLogWriter(conf, ugi, remoteNodeLogFileForApp);
+      this.logWriter = spy(new LogWriter());
       this.logValue = ArgumentCaptor.forClass(LogValue.class);
     }
 
@@ -425,10 +424,5 @@ public class TestAppLogAggregatorImpl {
     protected LogWriter createLogWriter() {
       return this.logWriter;
     }
-
-    private LogWriter getSpiedLogWriter(Configuration conf,
-        UserGroupInformation ugi, Path remoteAppLogFile) throws IOException {
-      return spy(new LogWriter(conf, remoteAppLogFile, ugi));
-    }
   }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[24/50] [abbrv] hadoop git commit: HADOOP-14268. Fix markdown itemization in hadoop-aws documents. Contributed by Akira Ajisaka

Posted by in...@apache.org.
HADOOP-14268. Fix markdown itemization in hadoop-aws documents. Contributed by Akira Ajisaka


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

Branch: refs/heads/HDFS-10467
Commit: aeb249eaefe45e941beb29231510b1676846d218
Parents: b4d6577
Author: Mingliang Liu <li...@apache.org>
Authored: Mon Apr 3 11:07:14 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../hadoop-aws/src/site/markdown/tools/hadoop-aws/index.md         | 2 ++
 .../hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md       | 1 +
 2 files changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/aeb249ea/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 82c3588..18c0ceb 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
@@ -41,6 +41,7 @@ The specifics of using these filesystems are documented in this section.
 
 
 See also:
+
 * [Testing](testing.html)
 * [Troubleshooting S3a](troubleshooting_s3a.html)
 
@@ -99,6 +100,7 @@ access to the data. Anyone with the credentials can not only read your datasets
 \u2014they can delete them.
 
 Do not inadvertently share these credentials through means such as
+
 1. Checking in to SCM any configuration files containing the secrets.
 1. Logging them to a console, as they invariably end up being seen.
 1. Defining filesystem URIs with the credentials in the URL, such as

http://git-wip-us.apache.org/repos/asf/hadoop/blob/aeb249ea/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md b/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md
index 79551a3..39ca8f4 100644
--- a/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md
+++ b/hadoop-tools/hadoop-aws/src/site/markdown/tools/hadoop-aws/testing.md
@@ -643,6 +643,7 @@ located.
 
 New tests are always welcome. Bear in mind that we need to keep costs
 and test time down, which is done by
+
 * Not duplicating tests.
 * Being efficient in your use of Hadoop API calls.
 * Isolating large/slow tests into the "scale" test group.


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[13/50] [abbrv] hadoop git commit: YARN-6414. ATSv2 HBase related tests fail due to guava version upgrade (Haibo Chen via Varun Saxena)

Posted by in...@apache.org.
YARN-6414. ATSv2 HBase related tests fail due to guava version upgrade (Haibo Chen via Varun Saxena)


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

Branch: refs/heads/HDFS-10467
Commit: 288201346ec459b4afea184b0dee4937fe9d7cf5
Parents: b1543f9c
Author: Varun Saxena <va...@apache.org>
Authored: Sun Apr 2 04:37:34 2017 +0530
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 hadoop-project/pom.xml                           |  1 +
 .../pom.xml                                      | 19 +++++++++++++++++++
 2 files changed, 20 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/28820134/hadoop-project/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-project/pom.xml b/hadoop-project/pom.xml
index e55308f..f327933 100644
--- a/hadoop-project/pom.xml
+++ b/hadoop-project/pom.xml
@@ -51,6 +51,7 @@
     <kafka.version>0.8.2.1</kafka.version>
     <hbase.version>1.2.4</hbase.version>
     <hbase-compatible-hadoop.version>2.5.1</hbase-compatible-hadoop.version>
+    <hbase-compatible-guava.version>11.0.2</hbase-compatible-guava.version>
 
     <hadoop.assemblies.version>${project.version}</hadoop.assemblies.version>
     <commons-daemon.version>1.0.13</commons-daemon.version>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/28820134/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/pom.xml
index d44aa22..afe440f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase-tests/pom.xml
@@ -141,6 +141,7 @@
     <dependency>
       <groupId>com.google.guava</groupId>
       <artifactId>guava</artifactId>
+      <version>${hbase-compatible-guava.version}</version>
       <scope>test</scope>
     </dependency>
 
@@ -369,6 +370,24 @@
           </additionnalDependencies>
         </configuration>
       </plugin>
+
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-enforcer-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>depcheck</id>
+            <configuration>
+              <!-- disable dependency convergence check -->
+              <skip>true</skip>
+            </configuration>
+            <goals>
+              <goal>enforce</goal>
+            </goals>
+            <phase/>
+          </execution>
+        </executions>
+      </plugin>
     </plugins>
   </build>
 </project>


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[37/50] [abbrv] hadoop git commit: YARN-6424. TimelineCollector is not stopped when an app finishes in RM. Contributed by Varun Saxena.

Posted by in...@apache.org.
YARN-6424. TimelineCollector is not stopped when an app finishes in RM. 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/52c0ac5a
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/52c0ac5a
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/52c0ac5a

Branch: refs/heads/HDFS-10467
Commit: 52c0ac5a150090cd1df7892669b7797b40d03b0a
Parents: 6ae4d41
Author: Rohith Sharma K S <ro...@apache.org>
Authored: Thu Apr 6 10:15:22 2017 +0530
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../metrics/TimelineServiceV2Publisher.java              | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/52c0ac5a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/TimelineServiceV2Publisher.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/metrics/TimelineServiceV2Publisher.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/TimelineServiceV2Publisher.java
index 412d573..a8bf6bd 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/TimelineServiceV2Publisher.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/TimelineServiceV2Publisher.java
@@ -179,8 +179,9 @@ public class TimelineServiceV2Publisher extends AbstractSystemMetricsPublisher {
         getTimelinelineAppMetrics(appMetrics, finishedTime);
     entity.setMetrics(entityMetrics);
 
-    getDispatcher().getEventHandler().handle(new TimelineV2PublishEvent(
-        SystemMetricsEventType.PUBLISH_ENTITY, entity, app.getApplicationId()));
+    getDispatcher().getEventHandler().handle(
+        new ApplicationFinishPublishEvent(SystemMetricsEventType.
+            PUBLISH_APPLICATION_FINISHED_ENTITY, entity, app));
   }
 
   private Set<TimelineMetric> getTimelinelineAppMetrics(
@@ -452,16 +453,16 @@ public class TimelineServiceV2Publisher extends AbstractSystemMetricsPublisher {
   }
 
   private class ApplicationFinishPublishEvent extends TimelineV2PublishEvent {
-    private RMAppImpl app;
+    private RMApp app;
 
     public ApplicationFinishPublishEvent(SystemMetricsEventType type,
-        TimelineEntity entity, RMAppImpl app) {
+        TimelineEntity entity, RMApp app) {
       super(type, entity, app.getApplicationId());
       this.app = app;
     }
 
     public RMAppImpl getRMAppImpl() {
-      return app;
+      return (RMAppImpl) app;
     }
   }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[44/50] [abbrv] hadoop git commit: HDFS-11302. Improve Logging for SSLHostnameVerifier. Contributed by Chen Liang.

Posted by in...@apache.org.
HDFS-11302. Improve Logging for SSLHostnameVerifier. Contributed by Chen Liang.


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

Branch: refs/heads/HDFS-10467
Commit: a8d602e1089e8a44f557c24217264876e397078f
Parents: 4db939d
Author: Xiaoyu Yao <xy...@apache.org>
Authored: Wed Apr 5 17:25:18 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../security/ssl/SSLHostnameVerifier.java       | 21 +++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a8d602e1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLHostnameVerifier.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLHostnameVerifier.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLHostnameVerifier.java
index b5ef2b2..27e4920 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLHostnameVerifier.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/ssl/SSLHostnameVerifier.java
@@ -53,6 +53,8 @@ import javax.net.ssl.SSLSocket;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.classification.InterfaceStability;
 import org.apache.hadoop.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  ************************************************************************
@@ -229,6 +231,12 @@ public interface SSLHostnameVerifier extends javax.net.ssl.HostnameVerifier {
     abstract class AbstractVerifier implements SSLHostnameVerifier {
 
         /**
+         * Writes as SSLFactory logs as it is the only consumer of this verifier
+         * class.
+         */
+        static final Logger LOG = LoggerFactory.getLogger(SSLFactory.class);
+
+        /**
          * This contains a list of 2nd-level domains that aren't allowed to
          * have wildcards when combined with country-codes.
          * For example: [*.co.uk].
@@ -354,13 +362,24 @@ public interface SSLHostnameVerifier extends javax.net.ssl.HostnameVerifier {
             throws SSLException {
             String[] cns = Certificates.getCNs(cert);
             String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
-            check(host, cns, subjectAlts);
+            try {
+                check(host, cns, subjectAlts);
+            } catch (SSLException e) {
+                LOG.error("Host check error {}", e);
+                throw e;
+            }
         }
 
         public void check(final String[] hosts, final String[] cns,
                           final String[] subjectAlts, final boolean ie6,
                           final boolean strictWithSubDomains)
             throws SSLException {
+            if (LOG.isTraceEnabled()) {
+                LOG.trace("Hosts:{}, CNs:{} subjectAlts:{}, ie6:{}, " +
+                    "strictWithSubDomains{}", Arrays.toString(hosts),
+                    Arrays.toString(cns), Arrays.toString(subjectAlts), ie6,
+                    strictWithSubDomains);
+            }
             // Build up lists of allowed hosts For logging/debugging purposes.
             StringBuffer buf = new StringBuffer(32);
             buf.append('<');


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[38/50] [abbrv] hadoop git commit: HDFS-11362. StorageDirectory should initialize a non-null default StorageDirType. Contribute by Hanisha Koneru.

Posted by in...@apache.org.
HDFS-11362. StorageDirectory should initialize a non-null default StorageDirType. Contribute by Hanisha Koneru.


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

Branch: refs/heads/HDFS-10467
Commit: 7c477f238b022bba1865bc9650fff50d4afd4065
Parents: 8c11900
Author: Xiaoyu Yao <xy...@apache.org>
Authored: Thu Apr 6 14:13:22 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../java/org/apache/hadoop/hdfs/server/common/Storage.java     | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/7c477f23/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java
index 4493772..414d3a7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java
@@ -43,6 +43,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
 import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
 import org.apache.hadoop.hdfs.server.datanode.StorageLocation;
+import org.apache.hadoop.hdfs.server.namenode.NNStorage.NameNodeDirType;
 import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
 import org.apache.hadoop.io.nativeio.NativeIO;
 import org.apache.hadoop.io.nativeio.NativeIOException;
@@ -275,12 +276,10 @@ public abstract class Storage extends StorageInfo {
     
     private final StorageLocation location;
     public StorageDirectory(File dir) {
-      // default dirType is null
       this(dir, null, false);
     }
     
     public StorageDirectory(StorageLocation location) {
-      // default dirType is null
       this(null, false, location);
     }
 
@@ -337,7 +336,8 @@ public abstract class Storage extends StorageInfo {
         boolean isShared, StorageLocation location) {
       this.root = dir;
       this.lock = null;
-      this.dirType = dirType;
+      // default dirType is UNDEFINED
+      this.dirType = (dirType == null ? NameNodeDirType.UNDEFINED : dirType);
       this.isShared = isShared;
       this.location = location;
       assert location == null || dir == null ||


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[49/50] [abbrv] hadoop git commit: MAPREDUCE-6201. TestNetworkedJob fails on trunk (pbacsko via rkanter)

Posted by in...@apache.org.
MAPREDUCE-6201. TestNetworkedJob fails on trunk (pbacsko via rkanter)


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

Branch: refs/heads/HDFS-10467
Commit: 83b1d223da9c0ac55c4d1c858c1fd393b494f665
Parents: b2e33d5
Author: Robert Kanter <rk...@apache.org>
Authored: Thu Apr 6 17:44:47 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:24 2017 -0700

----------------------------------------------------------------------
 .../src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java  | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/83b1d223/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java
index 45c7d1f..65b9dbd 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestNetworkedJob.java
@@ -381,6 +381,9 @@ public class TestNetworkedJob {
     // Expected queue names depending on Capacity Scheduler queue naming
     conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class,
         CapacityScheduler.class);
+    // Default value is 90 - if you have low disk space,
+    // testNetworkedJob will fail
+    conf.set(YarnConfiguration.NM_MAX_PER_DISK_UTILIZATION_PERCENTAGE, "99");
     return MiniMRClientClusterFactory.create(this.getClass(), 2, conf);
   }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[11/50] [abbrv] hadoop git commit: YARN-6411. Clean up the overwrite of createDispatcher() in subclass of MockRM. Contributed by Yufei Gu

Posted by in...@apache.org.
YARN-6411. Clean up the overwrite of createDispatcher() in subclass of MockRM. Contributed by Yufei Gu


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

Branch: refs/heads/HDFS-10467
Commit: a0db5dd2732849a268153154fef89167cc39351b
Parents: af40cfa
Author: Jason Lowe <jl...@yahoo-inc.com>
Authored: Fri Mar 31 10:05:34 2017 -0500
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../v2/app/rm/TestRMContainerAllocator.java     | 453 +++++++++----------
 .../api/impl/TestAMRMClientOnRMRestart.java     |  59 +--
 .../server/resourcemanager/ACLsTestBase.java    |  10 -
 .../server/resourcemanager/RMHATestBase.java    |  20 +-
 .../ReservationACLsTestBase.java                |   5 +-
 .../resourcemanager/TestApplicationCleanup.java |  44 +-
 .../TestApplicationMasterLauncher.java          |  11 +-
 .../TestApplicationMasterService.java           |  19 +-
 .../TestNodeBlacklistingOnAMFailures.java       |  41 +-
 .../TestReservationSystemWithRMHA.java          |   5 +-
 .../TestAMRMRPCNodeUpdates.java                 |  18 +-
 .../resourcetracker/TestNMReconnect.java        |  14 +-
 .../rmcontainer/TestRMContainerImpl.java        |   1 -
 .../capacity/TestApplicationPriority.java       |  29 +-
 .../security/TestClientToAMTokens.java          |  23 +-
 15 files changed, 277 insertions(+), 475 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java
index e6aee6e..933bd01 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java
@@ -179,21 +179,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -207,7 +205,7 @@ public class TestRMContainerAllocator {
     MockNM nodeManager1 = rm.registerNode("h1:1234", 10240);
     MockNM nodeManager2 = rm.registerNode("h2:1234", 10240);
     MockNM nodeManager3 = rm.registerNode("h3:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container request
     ContainerRequestEvent event1 = createReq(jobId, 1, 1024,
@@ -222,7 +220,7 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
     Assert.assertEquals(4, rm.getMyFifoScheduler().lastAsk.size());
 
@@ -234,7 +232,7 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
     Assert.assertEquals(3, rm.getMyFifoScheduler().lastAsk.size());
     
@@ -242,18 +240,18 @@ public class TestRMContainerAllocator {
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
     nodeManager2.nodeHeartbeat(true); // Node heartbeat
     nodeManager3.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0, rm.getMyFifoScheduler().lastAsk.size());
     checkAssignments(new ContainerRequestEvent[] { event1, event2, event3 },
         assigned, false);
     
     // check that the assigned container requests are cancelled
-    assigned = allocator.schedule();
-    dispatcher.await();
-    Assert.assertEquals(5, rm.getMyFifoScheduler().lastAsk.size());    
+    allocator.schedule();
+    rm.drainEvents();
+    Assert.assertEquals(5, rm.getMyFifoScheduler().lastAsk.size());
   }
   
   @Test 
@@ -269,21 +267,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -297,7 +293,7 @@ public class TestRMContainerAllocator {
     MockNM nodeManager1 = rm.registerNode("h1:1234", 3072); // can assign 2 maps 
     rm.registerNode("h2:1234", 10240); // wont heartbeat on node local node
     MockNM nodeManager3 = rm.registerNode("h3:1234", 1536); // assign 1 map
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container requests for maps
     ContainerRequestEvent event1 = createReq(jobId, 1, 1024,
@@ -313,7 +309,7 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // update resources in scheduler
@@ -323,10 +319,10 @@ public class TestRMContainerAllocator {
     // Node heartbeat from node-local next. This allocates 2 node local 
     // containers for task1 and task2. These should be matched with those tasks.
     nodeManager1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     checkAssignments(new ContainerRequestEvent[] { event1, event2, event3 },
         assigned, false);
     // remove the rack-local assignment that should have happened for task3
@@ -350,21 +346,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -378,7 +372,7 @@ public class TestRMContainerAllocator {
     MockNM nodeManager1 = rm.registerNode("h1:1234", 10240);
     MockNM nodeManager2 = rm.registerNode("h2:1234", 10240);
     MockNM nodeManager3 = rm.registerNode("h3:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container request
     ContainerRequestEvent event1 = createReq(jobId, 1, 1024,
@@ -393,17 +387,17 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // update resources in scheduler
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
     nodeManager2.nodeHeartbeat(true); // Node heartbeat
     nodeManager3.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     checkAssignments(new ContainerRequestEvent[] { event1, event2 },
         assigned, false);
   }
@@ -416,19 +410,17 @@ public class TestRMContainerAllocator {
     conf.setFloat(MRJobConfig.COMPLETED_MAPS_FOR_REDUCE_SLOWSTART, 0.0f);
     final MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    final DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
     final RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     final String host = "host1";
     final MockNM nm = rm.registerNode(String.format("%s:1234", host), 2048);
     nm.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     final ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
     final JobId jobId = MRBuilderUtils
         .newJobId(appAttemptId.getApplicationId(), 0);
     final Job mockJob = mock(Job.class);
@@ -438,20 +430,20 @@ public class TestRMContainerAllocator {
     final MyContainerAllocator allocator = new MyContainerAllocator(rm, conf,
         appAttemptId, mockJob, SystemClock.getInstance());
     // add resources to scheduler
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container request
     final String[] locations = new String[] { host };
     allocator.sendRequest(createReq(jobId, 0, 1024, locations, false, true));
     for (int i = 0; i < 1;) {
-      dispatcher.await();
+      rm.drainEvents();
       i += allocator.schedule().size();
       nm.nodeHeartbeat(true);
     }
 
     allocator.sendRequest(createReq(jobId, 0, 1024, locations, true, false));
     while (allocator.getTaskAttemptKillEvents().size() == 0) {
-      dispatcher.await();
+      rm.drainEvents();
       allocator.schedule().size();
       nm.nodeHeartbeat(true);
     }
@@ -468,21 +460,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -521,21 +511,19 @@ public class TestRMContainerAllocator {
 
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -584,21 +572,19 @@ public class TestRMContainerAllocator {
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(8192, 8));
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -639,18 +625,16 @@ public class TestRMContainerAllocator {
     conf.setFloat(MRJobConfig.COMPLETED_MAPS_FOR_REDUCE_SLOWSTART, 0.0f);
     final MyResourceManager2 rm = new MyResourceManager2(conf);
     rm.start();
-    final DrainDispatcher dispatcher = (DrainDispatcher)rm.getRMContext()
-            .getDispatcher();
     final RMApp app = rm.submitApp(2048);
-    dispatcher.await();
+    rm.drainEvents();
     final String host = "host1";
     final MockNM nm = rm.registerNode(String.format("%s:1234", host), 4096);
     nm.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     final ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
           .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
     final JobId jobId = MRBuilderUtils
                  .newJobId(appAttemptId.getApplicationId(), 0);
     final Job mockJob = mock(Job.class);
@@ -666,14 +650,14 @@ public class TestRMContainerAllocator {
     allocator.scheduleAllReduces();
     allocator.makeRemoteRequest();
     nm.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     allocator.sendRequest(createReq(jobId, 1, 1024, locations, false, false));
 
     int assignedContainer;
     for (assignedContainer = 0; assignedContainer < 1;) {
       assignedContainer += allocator.schedule().size();
       nm.nodeHeartbeat(true);
-      dispatcher.await();
+      rm.drainEvents();
     }
     // only 1 allocated container should be assigned
     Assert.assertEquals(assignedContainer, 1);
@@ -773,21 +757,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -801,7 +783,7 @@ public class TestRMContainerAllocator {
     MockNM nodeManager1 = rm.registerNode("h1:1234", 1024);
     MockNM nodeManager2 = rm.registerNode("h2:1234", 10240);
     MockNM nodeManager3 = rm.registerNode("h3:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container request
     // send MAP request
@@ -822,17 +804,17 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // update resources in scheduler
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
     nodeManager2.nodeHeartbeat(true); // Node heartbeat
     nodeManager3.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     checkAssignments(new ContainerRequestEvent[] { event1, event3 },
         assigned, false);
 
@@ -864,11 +846,6 @@ public class TestRMContainerAllocator {
     }
 
     @Override
-    protected Dispatcher createDispatcher() {
-      return new DrainDispatcher();
-    }
-
-    @Override
     protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() {
       // Dispatch inline for test sanity
       return new EventHandler<SchedulerEvent>() {
@@ -912,16 +889,16 @@ public class TestRMContainerAllocator {
 
     // Submit the application
     RMApp rmApp = rm.submitApp(1024);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 21504);
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     final ApplicationAttemptId appAttemptId = rmApp.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MRApp mrApp = new MRApp(appAttemptId, ContainerId.newContainerId(
       appAttemptId, 0), 10, 10, false, this.getClass().getName(), true, 1) {
@@ -959,11 +936,11 @@ public class TestRMContainerAllocator {
     amDispatcher.await();
 
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
 
     // Wait for all map-tasks to be running
     for (Task t : job.getTasks().values()) {
@@ -973,7 +950,7 @@ public class TestRMContainerAllocator {
     }
 
     allocator.schedule(); // Send heartbeat
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.05f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.05f, rmApp.getProgress(), 0.001f);
 
@@ -981,14 +958,14 @@ public class TestRMContainerAllocator {
     Iterator<Task> it = job.getTasks().values().iterator();
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 1);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.095f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.095f, rmApp.getProgress(), 0.001f);
 
     // Finish off 7 more so that map-progress is 80%
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 7);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.41f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.41f, rmApp.getProgress(), 0.001f);
 
@@ -996,11 +973,11 @@ public class TestRMContainerAllocator {
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 2);
 
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
 
     // Wait for all reduce-tasks to be running
     for (Task t : job.getTasks().values()) {
@@ -1013,14 +990,14 @@ public class TestRMContainerAllocator {
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 2);
 
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.59f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.59f, rmApp.getProgress(), 0.001f);
 
     // Finish off the remaining 8 reduces.
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 8);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     // Remaining is JobCleanup
     Assert.assertEquals(0.95f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.95f, rmApp.getProgress(), 0.001f);
@@ -1064,16 +1041,16 @@ public class TestRMContainerAllocator {
 
     // Submit the application
     RMApp rmApp = rm.submitApp(1024);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 11264);
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     final ApplicationAttemptId appAttemptId = rmApp.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MRApp mrApp = new MRApp(appAttemptId, ContainerId.newContainerId(
       appAttemptId, 0), 10, 0, false, this.getClass().getName(), true, 1) {
@@ -1109,11 +1086,11 @@ public class TestRMContainerAllocator {
     amDispatcher.await();
 
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
 
     // Wait for all map-tasks to be running
     for (Task t : job.getTasks().values()) {
@@ -1121,7 +1098,7 @@ public class TestRMContainerAllocator {
     }
 
     allocator.schedule(); // Send heartbeat
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.05f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.05f, rmApp.getProgress(), 0.001f);
 
@@ -1130,21 +1107,21 @@ public class TestRMContainerAllocator {
     // Finish off 1 map so that map-progress is 10%
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 1);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.14f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.14f, rmApp.getProgress(), 0.001f);
 
     // Finish off 5 more map so that map-progress is 60%
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 5);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.59f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.59f, rmApp.getProgress(), 0.001f);
 
     // Finish off remaining map so that map-progress is 100%
     finishNextNTasks(rmDispatcher, amNodeManager, mrApp, it, 4);
     allocator.schedule();
-    rmDispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0.95f, job.getProgress(), 0.001f);
     Assert.assertEquals(0.95f, rmApp.getProgress(), 0.001f);
   }
@@ -1154,21 +1131,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
-    
+    rm.drainEvents();
+
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
     MyContainerAllocator allocator = new MyContainerAllocator(rm, conf,
@@ -1177,7 +1152,7 @@ public class TestRMContainerAllocator {
     // add resources to scheduler
     MockNM nm1 = rm.registerNode("h1:1234", 10240);
     MockNM nm2 = rm.registerNode("h2:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the map container request
     ContainerRequestEvent event = createReq(jobId, 1, 1024,
@@ -1193,16 +1168,16 @@ public class TestRMContainerAllocator {
 
     // this tells the scheduler about the requests
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(1, allocator.getJobUpdatedNodeEvents().size());
     Assert.assertEquals(3, allocator.getJobUpdatedNodeEvents().get(0).getUpdatedNodes().size());
     allocator.getJobUpdatedNodeEvents().clear();
     // get the assignment
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(1, assigned.size());
     Assert.assertEquals(nm1.getNodeId(), assigned.get(0).getContainer().getNodeId());
     // no updated nodes reported
@@ -1212,11 +1187,11 @@ public class TestRMContainerAllocator {
     // mark nodes bad
     nm1.nodeHeartbeat(false);
     nm2.nodeHeartbeat(false);
-    dispatcher.await();
-    
+    rm.drainEvents();
+
     // schedule response returns updated nodes
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0, assigned.size());
     // updated nodes are reported
     Assert.assertEquals(1, allocator.getJobUpdatedNodeEvents().size());
@@ -1227,7 +1202,7 @@ public class TestRMContainerAllocator {
     allocator.getTaskAttemptKillEvents().clear();
     
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals(0, assigned.size());
     // no updated nodes reported
     Assert.assertTrue(allocator.getJobUpdatedNodeEvents().isEmpty());
@@ -1247,21 +1222,19 @@ public class TestRMContainerAllocator {
     
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
     
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -1275,7 +1248,7 @@ public class TestRMContainerAllocator {
     MockNM nodeManager1 = rm.registerNode("h1:1234", 10240);
     MockNM nodeManager2 = rm.registerNode("h2:1234", 10240);
     MockNM nodeManager3 = rm.registerNode("h3:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     // create the container request
     ContainerRequestEvent event1 = createReq(jobId, 1, 1024,
@@ -1295,7 +1268,7 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // Send events to blacklist nodes h1 and h2
@@ -1307,28 +1280,28 @@ public class TestRMContainerAllocator {
     // update resources in scheduler
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
     nodeManager2.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
     assertBlacklistAdditionsAndRemovals(2, 0, rm);
 
     // mark h1/h2 as bad nodes
     nodeManager1.nodeHeartbeat(false);
     nodeManager2.nodeHeartbeat(false);
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());    
 
     nodeManager3.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
         
     Assert.assertTrue("No of assignments must be 3", assigned.size() == 3);
@@ -1352,24 +1325,22 @@ public class TestRMContainerAllocator {
 
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM[] nodeManagers = new MockNM[10];
     int nmNum = 0;
     List<TaskAttemptContainerAssignedEvent> assigned = null;
-    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
     nodeManagers[0].nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -1382,7 +1353,7 @@ public class TestRMContainerAllocator {
     // Known=1, blacklisted=0, ignore should be false - assign first container
     assigned =
         getContainerOnHost(jobId, 1, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[0], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
     LOG.info("Failing container _1 on H1 (Node should be blacklisted and"
@@ -1397,47 +1368,47 @@ public class TestRMContainerAllocator {
     // The current call will send blacklisted node "h1" to RM
     assigned =
         getContainerOnHost(jobId, 2, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 1, 0, 0, 1, rm);
+            nodeManagers[0], allocator, 1, 0, 0, 1, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // Known=1, blacklisted=1, ignore should be true - assign 1
     assigned =
         getContainerOnHost(jobId, 2, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[0], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
-    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
     // Known=2, blacklisted=1, ignore should be true - assign 1 anyway.
     assigned =
         getContainerOnHost(jobId, 3, 1024, new String[] { "h2" },
-            nodeManagers[1], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[1], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
-    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
     // Known=3, blacklisted=1, ignore should be true - assign 1 anyway.
     assigned =
         getContainerOnHost(jobId, 4, 1024, new String[] { "h3" },
-            nodeManagers[2], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[2], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
     // Known=3, blacklisted=1, ignore should be true - assign 1
     assigned =
         getContainerOnHost(jobId, 5, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[0], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
-    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
     // Known=4, blacklisted=1, ignore should be false - assign 1 anyway
     assigned =
         getContainerOnHost(jobId, 6, 1024, new String[] { "h4" },
-            nodeManagers[3], dispatcher, allocator, 0, 0, 1, 0, rm);
+            nodeManagers[3], allocator, 0, 0, 1, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
     // Test blacklisting re-enabled.
     // Known=4, blacklisted=1, ignore should be false - no assignment on h1
     assigned =
         getContainerOnHost(jobId, 7, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[0], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
     // RMContainerRequestor would have created a replacement request.
 
@@ -1450,61 +1421,61 @@ public class TestRMContainerAllocator {
     // container for the same reason above.
     assigned =
         getContainerOnHost(jobId, 8, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 1, 0, 0, 2, rm);
+            nodeManagers[0], allocator, 1, 0, 0, 2, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // Known=4, blacklisted=2, ignore should be true. Should assign 2
     // containers.
     assigned =
         getContainerOnHost(jobId, 8, 1024, new String[] { "h1" },
-            nodeManagers[0], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[0], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 2", 2, assigned.size());
 
     // Known=4, blacklisted=2, ignore should be true.
     assigned =
         getContainerOnHost(jobId, 9, 1024, new String[] { "h2" },
-            nodeManagers[1], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[1], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
 
     // Test blacklist while ignore blacklisting enabled
     ContainerFailedEvent f3 = createFailEvent(jobId, 4, "h3", false);
     allocator.sendFailure(f3);
 
-    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+    nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
     // Known=5, blacklisted=3, ignore should be true.
     assigned =
         getContainerOnHost(jobId, 10, 1024, new String[] { "h3" },
-            nodeManagers[2], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[2], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
     
     // Assign on 5 more nodes - to re-enable blacklisting
     for (int i = 0; i < 5; i++) {
-      nodeManagers[nmNum] = registerNodeManager(nmNum++, rm, dispatcher);
+      nodeManagers[nmNum] = registerNodeManager(nmNum++, rm);
       assigned =
           getContainerOnHost(jobId, 11 + i, 1024,
               new String[] { String.valueOf(5 + i) }, nodeManagers[4 + i],
-              dispatcher, allocator, 0, 0, (i == 4 ? 3 : 0), 0, rm);
+              allocator, 0, 0, (i == 4 ? 3 : 0), 0, rm);
       Assert.assertEquals("No of assignments must be 1", 1, assigned.size());
     }
 
     // Test h3 (blacklisted while ignoring blacklisting) is blacklisted.
     assigned =
         getContainerOnHost(jobId, 20, 1024, new String[] { "h3" },
-            nodeManagers[2], dispatcher, allocator, 0, 0, 0, 0, rm);
+            nodeManagers[2], allocator, 0, 0, 0, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
   }
 
-  private MockNM registerNodeManager(int i, MyResourceManager rm,
-      DrainDispatcher dispatcher) throws Exception {
+  private MockNM registerNodeManager(int i, MyResourceManager rm)
+      throws Exception {
     MockNM nm = rm.registerNode("h" + (i + 1) + ":1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
     return nm;
   }
 
   private
       List<TaskAttemptContainerAssignedEvent> getContainerOnHost(JobId jobId,
           int taskAttemptId, int memory, String[] hosts, MockNM mockNM,
-          DrainDispatcher dispatcher, MyContainerAllocator allocator,
+          MyContainerAllocator allocator,
           int expectedAdditions1, int expectedRemovals1,
           int expectedAdditions2, int expectedRemovals2, MyResourceManager rm)
           throws Exception {
@@ -1514,17 +1485,17 @@ public class TestRMContainerAllocator {
 
     // Send the request to the RM
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(
         expectedAdditions1, expectedRemovals1, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     // Heartbeat from the required nodeManager
     mockNM.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(
         expectedAdditions2, expectedRemovals2, rm);
     return assigned;
@@ -1542,21 +1513,19 @@ public class TestRMContainerAllocator {
     
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
     
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -1569,7 +1538,7 @@ public class TestRMContainerAllocator {
     // add resources to scheduler
     MockNM nodeManager1 = rm.registerNode("h1:1234", 10240);
     MockNM nodeManager3 = rm.registerNode("h3:1234", 10240);
-    dispatcher.await();
+    rm.drainEvents();
 
     LOG.info("Requesting 1 Containers _1 on H1");
     // create the container request
@@ -1581,17 +1550,17 @@ public class TestRMContainerAllocator {
     // this tells the scheduler about the requests
     // as nodes are not added, no allocations
     List<TaskAttemptContainerAssignedEvent> assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
     LOG.info("h1 Heartbeat (To actually schedule the containers)");
     // update resources in scheduler
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
     
     LOG.info("RM Heartbeat (To process the scheduled containers)");
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
     Assert.assertEquals("No of assignments must be 1", 1, assigned.size());    
     
@@ -1608,7 +1577,7 @@ public class TestRMContainerAllocator {
 
     //Update the Scheduler with the new requests.
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(1, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
 
@@ -1623,11 +1592,11 @@ public class TestRMContainerAllocator {
     LOG.info("h1 Heartbeat (To actually schedule the containers)");
     // update resources in scheduler
     nodeManager1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
     
     LOG.info("RM Heartbeat (To process the scheduled containers)");
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());    
     
@@ -1636,19 +1605,19 @@ public class TestRMContainerAllocator {
     //Send a release for the p:5 container + another request.
     LOG.info("RM Heartbeat (To process the re-scheduled containers)");
     assigned = allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
     Assert.assertEquals("No of assignments must be 0", 0, assigned.size());
     
     //Hearbeat from H3 to schedule on this host.
     LOG.info("h3 Heartbeat (To re-schedule the containers)");
     nodeManager3.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm.drainEvents();
     
     LOG.info("RM Heartbeat (To process the re-scheduled containers for H3)");
     assigned = allocator.schedule();
     assertBlacklistAdditionsAndRemovals(0, 0, rm);
-    dispatcher.await();
+    rm.drainEvents();
      
     // For debugging
     for (TaskAttemptContainerAssignedEvent assig : assigned) {
@@ -2229,22 +2198,20 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     final MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Make a node to register so as to launch the AM.
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job job = mock(Job.class);
@@ -2381,21 +2348,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     final MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher rmDispatcher =
-        (DrainDispatcher) rm.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp rmApp = rm.submitApp(1024);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 11264);
     amNodeManager.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     final ApplicationAttemptId appAttemptId =
         rmApp.getCurrentAppAttempt().getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    rmDispatcher.await();
+    rm.drainEvents();
 
     MRApp mrApp =
         new MRApp(appAttemptId, ContainerId.newContainerId(appAttemptId, 0), 10,
@@ -2454,22 +2419,20 @@ public class TestRMContainerAllocator {
 
     MyResourceManager rm1 = new MyResourceManager(conf, memStore);
     rm1.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm1.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm1.submitApp(1024);
-    dispatcher.await();
+    rm1.drainEvents();
 
     MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm1.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm1.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -2498,7 +2461,7 @@ public class TestRMContainerAllocator {
     // send allocate request and 1 blacklisted nodes
     List<TaskAttemptContainerAssignedEvent> assignedContainers =
         allocator.schedule();
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0,
         assignedContainers.size());
     // Why ask is 3, not 4? --> ask from blacklisted node h2 is removed
@@ -2506,11 +2469,11 @@ public class TestRMContainerAllocator {
     assertBlacklistAdditionsAndRemovals(1, 0, rm1);
 
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     // Step-2 : 2 containers are allocated by RM.
     assignedContainers = allocator.schedule();
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("No of assignments must be 2", 2,
         assignedContainers.size());
     assertAsksAndReleases(0, 0, rm1);
@@ -2545,7 +2508,6 @@ public class TestRMContainerAllocator {
     rm2.start();
     nm1.setResourceTrackerService(rm2.getResourceTrackerService());
     allocator.updateSchedulerProxy(rm2);
-    dispatcher = (DrainDispatcher) rm2.getRMContext().getDispatcher();
 
     // NM should be rebooted on heartbeat, even first heartbeat for nm2
     NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true);
@@ -2555,7 +2517,7 @@ public class TestRMContainerAllocator {
     nm1 = new MockNM("h1:1234", 10240, rm2.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm2.drainEvents();
 
     // Step-4 : On RM restart, AM(does not know RM is restarted) sends
     // additional containerRequest(event4) and blacklisted nodes.
@@ -2576,7 +2538,7 @@ public class TestRMContainerAllocator {
 
     // send allocate request to 2nd RM and get resync command
     allocator.schedule();
-    dispatcher.await();
+    rm2.drainEvents();
 
     // Step-5 : On Resync,AM sends all outstanding
     // asks,release,blacklistAaddition
@@ -2587,16 +2549,16 @@ public class TestRMContainerAllocator {
 
     // send all outstanding request again.
     assignedContainers = allocator.schedule();
-    dispatcher.await();
+    rm2.drainEvents();
     assertAsksAndReleases(3, 2, rm2);
     assertBlacklistAdditionsAndRemovals(2, 0, rm2);
 
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm2.drainEvents();
 
     // Step-6 : RM allocates containers i.e event3,event4 and cRequest5
     assignedContainers = allocator.schedule();
-    dispatcher.await();
+    rm2.drainEvents();
 
     Assert.assertEquals("Number of container should be 3", 3,
         assignedContainers.size());
@@ -2699,20 +2661,19 @@ public class TestRMContainerAllocator {
       MRJobConfig.MR_AM_TO_RM_WAIT_INTERVAL_MS, 0);
     MyResourceManager rm1 = new MyResourceManager(conf);
     rm1.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm1.getRMContext().getDispatcher();
+
     RMApp app = rm1.submitApp(1024);
-    dispatcher.await();
+    rm1.drainEvents();
 
     MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm1.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm1.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm1.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -2728,7 +2689,7 @@ public class TestRMContainerAllocator {
     } catch (RMContainerAllocationException e) {
       Assert.assertTrue(e.getMessage().contains("Could not contact RM after"));
     }
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("Should Have 1 Job Event", 1,
         allocator.jobEvents.size());
     JobEvent event = allocator.jobEvents.get(0); 
@@ -2750,22 +2711,20 @@ public class TestRMContainerAllocator {
     rm.start();
     AMRMTokenSecretManager secretMgr =
         rm.getRMContext().getAMRMTokenSecretManager();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     final ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     final ApplicationId appId = app.getApplicationId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     final Job mockJob = mock(Job.class);
@@ -2953,21 +2912,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher = (DrainDispatcher) rm.getRMContext()
-        .getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 2048);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -2989,21 +2946,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 1260);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -3018,7 +2973,7 @@ public class TestRMContainerAllocator {
 
     // Register nodes to RM.
     MockNM nodeManager = rm.registerNode("h1:1234", 1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Request 2 maps and 1 reducer(sone on nodes which are not registered).
     ContainerRequestEvent event1 =
@@ -3034,7 +2989,7 @@ public class TestRMContainerAllocator {
     // This will tell the scheduler about the requests but there will be no
     // allocations as nodes are not added.
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Advance clock so that maps can be considered as hanging.
     clock.setTime(System.currentTimeMillis() + 500000L);
@@ -3045,15 +3000,15 @@ public class TestRMContainerAllocator {
     allocator.sendRequest(event4);
 
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Update resources in scheduler through node heartbeat from h1.
     nodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(1024, 1));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // One map is assigned.
     Assert.assertEquals(1, allocator.getAssignedRequests().maps.size());
@@ -3087,7 +3042,7 @@ public class TestRMContainerAllocator {
     // On next allocate request to scheduler, headroom reported will be 0.
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(0, 0));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     // After allocate response from scheduler, all scheduled reduces are ramped
     // down and move to pending. 3 asks are also updated with 0 containers to
     // indicate ramping down of reduces to scheduler.
@@ -3155,21 +3110,19 @@ public class TestRMContainerAllocator {
     Configuration conf = new Configuration();
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 1260);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -3184,7 +3137,7 @@ public class TestRMContainerAllocator {
 
     // Register nodes to RM.
     MockNM nodeManager = rm.registerNode("h1:1234", 1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Request 2 maps and 1 reducer(sone on nodes which are not registered).
     ContainerRequestEvent event1 =
@@ -3200,7 +3153,7 @@ public class TestRMContainerAllocator {
     // This will tell the scheduler about the requests but there will be no
     // allocations as nodes are not added.
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Advance clock so that maps can be considered as hanging.
     clock.setTime(System.currentTimeMillis() + 500000L);
@@ -3211,15 +3164,15 @@ public class TestRMContainerAllocator {
     allocator.sendRequest(event4);
 
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Update resources in scheduler through node heartbeat from h1.
     nodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(1024, 1));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // One map is assigned.
     Assert.assertEquals(1, allocator.getAssignedRequests().maps.size());
@@ -3256,7 +3209,7 @@ public class TestRMContainerAllocator {
     // On next allocate request to scheduler, headroom reported will be 2048.
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(2048, 0));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     // After allocate response from scheduler, all scheduled reduces are ramped
     // down and move to pending. 3 asks are also updated with 0 containers to
     // indicate ramping down of reduces to scheduler.
@@ -3285,21 +3238,19 @@ public class TestRMContainerAllocator {
     conf.setInt(MRJobConfig.MR_JOB_REDUCER_UNCONDITIONAL_PREEMPT_DELAY_SEC, -1);
     MyResourceManager rm = new MyResourceManager(conf);
     rm.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm.submitApp(1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockNM amNodeManager = rm.registerNode("amNM:1234", 1260);
     amNodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttemptId = app.getCurrentAppAttempt()
         .getAppAttemptId();
     rm.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm.drainEvents();
 
     JobId jobId = MRBuilderUtils.newJobId(appAttemptId.getApplicationId(), 0);
     Job mockJob = mock(Job.class);
@@ -3315,10 +3266,10 @@ public class TestRMContainerAllocator {
         appAttemptId, mockJob);
 
     MockNM nodeManager = rm.registerNode("h1:1234", 4096);
-    dispatcher.await();
+    rm.drainEvents();
     // Register nodes to RM.
     MockNM nodeManager2 = rm.registerNode("h2:1234", 1024);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Request 2 maps and 1 reducer(sone on nodes which are not registered).
     ContainerRequestEvent event1 =
@@ -3334,7 +3285,7 @@ public class TestRMContainerAllocator {
     // This will tell the scheduler about the requests but there will be no
     // allocations as nodes are not added.
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Request for another reducer on h3 which has not registered.
     ContainerRequestEvent event4 =
@@ -3342,15 +3293,15 @@ public class TestRMContainerAllocator {
     allocator.sendRequest(event4);
 
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Update resources in scheduler through node heartbeat from h1.
     nodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(3072, 3));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // Two maps are assigned.
     Assert.assertEquals(2, allocator.getAssignedRequests().maps.size());
@@ -3363,15 +3314,15 @@ public class TestRMContainerAllocator {
     Assert.assertEquals(0, allocator.getAssignedRequests().maps.size());
 
     nodeManager.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(1024, 1));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
 
     // h2 heartbeats.
     nodeManager2.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Send request for one more mapper.
     ContainerRequestEvent event5 =
@@ -3380,7 +3331,7 @@ public class TestRMContainerAllocator {
 
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(2048, 2));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     // One reducer is assigned and one map is scheduled
     Assert.assertEquals(1, allocator.getScheduledRequests().maps.size());
     Assert.assertEquals(1, allocator.getAssignedRequests().reduces.size());
@@ -3388,7 +3339,7 @@ public class TestRMContainerAllocator {
     // enough if scheduled reducers resources are deducted.
     rm.getMyFifoScheduler().forceResourceLimit(Resource.newInstance(1260, 2));
     allocator.schedule();
-    dispatcher.await();
+    rm.drainEvents();
     // After allocate response, the one assigned reducer is preempted and killed
     Assert.assertEquals(1, MyContainerAllocator.getTaskAttemptKillEvents().size());
     Assert.assertEquals(RMContainerAllocator.RAMPDOWN_DIAGNOSTIC,

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java
index 39a7633..fa3c6af 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestAMRMClientOnRMRestart.java
@@ -49,8 +49,6 @@ import org.apache.hadoop.yarn.api.records.UpdateContainerRequest;
 import org.apache.hadoop.yarn.client.api.AMRMClient;
 import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.ipc.YarnRPC;
 import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
@@ -126,22 +124,20 @@ public class TestAMRMClientOnRMRestart {
     // Phase-1 Start 1st RM
     MyResourceManager rm1 = new MyResourceManager(conf, memStore);
     rm1.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm1.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm1.submitApp(1024);
-    dispatcher.await();
+    rm1.drainEvents();
 
     MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm1.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm1.drainEvents();
 
     org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> token =
         rm1.getRMContext().getRMApps().get(appAttemptId.getApplicationId())
@@ -176,7 +172,7 @@ public class TestAMRMClientOnRMRestart {
     blacklistAdditions.remove("h2");// remove from local list
 
     AllocateResponse allocateResponse = amClient.allocate(0.1f);
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, allocateResponse
         .getAllocatedContainers().size());
 
@@ -189,10 +185,10 @@ public class TestAMRMClientOnRMRestart {
     // Step-2 : NM heart beat is sent.
     // On 2nd AM allocate request, RM allocates 3 containers to AM
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     allocateResponse = amClient.allocate(0.2f);
-    dispatcher.await();
+    rm1.drainEvents();
     // 3 containers are allocated i.e for cRequest1, cRequest2 and cRequest3.
     Assert.assertEquals("No of assignments must be 0", 3, allocateResponse
         .getAllocatedContainers().size());
@@ -207,7 +203,7 @@ public class TestAMRMClientOnRMRestart {
     amClient.removeContainerRequest(cRequest3);
 
     allocateResponse = amClient.allocate(0.2f);
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, allocateResponse
         .getAllocatedContainers().size());
     assertAsksAndReleases(4, 0, rm1);
@@ -233,7 +229,7 @@ public class TestAMRMClientOnRMRestart {
     // request
     nm1.nodeHeartbeat(containerId.getApplicationAttemptId(),
         containerId.getContainerId(), ContainerState.RUNNING);
-    dispatcher.await();
+    rm1.drainEvents();
     amClient.requestContainerUpdate(
         container, UpdateContainerRequest.newInstance(
             container.getVersion(), container.getId(),
@@ -242,7 +238,7 @@ public class TestAMRMClientOnRMRestart {
     it.remove();
 
     allocateResponse = amClient.allocate(0.3f);
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, allocateResponse
         .getAllocatedContainers().size());
     assertAsksAndReleases(3, pendingRelease, rm1);
@@ -258,7 +254,6 @@ public class TestAMRMClientOnRMRestart {
     rm2.start();
     nm1.setResourceTrackerService(rm2.getResourceTrackerService());
     ((MyAMRMClientImpl) amClient).updateRMProxy(rm2);
-    dispatcher = (DrainDispatcher) rm2.getRMContext().getDispatcher();
 
     // NM should be rebooted on heartbeat, even first heartbeat for nm2
     NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true);
@@ -274,7 +269,7 @@ public class TestAMRMClientOnRMRestart {
         Collections.singletonList(
             containerId.getApplicationAttemptId().getApplicationId()));
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm2.drainEvents();
 
     blacklistAdditions.add("h3");
     amClient.updateBlacklist(blacklistAdditions, null);
@@ -296,7 +291,7 @@ public class TestAMRMClientOnRMRestart {
     // containerRequest and blacklisted nodes.
     // Intern RM send resync command,AMRMClient resend allocate request
     allocateResponse = amClient.allocate(0.3f);
-    dispatcher.await();
+    rm2.drainEvents();
 
     completedContainer =
         allocateResponse.getCompletedContainersStatuses().size();
@@ -313,7 +308,7 @@ public class TestAMRMClientOnRMRestart {
 
     // Step-5 : Allocater after resync command
     allocateResponse = amClient.allocate(0.5f);
-    dispatcher.await();
+    rm2.drainEvents();
     Assert.assertEquals("No of assignments must be 0", 0, allocateResponse
         .getAllocatedContainers().size());
 
@@ -326,10 +321,10 @@ public class TestAMRMClientOnRMRestart {
     int count = 5;
     while (count-- > 0) {
       nm1.nodeHeartbeat(true);
-      dispatcher.await();
+      rm2.drainEvents();
 
       allocateResponse = amClient.allocate(0.5f);
-      dispatcher.await();
+      rm2.drainEvents();
       noAssignedContainer += allocateResponse.getAllocatedContainers().size();
       if (noAssignedContainer == 3) {
         break;
@@ -358,22 +353,20 @@ public class TestAMRMClientOnRMRestart {
     // Phase-1 Start 1st RM
     MyResourceManager rm1 = new MyResourceManager(conf, memStore);
     rm1.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm1.getRMContext().getDispatcher();
 
     // Submit the application
     RMApp app = rm1.submitApp(1024);
-    dispatcher.await();
+    rm1.drainEvents();
 
     MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm1.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm1.drainEvents();
 
     org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> token =
         rm1.getRMContext().getRMApps().get(appAttemptId.getApplicationId())
@@ -393,7 +386,6 @@ public class TestAMRMClientOnRMRestart {
     rm2.start();
     nm1.setResourceTrackerService(rm2.getResourceTrackerService());
     ((MyAMRMClientImpl) amClient).updateRMProxy(rm2);
-    dispatcher = (DrainDispatcher) rm2.getRMContext().getDispatcher();
 
     // NM should be rebooted on heartbeat, even first heartbeat for nm2
     NodeHeartbeatResponse hbResponse = nm1.nodeHeartbeat(true);
@@ -409,7 +401,7 @@ public class TestAMRMClientOnRMRestart {
             Priority.newInstance(0), 0);
     nm1.registerNode(Arrays.asList(containerReport), null);
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm2.drainEvents();
 
     amClient.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED,
         null, null);
@@ -421,7 +413,6 @@ public class TestAMRMClientOnRMRestart {
     amClient.stop();
     rm1.stop();
     rm2.stop();
-
   }
 
 
@@ -439,22 +430,20 @@ public class TestAMRMClientOnRMRestart {
     // start first RM
     MyResourceManager2 rm1 = new MyResourceManager2(conf, memStore);
     rm1.start();
-    DrainDispatcher dispatcher =
-        (DrainDispatcher) rm1.getRMContext().getDispatcher();
     Long startTime = System.currentTimeMillis();
     // Submit the application
     RMApp app = rm1.submitApp(1024);
-    dispatcher.await();
+    rm1.drainEvents();
 
     MockNM nm1 = new MockNM("h1:1234", 15120, rm1.getResourceTrackerService());
     nm1.registerNode();
     nm1.nodeHeartbeat(true); // Node heartbeat
-    dispatcher.await();
+    rm1.drainEvents();
 
     ApplicationAttemptId appAttemptId =
         app.getCurrentAppAttempt().getAppAttemptId();
     rm1.sendAMLaunched(appAttemptId);
-    dispatcher.await();
+    rm1.drainEvents();
 
     AMRMTokenSecretManager amrmTokenSecretManagerForRM1 =
         rm1.getRMContext().getAMRMTokenSecretManager();
@@ -513,7 +502,6 @@ public class TestAMRMClientOnRMRestart {
     rm2.start();
     nm1.setResourceTrackerService(rm2.getResourceTrackerService());
     ((MyAMRMClientImpl) amClient).updateRMProxy(rm2);
-    dispatcher = (DrainDispatcher) rm2.getRMContext().getDispatcher();
 
     AMRMTokenSecretManager amrmTokenSecretManagerForRM2 =
         rm2.getRMContext().getAMRMTokenSecretManager();
@@ -616,11 +604,6 @@ public class TestAMRMClientOnRMRestart {
     }
 
     @Override
-    protected Dispatcher createDispatcher() {
-      return new DrainDispatcher();
-    }
-
-    @Override
     protected EventHandler<SchedulerEvent> createSchedulerEventDispatcher() {
       // Dispatch inline for test sanity
       return new EventHandler<SchedulerEvent>() {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ACLsTestBase.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/ACLsTestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ACLsTestBase.java
index fbd5ac3..100eb7f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ACLsTestBase.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ACLsTestBase.java
@@ -30,14 +30,9 @@ import org.apache.hadoop.security.authorize.AccessControlList;
 import org.apache.hadoop.service.Service.STATE;
 import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.ipc.YarnRPC;
 import org.junit.Before;
 
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
 public abstract class ACLsTestBase {
 
   protected static final String COMMON_USER = "common_user";
@@ -81,11 +76,6 @@ public abstract class ACLsTestBase {
       }
 
       @Override
-      protected Dispatcher createDispatcher() {
-        return new DrainDispatcher();
-      }
-
-      @Override
       protected void doSecureLogin() throws IOException {
       }
     };

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMHATestBase.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/RMHATestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMHATestBase.java
index c9ce7d7..c95bcdf 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMHATestBase.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/RMHATestBase.java
@@ -26,22 +26,17 @@ import org.apache.hadoop.ha.HAServiceProtocol;
 import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState;
 import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo;
 import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
-import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.conf.HAUtil;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.server.resourcemanager.recovery.ZKRMStateStore;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
 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.RMAppAttemptState;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.YarnScheduler;
 import org.apache.hadoop.yarn.server.security.ApplicationACLsManager;
-import org.apache.hadoop.yarn.server.utils.BuilderUtils;
 import org.junit.After;
 import org.junit.Assert;
 import org.junit.Before;
@@ -108,20 +103,9 @@ public abstract class RMHATestBase extends ClientBaseWithFixes{
   }
 
   protected void startRMs() throws IOException {
-    rm1 = new MockRM(confForRM1, null, false, false){
-      @Override
-      protected Dispatcher createDispatcher() {
-        return new DrainDispatcher();
-      }
-    };
-    rm2 = new MockRM(confForRM2, null, false, false){
-      @Override
-      protected Dispatcher createDispatcher() {
-        return new DrainDispatcher();
-      }
-    };
+    rm1 = new MockRM(confForRM1, null, false, false);
+    rm2 = new MockRM(confForRM2, null, false, false);
     startRMs(rm1, confForRM1, rm2, confForRM2);
-
   }
 
   protected void startRMsWithCustomizedRMAppManager() throws IOException {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ReservationACLsTestBase.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/ReservationACLsTestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ReservationACLsTestBase.java
index 03bc889..c8ee00e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ReservationACLsTestBase.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/ReservationACLsTestBase.java
@@ -47,7 +47,6 @@ import org.apache.hadoop.yarn.api.records.ReservationRequest;
 import org.apache.hadoop.yarn.api.records.ReservationRequestInterpreter;
 import org.apache.hadoop.yarn.api.records.ReservationRequests;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler;
@@ -463,9 +462,7 @@ public class ReservationACLsTestBase extends ACLsTestBase {
       int attempts = 10;
       Collection<Plan> plans;
       do {
-        DrainDispatcher dispatcher =
-                (DrainDispatcher) resourceManager.getRMContext().getDispatcher();
-        dispatcher.await();
+        resourceManager.drainEvents();
         LOG.info("Waiting for node capacity to be added to plan");
         plans = resourceManager.getRMContext().getReservationSystem()
                 .getAllPlans().values();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationCleanup.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/TestApplicationCleanup.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationCleanup.java
index c4197a1..422b7eb 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationCleanup.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationCleanup.java
@@ -40,8 +40,6 @@ 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.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.server.api.protocolrecords.NMContainerStatus;
 import org.apache.hadoop.yarn.server.api.protocolrecords.NodeHeartbeatResponse;
 import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore;
@@ -161,13 +159,7 @@ public class TestApplicationCleanup {
 
     Logger rootLogger = LogManager.getRootLogger();
     rootLogger.setLevel(Level.DEBUG);
-    final DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = new MockRM() {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-    };
+    MockRM rm = new MockRM();
     rm.start();
 
     MockNM nm1 = rm.registerNode("127.0.0.1:1234", 5000);
@@ -185,8 +177,8 @@ public class TestApplicationCleanup {
     int request = 2;
     am.allocate("127.0.0.1" , 1000, request, 
         new ArrayList<ContainerId>());
-    dispatcher.await();
-    
+    rm.drainEvents();
+
     //kick the scheduler
     nm1.nodeHeartbeat(true);
     List<Container> conts = am.allocate(new ArrayList<ResourceRequest>(),
@@ -199,7 +191,7 @@ public class TestApplicationCleanup {
       Thread.sleep(100);
       conts = am.allocate(new ArrayList<ResourceRequest>(),
           new ArrayList<ContainerId>()).getAllocatedContainers();
-      dispatcher.await();
+      rm.drainEvents();
       contReceived += conts.size();
       nm1.nodeHeartbeat(true);
     }
@@ -209,7 +201,7 @@ public class TestApplicationCleanup {
     ArrayList<ContainerId> release = new ArrayList<ContainerId>();
     release.add(conts.get(0).getId());
     am.allocate(new ArrayList<ResourceRequest>(), release);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Send one more heartbeat with a fake running container. This is to
     // simulate the situation that can happen if the NM reports that container
@@ -224,7 +216,7 @@ public class TestApplicationCleanup {
     containerStatuses.put(app.getApplicationId(), containerStatusList);
 
     NodeHeartbeatResponse resp = nm1.nodeHeartbeat(containerStatuses, true);
-    waitForContainerCleanup(dispatcher, nm1, resp);
+    waitForContainerCleanup(rm, nm1, resp);
 
     // Now to test the case when RM already gave cleanup, and NM suddenly
     // realizes that the container is running.
@@ -240,17 +232,17 @@ public class TestApplicationCleanup {
     resp = nm1.nodeHeartbeat(containerStatuses, true);
     // The cleanup list won't be instantaneous as it is given out by scheduler
     // and not RMNodeImpl.
-    waitForContainerCleanup(dispatcher, nm1, resp);
+    waitForContainerCleanup(rm, nm1, resp);
 
     rm.stop();
   }
 
-  protected void waitForContainerCleanup(DrainDispatcher dispatcher, MockNM nm,
+  protected void waitForContainerCleanup(MockRM rm, MockNM nm,
       NodeHeartbeatResponse resp) throws Exception {
     int waitCount = 0, cleanedConts = 0;
     List<ContainerId> contsToClean;
     do {
-      dispatcher.await();
+      rm.drainEvents();
       contsToClean = resp.getContainersToCleanup();
       cleanedConts += contsToClean.size();
       if (cleanedConts >= 1) {
@@ -400,13 +392,7 @@ public class TestApplicationCleanup {
     memStore.init(conf);
 
     // start RM
-    final DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm1 = new MockRM(conf, memStore) {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-    };
+    MockRM rm1 = new MockRM(conf, memStore);
     rm1.start();
     MockNM nm1 =
         new MockNM("127.0.0.1:1234", 15120, rm1.getResourceTrackerService());
@@ -419,13 +405,7 @@ public class TestApplicationCleanup {
     rm1.waitForState(app0.getApplicationId(), RMAppState.RUNNING);
 
     // start new RM
-    final DrainDispatcher dispatcher2 = new DrainDispatcher();
-    MockRM rm2 = new MockRM(conf, memStore) {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher2;
-      }
-    };
+    MockRM rm2 = new MockRM(conf, memStore);
     rm2.start();
 
     // nm1 register to rm2, and do a heartbeat
@@ -437,7 +417,7 @@ public class TestApplicationCleanup {
     NodeHeartbeatResponse response = nm1.nodeHeartbeat(am0
         .getApplicationAttemptId(), 2, ContainerState.RUNNING);
 
-    waitForContainerCleanup(dispatcher2, nm1, response);
+    waitForContainerCleanup(rm2, nm1, response);
 
     rm1.stop();
     rm2.stop();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterLauncher.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/TestApplicationMasterLauncher.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterLauncher.java
index 08b180f..9e84010 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterLauncher.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterLauncher.java
@@ -59,8 +59,6 @@ import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.api.records.SerializedException;
 import org.apache.hadoop.yarn.api.records.Token;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException;
 import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException;
 import org.apache.hadoop.yarn.exceptions.NMNotYetReadyException;
@@ -260,7 +258,6 @@ public class TestApplicationMasterLauncher {
     Configuration conf = new Configuration();
     conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 1);
     conf.setInt(YarnConfiguration.CLIENT_NM_CONNECT_RETRY_INTERVAL_MS, 1);
-    final DrainDispatcher dispatcher = new DrainDispatcher();
     MockRM rm = new MockRMWithCustomAMLauncher(conf, null) {
       @Override
       protected ApplicationMasterLauncher createAMLauncher() {
@@ -284,12 +281,8 @@ public class TestApplicationMasterLauncher {
           }
         };
       }
-
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
     };
+
     rm.start();
     MockNM nm1 = rm.registerNode("127.0.0.1:1234", 5120);
 
@@ -297,7 +290,7 @@ public class TestApplicationMasterLauncher {
 
     // kick the scheduling
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     MockRM.waitForState(app.getCurrentAppAttempt(),
       RMAppAttemptState.LAUNCHED, 500);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterService.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/TestApplicationMasterService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterService.java
index 23bed22..18c49bd 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestApplicationMasterService.java
@@ -42,8 +42,6 @@ import org.apache.hadoop.yarn.api.records.Priority;
 import org.apache.hadoop.yarn.api.records.ResourceRequest;
 import org.apache.hadoop.yarn.api.records.UpdateContainerRequest;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException;
 import org.apache.hadoop.yarn.exceptions.InvalidContainerReleaseException;
 import org.apache.hadoop.yarn.proto.YarnServiceProtos.SchedulerResourceTypes;
@@ -327,10 +325,8 @@ public class TestApplicationMasterService {
 
   @Test(timeout=1200000)
   public void  testAllocateAfterUnregister() throws Exception {
-    MyResourceManager rm = new MyResourceManager(conf);
+    MockRM rm = new MockRM(conf);
     rm.start();
-    DrainDispatcher rmDispatcher = (DrainDispatcher) rm.getRMContext()
-            .getDispatcher();
     // Register node1
     MockNM nm1 = rm.registerNode("127.0.0.1:1234", 6 * GB);
 
@@ -351,7 +347,7 @@ public class TestApplicationMasterService {
     AllocateResponse alloc1Response = am1.schedule();
 
     nm1.nodeHeartbeat(true);
-    rmDispatcher.await();
+    rm.drainEvents();
     alloc1Response = am1.schedule();
     Assert.assertEquals(0, alloc1Response.getAllocatedContainers().size());
   }
@@ -474,17 +470,6 @@ public class TestApplicationMasterService {
     rm.stop();
   }
 
-  private static class MyResourceManager extends MockRM {
-
-    public MyResourceManager(YarnConfiguration conf) {
-      super(conf);
-    }
-    @Override
-    protected Dispatcher createDispatcher() {
-      return new DrainDispatcher();
-    }
-  }
-  
   private void sentRMContainerLaunched(MockRM rm, ContainerId containerId) {
     CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
     RMContainer rmContainer = cs.getRMContainer(containerId);


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[10/50] [abbrv] hadoop git commit: YARN-6411. Clean up the overwrite of createDispatcher() in subclass of MockRM. Contributed by Yufei Gu

Posted by in...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestNodeBlacklistingOnAMFailures.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/TestNodeBlacklistingOnAMFailures.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestNodeBlacklistingOnAMFailures.java
index b4adf48..75ef5c7 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestNodeBlacklistingOnAMFailures.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestNodeBlacklistingOnAMFailures.java
@@ -33,8 +33,6 @@ 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.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.server.resourcemanager.applicationsmanager.TestAMRestart;
 import org.apache.hadoop.yarn.server.resourcemanager.recovery.MemoryRMStateStore;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
@@ -65,8 +63,7 @@ public class TestNodeBlacklistingOnAMFailures {
     conf.setBoolean(YarnConfiguration.AM_SCHEDULING_NODE_BLACKLISTING_ENABLED,
         true);
 
-    DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = startRM(conf, dispatcher);
+    MockRM rm = startRM(conf);
     CapacityScheduler scheduler = (CapacityScheduler) rm.getResourceScheduler();
 
     // Register 5 nodes, so that we can blacklist atleast one if AM container
@@ -122,7 +119,7 @@ public class TestNodeBlacklistingOnAMFailures {
     // Try the current node a few times
     for (int i = 0; i <= 2; i++) {
       currentNode.nodeHeartbeat(true);
-      dispatcher.await();
+      rm.drainEvents();
 
       Assert.assertEquals(
           "AppAttemptState should still be SCHEDULED if currentNode is "
@@ -132,7 +129,7 @@ public class TestNodeBlacklistingOnAMFailures {
 
     // Now try the other node
     otherNode.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Now the AM container should be allocated
     MockRM.waitForState(attempt, RMAppAttemptState.ALLOCATED, 20000);
@@ -169,8 +166,7 @@ public class TestNodeBlacklistingOnAMFailures {
     conf.setBoolean(YarnConfiguration.AM_SCHEDULING_NODE_BLACKLISTING_ENABLED,
         true);
 
-    DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = startRM(conf, dispatcher);
+    MockRM rm = startRM(conf);
     CapacityScheduler scheduler = (CapacityScheduler) rm.getResourceScheduler();
 
     // Register 5 nodes, so that we can blacklist atleast one if AM container
@@ -227,7 +223,7 @@ public class TestNodeBlacklistingOnAMFailures {
     System.out.println("New AppAttempt launched " + attempt.getAppAttemptId());
 
     nm2.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Now the AM container should be allocated
     MockRM.waitForState(attempt, RMAppAttemptState.ALLOCATED, 20000);
@@ -257,8 +253,7 @@ public class TestNodeBlacklistingOnAMFailures {
     conf.setBoolean(YarnConfiguration.AM_SCHEDULING_NODE_BLACKLISTING_ENABLED,
         true);
 
-    DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = startRM(conf, dispatcher);
+    MockRM rm = startRM(conf);
     CapacityScheduler scheduler = (CapacityScheduler) rm.getResourceScheduler();
 
     // Register 5 nodes, so that we can blacklist atleast one if AM container
@@ -319,7 +314,7 @@ public class TestNodeBlacklistingOnAMFailures {
     nm3.nodeHeartbeat(true);
     nm4.nodeHeartbeat(true);
     nm5.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     // Now the AM container should be allocated
     MockRM.waitForState(attempt, RMAppAttemptState.ALLOCATED, 20000);
@@ -352,8 +347,7 @@ public class TestNodeBlacklistingOnAMFailures {
         1.5f);
     conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS, 100);
 
-    DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = startRM(conf, dispatcher);
+    MockRM rm = startRM(conf);
 
     MockNM node =
         new MockNM("127.0.0.1:1234", 8000, rm.getResourceTrackerService());
@@ -367,7 +361,7 @@ public class TestNodeBlacklistingOnAMFailures {
     // Now the AM container should be allocated
     RMAppAttempt attempt = MockRM.waitForAttemptScheduled(app, rm);
     node.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     MockRM.waitForState(attempt, RMAppAttemptState.ALLOCATED, 20000);
     rm.sendAMLaunched(attempt.getAppAttemptId());
     rm.waitForState(attempt.getAppAttemptId(), RMAppAttemptState.LAUNCHED);
@@ -394,7 +388,7 @@ public class TestNodeBlacklistingOnAMFailures {
           .println("New AppAttempt launched " + attempt.getAppAttemptId());
 
       node.nodeHeartbeat(true);
-      dispatcher.await();
+      rm.drainEvents();
 
       MockRM.waitForState(attempt, RMAppAttemptState.ALLOCATED, 20000);
       rm.sendAMLaunched(attempt.getAppAttemptId());
@@ -418,20 +412,13 @@ public class TestNodeBlacklistingOnAMFailures {
     rm.waitForState(amAttemptID.getApplicationId(), RMAppState.ACCEPTED);
   }
 
-  private MockRM startRM(YarnConfiguration conf,
-      final DrainDispatcher dispatcher) {
-
+  private MockRM startRM(YarnConfiguration conf) {
     MemoryRMStateStore memStore = new MemoryRMStateStore();
     memStore.init(conf);
 
-    MockRM rm1 = new MockRM(conf, memStore) {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-    };
+    MockRM rm = new MockRM(conf, memStore);
 
-    rm1.start();
-    return rm1;
+    rm.start();
+    return rm;
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestReservationSystemWithRMHA.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/TestReservationSystemWithRMHA.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestReservationSystemWithRMHA.java
index 5a6fe67..f746dc2 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestReservationSystemWithRMHA.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestReservationSystemWithRMHA.java
@@ -29,7 +29,6 @@ import org.apache.hadoop.yarn.api.records.QueueInfo;
 import org.apache.hadoop.yarn.api.records.ReservationDefinition;
 import org.apache.hadoop.yarn.api.records.ReservationId;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.proto.YarnProtos.ReservationAllocationStateProto;
 import org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore.RMState;
 import org.apache.hadoop.yarn.server.resourcemanager.reservation.Plan;
@@ -186,9 +185,7 @@ public class TestReservationSystemWithRMHA extends RMHATestBase {
       rm.registerNode("127.0.0.1:1", memory, vCores);
       int attempts = 10;
       do {
-        DrainDispatcher dispatcher =
-            (DrainDispatcher) rm1.getRMContext().getDispatcher();
-        dispatcher.await();
+        rm1.drainEvents();
         rm.getRMContext().getReservationSystem()
             .synchronizePlan(ReservationSystemTestUtil.reservationQ, false);
         if (rm.getRMContext().getReservationSystem()

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRMRPCNodeUpdates.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/applicationsmanager/TestAMRMRPCNodeUpdates.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRMRPCNodeUpdates.java
index c8baa60..f9f0b74 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRMRPCNodeUpdates.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/applicationsmanager/TestAMRMRPCNodeUpdates.java
@@ -31,8 +31,6 @@ import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.NodeReport;
 import org.apache.hadoop.yarn.api.records.NodeState;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;
 import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService;
 import org.apache.hadoop.yarn.server.resourcemanager.MockAM;
@@ -47,12 +45,10 @@ import org.junit.Test;
 
 public class TestAMRMRPCNodeUpdates {
   private MockRM rm;
-  ApplicationMasterService amService = null;
-  DrainDispatcher dispatcher = null;
+  private ApplicationMasterService amService;
 
   @Before
   public void setUp() {
-    dispatcher = new DrainDispatcher();
     this.rm = new MockRM() {
       @Override
       public void init(Configuration conf) {
@@ -61,12 +57,8 @@ public class TestAMRMRPCNodeUpdates {
           "1.0");
         super.init(conf);
       }
-
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
     };
+
     rm.start();
     amService = rm.getApplicationMasterService();
   }
@@ -80,14 +72,14 @@ public class TestAMRMRPCNodeUpdates {
   
   private void syncNodeHeartbeat(MockNM nm, boolean health) throws Exception {
     nm.nodeHeartbeat(health);
-    dispatcher.await();
+    rm.drainEvents();
   }
   
   private void syncNodeLost(MockNM nm) throws Exception {
     rm.sendNodeStarted(nm);
     rm.waitForState(nm.getNodeId(), NodeState.RUNNING);
     rm.sendNodeLost(nm);
-    dispatcher.await();
+    rm.drainEvents();
   }
 
   private AllocateResponse allocate(final ApplicationAttemptId attemptId,
@@ -113,7 +105,7 @@ public class TestAMRMRPCNodeUpdates {
     MockNM nm2 = rm.registerNode("127.0.0.2:1234", 10000);
     MockNM nm3 = rm.registerNode("127.0.0.3:1234", 10000);
     MockNM nm4 = rm.registerNode("127.0.0.4:1234", 10000);
-    dispatcher.await();
+    rm.drainEvents();
 
     RMApp app1 = rm.submitApp(2000);
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/resourcetracker/TestNMReconnect.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/resourcetracker/TestNMReconnect.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/resourcetracker/TestNMReconnect.java
index e7c7e51..6a7325c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/resourcetracker/TestNMReconnect.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/resourcetracker/TestNMReconnect.java
@@ -28,7 +28,6 @@ import org.apache.hadoop.yarn.conf.ConfigurationProvider;
 import org.apache.hadoop.yarn.conf.ConfigurationProviderFactory;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.event.InlineDispatcher;
 import org.apache.hadoop.yarn.factories.RecordFactory;
@@ -228,21 +227,16 @@ public class TestNMReconnect extends ParameterizedSchedulerTestBase {
     // The node(127.0.0.1:1234) reconnected with RM. When it registered with
     // RM, RM set its lastNodeHeartbeatResponse's id to 0 asynchronously. But
     // the node's heartbeat come before RM succeeded setting the id to 0.
-    final DrainDispatcher dispatcher = new DrainDispatcher();
-    MockRM rm = new MockRM(){
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-    };
+    MockRM rm = new MockRM();
     rm.start();
+
     MockNM nm1 =
         new MockNM("127.0.0.1:1234", 15120, rm.getResourceTrackerService());
     nm1.registerNode();
     int i = 0;
     while(i < 3) {
       nm1.nodeHeartbeat(true);
-      dispatcher.await();
+      rm.drainEvents();
       i++;
     }
 
@@ -251,7 +245,7 @@ public class TestNMReconnect extends ParameterizedSchedulerTestBase {
     nm2.registerNode();
     RMNode rmNode = rm.getRMContext().getRMNodes().get(nm2.getNodeId());
     nm2.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     Assert.assertEquals("Node is Not in Running state.", NodeState.RUNNING,
         rmNode.getState());
     rm.stop();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/TestRMContainerImpl.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/rmcontainer/TestRMContainerImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/TestRMContainerImpl.java
index 893f802..db31448 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/TestRMContainerImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/TestRMContainerImpl.java
@@ -46,7 +46,6 @@ 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.Dispatcher;
 import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.event.EventHandler;
 import org.apache.hadoop.yarn.server.resourcemanager.MockAM;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestApplicationPriority.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/TestApplicationPriority.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/TestApplicationPriority.java
index ff52efd..fd17bd9 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/TestApplicationPriority.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/TestApplicationPriority.java
@@ -36,8 +36,6 @@ 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.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnException;
 import org.apache.hadoop.yarn.server.resourcemanager.MockAM;
 import org.apache.hadoop.yarn.server.resourcemanager.MockNM;
@@ -612,24 +610,17 @@ public class TestApplicationPriority {
     conf.setInt(YarnConfiguration.RM_AM_MAX_ATTEMPTS,
         YarnConfiguration.DEFAULT_RM_AM_MAX_ATTEMPTS);
     conf.setInt(YarnConfiguration.MAX_CLUSTER_LEVEL_APPLICATION_PRIORITY, 10);
-    final DrainDispatcher dispatcher = new DrainDispatcher();
 
     MemoryRMStateStore memStore = new MemoryRMStateStore();
     memStore.init(conf);
 
-    MockRM rm1 = new MockRM(conf, memStore) {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-    };
+    MockRM rm1 = new MockRM(conf, memStore);
     rm1.start();
 
     MockNM nm1 =
         new MockNM("127.0.0.1:1234", 16384, rm1.getResourceTrackerService());
     nm1.registerNode();
-
-    dispatcher.await();
+    rm1.drainEvents();
 
     ResourceScheduler scheduler = rm1.getRMContext().getScheduler();
     LeafQueue defaultQueue =
@@ -648,7 +639,7 @@ public class TestApplicationPriority {
     MockAM am2 = MockRM.launchAM(app2, rm1, nm1);
     am2.registerAppAttempt();
 
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals(2, defaultQueue.getNumActiveApplications());
     Assert.assertEquals(0, defaultQueue.getNumPendingApplications());
 
@@ -657,7 +648,7 @@ public class TestApplicationPriority {
     Priority appPriority3 = Priority.newInstance(7);
     RMApp app3 = rm1.submitApp(memory, appPriority3);
 
-    dispatcher.await();
+    rm1.drainEvents();
     Assert.assertEquals(2, defaultQueue.getNumActiveApplications());
     Assert.assertEquals(1, defaultQueue.getNumPendingApplications());
 
@@ -676,14 +667,8 @@ public class TestApplicationPriority {
     Assert.assertEquals(app3.getCurrentAppAttempt().getAppAttemptId(),
         fcApp3.getApplicationAttemptId());
 
-    final DrainDispatcher dispatcher1 = new DrainDispatcher();
     // create new RM to represent restart and recover state
-    MockRM rm2 = new MockRM(conf, memStore) {
-      @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher1;
-      }
-    };
+    MockRM rm2 = new MockRM(conf, memStore);
 
     // start new RM
     rm2.start();
@@ -693,7 +678,7 @@ public class TestApplicationPriority {
     // Verify RM Apps after this restart
     Assert.assertEquals(3, rm2.getRMContext().getRMApps().size());
 
-    dispatcher1.await();
+    rm2.drainEvents();
     scheduler = rm2.getRMContext().getScheduler();
     defaultQueue =
         (LeafQueue) ((CapacityScheduler) scheduler).getQueue("default");
@@ -714,7 +699,7 @@ public class TestApplicationPriority {
 
     // NM resync to new RM
     nm1.registerNode();
-    dispatcher1.await();
+    rm2.drainEvents();
 
     // wait for activating applications
     count = 50;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/a0db5dd2/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestClientToAMTokens.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/security/TestClientToAMTokens.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestClientToAMTokens.java
index a451356..d4e7727 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestClientToAMTokens.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/security/TestClientToAMTokens.java
@@ -50,8 +50,6 @@ import org.apache.hadoop.yarn.api.protocolrecords.StartContainersResponse;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.ApplicationReport;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
-import org.apache.hadoop.yarn.event.Dispatcher;
-import org.apache.hadoop.yarn.event.DrainDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 import org.apache.hadoop.yarn.security.client.ClientToAMTokenIdentifier;
 import org.apache.hadoop.yarn.security.client.ClientToAMTokenSecretManager;
@@ -199,7 +197,6 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
     StartContainersResponse mockResponse = mock(StartContainersResponse.class);
     when(containerManager.startContainers((StartContainersRequest) any()))
       .thenReturn(mockResponse);
-    final DrainDispatcher dispatcher = new DrainDispatcher();
 
     MockRM rm = new MockRMWithCustomAMLauncher(conf, containerManager) {
       protected ClientRMService createClientRMService() {
@@ -209,11 +206,6 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
       };
 
       @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-
-      @Override
       protected void doSecureLogin() throws IOException {
       }
     };
@@ -225,11 +217,10 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
     // Set up a node.
     MockNM nm1 = rm.registerNode("localhost:1234", 3072);
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
     
-
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttempt = app.getCurrentAppAttempt().getAppAttemptId();
     final MockAM mockAM =
@@ -436,7 +427,6 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
     StartContainersResponse mockResponse = mock(StartContainersResponse.class);
     when(containerManager.startContainers((StartContainersRequest) any()))
       .thenReturn(mockResponse);
-    final DrainDispatcher dispatcher = new DrainDispatcher();
 
     MockRM rm = new MockRMWithCustomAMLauncher(conf, containerManager) {
       protected ClientRMService createClientRMService() {
@@ -446,11 +436,6 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
       };
 
       @Override
-      protected Dispatcher createDispatcher() {
-        return dispatcher;
-      }
-
-      @Override
       protected void doSecureLogin() throws IOException {
       }
     };
@@ -462,10 +447,10 @@ public class TestClientToAMTokens extends ParameterizedSchedulerTestBase {
     // Set up a node.
     MockNM nm1 = rm.registerNode("localhost:1234", 3072);
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     nm1.nodeHeartbeat(true);
-    dispatcher.await();
+    rm.drainEvents();
 
     ApplicationAttemptId appAttempt = app.getCurrentAppAttempt().getAppAttemptId();
     final MockAM mockAM =


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[42/50] [abbrv] hadoop git commit: YARN-6381. FSAppAttempt has several variables that should be final (Contributed by Ameet Zaveri via Daniel Templeton)

Posted by in...@apache.org.
YARN-6381. FSAppAttempt has several variables that should be final
(Contributed by Ameet Zaveri via Daniel Templeton)


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

Branch: refs/heads/HDFS-10467
Commit: 8bbd335710476efd1d49c955dbad5495a7d62e00
Parents: 546d533
Author: Daniel Templeton <te...@apache.org>
Authored: Wed Apr 5 16:06:00 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../resourcemanager/scheduler/fair/FSAppAttempt.java    | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/8bbd3357/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 ccfcffb..e0dfb73 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
@@ -74,11 +74,11 @@ public class FSAppAttempt extends SchedulerApplicationAttempt
   private static final DefaultResourceCalculator RESOURCE_CALCULATOR
       = new DefaultResourceCalculator();
 
-  private long startTime;
-  private Priority appPriority;
-  private ResourceWeights resourceWeights;
+  private final long startTime;
+  private final Priority appPriority;
+  private final ResourceWeights resourceWeights;
   private Resource demand = Resources.createResource(0);
-  private FairScheduler scheduler;
+  private final FairScheduler scheduler;
   private FSQueue fsQueue;
   private Resource fairShare = Resources.createResource(0, 0);
 
@@ -96,9 +96,9 @@ public class FSAppAttempt extends SchedulerApplicationAttempt
 
   // Used to record node reservation by an app.
   // Key = RackName, Value = Set of Nodes reserved by app on rack
-  private Map<String, Set<String>> reservations = new HashMap<>();
+  private final Map<String, Set<String>> reservations = new HashMap<>();
 
-  private List<FSSchedulerNode> blacklistNodeIds = new ArrayList<>();
+  private final List<FSSchedulerNode> blacklistNodeIds = new ArrayList<>();
   /**
    * Delay scheduling: We often want to prioritize scheduling of node-local
    * containers over rack-local or off-switch containers. To achieve this


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[36/50] [abbrv] hadoop git commit: HDFS-11628. Clarify the behavior of HDFS Mover in documentation. Contributed by Xiaobing Zhou.

Posted by in...@apache.org.
HDFS-11628. Clarify the behavior of HDFS Mover in documentation. Contributed by Xiaobing Zhou.


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

Branch: refs/heads/HDFS-10467
Commit: 6b8607d03fe78993743fabc7ea920bf0935500c9
Parents: 26f5552
Author: Xiaobing Zhou <xi...@apache.org>
Authored: Wed Apr 5 15:33:08 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../hadoop-hdfs/src/site/markdown/ArchivalStorage.md               | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/6b8607d0/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ArchivalStorage.md
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ArchivalStorage.md b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ArchivalStorage.md
index 56a2ab8..91ad107 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ArchivalStorage.md
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/site/markdown/ArchivalStorage.md
@@ -98,7 +98,7 @@ The effective storage policy can be retrieved by the "[`storagepolicies -getStor
 Mover - A New Data Migration Tool
 ---------------------------------
 
-A new data migration tool is added for archiving data. The tool is similar to Balancer. It periodically scans the files in HDFS to check if the block placement satisfies the storage policy. For the blocks violating the storage policy, it moves the replicas to a different storage type in order to fulfill the storage policy requirement.
+A new data migration tool is added for archiving data. The tool is similar to Balancer. It periodically scans the files in HDFS to check if the block placement satisfies the storage policy. For the blocks violating the storage policy, it moves the replicas to a different storage type in order to fulfill the storage policy requirement. Note that it always tries to move block replicas within the same node whenever possible. If that is not possible (e.g. when a node doesn\u2019t have the target storage type) then it will copy the block replicas to another node over the network.
 
 * Command:
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[14/50] [abbrv] hadoop git commit: HADOOP-14267. Make DistCpOptions immutable. Contributed by Mingliang Liu

Posted by in...@apache.org.
http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
index af91347..8111b04 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
@@ -123,10 +123,10 @@ public class SimpleCopyListing extends CopyListing {
   }
 
   @Override
-  protected void validatePaths(DistCpOptions options)
+  protected void validatePaths(DistCpContext context)
       throws IOException, InvalidInputException {
 
-    Path targetPath = options.getTargetPath();
+    Path targetPath = context.getTargetPath();
     FileSystem targetFS = targetPath.getFileSystem(getConf());
     boolean targetExists = false;
     boolean targetIsFile = false;
@@ -142,12 +142,12 @@ public class SimpleCopyListing extends CopyListing {
 
     //If target is a file, then source has to be single file
     if (targetIsFile) {
-      if (options.getSourcePaths().size() > 1) {
+      if (context.getSourcePaths().size() > 1) {
         throw new InvalidInputException("Multiple source being copied to a file: " +
             targetPath);
       }
 
-      Path srcPath = options.getSourcePaths().get(0);
+      Path srcPath = context.getSourcePaths().get(0);
       FileSystem sourceFS = srcPath.getFileSystem(getConf());
       if (!sourceFS.isFile(srcPath)) {
         throw new InvalidInputException("Cannot copy " + srcPath +
@@ -155,12 +155,12 @@ public class SimpleCopyListing extends CopyListing {
       }
     }
 
-    if (options.shouldAtomicCommit() && targetExists) {
+    if (context.shouldAtomicCommit() && targetExists) {
       throw new InvalidInputException("Target path for atomic-commit already exists: " +
         targetPath + ". Cannot atomic-commit to pre-existing target-path.");
     }
 
-    for (Path path: options.getSourcePaths()) {
+    for (Path path: context.getSourcePaths()) {
       FileSystem fs = path.getFileSystem(getConf());
       if (!fs.exists(path)) {
         throw new InvalidInputException(path + " doesn't exist");
@@ -184,7 +184,7 @@ public class SimpleCopyListing extends CopyListing {
     }
 
     if (targetIsReservedRaw) {
-      options.preserveRawXattrs();
+      context.setPreserveRawXattrs(true);
       getConf().setBoolean(DistCpConstants.CONF_LABEL_PRESERVE_RAWXATTRS, true);
     }
 
@@ -194,18 +194,19 @@ public class SimpleCopyListing extends CopyListing {
      */
     Credentials credentials = getCredentials();
     if (credentials != null) {
-      Path[] inputPaths = options.getSourcePaths().toArray(new Path[1]);
+      Path[] inputPaths = context.getSourcePaths()
+          .toArray(new Path[1]);
       TokenCache.obtainTokensForNamenodes(credentials, inputPaths, getConf());
     }
   }
 
   @Override
   protected void doBuildListing(Path pathToListingFile,
-                                DistCpOptions options) throws IOException {
-    if(options.shouldUseSnapshotDiff()) {
-      doBuildListingWithSnapshotDiff(getWriter(pathToListingFile), options);
-    }else {
-      doBuildListing(getWriter(pathToListingFile), options);
+                                DistCpContext context) throws IOException {
+    if (context.shouldUseSnapshotDiff()) {
+      doBuildListingWithSnapshotDiff(getWriter(pathToListingFile), context);
+    } else {
+      doBuildListing(getWriter(pathToListingFile), context);
     }
   }
 
@@ -232,22 +233,22 @@ public class SimpleCopyListing extends CopyListing {
    * @throws IOException
    */
   private void addToFileListing(SequenceFile.Writer fileListWriter,
-      Path sourceRoot, Path path, DistCpOptions options) throws IOException {
+      Path sourceRoot, Path path, DistCpContext context) throws IOException {
     sourceRoot = getPathWithSchemeAndAuthority(sourceRoot);
     path = getPathWithSchemeAndAuthority(path);
     path = makeQualified(path);
 
     FileSystem sourceFS = sourceRoot.getFileSystem(getConf());
     FileStatus fileStatus = sourceFS.getFileStatus(path);
-    final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
-    final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
-    final boolean preserveRawXAttrs = options.shouldPreserveRawXattrs();
+    final boolean preserveAcls = context.shouldPreserve(FileAttribute.ACL);
+    final boolean preserveXAttrs = context.shouldPreserve(FileAttribute.XATTR);
+    final boolean preserveRawXAttrs = context.shouldPreserveRawXattrs();
     LinkedList<CopyListingFileStatus> fileCopyListingStatus =
         DistCpUtils.toCopyListingFileStatus(sourceFS, fileStatus,
             preserveAcls, preserveXAttrs, preserveRawXAttrs,
-            options.getBlocksPerChunk());
+            context.getBlocksPerChunk());
     writeToFileListingRoot(fileListWriter, fileCopyListingStatus,
-        sourceRoot, options);
+        sourceRoot, context);
   }
 
   /**
@@ -258,14 +259,16 @@ public class SimpleCopyListing extends CopyListing {
    * {@link org.apache.hadoop.tools.DistCpSync#sync}. An item can be
    * created/modified and renamed, in which case, the target path is put
    * into the list.
+   * @param fileListWriter the list for holding processed results
+   * @param context The DistCp context with associated input options
    * @throws IOException
    */
   @VisibleForTesting
   protected void doBuildListingWithSnapshotDiff(
-      SequenceFile.Writer fileListWriter, DistCpOptions options)
+      SequenceFile.Writer fileListWriter, DistCpContext context)
       throws IOException {
     ArrayList<DiffInfo> diffList = distCpSync.prepareDiffListForCopyListing();
-    Path sourceRoot = options.getSourcePaths().get(0);
+    Path sourceRoot = context.getSourcePaths().get(0);
     FileSystem sourceFS = sourceRoot.getFileSystem(getConf());
 
     try {
@@ -273,13 +276,13 @@ public class SimpleCopyListing extends CopyListing {
       for (DiffInfo diff : diffList) {
         // add snapshot paths prefix
         diff.setTarget(
-            new Path(options.getSourcePaths().get(0), diff.getTarget()));
+            new Path(context.getSourcePaths().get(0), diff.getTarget()));
         if (diff.getType() == SnapshotDiffReport.DiffType.MODIFY) {
           addToFileListing(fileListWriter,
-              sourceRoot, diff.getTarget(), options);
+              sourceRoot, diff.getTarget(), context);
         } else if (diff.getType() == SnapshotDiffReport.DiffType.CREATE) {
           addToFileListing(fileListWriter,
-              sourceRoot, diff.getTarget(), options);
+              sourceRoot, diff.getTarget(), context);
 
           FileStatus sourceStatus = sourceFS.getFileStatus(diff.getTarget());
           if (sourceStatus.isDirectory()) {
@@ -290,13 +293,13 @@ public class SimpleCopyListing extends CopyListing {
 
             HashSet<String> excludeList =
                 distCpSync.getTraverseExcludeList(diff.getSource(),
-                    options.getSourcePaths().get(0));
+                    context.getSourcePaths().get(0));
 
             ArrayList<FileStatus> sourceDirs = new ArrayList<>();
             sourceDirs.add(sourceStatus);
 
             traverseDirectory(fileListWriter, sourceFS, sourceDirs,
-                sourceRoot, options, excludeList, fileStatuses);
+                sourceRoot, context, excludeList, fileStatuses);
           }
         }
       }
@@ -325,27 +328,30 @@ public class SimpleCopyListing extends CopyListing {
    * See computeSourceRootPath method for how the root path of the source is
    *     computed.
    * @param fileListWriter
-   * @param options
+   * @param context The distcp context with associated input options
    * @throws IOException
    */
   @VisibleForTesting
   protected void doBuildListing(SequenceFile.Writer fileListWriter,
-      DistCpOptions options) throws IOException {
-    if (options.getNumListstatusThreads() > 0) {
-      numListstatusThreads = options.getNumListstatusThreads();
+      DistCpContext context) throws IOException {
+    if (context.getNumListstatusThreads() > 0) {
+      numListstatusThreads = context.getNumListstatusThreads();
     }
 
     try {
       List<FileStatusInfo> statusList = Lists.newArrayList();
-      for (Path path: options.getSourcePaths()) {
+      for (Path path: context.getSourcePaths()) {
         FileSystem sourceFS = path.getFileSystem(getConf());
-        final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
-        final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
-        final boolean preserveRawXAttrs = options.shouldPreserveRawXattrs();
+        final boolean preserveAcls =
+            context.shouldPreserve(FileAttribute.ACL);
+        final boolean preserveXAttrs =
+            context.shouldPreserve(FileAttribute.XATTR);
+        final boolean preserveRawXAttrs =
+            context.shouldPreserveRawXattrs();
         path = makeQualified(path);
 
         FileStatus rootStatus = sourceFS.getFileStatus(path);
-        Path sourcePathRoot = computeSourceRootPath(rootStatus, options);
+        Path sourcePathRoot = computeSourceRootPath(rootStatus, context);
 
         FileStatus[] sourceFiles = sourceFS.listStatus(path);
         boolean explore = (sourceFiles != null && sourceFiles.length > 0);
@@ -353,9 +359,9 @@ public class SimpleCopyListing extends CopyListing {
           LinkedList<CopyListingFileStatus> rootCopyListingStatus =
               DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
                   preserveAcls, preserveXAttrs, preserveRawXAttrs,
-                  options.getBlocksPerChunk());
+                  context.getBlocksPerChunk());
           writeToFileListingRoot(fileListWriter, rootCopyListingStatus,
-              sourcePathRoot, options);
+              sourcePathRoot, context);
         }
         if (explore) {
           ArrayList<FileStatus> sourceDirs = new ArrayList<FileStatus>();
@@ -368,7 +374,7 @@ public class SimpleCopyListing extends CopyListing {
                     preserveAcls && sourceStatus.isDirectory(),
                     preserveXAttrs && sourceStatus.isDirectory(),
                     preserveRawXAttrs && sourceStatus.isDirectory(),
-                    options.getBlocksPerChunk());
+                    context.getBlocksPerChunk());
             for (CopyListingFileStatus fs : sourceCopyListingStatus) {
               if (randomizeFileListing) {
                 addToFileListing(statusList,
@@ -385,7 +391,7 @@ public class SimpleCopyListing extends CopyListing {
             }
           }
           traverseDirectory(fileListWriter, sourceFS, sourceDirs,
-              sourcePathRoot, options, null, statusList);
+              sourcePathRoot, context, null, statusList);
         }
       }
       if (randomizeFileListing) {
@@ -447,13 +453,13 @@ public class SimpleCopyListing extends CopyListing {
   }
 
   private Path computeSourceRootPath(FileStatus sourceStatus,
-                                     DistCpOptions options) throws IOException {
+      DistCpContext context) throws IOException {
 
-    Path target = options.getTargetPath();
+    Path target = context.getTargetPath();
     FileSystem targetFS = target.getFileSystem(getConf());
-    final boolean targetPathExists = options.getTargetPathExists();
+    final boolean targetPathExists = context.isTargetPathExists();
 
-    boolean solitaryFile = options.getSourcePaths().size() == 1
+    boolean solitaryFile = context.getSourcePaths().size() == 1
                                                 && !sourceStatus.isDirectory();
 
     if (solitaryFile) {
@@ -463,8 +469,11 @@ public class SimpleCopyListing extends CopyListing {
         return sourceStatus.getPath().getParent();
       }
     } else {
-      boolean specialHandling = (options.getSourcePaths().size() == 1 && !targetPathExists) ||
-          options.shouldSyncFolder() || options.shouldOverwrite();
+      boolean specialHandling =
+          (context.getSourcePaths().size() == 1 &&
+              !targetPathExists) ||
+              context.shouldSyncFolder() ||
+              context.shouldOverwrite();
 
       if ((specialHandling && sourceStatus.isDirectory()) ||
           sourceStatus.getPath().isRoot()) {
@@ -610,13 +619,13 @@ public class SimpleCopyListing extends CopyListing {
                                  FileSystem sourceFS,
                                  ArrayList<FileStatus> sourceDirs,
                                  Path sourcePathRoot,
-                                 DistCpOptions options,
+                                 DistCpContext context,
                                  HashSet<String> excludeList,
                                  List<FileStatusInfo> fileStatuses)
                                  throws IOException {
-    final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
-    final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
-    final boolean preserveRawXattrs = options.shouldPreserveRawXattrs();
+    final boolean preserveAcls = context.shouldPreserve(FileAttribute.ACL);
+    final boolean preserveXAttrs = context.shouldPreserve(FileAttribute.XATTR);
+    final boolean preserveRawXattrs = context.shouldPreserveRawXattrs();
 
     assert numListstatusThreads > 0;
     if (LOG.isDebugEnabled()) {
@@ -649,7 +658,7 @@ public class SimpleCopyListing extends CopyListing {
                 preserveAcls && child.isDirectory(),
                 preserveXAttrs && child.isDirectory(),
                 preserveRawXattrs && child.isDirectory(),
-                options.getBlocksPerChunk());
+                context.getBlocksPerChunk());
 
             for (CopyListingFileStatus fs : childCopyListingStatus) {
               if (randomizeFileListing) {
@@ -681,9 +690,9 @@ public class SimpleCopyListing extends CopyListing {
 
   private void writeToFileListingRoot(SequenceFile.Writer fileListWriter,
       LinkedList<CopyListingFileStatus> fileStatus, Path sourcePathRoot,
-      DistCpOptions options) throws IOException {
-    boolean syncOrOverwrite = options.shouldSyncFolder() ||
-        options.shouldOverwrite();
+      DistCpContext context) throws IOException {
+    boolean syncOrOverwrite = context.shouldSyncFolder() ||
+        context.shouldOverwrite();
     for (CopyListingFileStatus fs : fileStatus) {
       if (fs.getPath().equals(sourcePathRoot) &&
           fs.isDirectory() && syncOrOverwrite) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
index 6ddaab9..81c2be7 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
@@ -36,6 +36,7 @@ import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.CopyListingFileStatus;
 import org.apache.hadoop.tools.DistCpConstants;
 import org.apache.hadoop.tools.DistCpOptionSwitch;
+import org.apache.hadoop.tools.DistCpContext;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.GlobbedCopyListing;
@@ -354,16 +355,18 @@ public class CopyCommitter extends FileOutputCommitter {
     Path resultNonePath = Path.getPathWithoutSchemeAndAuthority(targetFinalPath)
         .toString().startsWith(DistCpConstants.HDFS_RESERVED_RAW_DIRECTORY_NAME)
         ? DistCpConstants.RAW_NONE_PATH : DistCpConstants.NONE_PATH;
-    DistCpOptions options = new DistCpOptions(targets, resultNonePath);
     //
     // Set up options to be the same from the CopyListing.buildListing's perspective,
     // so to collect similar listings as when doing the copy
     //
-    options.setOverwrite(overwrite);
-    options.setSyncFolder(syncFolder);
-    options.setTargetPathExists(targetPathExists);
-    
-    target.buildListing(targetListing, options);
+    DistCpOptions options = new DistCpOptions.Builder(targets, resultNonePath)
+        .withOverwrite(overwrite)
+        .withSyncFolder(syncFolder)
+        .build();
+    DistCpContext distCpContext = new DistCpContext(options);
+    distCpContext.setTargetPathExists(targetPathExists);
+
+    target.buildListing(targetListing, distCpContext);
     Path sortedTargetListing = DistCpUtils.sortListing(clusterFS, conf, targetListing);
     long totalLen = clusterFS.getFileStatus(sortedTargetListing).getLen();
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
index e315b84..dbe750a 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
@@ -39,7 +39,7 @@ import org.apache.hadoop.mapreduce.InputFormat;
 import org.apache.hadoop.tools.CopyListing.AclsNotSupportedException;
 import org.apache.hadoop.tools.CopyListing.XAttrsNotSupportedException;
 import org.apache.hadoop.tools.CopyListingFileStatus;
-import org.apache.hadoop.tools.DistCpOptions;
+import org.apache.hadoop.tools.DistCpContext;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.mapred.UniformSizeInputFormat;
 import org.apache.hadoop.util.StringUtils;
@@ -116,13 +116,13 @@ public class DistCpUtils {
    * a particular strategy from distcp-default.xml
    *
    * @param conf - Configuration object
-   * @param options - Handle to input options
+   * @param context - Distcp context with associated input options
    * @return Class implementing the strategy specified in options.
    */
   public static Class<? extends InputFormat> getStrategy(Configuration conf,
-      DistCpOptions options) {
+      DistCpContext context) {
     String confLabel = "distcp."
-        + StringUtils.toLowerCase(options.getCopyStrategy())
+        + StringUtils.toLowerCase(context.getCopyStrategy())
         + ".strategy" + ".impl";
     return conf.getClass(confLabel, UniformSizeInputFormat.class, InputFormat.class);
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestCopyListing.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestCopyListing.java
index ea63e23..97a6f62 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestCopyListing.java
@@ -103,20 +103,19 @@ public class TestCopyListing extends SimpleCopyListing {
       List<Path> srcPaths = new ArrayList<Path>();
       srcPaths.add(new Path("/tmp/in/1"));
       srcPaths.add(new Path("/tmp/in/2"));
-      Path target = new Path("/tmp/out/1");
+      final Path target = new Path("/tmp/out/1");
       TestDistCpUtils.createFile(fs, "/tmp/in/1");
       TestDistCpUtils.createFile(fs, "/tmp/in/2");
       fs.mkdirs(target);
-      DistCpOptions options = new DistCpOptions(srcPaths, target);
-      validatePaths(options);
+      final DistCpOptions options = new DistCpOptions.Builder(srcPaths, target)
+          .build();
+      validatePaths(new DistCpContext(options));
       TestDistCpUtils.delete(fs, "/tmp");
       //No errors
 
-      target = new Path("/tmp/out/1");
       fs.create(target).close();
-      options = new DistCpOptions(srcPaths, target);
       try {
-        validatePaths(options);
+        validatePaths(new DistCpContext(options));
         Assert.fail("Invalid inputs accepted");
       } catch (InvalidInputException ignore) { }
       TestDistCpUtils.delete(fs, "/tmp");
@@ -124,11 +123,9 @@ public class TestCopyListing extends SimpleCopyListing {
       srcPaths.clear();
       srcPaths.add(new Path("/tmp/in/1"));
       fs.mkdirs(new Path("/tmp/in/1"));
-      target = new Path("/tmp/out/1");
       fs.create(target).close();
-      options = new DistCpOptions(srcPaths, target);
       try {
-        validatePaths(options);
+        validatePaths(new DistCpContext(options));
         Assert.fail("Invalid inputs accepted");
       } catch (InvalidInputException ignore) { }
       TestDistCpUtils.delete(fs, "/tmp");
@@ -151,10 +148,13 @@ public class TestCopyListing extends SimpleCopyListing {
       TestDistCpUtils.createFile(fs, "/tmp/in/src2/1.txt");
       Path target = new Path("/tmp/out");
       Path listingFile = new Path("/tmp/list");
-      DistCpOptions options = new DistCpOptions(srcPaths, target);
-      CopyListing listing = CopyListing.getCopyListing(getConf(), CREDENTIALS, options);
+      final DistCpOptions options = new DistCpOptions.Builder(srcPaths, target)
+          .build();
+      final DistCpContext context = new DistCpContext(options);
+      CopyListing listing = CopyListing.getCopyListing(getConf(), CREDENTIALS,
+          context);
       try {
-        listing.buildListing(listingFile, options);
+        listing.buildListing(listingFile, context);
         Assert.fail("Duplicates not detected");
       } catch (DuplicateFileException ignore) {
       }
@@ -196,11 +196,12 @@ public class TestCopyListing extends SimpleCopyListing {
 
       Path listingFile = new Path("/tmp/file");
 
-      DistCpOptions options = new DistCpOptions(srcPaths, target);
-      options.setSyncFolder(true);
+      final DistCpOptions options = new DistCpOptions.Builder(srcPaths, target)
+          .withSyncFolder(true)
+          .build();
       CopyListing listing = new SimpleCopyListing(getConf(), CREDENTIALS);
       try {
-        listing.buildListing(listingFile, options);
+        listing.buildListing(listingFile, new DistCpContext(options));
         Assert.fail("Duplicates not detected");
       } catch (DuplicateFileException ignore) {
       }
@@ -209,7 +210,7 @@ public class TestCopyListing extends SimpleCopyListing {
       TestDistCpUtils.delete(fs, "/tmp");
 
       try {
-        listing.buildListing(listingFile, options);
+        listing.buildListing(listingFile, new DistCpContext(options));
         Assert.fail("Invalid input not detected");
       } catch (InvalidInputException ignore) {
       }
@@ -244,14 +245,14 @@ public class TestCopyListing extends SimpleCopyListing {
       }
 
       Path listingFile = new Path("/tmp/file");
-      DistCpOptions options = new DistCpOptions(srcPaths, target);
-      options.setSyncFolder(true);
+      final DistCpOptions options = new DistCpOptions.Builder(srcPaths, target)
+          .withSyncFolder(true).build();
 
       // Check without randomizing files
       getConf().setBoolean(
           DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES, false);
       SimpleCopyListing listing = new SimpleCopyListing(getConf(), CREDENTIALS);
-      listing.buildListing(listingFile, options);
+      listing.buildListing(listingFile, new DistCpContext(options));
 
       Assert.assertEquals(listing.getNumberOfPaths(), pathCount);
       validateFinalListing(listingFile, srcFiles);
@@ -265,7 +266,7 @@ public class TestCopyListing extends SimpleCopyListing {
       // Set the seed for randomness, so that it can be verified later
       long seed = System.nanoTime();
       listing.setSeedForRandomListing(seed);
-      listing.buildListing(listingFile, options);
+      listing.buildListing(listingFile, new DistCpContext(options));
       Assert.assertEquals(listing.getNumberOfPaths(), pathCount);
 
       // validate randomness
@@ -322,11 +323,12 @@ public class TestCopyListing extends SimpleCopyListing {
       List<Path> srcPaths = new ArrayList<Path>();
       srcPaths.add(sourceFile);
 
-      DistCpOptions options = new DistCpOptions(srcPaths, targetFile);
+      DistCpOptions options = new DistCpOptions.Builder(srcPaths, targetFile)
+          .build();
       CopyListing listing = new SimpleCopyListing(getConf(), CREDENTIALS);
 
       final Path listFile = new Path(testRoot, "/tmp/fileList.seq");
-      listing.buildListing(listFile, options);
+      listing.buildListing(listFile, new DistCpContext(options));
 
       reader = new SequenceFile.Reader(getConf(), SequenceFile.Reader.file(listFile));
 
@@ -359,10 +361,11 @@ public class TestCopyListing extends SimpleCopyListing {
     doThrow(expectedEx).when(writer).close();
     
     SimpleCopyListing listing = new SimpleCopyListing(getConf(), CREDENTIALS);
-    DistCpOptions options = new DistCpOptions(srcs, new Path(outFile.toURI()));
+    final DistCpOptions options = new DistCpOptions.Builder(srcs,
+        new Path(outFile.toURI())).build();
     Exception actualEx = null;
     try {
-      listing.doBuildListing(writer, options);
+      listing.doBuildListing(writer, new DistCpContext(options));
     } catch (Exception e) {
       actualEx = e;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpOptions.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpOptions.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpOptions.java
new file mode 100644
index 0000000..3525194
--- /dev/null
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpOptions.java
@@ -0,0 +1,500 @@
+/**
+ * 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.tools;
+
+import java.util.Collections;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
+
+import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
+import static org.apache.hadoop.tools.DistCpOptions.MAX_NUM_LISTSTATUS_THREADS;
+import static org.junit.Assert.fail;
+
+/**
+ * This is to test constructing {@link DistCpOptions} manually with setters.
+ *
+ * The test cases in this class is very similar to the parser test, see
+ * {@link TestOptionsParser}.
+ */
+public class TestDistCpOptions {
+
+  private static final float DELTA = 0.001f;
+
+  @Test
+  public void testSetIgnoreFailure() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldIgnoreFailures());
+
+    builder.withIgnoreFailures(true);
+    Assert.assertTrue(builder.build().shouldIgnoreFailures());
+  }
+
+  @Test
+  public void testSetOverwrite() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldOverwrite());
+
+    builder.withOverwrite(true);
+    Assert.assertTrue(builder.build().shouldOverwrite());
+
+    try {
+      builder.withSyncFolder(true).build();
+      Assert.fail("Update and overwrite aren't allowed together");
+    } catch (IllegalArgumentException ignore) {
+    }
+  }
+
+  @Test
+  public void testLogPath() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertNull(builder.build().getLogPath());
+
+    final Path logPath = new Path("hdfs://localhost:8020/logs");
+    builder.withLogPath(logPath);
+    Assert.assertEquals(logPath, builder.build().getLogPath());
+  }
+
+  @Test
+  public void testSetBlokcing() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertTrue(builder.build().shouldBlock());
+
+    builder.withBlocking(false);
+    Assert.assertFalse(builder.build().shouldBlock());
+  }
+
+  @Test
+  public void testSetBandwidth() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertEquals(0, builder.build().getMapBandwidth(), DELTA);
+
+    builder.withMapBandwidth(11);
+    Assert.assertEquals(11, builder.build().getMapBandwidth(), DELTA);
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testSetNonPositiveBandwidth() {
+    new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"))
+        .withMapBandwidth(-11)
+        .build();
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testSetZeroBandwidth() {
+    new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"))
+        .withMapBandwidth(0)
+        .build();
+  }
+
+  @Test
+  public void testSetSkipCRC() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldSkipCRC());
+
+    final DistCpOptions options = builder.withSyncFolder(true).withCRC(true)
+        .build();
+    Assert.assertTrue(options.shouldSyncFolder());
+    Assert.assertTrue(options.shouldSkipCRC());
+  }
+
+  @Test
+  public void testSetAtomicCommit() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldAtomicCommit());
+
+    builder.withAtomicCommit(true);
+    Assert.assertTrue(builder.build().shouldAtomicCommit());
+
+    try {
+      builder.withSyncFolder(true).build();
+      Assert.fail("Atomic and sync folders were mutually exclusive");
+    } catch (IllegalArgumentException ignore) {
+    }
+  }
+
+  @Test
+  public void testSetWorkPath() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertNull(builder.build().getAtomicWorkPath());
+
+    builder.withAtomicCommit(true);
+    Assert.assertNull(builder.build().getAtomicWorkPath());
+
+    final Path workPath = new Path("hdfs://localhost:8020/work");
+    builder.withAtomicWorkPath(workPath);
+    Assert.assertEquals(workPath, builder.build().getAtomicWorkPath());
+  }
+
+  @Test
+  public void testSetSyncFolders() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldSyncFolder());
+
+    builder.withSyncFolder(true);
+    Assert.assertTrue(builder.build().shouldSyncFolder());
+  }
+
+  @Test
+  public void testSetDeleteMissing() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertFalse(builder.build().shouldDeleteMissing());
+
+    DistCpOptions options = builder.withSyncFolder(true)
+        .withDeleteMissing(true)
+        .build();
+    Assert.assertTrue(options.shouldSyncFolder());
+    Assert.assertTrue(options.shouldDeleteMissing());
+
+    options = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"))
+        .withOverwrite(true)
+        .withDeleteMissing(true)
+        .build();
+    Assert.assertTrue(options.shouldOverwrite());
+    Assert.assertTrue(options.shouldDeleteMissing());
+
+    try {
+      new DistCpOptions.Builder(
+          Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+          new Path("hdfs://localhost:8020/target/"))
+          .withDeleteMissing(true)
+          .build();
+      fail("Delete missing should fail without update or overwrite options");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains("Delete missing is applicable only with update " +
+          "or overwrite options", e);
+    }
+    try {
+      new DistCpOptions.Builder(
+          new Path("hdfs://localhost:8020/source/first"),
+          new Path("hdfs://localhost:8020/target/"))
+          .withSyncFolder(true)
+          .withDeleteMissing(true)
+          .withUseDiff("s1", "s2")
+          .build();
+      fail("Should have failed as -delete and -diff are mutually exclusive.");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive.", e);
+    }
+  }
+
+  @Test
+  public void testSetMaps() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertEquals(DistCpConstants.DEFAULT_MAPS,
+        builder.build().getMaxMaps());
+
+    builder.maxMaps(1);
+    Assert.assertEquals(1, builder.build().getMaxMaps());
+
+    builder.maxMaps(0);
+    Assert.assertEquals(1, builder.build().getMaxMaps());
+  }
+
+  @Test
+  public void testSetNumListtatusThreads() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"));
+    // If command line argument isn't set, we expect .getNumListstatusThreads
+    // option to be zero (so that we know when to override conf properties).
+    Assert.assertEquals(0, builder.build().getNumListstatusThreads());
+
+    builder.withNumListstatusThreads(12);
+    Assert.assertEquals(12, builder.build().getNumListstatusThreads());
+
+    builder.withNumListstatusThreads(0);
+    Assert.assertEquals(0, builder.build().getNumListstatusThreads());
+
+    // Ignore large number of threads.
+    builder.withNumListstatusThreads(MAX_NUM_LISTSTATUS_THREADS * 2);
+    Assert.assertEquals(MAX_NUM_LISTSTATUS_THREADS,
+        builder.build().getNumListstatusThreads());
+  }
+
+  @Test
+  public void testSourceListing() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertEquals(new Path("hdfs://localhost:8020/source/first"),
+        builder.build().getSourceFileListing());
+  }
+
+  @Test(expected = IllegalArgumentException.class)
+  public void testMissingTarget() {
+    new DistCpOptions.Builder(new Path("hdfs://localhost:8020/source/first"),
+        null);
+  }
+
+  @Test
+  public void testToString() {
+    DistCpOptions option = new DistCpOptions.Builder(new Path("abc"),
+        new Path("xyz")).build();
+    String val = "DistCpOptions{atomicCommit=false, syncFolder=false, " +
+        "deleteMissing=false, ignoreFailures=false, overwrite=false, " +
+        "append=false, useDiff=false, useRdiff=false, " +
+        "fromSnapshot=null, toSnapshot=null, " +
+        "skipCRC=false, blocking=true, numListstatusThreads=0, maxMaps=20, " +
+        "mapBandwidth=0.0, copyStrategy='uniformsize', preserveStatus=[], " +
+        "atomicWorkPath=null, logPath=null, sourceFileListing=abc, " +
+        "sourcePaths=null, targetPath=xyz, filtersFile='null'," +
+        " blocksPerChunk=0}";
+    String optionString = option.toString();
+    Assert.assertEquals(val, optionString);
+    Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),
+        DistCpOptionSwitch.ATOMIC_COMMIT.name());
+  }
+
+  @Test
+  public void testCopyStrategy() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertEquals(DistCpConstants.UNIFORMSIZE,
+        builder.build().getCopyStrategy());
+    builder.withCopyStrategy("dynamic");
+    Assert.assertEquals("dynamic", builder.build().getCopyStrategy());
+  }
+
+  @Test
+  public void testTargetPath() {
+    final DistCpOptions options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/")).build();
+    Assert.assertEquals(new Path("hdfs://localhost:8020/target/"),
+        options.getTargetPath());
+  }
+
+  @Test
+  public void testPreserve() {
+    DistCpOptions options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"))
+        .build();
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.BLOCKSIZE));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.REPLICATION));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.PERMISSION));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.USER));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.GROUP));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.CHECKSUMTYPE));
+
+    options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"))
+        .preserve(FileAttribute.ACL)
+        .build();
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.BLOCKSIZE));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.REPLICATION));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.PERMISSION));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.USER));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.GROUP));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.CHECKSUMTYPE));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.ACL));
+
+    options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"))
+        .preserve(FileAttribute.BLOCKSIZE)
+        .preserve(FileAttribute.REPLICATION)
+        .preserve(FileAttribute.PERMISSION)
+        .preserve(FileAttribute.USER)
+        .preserve(FileAttribute.GROUP)
+        .preserve(FileAttribute.CHECKSUMTYPE)
+        .build();
+
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.BLOCKSIZE));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.REPLICATION));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.PERMISSION));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.USER));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.GROUP));
+    Assert.assertTrue(options.shouldPreserve(FileAttribute.CHECKSUMTYPE));
+    Assert.assertFalse(options.shouldPreserve(FileAttribute.XATTR));
+  }
+
+  @Test
+  public void testAppendOption() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+        new Path("hdfs://localhost:8020/target/"))
+        .withSyncFolder(true)
+        .withAppend(true);
+    Assert.assertTrue(builder.build().shouldAppend());
+
+    try {
+      // make sure -append is only valid when -update is specified
+      new DistCpOptions.Builder(
+          Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+          new Path("hdfs://localhost:8020/target/"))
+          .withAppend(true)
+          .build();
+      fail("Append should fail if update option is not specified");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "Append is valid only with update options", e);
+    }
+
+    try {
+      // make sure -append is invalid when skipCrc is specified
+      new DistCpOptions.Builder(
+          Collections.singletonList(new Path("hdfs://localhost:8020/source")),
+          new Path("hdfs://localhost:8020/target/"))
+          .withSyncFolder(true)
+          .withAppend(true)
+          .withCRC(true)
+          .build();
+      fail("Append should fail if skipCrc option is specified");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "Append is disallowed when skipping CRC", e);
+    }
+  }
+
+  @Test
+  public void testDiffOption() {
+    DistCpOptions options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"))
+        .withSyncFolder(true)
+        .withUseDiff("s1", "s2")
+        .build();
+    Assert.assertTrue(options.shouldUseDiff());
+    Assert.assertEquals("s1", options.getFromSnapshot());
+    Assert.assertEquals("s2", options.getToSnapshot());
+
+    options = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"))
+        .withSyncFolder(true)
+        .withUseDiff("s1", ".")
+        .build();
+    Assert.assertTrue(options.shouldUseDiff());
+    Assert.assertEquals("s1", options.getFromSnapshot());
+    Assert.assertEquals(".", options.getToSnapshot());
+
+    // make sure -diff is only valid when -update is specified
+    try {
+      new DistCpOptions.Builder(new Path("hdfs://localhost:8020/source/first"),
+          new Path("hdfs://localhost:8020/target/"))
+          .withUseDiff("s1", "s2")
+          .build();
+      fail("-diff should fail if -update option is not specified");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "-diff/-rdiff is valid only with -update option", e);
+    }
+
+    try {
+      new DistCpOptions.Builder(
+          new Path("hdfs://localhost:8020/source/first"),
+          new Path("hdfs://localhost:8020/target/"))
+          .withSyncFolder(true)
+          .withUseDiff("s1", "s2")
+          .withDeleteMissing(true)
+          .build();
+      fail("Should fail as -delete and -diff/-rdiff are mutually exclusive.");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive.", e);
+    }
+
+    try {
+      new DistCpOptions.Builder(new Path("hdfs://localhost:8020/source/first"),
+          new Path("hdfs://localhost:8020/target/"))
+          .withUseDiff("s1", "s2")
+          .withDeleteMissing(true)
+          .build();
+      fail("-diff should fail if -update option is not specified");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive.", e);
+    }
+
+    try {
+      new DistCpOptions.Builder(new Path("hdfs://localhost:8020/source/first"),
+          new Path("hdfs://localhost:8020/target/"))
+          .withDeleteMissing(true)
+          .withUseDiff("s1", "s2")
+          .build();
+      fail("Should have failed as -delete and -diff are mutually exclusive");
+    } catch (IllegalArgumentException e) {
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive", e);
+    }
+  }
+
+  @Test
+  public void testExclusionsOption() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/first"),
+        new Path("hdfs://localhost:8020/target/"));
+    Assert.assertNull(builder.build().getFiltersFile());
+
+    builder.withFiltersFile("/tmp/filters.txt");
+    Assert.assertEquals("/tmp/filters.txt", builder.build().getFiltersFile());
+  }
+
+  @Test
+  public void testSetOptionsForSplitLargeFile() {
+    final DistCpOptions.Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:8020/source/"),
+        new Path("hdfs://localhost:8020/target/"))
+        .withAppend(true)
+        .withSyncFolder(true);
+    Assert.assertFalse(builder.build().shouldPreserve(FileAttribute.BLOCKSIZE));
+    Assert.assertTrue(builder.build().shouldAppend());
+
+    builder.withBlocksPerChunk(5440);
+    Assert.assertTrue(builder.build().shouldPreserve(FileAttribute.BLOCKSIZE));
+    Assert.assertFalse(builder.build().shouldAppend());
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSync.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSync.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSync.java
index 94e8604..717b2f0 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSync.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSync.java
@@ -39,7 +39,7 @@ import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -47,7 +47,7 @@ public class TestDistCpSync {
   private MiniDFSCluster cluster;
   private final Configuration conf = new HdfsConfiguration();
   private DistributedFileSystem dfs;
-  private DistCpOptions options;
+  private DistCpContext context;
   private final Path source = new Path("/source");
   private final Path target = new Path("/target");
   private final long BLOCK_SIZE = 1024;
@@ -62,10 +62,13 @@ public class TestDistCpSync {
     dfs.mkdirs(source);
     dfs.mkdirs(target);
 
-    options = new DistCpOptions(Arrays.asList(source), target);
-    options.setSyncFolder(true);
-    options.setUseDiff("s1", "s2");
+    final DistCpOptions options = new DistCpOptions.Builder(
+        Collections.singletonList(source), target)
+        .withSyncFolder(true)
+        .withUseDiff("s1", "s2")
+        .build();
     options.appendToConf(conf);
+    context = new DistCpContext(options);
 
     conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, target.toString());
     conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, target.toString());
@@ -92,34 +95,34 @@ public class TestDistCpSync {
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
         HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s2");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, context.getSourcePaths().get(0));
 
     // reset source path in options
-    options.setSourcePaths(Arrays.asList(source));
+    context.setSourcePaths(Collections.singletonList(source));
     // the source/target does not have the given snapshots
     dfs.allowSnapshot(source);
     dfs.allowSnapshot(target);
     Assert.assertFalse(sync());
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, context.getSourcePaths().get(0));
 
     // reset source path in options
-    options.setSourcePaths(Arrays.asList(source));
+    context.setSourcePaths(Collections.singletonList(source));
     dfs.createSnapshot(source, "s1");
     dfs.createSnapshot(source, "s2");
     dfs.createSnapshot(target, "s1");
     Assert.assertTrue(sync());
 
     // reset source paths in options
-    options.setSourcePaths(Arrays.asList(source));
+    context.setSourcePaths(Collections.singletonList(source));
     // changes have been made in target
     final Path subTarget = new Path(target, "sub");
     dfs.mkdirs(subTarget);
     Assert.assertFalse(sync());
     // make sure the source path has been updated to the snapshot path
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, context.getSourcePaths().get(0));
 
     // reset source paths in options
-    options.setSourcePaths(Arrays.asList(source));
+    context.setSourcePaths(Collections.singletonList(source));
     dfs.delete(subTarget, true);
     Assert.assertTrue(sync());
   }
@@ -137,7 +140,7 @@ public class TestDistCpSync {
   }
 
   private boolean sync() throws Exception {
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    DistCpSync distCpSync = new DistCpSync(context, conf);
     return distCpSync.sync();
   }
 
@@ -231,7 +234,7 @@ public class TestDistCpSync {
     SnapshotDiffReport report = dfs.getSnapshotDiffReport(source, "s1", "s2");
     System.out.println(report);
 
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    DistCpSync distCpSync = new DistCpSync(context, conf);
 
     // do the sync
     Assert.assertTrue(distCpSync.sync());
@@ -239,24 +242,24 @@ public class TestDistCpSync {
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
             HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s2");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, context.getSourcePaths().get(0));
 
     // build copy listing
     final Path listingPath = new Path("/tmp/META/fileList.seq");
     CopyListing listing = new SimpleCopyListing(conf, new Credentials(), distCpSync);
-    listing.buildListing(listingPath, options);
+    listing.buildListing(listingPath, context);
 
     Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath);
     CopyMapper copyMapper = new CopyMapper();
     StubContext stubContext = new StubContext(conf, null, 0);
-    Mapper<Text, CopyListingFileStatus, Text, Text>.Context context =
+    Mapper<Text, CopyListingFileStatus, Text, Text>.Context mapContext =
         stubContext.getContext();
     // Enable append
-    context.getConfiguration().setBoolean(
+    mapContext.getConfiguration().setBoolean(
         DistCpOptionSwitch.APPEND.getConfigLabel(), true);
-    copyMapper.setup(context);
+    copyMapper.setup(mapContext);
     for (Map.Entry<Text, CopyListingFileStatus> entry : copyListing.entrySet()) {
-      copyMapper.map(entry.getKey(), entry.getValue(), context);
+      copyMapper.map(entry.getKey(), entry.getValue(), mapContext);
     }
 
     // verify that we only list modified and created files/directories
@@ -312,7 +315,12 @@ public class TestDistCpSync {
    */
   @Test
   public void testSyncWithCurrent() throws Exception {
-    options.setUseDiff("s1", ".");
+    final DistCpOptions options = new DistCpOptions.Builder(
+        Collections.singletonList(source), target)
+        .withSyncFolder(true)
+        .withUseDiff("s1", ".")
+        .build();
+    context = new DistCpContext(options);
     initData(source);
     initData(target);
     enableAndCreateFirstSnapshot();
@@ -323,7 +331,7 @@ public class TestDistCpSync {
     // do the sync
     sync();
     // make sure the source path is still unchanged
-    Assert.assertEquals(source, options.getSourcePaths().get(0));
+    Assert.assertEquals(source, context.getSourcePaths().get(0));
   }
 
   private void initData2(Path dir) throws Exception {
@@ -501,32 +509,32 @@ public class TestDistCpSync {
     SnapshotDiffReport report = dfs.getSnapshotDiffReport(source, "s1", "s2");
     System.out.println(report);
 
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    DistCpSync distCpSync = new DistCpSync(context, conf);
     // do the sync
     Assert.assertTrue(distCpSync.sync());
 
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
             HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s2");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, context.getSourcePaths().get(0));
 
     // build copy listing
     final Path listingPath = new Path("/tmp/META/fileList.seq");
     CopyListing listing = new SimpleCopyListing(conf, new Credentials(), distCpSync);
-    listing.buildListing(listingPath, options);
+    listing.buildListing(listingPath, context);
 
     Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath);
     CopyMapper copyMapper = new CopyMapper();
     StubContext stubContext = new StubContext(conf, null, 0);
-    Mapper<Text, CopyListingFileStatus, Text, Text>.Context context =
+    Mapper<Text, CopyListingFileStatus, Text, Text>.Context mapContext =
             stubContext.getContext();
     // Enable append
-    context.getConfiguration().setBoolean(
+    mapContext.getConfiguration().setBoolean(
             DistCpOptionSwitch.APPEND.getConfigLabel(), true);
-    copyMapper.setup(context);
+    copyMapper.setup(mapContext);
     for (Map.Entry<Text, CopyListingFileStatus> entry :
             copyListing.entrySet()) {
-      copyMapper.map(entry.getKey(), entry.getValue(), context);
+      copyMapper.map(entry.getKey(), entry.getValue(), mapContext);
     }
 
     // verify that we only list modified and created files/directories
@@ -729,7 +737,7 @@ public class TestDistCpSync {
 
     boolean threwException = false;
     try {
-      DistCpSync distCpSync = new DistCpSync(options, conf);
+      DistCpSync distCpSync = new DistCpSync(context, conf);
       // do the sync
       distCpSync.sync();
     } catch (HadoopIllegalArgumentException e) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java
index fea374e..cca1c53 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSyncReverseBase.java
@@ -56,7 +56,8 @@ public abstract class TestDistCpSyncReverseBase {
   private MiniDFSCluster cluster;
   private final Configuration conf = new HdfsConfiguration();
   private DistributedFileSystem dfs;
-  private DistCpOptions options;
+  private DistCpOptions.Builder optionsBuilder;
+  private DistCpContext distCpContext;
   private Path source;
   private boolean isSrcNotSameAsTgt = true;
   private final Path target = new Path("/target");
@@ -139,10 +140,12 @@ public abstract class TestDistCpSyncReverseBase {
     }
     dfs.mkdirs(target);
 
-    options = new DistCpOptions(Arrays.asList(source), target);
-    options.setSyncFolder(true);
-    options.setUseRdiff("s2", "s1");
+    optionsBuilder = new DistCpOptions.Builder(Arrays.asList(source), target)
+        .withSyncFolder(true)
+        .withUseRdiff("s2", "s1");
+    final DistCpOptions options = optionsBuilder.build();
     options.appendToConf(conf);
+    distCpContext = new DistCpContext(options);
 
     conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, target.toString());
     conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, target.toString());
@@ -169,33 +172,33 @@ public abstract class TestDistCpSyncReverseBase {
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
         HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
 
     // reset source path in options
-    options.setSourcePaths(Arrays.asList(source));
+    optionsBuilder.withSourcePaths(Arrays.asList(source));
     // the source/target does not have the given snapshots
     dfs.allowSnapshot(source);
     dfs.allowSnapshot(target);
     Assert.assertFalse(sync());
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
 
     // reset source path in options
-    options.setSourcePaths(Arrays.asList(source));
+    optionsBuilder.withSourcePaths(Arrays.asList(source));
     this.enableAndCreateFirstSnapshot();
     dfs.createSnapshot(target, "s2");
     Assert.assertTrue(sync());
 
     // reset source paths in options
-    options.setSourcePaths(Arrays.asList(source));
+    optionsBuilder.withSourcePaths(Arrays.asList(source));
     // changes have been made in target
     final Path subTarget = new Path(target, "sub");
     dfs.mkdirs(subTarget);
     Assert.assertFalse(sync());
     // make sure the source path has been updated to the snapshot path
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
 
     // reset source paths in options
-    options.setSourcePaths(Arrays.asList(source));
+    optionsBuilder.withSourcePaths(Arrays.asList(source));
     dfs.delete(subTarget, true);
     Assert.assertTrue(sync());
   }
@@ -215,7 +218,8 @@ public abstract class TestDistCpSyncReverseBase {
   }
 
   private boolean sync() throws Exception {
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    distCpContext = new DistCpContext(optionsBuilder.build());
+    final DistCpSync distCpSync = new DistCpSync(distCpContext, conf);
     return distCpSync.sync();
   }
 
@@ -328,7 +332,7 @@ public abstract class TestDistCpSyncReverseBase {
     SnapshotDiffReport report = dfs.getSnapshotDiffReport(target, "s2", "s1");
     System.out.println(report);
 
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    final DistCpSync distCpSync = new DistCpSync(distCpContext, conf);
 
     lsr("Before sync target: ", shell, target);
 
@@ -340,13 +344,13 @@ public abstract class TestDistCpSyncReverseBase {
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
         HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
 
     // build copy listing
     final Path listingPath = new Path("/tmp/META/fileList.seq");
     CopyListing listing = new SimpleCopyListing(conf, new Credentials(),
         distCpSync);
-    listing.buildListing(listingPath, options);
+    listing.buildListing(listingPath, distCpContext);
 
     Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath);
     CopyMapper copyMapper = new CopyMapper();
@@ -425,7 +429,7 @@ public abstract class TestDistCpSyncReverseBase {
    */
   @Test
   public void testSyncWithCurrent() throws Exception {
-    options.setUseRdiff(".", "s1");
+    optionsBuilder.withUseRdiff(".", "s1");
     if (isSrcNotSameAsTgt) {
       initData(source);
     }
@@ -440,7 +444,7 @@ public abstract class TestDistCpSyncReverseBase {
     final Path spath = new Path(source,
         HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1");
     // make sure the source path is still unchanged
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
   }
 
   private void initData2(Path dir) throws Exception {
@@ -649,7 +653,7 @@ public abstract class TestDistCpSyncReverseBase {
     lsrSource("Before sync source: ", shell, source);
     lsr("Before sync target: ", shell, target);
 
-    DistCpSync distCpSync = new DistCpSync(options, conf);
+    DistCpSync distCpSync = new DistCpSync(distCpContext, conf);
     // do the sync
     distCpSync.sync();
 
@@ -658,12 +662,12 @@ public abstract class TestDistCpSyncReverseBase {
     // make sure the source path has been updated to the snapshot path
     final Path spath = new Path(source,
             HdfsConstants.DOT_SNAPSHOT_DIR + Path.SEPARATOR + "s1");
-    Assert.assertEquals(spath, options.getSourcePaths().get(0));
+    Assert.assertEquals(spath, distCpContext.getSourcePaths().get(0));
 
     // build copy listing
     final Path listingPath = new Path("/tmp/META/fileList.seq");
     CopyListing listing = new SimpleCopyListing(conf, new Credentials(), distCpSync);
-    listing.buildListing(listingPath, options);
+    listing.buildListing(listingPath, distCpContext);
 
     Map<Text, CopyListingFileStatus> copyListing = getListing(listingPath);
     CopyMapper copyMapper = new CopyMapper();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpViewFs.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpViewFs.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpViewFs.java
index 5511e09..d6d0542 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpViewFs.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpViewFs.java
@@ -413,11 +413,13 @@ public class TestDistCpViewFs {
 
   private void runTest(Path listFile, Path target, boolean targetExists, 
       boolean sync) throws IOException {
-    DistCpOptions options = new DistCpOptions(listFile, target);
-    options.setSyncFolder(sync);
-    options.setTargetPathExists(targetExists);
+    final DistCpOptions options = new DistCpOptions.Builder(listFile, target)
+        .withSyncFolder(sync)
+        .build();
     try {
-      new DistCp(getConf(), options).execute();
+      final DistCp distcp = new DistCp(getConf(), options);
+      distcp.context.setTargetPathExists(targetExists);
+      distcp.execute();
     } catch (Exception e) {
       LOG.error("Exception encountered ", e);
       throw new IOException(e);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestFileBasedCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestFileBasedCopyListing.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestFileBasedCopyListing.java
index fe2c668..203de1a 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestFileBasedCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestFileBasedCopyListing.java
@@ -514,10 +514,11 @@ public class TestFileBasedCopyListing {
   private void runTest(Path listFile, Path target, boolean targetExists,
       boolean sync) throws IOException {
     CopyListing listing = new FileBasedCopyListing(config, CREDENTIALS);
-    DistCpOptions options = new DistCpOptions(listFile, target);
-    options.setSyncFolder(sync);
-    options.setTargetPathExists(targetExists);
-    listing.buildListing(listFile, options);
+    final DistCpOptions options = new DistCpOptions.Builder(listFile, target)
+        .withSyncFolder(sync).build();
+    final DistCpContext context = new DistCpContext(options);
+    context.setTargetPathExists(targetExists);
+    listing.buildListing(listFile, context);
   }
 
   private void checkResult(Path listFile, int count) throws IOException {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestGlobbedCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestGlobbedCopyListing.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestGlobbedCopyListing.java
index 6c03b4e..1c92a9c 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestGlobbedCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestGlobbedCopyListing.java
@@ -34,7 +34,7 @@ import org.junit.Test;
 
 import java.io.DataOutputStream;
 import java.net.URI;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -109,9 +109,12 @@ public class TestGlobbedCopyListing {
     Path source = new Path(fileSystemPath.toString() + "/tmp/source");
     Path target = new Path(fileSystemPath.toString() + "/tmp/target");
     Path listingPath = new Path(fileSystemPath.toString() + "/tmp/META/fileList.seq");
-    DistCpOptions options = new DistCpOptions(Arrays.asList(source), target);
-    options.setTargetPathExists(false);
-    new GlobbedCopyListing(new Configuration(), CREDENTIALS).buildListing(listingPath, options);
+    DistCpOptions options = new DistCpOptions.Builder(
+        Collections.singletonList(source), target).build();
+    DistCpContext context = new DistCpContext(options);
+    context.setTargetPathExists(false);
+    new GlobbedCopyListing(new Configuration(), CREDENTIALS)
+        .buildListing(listingPath, context);
 
     verifyContents(listingPath);
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestIntegration.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestIntegration.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestIntegration.java
index ee8e7cc..7574ded 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestIntegration.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestIntegration.java
@@ -26,7 +26,6 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.mapreduce.Cluster;
 import org.apache.hadoop.mapreduce.JobSubmissionFiles;
-import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.tools.util.TestDistCpUtils;
 import org.junit.Assert;
 import org.junit.BeforeClass;
@@ -493,7 +492,8 @@ public class TestIntegration {
       List<Path> sources = new ArrayList<Path>();
       sources.add(sourcePath);
 
-      DistCpOptions options = new DistCpOptions(sources, target);
+      DistCpOptions options = new DistCpOptions.Builder(sources, target)
+          .build();
 
       Configuration conf = getConf();
       Path stagingDir = JobSubmissionFiles.getStagingDir(
@@ -559,14 +559,16 @@ public class TestIntegration {
   private void runTest(Path listFile, Path target, boolean targetExists, 
       boolean sync, boolean delete,
       boolean overwrite) throws IOException {
-    DistCpOptions options = new DistCpOptions(listFile, target);
-    options.setSyncFolder(sync);
-    options.setDeleteMissing(delete);
-    options.setOverwrite(overwrite);
-    options.setTargetPathExists(targetExists);
-    options.setNumListstatusThreads(numListstatusThreads);
+    final DistCpOptions options = new DistCpOptions.Builder(listFile, target)
+        .withSyncFolder(sync)
+        .withDeleteMissing(delete)
+        .withOverwrite(overwrite)
+        .withNumListstatusThreads(numListstatusThreads)
+        .build();
     try {
-      new DistCp(getConf(), options).execute();
+      final DistCp distCp = new DistCp(getConf(), options);
+      distCp.context.setTargetPathExists(targetExists);
+      distCp.execute();
     } catch (Exception e) {
       LOG.error("Exception encountered ", e);
       throw new IOException(e);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/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 f94ba97..e7fdc51 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
@@ -18,7 +18,7 @@
 
 package org.apache.hadoop.tools;
 
-import static org.junit.Assert.assertFalse;
+import static org.apache.hadoop.test.GenericTestUtils.assertExceptionContains;
 import static org.junit.Assert.fail;
 
 import org.junit.Assert;
@@ -28,7 +28,6 @@ import org.apache.hadoop.test.GenericTestUtils;
 import org.apache.hadoop.tools.DistCpOptions.*;
 import org.apache.hadoop.conf.Configuration;
 
-import java.util.Iterator;
 import java.util.NoSuchElementException;
 
 public class TestOptionsParser {
@@ -329,7 +328,7 @@ public class TestOptionsParser {
         "100",
         "hdfs://localhost:9820/source/first",
         "hdfs://localhost:9820/target/"});
-    Assert.assertEquals(DistCpOptions.maxNumListstatusThreads,
+    Assert.assertEquals(DistCpOptions.MAX_NUM_LISTSTATUS_THREADS,
                         options.getNumListstatusThreads());
   }
 
@@ -383,25 +382,6 @@ 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, overwrite=false, "
-        + "append=false, useDiff=false, useRdiff=false, "
-        + "fromSnapshot=null, toSnapshot=null, "
-        + "skipCRC=false, blocking=true, numListstatusThreads=0, maxMaps=20, "
-        + "mapBandwidth=0.0, "
-        + "copyStrategy='uniformsize', preserveStatus=[], "
-        + "preserveRawXattrs=false, atomicWorkPath=null, logPath=null, "
-        + "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, "
-        + "targetPathExists=true, filtersFile='null', blocksPerChunk=0}";
-    String optionString = option.toString();
-    Assert.assertEquals(val, optionString);
-    Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),
-        DistCpOptionSwitch.ATOMIC_COMMIT.name());
-  }
-
-  @Test
   public void testCopyStrategy() {
     DistCpOptions options = OptionsParser.parse(new String[] {
         "-strategy",
@@ -529,13 +509,8 @@ public class TestOptionsParser {
         "-f",
         "hdfs://localhost:9820/source/first",
         "hdfs://localhost:9820/target/"});
-    int i = 0;
-    Iterator<FileAttribute> attribIterator = options.preserveAttributes();
-    while (attribIterator.hasNext()) {
-      attribIterator.next();
-      i++;
-    }
-    Assert.assertEquals(i, DistCpOptionSwitch.PRESERVE_STATUS_DEFAULT.length() - 2);
+    Assert.assertEquals(DistCpOptionSwitch.PRESERVE_STATUS_DEFAULT.length() - 2,
+        options.getPreserveAttributes().size());
 
     try {
       OptionsParser.parse(new String[] {
@@ -545,19 +520,18 @@ public class TestOptionsParser {
           "hdfs://localhost:9820/target"});
       Assert.fail("Invalid preserve attribute");
     }
-    catch (IllegalArgumentException ignore) {}
     catch (NoSuchElementException ignore) {}
 
-    options = OptionsParser.parse(new String[] {
-        "-f",
-        "hdfs://localhost:9820/source/first",
-        "hdfs://localhost:9820/target/"});
-    Assert.assertFalse(options.shouldPreserve(FileAttribute.PERMISSION));
-    options.preserve(FileAttribute.PERMISSION);
-    Assert.assertTrue(options.shouldPreserve(FileAttribute.PERMISSION));
+    Builder builder = new DistCpOptions.Builder(
+        new Path("hdfs://localhost:9820/source/first"),
+        new Path("hdfs://localhost:9820/target/"));
+    Assert.assertFalse(
+        builder.build().shouldPreserve(FileAttribute.PERMISSION));
+    builder.preserve(FileAttribute.PERMISSION);
+    Assert.assertTrue(builder.build().shouldPreserve(FileAttribute.PERMISSION));
 
-    options.preserve(FileAttribute.PERMISSION);
-    Assert.assertTrue(options.shouldPreserve(FileAttribute.PERMISSION));
+    builder.preserve(FileAttribute.PERMISSION);
+    Assert.assertTrue(builder.build().shouldPreserve(FileAttribute.PERMISSION));
   }
 
   @Test
@@ -756,28 +730,25 @@ public class TestOptionsParser {
     }
 
     try {
-      options = OptionsParser.parse(new String[] {
-          optionStr, "s1", "s2", "-update", "-delete",
+      OptionsParser.parse(new String[] {
+          "-diff", "s1", "s2", "-update", "-delete",
           "hdfs://localhost:9820/source/first",
           "hdfs://localhost:9820/target/" });
-      assertFalse("-delete should be ignored when "
-          + optionStr + " is specified",
-          options.shouldDeleteMissing());
+      fail("Should fail as -delete and -diff/-rdiff are mutually exclusive");
     } catch (IllegalArgumentException e) {
-      fail("Got unexpected IllegalArgumentException: " + e.getMessage());
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive", e);
     }
 
     try {
-      options = OptionsParser.parse(new String[] {
-          optionStr, "s1", "s2", "-delete",
+      OptionsParser.parse(new String[] {
+          "-diff", "s1", "s2", "-delete",
           "hdfs://localhost:9820/source/first",
           "hdfs://localhost:9820/target/" });
-      fail(optionStr + " should fail if -update option is not specified");
+      fail("Should fail as -delete and -diff/-rdiff are mutually exclusive");
     } catch (IllegalArgumentException e) {
-      assertFalse("-delete should be ignored when -diff is specified",
-          options.shouldDeleteMissing());
-      GenericTestUtils.assertExceptionContains(
-          "-diff/-rdiff is valid only with -update option", e);
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive", e);
     }
 
     try {
@@ -785,10 +756,10 @@ public class TestOptionsParser {
           "-delete", "-overwrite",
           "hdfs://localhost:9820/source/first",
           "hdfs://localhost:9820/target/" });
-      fail(optionStr + " should fail if -update option is not specified");
+      fail("Should fail as -delete and -diff are mutually exclusive");
     } catch (IllegalArgumentException e) {
-      GenericTestUtils.assertExceptionContains(
-          "-diff/-rdiff is valid only with -update option", e);
+      assertExceptionContains(
+          "-delete and -diff/-rdiff are mutually exclusive", e);
     }
 
     final String optionStrOther = isDiff? "-rdiff" : "-diff";

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/contract/AbstractContractDistCpTest.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/contract/AbstractContractDistCpTest.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/contract/AbstractContractDistCpTest.java
index 21a14d3..fb1a64d 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/contract/AbstractContractDistCpTest.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/contract/AbstractContractDistCpTest.java
@@ -19,9 +19,8 @@
 package org.apache.hadoop.tools.contract;
 
 import static org.apache.hadoop.fs.contract.ContractTestUtils.*;
-import static org.junit.Assert.*;
 
-import java.util.Arrays;
+import java.util.Collections;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileSystem;
@@ -184,7 +183,8 @@ public abstract class AbstractContractDistCpTest
    * @throws Exception if there is a failure
    */
   private void runDistCp(Path src, Path dst) throws Exception {
-    DistCpOptions options = new DistCpOptions(Arrays.asList(src), dst);
+    DistCpOptions options = new DistCpOptions.Builder(
+        Collections.singletonList(src), dst).build();
     Job job = new DistCp(conf, options).execute();
     assertNotNull("Unexpected null job returned from DistCp execution.", job);
     assertTrue("DistCp job did not complete.", job.isComplete());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
index 2452d6f..6ee37cc 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
@@ -32,6 +32,7 @@ import org.apache.hadoop.mapreduce.task.JobContextImpl;
 import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
 import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.DistCpConstants;
+import org.apache.hadoop.tools.DistCpContext;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.GlobbedCopyListing;
@@ -146,15 +147,16 @@ public class TestCopyCommitter {
       sourceBase = TestDistCpUtils.createTestSetup(fs, sourcePerm);
       targetBase = TestDistCpUtils.createTestSetup(fs, initialPerm);
 
-      DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)),
-          new Path("/out"));
-      options.preserve(FileAttribute.PERMISSION);
+      final DistCpOptions options = new DistCpOptions.Builder(
+          Collections.singletonList(new Path(sourceBase)), new Path("/out"))
+          .preserve(FileAttribute.PERMISSION).build();
       options.appendToConf(conf);
-      options.setTargetPathExists(false);
-      
+      final DistCpContext context = new DistCpContext(options);
+      context.setTargetPathExists(false);
+
       CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS);
       Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong()));
-      listing.buildListing(listingFile, options);
+      listing.buildListing(listingFile, context);
 
       conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase);
 
@@ -197,15 +199,15 @@ public class TestCopyCommitter {
       String targetBaseAdd = TestDistCpUtils.createTestSetup(fs, FsPermission.getDefault());
       fs.rename(new Path(targetBaseAdd), new Path(targetBase));
 
-      DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)),
-          new Path("/out"));
-      options.setSyncFolder(true);
-      options.setDeleteMissing(true);
+      final DistCpOptions options = new DistCpOptions.Builder(
+          Collections.singletonList(new Path(sourceBase)), new Path("/out"))
+          .withSyncFolder(true).withDeleteMissing(true).build();
       options.appendToConf(conf);
+      final DistCpContext context = new DistCpContext(options);
 
       CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS);
       Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong()));
-      listing.buildListing(listingFile, options);
+      listing.buildListing(listingFile, context);
 
       conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase);
       conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, targetBase);
@@ -266,15 +268,15 @@ public class TestCopyCommitter {
       TestDistCpUtils.createFile(fs, targetBase + "/9");
       TestDistCpUtils.createFile(fs, targetBase + "/A");
 
-      DistCpOptions options = new DistCpOptions(Arrays.asList(new Path(sourceBase)), 
-          new Path("/out"));
-      options.setSyncFolder(true);
-      options.setDeleteMissing(true);
+      final DistCpOptions options = new DistCpOptions.Builder(
+          Collections.singletonList(new Path(sourceBase)), new Path("/out"))
+          .withSyncFolder(true).withDeleteMissing(true).build();
       options.appendToConf(conf);
+      final DistCpContext context = new DistCpContext(options);
 
       CopyListing listing = new GlobbedCopyListing(conf, CREDENTIALS);
       Path listingFile = new Path("/tmp1/" + String.valueOf(rand.nextLong()));
-      listing.buildListing(listingFile, options);
+      listing.buildListing(listingFile, context);
 
       conf.set(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH, targetBase);
       conf.set(DistCpConstants.CONF_LABEL_TARGET_FINAL_PATH, targetBase);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestUniformSizeInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestUniformSizeInputFormat.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestUniformSizeInputFormat.java
index 78e2262..5315137 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestUniformSizeInputFormat.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestUniformSizeInputFormat.java
@@ -31,6 +31,7 @@ import org.apache.hadoop.mapreduce.task.JobContextImpl;
 import org.apache.hadoop.mapreduce.lib.input.FileSplit;
 import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.CopyListingFileStatus;
+import org.apache.hadoop.tools.DistCpContext;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.StubContext;
 import org.apache.hadoop.security.Credentials;
@@ -74,9 +75,9 @@ public class TestUniformSizeInputFormat {
 
     List<Path> sourceList = new ArrayList<Path>();
     sourceList.add(sourcePath);
-    final DistCpOptions distCpOptions = new DistCpOptions(sourceList, targetPath);
-    distCpOptions.setMaxMaps(nMaps);
-    return distCpOptions;
+    return new DistCpOptions.Builder(sourceList, targetPath)
+        .maxMaps(nMaps)
+        .build();
   }
 
   private static int createFile(String path, int fileSize) throws Exception {
@@ -100,14 +101,14 @@ public class TestUniformSizeInputFormat {
   }
 
   public void testGetSplits(int nMaps) throws Exception {
-    DistCpOptions options = getOptions(nMaps);
+    DistCpContext context = new DistCpContext(getOptions(nMaps));
     Configuration configuration = new Configuration();
     configuration.set("mapred.map.tasks",
-                      String.valueOf(options.getMaxMaps()));
+                      String.valueOf(context.getMaxMaps()));
     Path listFile = new Path(cluster.getFileSystem().getUri().toString()
         + "/tmp/testGetSplits_1/fileList.seq");
-    CopyListing.getCopyListing(configuration, CREDENTIALS, options).
-        buildListing(listFile, options);
+    CopyListing.getCopyListing(configuration, CREDENTIALS, context)
+        .buildListing(listFile, context);
 
     JobContext jobContext = new JobContextImpl(configuration, new JobID());
     UniformSizeInputFormat uniformSizeInputFormat = new UniformSizeInputFormat();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/lib/TestDynamicInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/lib/TestDynamicInputFormat.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/lib/TestDynamicInputFormat.java
index bb2dd9d..87290ca 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/lib/TestDynamicInputFormat.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/lib/TestDynamicInputFormat.java
@@ -19,6 +19,7 @@
 package org.apache.hadoop.tools.mapred.lib;
 
 import org.apache.hadoop.tools.DistCpConstants;
+import org.apache.hadoop.tools.DistCpContext;
 import org.junit.Assert;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -84,9 +85,9 @@ public class TestDynamicInputFormat {
 
     List<Path> sourceList = new ArrayList<Path>();
     sourceList.add(sourcePath);
-    DistCpOptions options = new DistCpOptions(sourceList, targetPath);
-    options.setMaxMaps(NUM_SPLITS);
-    return options;
+    return new DistCpOptions.Builder(sourceList, targetPath)
+        .maxMaps(NUM_SPLITS)
+        .build();
   }
 
   private static void createFile(String path) throws Exception {
@@ -110,13 +111,13 @@ public class TestDynamicInputFormat {
 
   @Test
   public void testGetSplits() throws Exception {
-    DistCpOptions options = getOptions();
+    final DistCpContext context = new DistCpContext(getOptions());
     Configuration configuration = new Configuration();
     configuration.set("mapred.map.tasks",
-                      String.valueOf(options.getMaxMaps()));
-    CopyListing.getCopyListing(configuration, CREDENTIALS, options).buildListing(
-            new Path(cluster.getFileSystem().getUri().toString()
-                    +"/tmp/testDynInputFormat/fileList.seq"), options);
+                      String.valueOf(context.getMaxMaps()));
+    CopyListing.getCopyListing(configuration, CREDENTIALS, context)
+        .buildListing(new Path(cluster.getFileSystem().getUri().toString()
+            +"/tmp/testDynInputFormat/fileList.seq"), context);
 
     JobContext jobContext = new JobContextImpl(configuration, new JobID());
     DynamicInputFormat<Text, CopyListingFileStatus> inputFormat =


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[41/50] [abbrv] hadoop git commit: HFDS-11596. hadoop-hdfs-client jar is in the wrong directory in release tarball. Contributed by Yuanbo Liu.

Posted by in...@apache.org.
HFDS-11596. hadoop-hdfs-client jar is in the wrong directory in release tarball. Contributed by Yuanbo Liu.


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

Branch: refs/heads/HDFS-10467
Commit: 546d533928319f9ef2cb0d8fb0c31715c6738d17
Parents: e054888
Author: Andrew Wang <wa...@apache.org>
Authored: Wed Apr 5 16:04:09 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml                  | 5 +++++
 hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml                     | 5 +++++
 hadoop-hdfs-project/hadoop-hdfs/pom.xml                         | 2 +-
 hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml        | 5 +++++
 .../hadoop-yarn-applications-distributedshell/pom.xml           | 5 +++++
 .../hadoop-yarn-server-resourcemanager/pom.xml                  | 5 +++++
 .../hadoop-yarn-server-timeline-pluginstorage/pom.xml           | 5 +++++
 7 files changed, 31 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml b/hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml
index f5cfd01..a05304b 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/pom.xml
@@ -173,6 +173,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-common</artifactId>
       <scope>test</scope>
       <type>test-jar</type>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml b/hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml
index aceb5bc..403f097 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs-nfs/pom.xml
@@ -57,6 +57,11 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
     </dependency>
     <dependency>
       <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-hdfs</artifactId>
       <scope>test</scope>
       <type>test-jar</type>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-hdfs-project/hadoop-hdfs/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/pom.xml b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
index 65c3943..9b6c058 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/pom.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
@@ -60,7 +60,7 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <dependency>
       <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-hdfs-client</artifactId>
-      <scope>compile</scope>
+      <scope>provided</scope>
     </dependency>
     <dependency>
       <groupId>org.apache.zookeeper</groupId>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml b/hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml
index 0d9e789..1d692a5 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/pom.xml
@@ -105,6 +105,11 @@
       <scope>test</scope>
     </dependency>
     <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
       <groupId>com.google.inject.extensions</groupId>
       <artifactId>guice-servlet</artifactId>
     </dependency>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
index a564b82..b3db4e7 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/pom.xml
@@ -153,6 +153,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-hdfs</artifactId>
       <scope>test</scope>
       <type>test-jar</type>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/pom.xml
index 0a85d0c..533be9e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/pom.xml
@@ -92,6 +92,11 @@
       <scope>test</scope>
     </dependency>
     <dependency>
+      <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
       <groupId>com.google.inject</groupId>
       <artifactId>guice</artifactId>
     </dependency>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/546d5339/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/pom.xml b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/pom.xml
index 4dc8492..a3a44f8 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/pom.xml
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/pom.xml
@@ -110,6 +110,11 @@
     </dependency>
     <dependency>
       <groupId>org.apache.hadoop</groupId>
+      <artifactId>hadoop-hdfs-client</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-hdfs</artifactId>
       <scope>test</scope>
       <type>test-jar</type>


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[08/50] [abbrv] hadoop git commit: HDFS-11603. Improve slow mirror/disk warnings in BlockReceiver.

Posted by in...@apache.org.
HDFS-11603. Improve slow mirror/disk warnings in BlockReceiver.


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

Branch: refs/heads/HDFS-10467
Commit: 707089566cbfa6abbb77760f78f80556f175aeca
Parents: 98c25b7
Author: Arpit Agarwal <ar...@apache.org>
Authored: Fri Mar 31 12:10:20 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../hadoop/hdfs/protocol/DatanodeInfo.java      |  1 +
 .../hdfs/server/datanode/BlockReceiver.java     | 61 +++++++++++++++-----
 2 files changed, 47 insertions(+), 15 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/70708956/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java
index e1698c9..0a8c915 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java
@@ -55,6 +55,7 @@ public class DatanodeInfo extends DatanodeID implements Node {
   private String softwareVersion;
   private List<String> dependentHostNames = new LinkedList<>();
   private String upgradeDomain;
+  public static final DatanodeInfo[] EMPTY_ARRAY = {};
 
   // Datanode administrative states
   public enum AdminStates {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/70708956/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
index bb6bd55..00109e0 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/BlockReceiver.java
@@ -100,6 +100,7 @@ class BlockReceiver implements Closeable {
   private DataTransferThrottler throttler;
   private ReplicaOutputStreams streams;
   private DatanodeInfo srcDataNode = null;
+  private DatanodeInfo[] downstreamDNs = DatanodeInfo.EMPTY_ARRAY;
   private final DataNode datanode;
   volatile private boolean mirrorError;
 
@@ -424,10 +425,10 @@ class BlockReceiver implements Closeable {
       }
     }
     long duration = Time.monotonicNow() - begin;
-    if (duration > datanodeSlowLogThresholdMs) {
+    if (duration > datanodeSlowLogThresholdMs && LOG.isWarnEnabled()) {
       LOG.warn("Slow flushOrSync took " + duration + "ms (threshold="
           + datanodeSlowLogThresholdMs + "ms), isSync:" + isSync + ", flushTotalNanos="
-          + flushTotalNanos + "ns");
+          + flushTotalNanos + "ns, volume=" + getVolumeBaseUri());
     }
   }
 
@@ -578,9 +579,10 @@ class BlockReceiver implements Closeable {
             mirrorAddr,
             duration);
         trackSendPacketToLastNodeInPipeline(duration);
-        if (duration > datanodeSlowLogThresholdMs) {
+        if (duration > datanodeSlowLogThresholdMs && LOG.isWarnEnabled()) {
           LOG.warn("Slow BlockReceiver write packet to mirror took " + duration
-              + "ms (threshold=" + datanodeSlowLogThresholdMs + "ms)");
+              + "ms (threshold=" + datanodeSlowLogThresholdMs + "ms), "
+              + "downstream DNs=" + Arrays.toString(downstreamDNs));
         }
       } catch (IOException e) {
         handleMirrorOutError(e);
@@ -711,9 +713,10 @@ class BlockReceiver implements Closeable {
           streams.writeDataToDisk(dataBuf.array(),
               startByteToDisk, numBytesToDisk);
           long duration = Time.monotonicNow() - begin;
-          if (duration > datanodeSlowLogThresholdMs) {
+          if (duration > datanodeSlowLogThresholdMs && LOG.isWarnEnabled()) {
             LOG.warn("Slow BlockReceiver write data to disk cost:" + duration
-                + "ms (threshold=" + datanodeSlowLogThresholdMs + "ms)");
+                + "ms (threshold=" + datanodeSlowLogThresholdMs + "ms), "
+                + "volume=" + getVolumeBaseUri());
           }
 
           if (duration > maxWriteToDiskMs) {
@@ -902,9 +905,10 @@ class BlockReceiver implements Closeable {
         }
         lastCacheManagementOffset = offsetInBlock;
         long duration = Time.monotonicNow() - begin;
-        if (duration > datanodeSlowLogThresholdMs) {
+        if (duration > datanodeSlowLogThresholdMs && LOG.isWarnEnabled()) {
           LOG.warn("Slow manageWriterOsCache took " + duration
-              + "ms (threshold=" + datanodeSlowLogThresholdMs + "ms)");
+              + "ms (threshold=" + datanodeSlowLogThresholdMs
+              + "ms), volume=" + getVolumeBaseUri());
         }
       }
     } catch (Throwable t) {
@@ -932,13 +936,7 @@ class BlockReceiver implements Closeable {
     boolean responderClosed = false;
     mirrorOut = mirrOut;
     mirrorAddr = mirrAddr;
-    isPenultimateNode = ((downstreams != null) && (downstreams.length == 1));
-    if (isPenultimateNode) {
-      mirrorNameForMetrics = (downstreams[0].getInfoSecurePort() != 0 ?
-          downstreams[0].getInfoSecureAddr() : downstreams[0].getInfoAddr());
-      LOG.debug("Will collect peer metrics for downstream node {}",
-          mirrorNameForMetrics);
-    }
+    initPerfMonitoring(downstreams);
     throttler = throttlerArg;
 
     this.replyOut = replyOut;
@@ -1058,6 +1056,39 @@ class BlockReceiver implements Closeable {
     }
   }
 
+  /**
+   * If we have downstream DNs and peerMetrics are enabled, then initialize
+   * some state for monitoring the performance of downstream DNs.
+   *
+   * @param downstreams downstream DNs, or null if there are none.
+   */
+  private void initPerfMonitoring(DatanodeInfo[] downstreams) {
+    if (downstreams != null && downstreams.length > 0) {
+      downstreamDNs = downstreams;
+      isPenultimateNode = (downstreams.length == 1);
+      if (isPenultimateNode && datanode.getPeerMetrics() != null) {
+        mirrorNameForMetrics = (downstreams[0].getInfoSecurePort() != 0 ?
+            downstreams[0].getInfoSecureAddr() : downstreams[0].getInfoAddr());
+        LOG.debug("Will collect peer metrics for downstream node {}",
+            mirrorNameForMetrics);
+      }
+    }
+  }
+
+  /**
+   * Fetch the base URI of the volume on which this replica resides.
+   *
+   * @returns Volume base URI as string if available. Else returns the
+   *          the string "unavailable".
+   */
+  private String getVolumeBaseUri() {
+    final ReplicaInfo ri = replicaInfo.getReplicaInfo();
+    if (ri != null && ri.getVolume() != null) {
+      return ri.getVolume().getBaseURI().toString();
+    }
+    return "unavailable";
+  }
+
   /** Cleanup a partial block 
    * if this write is for a replication request (and not from a client)
    */


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[07/50] [abbrv] hadoop git commit: MAPREDUCE-6824. TaskAttemptImpl#createCommonContainerLaunchContext is longer than 150 lines. Contributed by Chris Trezzo.

Posted by in...@apache.org.
MAPREDUCE-6824. TaskAttemptImpl#createCommonContainerLaunchContext is longer than 150 lines. 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/2b87e1a2
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/2b87e1a2
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/2b87e1a2

Branch: refs/heads/HDFS-10467
Commit: 2b87e1a219a46de8537e53f774943c509bc0d678
Parents: 51456bf
Author: Akira Ajisaka <aa...@apache.org>
Authored: Mon Apr 3 13:06:24 2017 +0900
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../v2/app/job/impl/TaskAttemptImpl.java        | 285 ++++++++++---------
 1 file changed, 153 insertions(+), 132 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/2b87e1a2/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.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/TaskAttemptImpl.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.java
index 4305824..9ea1b9a 100755
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.java
@@ -755,7 +755,7 @@ public abstract class TaskAttemptImpl implements
         new HashMap<String, LocalResource>();
     
     // Application environment
-    Map<String, String> environment = new HashMap<String, String>();
+    Map<String, String> environment;
 
     // Service data
     Map<String, ByteBuffer> serviceData = new HashMap<String, ByteBuffer>();
@@ -763,157 +763,178 @@ public abstract class TaskAttemptImpl implements
     // Tokens
     ByteBuffer taskCredentialsBuffer = ByteBuffer.wrap(new byte[]{});
     try {
-      FileSystem remoteFS = FileSystem.get(conf);
-
-      // //////////// Set up JobJar to be localized properly on the remote NM.
-      String jobJar = conf.get(MRJobConfig.JAR);
-      if (jobJar != null) {
-        final Path jobJarPath = new Path(jobJar);
-        final FileSystem jobJarFs = FileSystem.get(jobJarPath.toUri(), conf);
-        Path remoteJobJar = jobJarPath.makeQualified(jobJarFs.getUri(),
-            jobJarFs.getWorkingDirectory());
-        LocalResource rc = createLocalResource(jobJarFs, remoteJobJar,
-            LocalResourceType.PATTERN, LocalResourceVisibility.APPLICATION);
-        String pattern = conf.getPattern(JobContext.JAR_UNPACK_PATTERN, 
-            JobConf.UNPACK_JAR_PATTERN_DEFAULT).pattern();
-        rc.setPattern(pattern);
-        localResources.put(MRJobConfig.JOB_JAR, rc);
-        LOG.info("The job-jar file on the remote FS is "
-            + remoteJobJar.toUri().toASCIIString());
-      } else {
-        // Job jar may be null. For e.g, for pipes, the job jar is the hadoop
-        // mapreduce jar itself which is already on the classpath.
-        LOG.info("Job jar is not present. "
-            + "Not adding any jar to the list of resources.");
-      }
-      // //////////// End of JobJar setup
-
-      // //////////// Set up JobConf to be localized properly on the remote NM.
-      Path path =
-          MRApps.getStagingAreaDir(conf, UserGroupInformation
-              .getCurrentUser().getShortUserName());
-      Path remoteJobSubmitDir =
-          new Path(path, oldJobId.toString());
-      Path remoteJobConfPath = 
-          new Path(remoteJobSubmitDir, MRJobConfig.JOB_CONF_FILE);
-      localResources.put(
-          MRJobConfig.JOB_CONF_FILE,
-          createLocalResource(remoteFS, remoteJobConfPath,
-              LocalResourceType.FILE, LocalResourceVisibility.APPLICATION));
-      LOG.info("The job-conf file on the remote FS is "
-          + remoteJobConfPath.toUri().toASCIIString());
-      // //////////// End of JobConf setup
 
-      // Setup DistributedCache
-      MRApps.setupDistributedCache(conf, localResources);
+      configureJobJar(conf, localResources);
 
-      // Setup up task credentials buffer
-      LOG.info("Adding #" + credentials.numberOfTokens()
-          + " tokens and #" + credentials.numberOfSecretKeys()
-          + " secret keys for NM use for launching container");
-      Credentials taskCredentials = new Credentials(credentials);
+      configureJobConf(conf, localResources, oldJobId);
 
-      // LocalStorageToken is needed irrespective of whether security is enabled
-      // or not.
-      TokenCache.setJobToken(jobToken, taskCredentials);
+      // Setup DistributedCache
+      MRApps.setupDistributedCache(conf, localResources);
 
-      DataOutputBuffer containerTokens_dob = new DataOutputBuffer();
-      LOG.info("Size of containertokens_dob is "
-          + taskCredentials.numberOfTokens());
-      taskCredentials.writeTokenStorageToStream(containerTokens_dob);
       taskCredentialsBuffer =
-          ByteBuffer.wrap(containerTokens_dob.getData(), 0,
-              containerTokens_dob.getLength());
-
-      // Add shuffle secret key
-      // The secret key is converted to a JobToken to preserve backwards
-      // compatibility with an older ShuffleHandler running on an NM.
-      LOG.info("Putting shuffle token in serviceData");
-      byte[] shuffleSecret = TokenCache.getShuffleSecretKey(credentials);
-      if (shuffleSecret == null) {
-        LOG.warn("Cannot locate shuffle secret in credentials."
-            + " Using job token as shuffle secret.");
-        shuffleSecret = jobToken.getPassword();
-      }
-      Token<JobTokenIdentifier> shuffleToken = new Token<JobTokenIdentifier>(
-          jobToken.getIdentifier(), shuffleSecret, jobToken.getKind(),
-          jobToken.getService());
-      serviceData.put(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID,
-          ShuffleHandler.serializeServiceData(shuffleToken));
-
-      // add external shuffle-providers - if any
-      Collection<String> shuffleProviders = conf.getStringCollection(
-          MRJobConfig.MAPREDUCE_JOB_SHUFFLE_PROVIDER_SERVICES);
-      if (! shuffleProviders.isEmpty()) {
-        Collection<String> auxNames = conf.getStringCollection(
-            YarnConfiguration.NM_AUX_SERVICES);
-
-        for (final String shuffleProvider : shuffleProviders) {
-          if (shuffleProvider.equals(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID)) {
-            continue; // skip built-in shuffle-provider that was already inserted with shuffle secret key
-          }
-          if (auxNames.contains(shuffleProvider)) {
-                LOG.info("Adding ShuffleProvider Service: " + shuffleProvider + " to serviceData");
-                // This only serves for INIT_APP notifications
-                // The shuffle service needs to be able to work with the host:port information provided by the AM
-                // (i.e. shuffle services which require custom location / other configuration are not supported)
-                serviceData.put(shuffleProvider, ByteBuffer.allocate(0));
-          }
-          else {
-            throw new YarnRuntimeException("ShuffleProvider Service: " + shuffleProvider +
-            " was NOT found in the list of aux-services that are available in this NM." +
-            " You may need to specify this ShuffleProvider as an aux-service in your yarn-site.xml");
-          }
-        }
-      }
+          configureTokens(jobToken, credentials, serviceData);
 
-      MRApps.addToEnvironment(
-          environment,  
-          Environment.CLASSPATH.name(), 
-          getInitialClasspath(conf), conf);
+      addExternalShuffleProviders(conf, serviceData);
+
+      environment = configureEnv(conf);
 
-      if (initialAppClasspath != null) {
-        MRApps.addToEnvironment(
-            environment,  
-            Environment.APP_CLASSPATH.name(), 
-            initialAppClasspath, conf);
-      }
     } catch (IOException e) {
       throw new YarnRuntimeException(e);
     }
 
-    // Shell
-    environment.put(
-        Environment.SHELL.name(), 
-        conf.get(
-            MRJobConfig.MAPRED_ADMIN_USER_SHELL, 
-            MRJobConfig.DEFAULT_SHELL)
-            );
-
-    // Add pwd to LD_LIBRARY_PATH, add this before adding anything else
-    MRApps.addToEnvironment(
-        environment, 
-        Environment.LD_LIBRARY_PATH.name(), 
-        MRApps.crossPlatformifyMREnv(conf, Environment.PWD), conf);
-
-    // Add the env variables passed by the admin
-    MRApps.setEnvFromInputString(
-        environment, 
-        conf.get(
-            MRJobConfig.MAPRED_ADMIN_USER_ENV, 
-            MRJobConfig.DEFAULT_MAPRED_ADMIN_USER_ENV), conf
-        );
-
     // Construct the actual Container
     // The null fields are per-container and will be constructed for each
     // container separately.
     ContainerLaunchContext container =
         ContainerLaunchContext.newInstance(localResources, environment, null,
-          serviceData, taskCredentialsBuffer, applicationACLs);
+            serviceData, taskCredentialsBuffer, applicationACLs);
 
     return container;
   }
 
+  private static Map<String, String> configureEnv(Configuration conf)
+      throws IOException {
+    Map<String, String> environment = new HashMap<String, String>();
+    MRApps.addToEnvironment(environment, Environment.CLASSPATH.name(),
+        getInitialClasspath(conf), conf);
+
+    if (initialAppClasspath != null) {
+      MRApps.addToEnvironment(environment, Environment.APP_CLASSPATH.name(),
+          initialAppClasspath, conf);
+    }
+
+    // Shell
+    environment.put(Environment.SHELL.name(), conf
+        .get(MRJobConfig.MAPRED_ADMIN_USER_SHELL, MRJobConfig.DEFAULT_SHELL));
+
+    // Add pwd to LD_LIBRARY_PATH, add this before adding anything else
+    MRApps.addToEnvironment(environment, Environment.LD_LIBRARY_PATH.name(),
+        MRApps.crossPlatformifyMREnv(conf, Environment.PWD), conf);
+
+    // Add the env variables passed by the admin
+    MRApps.setEnvFromInputString(environment,
+        conf.get(MRJobConfig.MAPRED_ADMIN_USER_ENV,
+            MRJobConfig.DEFAULT_MAPRED_ADMIN_USER_ENV),
+        conf);
+    return environment;
+  }
+
+  private static void configureJobJar(Configuration conf,
+      Map<String, LocalResource> localResources) throws IOException {
+    // Set up JobJar to be localized properly on the remote NM.
+    String jobJar = conf.get(MRJobConfig.JAR);
+    if (jobJar != null) {
+      final Path jobJarPath = new Path(jobJar);
+      final FileSystem jobJarFs = FileSystem.get(jobJarPath.toUri(), conf);
+      Path remoteJobJar = jobJarPath.makeQualified(jobJarFs.getUri(),
+          jobJarFs.getWorkingDirectory());
+      LocalResource rc = createLocalResource(jobJarFs, remoteJobJar,
+          LocalResourceType.PATTERN, LocalResourceVisibility.APPLICATION);
+      String pattern = conf.getPattern(JobContext.JAR_UNPACK_PATTERN,
+          JobConf.UNPACK_JAR_PATTERN_DEFAULT).pattern();
+      rc.setPattern(pattern);
+      localResources.put(MRJobConfig.JOB_JAR, rc);
+      LOG.info("The job-jar file on the remote FS is "
+          + remoteJobJar.toUri().toASCIIString());
+    } else {
+      // Job jar may be null. For e.g, for pipes, the job jar is the hadoop
+      // mapreduce jar itself which is already on the classpath.
+      LOG.info("Job jar is not present. "
+          + "Not adding any jar to the list of resources.");
+    }
+  }
+
+  private static void configureJobConf(Configuration conf,
+      Map<String, LocalResource> localResources,
+      final org.apache.hadoop.mapred.JobID oldJobId) throws IOException {
+    // Set up JobConf to be localized properly on the remote NM.
+    Path path = MRApps.getStagingAreaDir(conf,
+        UserGroupInformation.getCurrentUser().getShortUserName());
+    Path remoteJobSubmitDir = new Path(path, oldJobId.toString());
+    Path remoteJobConfPath =
+        new Path(remoteJobSubmitDir, MRJobConfig.JOB_CONF_FILE);
+    FileSystem remoteFS = FileSystem.get(conf);
+    localResources.put(MRJobConfig.JOB_CONF_FILE,
+        createLocalResource(remoteFS, remoteJobConfPath, LocalResourceType.FILE,
+            LocalResourceVisibility.APPLICATION));
+    LOG.info("The job-conf file on the remote FS is "
+        + remoteJobConfPath.toUri().toASCIIString());
+  }
+
+  private static ByteBuffer configureTokens(Token<JobTokenIdentifier> jobToken,
+      Credentials credentials,
+      Map<String, ByteBuffer> serviceData) throws IOException {
+    // Setup up task credentials buffer
+    LOG.info("Adding #" + credentials.numberOfTokens() + " tokens and #"
+        + credentials.numberOfSecretKeys()
+        + " secret keys for NM use for launching container");
+    Credentials taskCredentials = new Credentials(credentials);
+
+    // LocalStorageToken is needed irrespective of whether security is enabled
+    // or not.
+    TokenCache.setJobToken(jobToken, taskCredentials);
+
+    DataOutputBuffer containerTokens_dob = new DataOutputBuffer();
+    LOG.info(
+        "Size of containertokens_dob is " + taskCredentials.numberOfTokens());
+    taskCredentials.writeTokenStorageToStream(containerTokens_dob);
+    ByteBuffer taskCredentialsBuffer =
+        ByteBuffer.wrap(containerTokens_dob.getData(), 0,
+            containerTokens_dob.getLength());
+
+    // Add shuffle secret key
+    // The secret key is converted to a JobToken to preserve backwards
+    // compatibility with an older ShuffleHandler running on an NM.
+    LOG.info("Putting shuffle token in serviceData");
+    byte[] shuffleSecret = TokenCache.getShuffleSecretKey(credentials);
+    if (shuffleSecret == null) {
+      LOG.warn("Cannot locate shuffle secret in credentials."
+          + " Using job token as shuffle secret.");
+      shuffleSecret = jobToken.getPassword();
+    }
+    Token<JobTokenIdentifier> shuffleToken =
+        new Token<JobTokenIdentifier>(jobToken.getIdentifier(), shuffleSecret,
+            jobToken.getKind(), jobToken.getService());
+    serviceData.put(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID,
+        ShuffleHandler.serializeServiceData(shuffleToken));
+    return taskCredentialsBuffer;
+  }
+
+  private static void addExternalShuffleProviders(Configuration conf,
+      Map<String, ByteBuffer> serviceData) {
+    // add external shuffle-providers - if any
+    Collection<String> shuffleProviders = conf.getStringCollection(
+        MRJobConfig.MAPREDUCE_JOB_SHUFFLE_PROVIDER_SERVICES);
+    if (!shuffleProviders.isEmpty()) {
+      Collection<String> auxNames =
+          conf.getStringCollection(YarnConfiguration.NM_AUX_SERVICES);
+
+      for (final String shuffleProvider : shuffleProviders) {
+        if (shuffleProvider
+            .equals(ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID)) {
+          continue; // skip built-in shuffle-provider that was already inserted
+                    // with shuffle secret key
+        }
+        if (auxNames.contains(shuffleProvider)) {
+          LOG.info("Adding ShuffleProvider Service: " + shuffleProvider
+              + " to serviceData");
+          // This only serves for INIT_APP notifications
+          // The shuffle service needs to be able to work with the host:port
+          // information provided by the AM
+          // (i.e. shuffle services which require custom location / other
+          // configuration are not supported)
+          serviceData.put(shuffleProvider, ByteBuffer.allocate(0));
+        } else {
+          throw new YarnRuntimeException("ShuffleProvider Service: "
+              + shuffleProvider
+              + " was NOT found in the list of aux-services that are "
+              + "available in this NM. You may need to specify this "
+              + "ShuffleProvider as an aux-service in your yarn-site.xml");
+        }
+      }
+    }
+  }
+
   static ContainerLaunchContext createContainerLaunchContext(
       Map<ApplicationAccessType, String> applicationACLs,
       Configuration conf, Token<JobTokenIdentifier> jobToken, Task remoteTask,


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[30/50] [abbrv] hadoop git commit: YARN-5007. Remove deprecated constructors of MiniYARNCluster and MiniMRYarnCluster. Contributed by Andras Bokor.

Posted by in...@apache.org.
YARN-5007. Remove deprecated constructors of MiniYARNCluster and MiniMRYarnCluster. Contributed by Andras Bokor.


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

Branch: refs/heads/HDFS-10467
Commit: ca331979c69ff91c50ab51fe0f7520ba04377f01
Parents: c58c01f
Author: Akira Ajisaka <aa...@apache.org>
Authored: Wed Apr 5 17:33:07 2017 +0900
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../mapred/TestMRTimelineEventHandling.java     |  2 +-
 .../hadoop/mapreduce/v2/MiniMRYarnCluster.java  |  6 +---
 .../hadoop/yarn/client/ProtocolHATestBase.java  |  6 ++--
 .../hadoop/yarn/server/MiniYARNCluster.java     | 22 ++-----------
 .../hadoop/yarn/server/TestMiniYarnCluster.java | 34 ++------------------
 5 files changed, 9 insertions(+), 61 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/ca331979/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRTimelineEventHandling.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRTimelineEventHandling.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRTimelineEventHandling.java
index cbca3c8..eca51fb 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRTimelineEventHandling.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestMRTimelineEventHandling.java
@@ -203,7 +203,7 @@ public class TestMRTimelineEventHandling {
     MiniMRYarnCluster cluster = null;
     try {
       cluster = new MiniMRYarnCluster(
-          TestMRTimelineEventHandling.class.getSimpleName(), 1, true);
+          TestMRTimelineEventHandling.class.getSimpleName(), 1);
       cluster.init(conf);
       cluster.start();
       LOG.info("A MiniMRYarnCluster get start.");

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ca331979/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java
index 06e37dd..bcfc963 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/v2/MiniMRYarnCluster.java
@@ -74,11 +74,7 @@ public class MiniMRYarnCluster extends MiniYARNCluster {
   }
 
   public MiniMRYarnCluster(String testName, int noOfNMs) {
-    this(testName, noOfNMs, false);
-  }
-  @Deprecated
-  public MiniMRYarnCluster(String testName, int noOfNMs, boolean enableAHS) {
-    super(testName, 1, noOfNMs, 4, 4, enableAHS);
+    super(testName, 1, noOfNMs, 4, 4);
     historyServerWrapper = new JobHistoryServerWrapper();
     addService(historyServerWrapper);
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ca331979/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java
index a8e9132..c185abc 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/ProtocolHATestBase.java
@@ -274,7 +274,7 @@ public abstract class ProtocolHATestBase extends ClientBaseWithFixes {
     conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false);
     cluster =
         new MiniYARNClusterForHATesting(TestRMFailover.class.getName(), 2,
-            numOfNMs, 1, 1, false, overrideClientRMService, overrideRTS,
+            numOfNMs, 1, 1, overrideClientRMService, overrideRTS,
             overrideApplicationMasterService);
     cluster.resetStartFailoverFlag(false);
     cluster.init(conf);
@@ -304,10 +304,10 @@ public abstract class ProtocolHATestBase extends ClientBaseWithFixes {
 
     public MiniYARNClusterForHATesting(String testName,
         int numResourceManagers, int numNodeManagers, int numLocalDirs,
-        int numLogDirs, boolean enableAHS, boolean overrideClientRMService,
+        int numLogDirs, boolean overrideClientRMService,
         boolean overrideRTS, boolean overrideApplicationMasterService) {
       super(testName, numResourceManagers, numNodeManagers, numLocalDirs,
-          numLogDirs, enableAHS);
+          numLogDirs);
       this.overrideClientRMService = overrideClientRMService;
       this.overrideRTS = overrideRTS;
       this.overrideApplicationMasterService = overrideApplicationMasterService;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ca331979/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java
index 77240c6..974ef09 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/MiniYARNCluster.java
@@ -146,7 +146,6 @@ public class MiniYARNCluster extends CompositeService {
   private int numLocalDirs;
   // Number of nm-log-dirs per nodemanager
   private int numLogDirs;
-  private boolean enableAHS;
 
   /**
    * @param testName name of the test
@@ -154,16 +153,13 @@ public class MiniYARNCluster extends CompositeService {
    * @param numNodeManagers the number of node managers in the cluster
    * @param numLocalDirs the number of nm-local-dirs per nodemanager
    * @param numLogDirs the number of nm-log-dirs per nodemanager
-   * @param enableAHS enable ApplicationHistoryServer or not
    */
-  @Deprecated
   public MiniYARNCluster(
       String testName, int numResourceManagers, int numNodeManagers,
-      int numLocalDirs, int numLogDirs, boolean enableAHS) {
+      int numLocalDirs, int numLogDirs) {
     super(testName.replace("$", ""));
     this.numLocalDirs = numLocalDirs;
     this.numLogDirs = numLogDirs;
-    this.enableAHS = enableAHS;
     String testSubDir = testName.replace("$", "");
     File targetWorkDir = new File("target", testSubDir);
     try {
@@ -215,20 +211,6 @@ public class MiniYARNCluster extends CompositeService {
 
   /**
    * @param testName name of the test
-   * @param numResourceManagers the number of resource managers in the cluster
-   * @param numNodeManagers the number of node managers in the cluster
-   * @param numLocalDirs the number of nm-local-dirs per nodemanager
-   * @param numLogDirs the number of nm-log-dirs per nodemanager
-   */
-  public MiniYARNCluster(
-      String testName, int numResourceManagers, int numNodeManagers,
-      int numLocalDirs, int numLogDirs) {
-    this(testName, numResourceManagers, numNodeManagers, numLocalDirs,
-        numLogDirs, false);
-  }
-
-  /**
-   * @param testName name of the test
    * @param numNodeManagers the number of node managers in the cluster
    * @param numLocalDirs the number of nm-local-dirs per nodemanager
    * @param numLogDirs the number of nm-log-dirs per nodemanager
@@ -288,7 +270,7 @@ public class MiniYARNCluster extends CompositeService {
     }
 
     if(conf.getBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED,
-        YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED) || enableAHS) {
+        YarnConfiguration.DEFAULT_TIMELINE_SERVICE_ENABLED)) {
         addService(new ApplicationHistoryServerWrapper());
     }
     

http://git-wip-us.apache.org/repos/asf/hadoop/blob/ca331979/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestMiniYarnCluster.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestMiniYarnCluster.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestMiniYarnCluster.java
index ff7fafc..92f63ea 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestMiniYarnCluster.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/TestMiniYarnCluster.java
@@ -34,18 +34,14 @@ public class TestMiniYarnCluster {
     int numNodeManagers = 1;
     int numLocalDirs = 1;
     int numLogDirs = 1;
-    boolean enableAHS;
 
     /*
      * Timeline service should not start if TIMELINE_SERVICE_ENABLED == false
-     * and enableAHS flag == false
      */
     conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, false);
-    enableAHS = false;
     try (MiniYARNCluster cluster =
         new MiniYARNCluster(TestMiniYarnCluster.class.getSimpleName(),
-            numNodeManagers, numLocalDirs, numLogDirs, numLogDirs,
-                enableAHS)) {
+            numNodeManagers, numLocalDirs, numLogDirs, numLogDirs)) {
 
       cluster.init(conf);
       cluster.start();
@@ -57,14 +53,11 @@ public class TestMiniYarnCluster {
 
     /*
      * Timeline service should start if TIMELINE_SERVICE_ENABLED == true
-     * and enableAHS == false
      */
     conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, true);
-    enableAHS = false;
     try (MiniYARNCluster cluster =
         new MiniYARNCluster(TestMiniYarnCluster.class.getSimpleName(),
-            numNodeManagers, numLocalDirs, numLogDirs, numLogDirs,
-                enableAHS)) {
+            numNodeManagers, numLocalDirs, numLogDirs, numLogDirs)) {
       cluster.init(conf);
 
       // Verify that the timeline-service starts on ephemeral ports by default
@@ -84,29 +77,6 @@ public class TestMiniYarnCluster {
       Assert.assertNotNull("Timeline Service should have been started",
           cluster.getApplicationHistoryServer());
     }
-    /*
-     * Timeline service should start if TIMELINE_SERVICE_ENABLED == false
-     * and enableAHS == true
-     */
-    conf.setBoolean(YarnConfiguration.TIMELINE_SERVICE_ENABLED, false);
-    enableAHS = true;
-    try (MiniYARNCluster cluster =
-        new MiniYARNCluster(TestMiniYarnCluster.class.getSimpleName(),
-            numNodeManagers, numLocalDirs, numLogDirs, numLogDirs,
-                enableAHS)) {
-      cluster.init(conf);
-      cluster.start();
-
-      //Timeline service may sometime take a while to get started
-      int wait = 0;
-      while(cluster.getApplicationHistoryServer() == null && wait < 20) {
-        Thread.sleep(500);
-        wait++;
-      }
-      //verify that the timeline service is started.
-      Assert.assertNotNull("Timeline Service should have been started",
-          cluster.getApplicationHistoryServer());
-    }
   }
 
   @Test


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[20/50] [abbrv] hadoop git commit: HADOOP-14273. Azure: NativeAzureFileSystem should respect config for kerberosSupportEnabled flag. Contributed by Santhosh G Nayak

Posted by in...@apache.org.
HADOOP-14273. Azure: NativeAzureFileSystem should respect config for kerberosSupportEnabled flag. Contributed by Santhosh G Nayak


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

Branch: refs/heads/HDFS-10467
Commit: 0edd758cdfc20aed55e7de5470092d3ce23c8f0e
Parents: c5e97cf
Author: Mingliang Liu <li...@apache.org>
Authored: Tue Apr 4 11:10:28 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java     | 2 ++
 1 file changed, 2 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/0edd758c/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java
index 1e6f00e..5469944 100644
--- a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java
+++ b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/NativeAzureFileSystem.java
@@ -1287,6 +1287,8 @@ public class NativeAzureFileSystem extends FileSystem {
 
     this.azureAuthorization = useSecureMode &&
         conf.getBoolean(KEY_AZURE_AUTHORIZATION, DEFAULT_AZURE_AUTHORIZATION);
+    this.kerberosSupportEnabled =
+        conf.getBoolean(Constants.AZURE_KERBEROS_SUPPORT_PROPERTY_NAME, false);
 
     if (this.azureAuthorization) {
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[06/50] [abbrv] hadoop git commit: HDFS-11515. -du throws ConcurrentModificationException. Contributed by Istvan Fajth, Wei-Chiu Chuang.

Posted by in...@apache.org.
HDFS-11515. -du throws ConcurrentModificationException. Contributed by Istvan Fajth, 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/285478a7
Tree: http://git-wip-us.apache.org/repos/asf/hadoop/tree/285478a7
Diff: http://git-wip-us.apache.org/repos/asf/hadoop/diff/285478a7

Branch: refs/heads/HDFS-10467
Commit: 285478a7d329b0c8cbb316c5414787fbab1ade08
Parents: 2b87e1a
Author: Wei-Chiu Chuang <we...@apache.org>
Authored: Mon Apr 3 07:32:27 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../snapshot/DirectoryWithSnapshotFeature.java  |  5 ++
 .../snapshot/TestRenameWithSnapshots.java       |  6 +-
 .../namenode/snapshot/TestSnapshotDeletion.java | 75 ++++++++++++++++++++
 3 files changed, 84 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/285478a7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/DirectoryWithSnapshotFeature.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/DirectoryWithSnapshotFeature.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/DirectoryWithSnapshotFeature.java
index 9addbfa..9840679 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/DirectoryWithSnapshotFeature.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/DirectoryWithSnapshotFeature.java
@@ -633,6 +633,11 @@ public class DirectoryWithSnapshotFeature implements INode.Feature {
     for(DirectoryDiff d : diffs) {
       for(INode deletedNode : d.getChildrenDiff().getList(ListType.DELETED)) {
         context.reportDeletedSnapshottedNode(deletedNode);
+        if (deletedNode.isDirectory()){
+          DirectoryWithSnapshotFeature sf =
+              deletedNode.asDirectory().getDirectoryWithSnapshotFeature();
+          sf.computeContentSummary4Snapshot(context);
+        }
       }
     }
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/285478a7/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestRenameWithSnapshots.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestRenameWithSnapshots.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestRenameWithSnapshots.java
index d1b3aa6..d06c384 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestRenameWithSnapshots.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestRenameWithSnapshots.java
@@ -26,6 +26,7 @@ import static org.mockito.Matchers.anyBoolean;
 import static org.mockito.Matchers.anyObject;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
+import static org.apache.hadoop.test.GenericTestUtils.getTestDir;
 
 import java.io.File;
 import java.io.IOException;
@@ -2429,7 +2430,7 @@ public class TestRenameWithSnapshots {
    */
   @Test (timeout=300000)
   public void testDu() throws Exception {
-    File tempFile = File.createTempFile("testDu-", ".tmp");
+    File tempFile = File.createTempFile("testDu-", ".tmp", getTestDir());
     tempFile.deleteOnExit();
 
     final FileSystem localfs = FileSystem.getLocal(conf);
@@ -2539,7 +2540,8 @@ public class TestRenameWithSnapshots {
    */
   @Test (timeout=300000)
   public void testDuMultipleDirs() throws Exception {
-    File tempFile = File.createTempFile("testDuMultipleDirs-", "" + ".tmp");
+    File tempFile = File.createTempFile("testDuMultipleDirs-", ".tmp",
+        getTestDir());
     tempFile.deleteOnExit();
 
     final FileSystem localfs = FileSystem.getLocal(conf);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/285478a7/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotDeletion.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotDeletion.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotDeletion.java
index ca53788..7926e44 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotDeletion.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/snapshot/TestSnapshotDeletion.java
@@ -27,6 +27,7 @@ import java.io.PrintStream;
 import java.security.PrivilegedAction;
 
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.ContentSummary;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FsShell;
 import org.apache.hadoop.fs.Path;
@@ -1232,4 +1233,78 @@ public class TestSnapshotDeletion {
     // make sure bar has been cleaned from inodeMap
     Assert.assertNull(fsdir.getInode(fileId));
   }
+
+  /**
+   * Test for HDFS-11515.
+   * In a scenario where a directory with subdirectories is removed from the
+   * file system after taking a snapshot on one of its ancestors, du command
+   * fails with a ConcurrentModificationException until a new snapshot is taken,
+   * or the old snapshots are removed.
+   * This test is testing this scenario with checks on the space consumed
+   * calculation.
+   *
+   * @throws Exception
+   */
+  @Test(timeout = 180000)
+  public void testDuWithRmdirInSnapshots() throws Exception {
+    final Path parent = new Path("/testDuWithRmdirInSnapshots");
+    final Path snapshotDir = new Path(parent, "snapshotDir");
+    final Path dir1 = new Path(snapshotDir, "d1"); //snapshotDir/d1
+    final Path dir2 = new Path(snapshotDir, "d2"); //snapshotDir/d2
+    final Path dir4 = new Path(dir2, "d4"); //snapshotDir/d2/d4
+    final Path dir3 = new Path(snapshotDir, "d3"); //snapshotDir/d3
+    final Path dir5 = new Path(dir3, "d5"); //snapshotDir/d3/d5
+    final Path aFileOutsideSnapshots = new Path(parent, "aFile");
+    final Path aFileInsideSnapshots = new Path(dir5, "aFile");
+
+    final String snapshotName = "s1";
+    final String snapshotName2 = "s2";
+
+    final long spaceConsumed = BLOCKSIZE * REPLICATION;
+    final long spaceConsumed2 = 2 * spaceConsumed;
+    ContentSummary summary = null;
+
+    DFSTestUtil.createFile(hdfs, aFileOutsideSnapshots,
+        BLOCKSIZE, REPLICATION, 0);
+    summary = hdfs.getContentSummary(parent);
+    assertEquals("Du is wrong even with one file without further ado.",
+        spaceConsumed, summary.getSpaceConsumed());
+
+    hdfs.mkdirs(snapshotDir);
+    hdfs.allowSnapshot(snapshotDir);
+    hdfs.mkdirs(dir1);
+
+    hdfs.createSnapshot(snapshotDir, snapshotName);
+
+    hdfs.mkdirs(dir4);
+    hdfs.mkdirs(dir5);
+    DFSTestUtil.createFile(hdfs, aFileInsideSnapshots,
+        BLOCKSIZE, REPLICATION, 0);
+    summary = hdfs.getContentSummary(parent);
+    assertEquals("Du is wrong with 2 files added to the file system.",
+        spaceConsumed2, summary.getSpaceConsumed());
+
+    hdfs.createSnapshot(snapshotDir, snapshotName2);
+
+    hdfs.delete(dir2, true);
+    hdfs.delete(dir3, true);
+
+    summary = hdfs.getContentSummary(parent);
+    assertEquals("Snapshot file count is not matching expected value.",
+        1, summary.getSnapshotFileCount());
+    assertEquals("Snapshot directory count is not matching expected value.",
+        4, summary.getSnapshotDirectoryCount());
+    assertEquals("Consumed space does not matching expected value.",
+        spaceConsumed, summary.getSnapshotSpaceConsumed());
+    assertEquals("Snapshot length is not matching expected value.",
+        BLOCKSIZE, summary.getSnapshotLength());
+    assertEquals("File count is not matching expected value.",
+        2, summary.getFileCount());
+    assertEquals("Directory count is not matching expected value.",
+        7, summary.getDirectoryCount());
+    assertEquals("Consumed space is not matching expected value.",
+        spaceConsumed2, summary.getSpaceConsumed());
+    assertEquals("Length is not matching expected value.",
+        2 * BLOCKSIZE, summary.getLength());
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[47/50] [abbrv] hadoop git commit: YARN-5797. Add metrics to the node manager for cleaning the PUBLIC and PRIVATE caches. (Chris Trezzo via mingma)

Posted by in...@apache.org.
YARN-5797. Add metrics to the node manager for cleaning the PUBLIC and PRIVATE caches. (Chris Trezzo via mingma)


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

Branch: refs/heads/HDFS-10467
Commit: 66b88300540d2147216a5f8b5e63ed3892625440
Parents: 60c3eda
Author: Ming Ma <mi...@apache.org>
Authored: Thu Apr 6 16:54:43 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../containermanager/ContainerManagerImpl.java  |  8 ++--
 .../localizer/ResourceLocalizationService.java  | 13 ++++++-
 .../nodemanager/metrics/NodeManagerMetrics.java | 41 ++++++++++++++++++++
 .../nodemanager/DummyContainerManager.java      |  5 ++-
 .../TestContainerManagerRecovery.java           | 11 ++++--
 .../localizer/TestLocalCacheCleanup.java        | 17 +++++++-
 .../TestLocalCacheDirectoryManager.java         |  8 +++-
 .../TestResourceLocalizationService.java        | 36 +++++++++--------
 8 files changed, 111 insertions(+), 28 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/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 85dc5fc..d82c728 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
@@ -230,7 +230,8 @@ public class ContainerManagerImpl extends CompositeService implements
     this.metrics = metrics;
 
     rsrcLocalizationSrvc =
-        createResourceLocalizationService(exec, deletionContext, context);
+        createResourceLocalizationService(exec, deletionContext, context,
+            metrics);
     addService(rsrcLocalizationSrvc);
 
     containersLauncher = createContainersLauncher(context, exec);
@@ -477,9 +478,10 @@ public class ContainerManagerImpl extends CompositeService implements
   }
 
   protected ResourceLocalizationService createResourceLocalizationService(
-      ContainerExecutor exec, DeletionService deletionContext, Context context) {
+      ContainerExecutor exec, DeletionService deletionContext,
+      Context nmContext, NodeManagerMetrics nmMetrics) {
     return new ResourceLocalizationService(this.dispatcher, exec,
-        deletionContext, dirsHandler, context);
+        deletionContext, dirsHandler, nmContext, nmMetrics);
   }
 
   protected SharedCacheUploadService createSharedCacheUploaderService() {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.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/localizer/ResourceLocalizationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java
index 37473e3..2208f8f 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/ResourceLocalizationService.java
@@ -131,6 +131,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.even
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.security.LocalizerTokenIdentifier;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.security.LocalizerTokenSecretManager;
 import org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext;
+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.LocalResourceTrackerState;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService.RecoveredLocalizationState;
@@ -165,6 +166,8 @@ public class ResourceLocalizationService extends CompositeService
   private final ScheduledExecutorService cacheCleanup;
   private LocalizerTokenSecretManager secretManager;
   private NMStateStoreService stateStore;
+  @VisibleForTesting
+  final NodeManagerMetrics metrics;
 
   @VisibleForTesting
   LocalResourcesTracker publicRsrc;
@@ -194,7 +197,8 @@ public class ResourceLocalizationService extends CompositeService
 
   public ResourceLocalizationService(Dispatcher dispatcher,
       ContainerExecutor exec, DeletionService delService,
-      LocalDirsHandlerService dirsHandler, Context context) {
+      LocalDirsHandlerService dirsHandler, Context context,
+      NodeManagerMetrics metrics) {
 
     super(ResourceLocalizationService.class.getName());
     this.exec = exec;
@@ -208,6 +212,7 @@ public class ResourceLocalizationService extends CompositeService
           .build());
     this.stateStore = context.getNMStateStore();
     this.nmContext = context;
+    this.metrics = metrics;
   }
 
   FileContext getLocalFileContext(Configuration conf) {
@@ -530,6 +535,12 @@ public class ResourceLocalizationService extends CompositeService
     } else if (LOG.isInfoEnabled()) {
       LOG.info(stats.toString());
     }
+
+    // Update metrics
+    metrics.setCacheSizeBeforeClean(stats.getCacheSizeBeforeClean());
+    metrics.setTotalBytesDeleted(stats.getTotalDelSize());
+    metrics.setPrivateBytesDeleted(stats.getPrivateDelSize());
+    metrics.setPublicBytesDeleted(stats.getPublicDelSize());
     return stats;
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/metrics/NodeManagerMetrics.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/metrics/NodeManagerMetrics.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/metrics/NodeManagerMetrics.java
index 291b488..a59bb5c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/metrics/NodeManagerMetrics.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/metrics/NodeManagerMetrics.java
@@ -69,6 +69,15 @@ public class NodeManagerMetrics {
   @Metric("# of running opportunistic containers")
       MutableGaugeInt runningOpportunisticContainers;
 
+  @Metric("Local cache size (public and private) before clean (Bytes)")
+  MutableGaugeLong cacheSizeBeforeClean;
+  @Metric("# of total bytes deleted from the public and private local cache")
+  MutableGaugeLong totalBytesDeleted;
+  @Metric("# of bytes deleted from the public local cache")
+  MutableGaugeLong publicBytesDeleted;
+  @Metric("# of bytes deleted from the private local cache")
+  MutableGaugeLong privateBytesDeleted;
+
   // CHECKSTYLE:ON:VisibilityModifier
 
   private JvmMetrics jvmMetrics = null;
@@ -215,6 +224,22 @@ public class NodeManagerMetrics {
     this.goodLogDirsDiskUtilizationPerc.set(goodLogDirsDiskUtilizationPerc);
   }
 
+  public void setCacheSizeBeforeClean(long cacheSizeBeforeClean) {
+    this.cacheSizeBeforeClean.set(cacheSizeBeforeClean);
+  }
+
+  public void setTotalBytesDeleted(long totalBytesDeleted) {
+    this.totalBytesDeleted.set(totalBytesDeleted);
+  }
+
+  public void setPublicBytesDeleted(long publicBytesDeleted) {
+    this.publicBytesDeleted.set(publicBytesDeleted);
+  }
+
+  public void setPrivateBytesDeleted(long privateBytesDeleted) {
+    this.privateBytesDeleted.set(privateBytesDeleted);
+  }
+
   public int getRunningContainers() {
     return containersRunning.value();
   }
@@ -275,4 +300,20 @@ public class NodeManagerMetrics {
   public int getRunningOpportunisticContainers() {
     return runningOpportunisticContainers.value();
   }
+
+  public long getCacheSizeBeforeClean() {
+    return this.cacheSizeBeforeClean.value();
+  }
+
+  public long getTotalBytesDeleted() {
+    return this.totalBytesDeleted.value();
+  }
+
+  public long getPublicBytesDeleted() {
+    return this.publicBytesDeleted.value();
+  }
+
+  public long getPrivateBytesDeleted() {
+    return this.privateBytesDeleted.value();
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.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/DummyContainerManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java
index 740ed19..8dc17a6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/DummyContainerManager.java
@@ -73,9 +73,10 @@ public class DummyContainerManager extends ContainerManagerImpl {
   @Override
   @SuppressWarnings("unchecked")
   protected ResourceLocalizationService createResourceLocalizationService(
-      ContainerExecutor exec, DeletionService deletionContext, Context context) {
+      ContainerExecutor exec, DeletionService deletionContext, Context context,
+      NodeManagerMetrics metrics) {
     return new ResourceLocalizationService(super.dispatcher, exec,
-        deletionContext, super.dirsHandler, context) {
+        deletionContext, super.dirsHandler, context, metrics) {
       @Override
       public void handle(LocalizationEvent event) {
         switch (event.getType()) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.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/TestContainerManagerRecovery.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
index ff19e9b..663113d 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManagerRecovery.java
@@ -99,6 +99,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.Contai
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.monitor.ContainersMonitorImpl;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.scheduler.ContainerScheduler;
 
+import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
@@ -699,8 +700,10 @@ public class TestContainerManagerRecovery extends BaseContainerManagerTest {
 
   private ContainerManagerImpl createContainerManager(Context context) {
     final LogHandler logHandler = mock(LogHandler.class);
+    final NodeManagerMetrics metrics = mock(NodeManagerMetrics.class);
     final ResourceLocalizationService rsrcSrv =
-        new ResourceLocalizationService(null, null, null, null, context) {
+        new ResourceLocalizationService(null, null, null, null, context,
+            metrics) {
           @Override
           public void serviceInit(Configuration conf) throws Exception {
           }
@@ -739,8 +742,10 @@ public class TestContainerManagerRecovery extends BaseContainerManagerTest {
           }
 
           @Override
-          protected ResourceLocalizationService createResourceLocalizationService(
-              ContainerExecutor exec, DeletionService deletionContext, Context context) {
+          protected ResourceLocalizationService
+              createResourceLocalizationService(
+              ContainerExecutor exec, DeletionService deletionContext,
+              Context context, NodeManagerMetrics metrics) {
             return rsrcSrv;
           }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheCleanup.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/localizer/TestLocalCacheCleanup.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheCleanup.java
index d6db67a..9f5b23c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheCleanup.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheCleanup.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
 import org.apache.hadoop.yarn.server.nodemanager.Context;
 import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalCacheCleaner.LocalCacheCleanerStats;
+import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.junit.Test;
 
 /**
@@ -80,8 +81,12 @@ public class TestLocalCacheCleanup {
         ((StubbedLocalResourcesTrackerImpl) privateRsrc.get("user2"))
             .getLocalRsrc().size());
     assertEquals(100, stats.getTotalDelSize());
+    assertEquals(100, rls.metrics.getTotalBytesDeleted());
     assertEquals(60, stats.getPublicDelSize());
+    assertEquals(60, rls.metrics.getPublicBytesDeleted());
     assertEquals(40, stats.getPrivateDelSize());
+    assertEquals(40, rls.metrics.getPrivateBytesDeleted());
+    assertEquals(100, rls.metrics.getCacheSizeBeforeClean());
   }
 
   @Test
@@ -105,8 +110,12 @@ public class TestLocalCacheCleanup {
     assertEquals(1, resources.getLocalRsrc().size());
     assertTrue(resources.getLocalRsrc().containsKey(survivor));
     assertEquals(20, stats.getTotalDelSize());
+    assertEquals(20, rls.metrics.getTotalBytesDeleted());
     assertEquals(20, stats.getPublicDelSize());
+    assertEquals(20, rls.metrics.getPublicBytesDeleted());
     assertEquals(0, stats.getPrivateDelSize());
+    assertEquals(0, rls.metrics.getPrivateBytesDeleted());
+    assertEquals(40, rls.metrics.getCacheSizeBeforeClean());
   }
 
   @Test
@@ -164,8 +173,12 @@ public class TestLocalCacheCleanup {
     assertTrue(usr2LocalRsrc.containsKey(usr2Surviver1));
 
     assertEquals(80, stats.getTotalDelSize());
+    assertEquals(80, rls.metrics.getTotalBytesDeleted());
     assertEquals(20, stats.getPublicDelSize());
+    assertEquals(20, rls.metrics.getPublicBytesDeleted());
     assertEquals(60, stats.getPrivateDelSize());
+    assertEquals(60, rls.metrics.getPrivateBytesDeleted());
+    assertEquals(160, rls.metrics.getCacheSizeBeforeClean());
   }
 
   private ResourceLocalizationService createLocService(
@@ -174,8 +187,10 @@ public class TestLocalCacheCleanup {
       long targetCacheSize) {
     Context mockedContext = mock(Context.class);
     when(mockedContext.getNMStateStore()).thenReturn(null);
+    NodeManagerMetrics metrics = NodeManagerMetrics.create();
     ResourceLocalizationService rls =
-        new ResourceLocalizationService(null, null, null, null, mockedContext);
+        new ResourceLocalizationService(null, null, null, null, mockedContext,
+            metrics);
     // We set the following members directly so we don't have to deal with
     // mocking out the service init method.
     rls.publicRsrc = new StubbedLocalResourcesTrackerImpl(null, publicRsrcs);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheDirectoryManager.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/localizer/TestLocalCacheDirectoryManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheDirectoryManager.java
index 82d9a94..95cca2c 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheDirectoryManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestLocalCacheDirectoryManager.java
@@ -18,13 +18,15 @@
 
 package org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer;
 
-import org.junit.Assert;
+import static org.mockito.Mockito.mock;
 
+import org.junit.Assert;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
 import org.apache.hadoop.yarn.server.nodemanager.NodeManager.NMContext;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.LocalCacheDirectoryManager.Directory;
+import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.security.NMContainerTokenSecretManager;
 import org.apache.hadoop.yarn.server.nodemanager.security.NMTokenSecretManagerInNM;
@@ -83,8 +85,10 @@ public class TestLocalCacheDirectoryManager {
           new NMTokenSecretManagerInNM(), null,
           new ApplicationACLsManager(conf), new NMNullStateStoreService(),
             false, conf);
+    NodeManagerMetrics metrics = mock(NodeManagerMetrics.class);
     ResourceLocalizationService service =
-        new ResourceLocalizationService(null, null, null, null, nmContext);
+        new ResourceLocalizationService(null, null, null, null, nmContext,
+            metrics);
     try {
       service.init(conf);
     } catch (Exception e1) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/66b88300/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.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/localizer/TestResourceLocalizationService.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
index 932e94f..5b97e08 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/TestResourceLocalizationService.java
@@ -70,7 +70,6 @@ import org.apache.hadoop.fs.Options;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.container.ContainerState;
 import org.apache.hadoop.yarn.server.nodemanager.executor.LocalizerStartContext;
 import org.junit.Assert;
-
 import org.apache.commons.io.FileUtils;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.AbstractFileSystem;
@@ -141,6 +140,7 @@ import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.even
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.LocalizerResourceRequestEvent;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceFailedLocalizationEvent;
 import org.apache.hadoop.yarn.server.nodemanager.containermanager.localizer.event.ResourceLocalizedEvent;
+import org.apache.hadoop.yarn.server.nodemanager.metrics.NodeManagerMetrics;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMMemoryStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMNullStateStoreService;
 import org.apache.hadoop.yarn.server.nodemanager.recovery.NMStateStoreService;
@@ -171,6 +171,7 @@ public class TestResourceLocalizationService {
   private AbstractFileSystem spylfs;
   private FileContext lfs;
   private NMContext nmContext;
+  private NodeManagerMetrics metrics;
   @BeforeClass
   public static void setupClass() {
     mockServer = mock(Server.class);
@@ -189,6 +190,7 @@ public class TestResourceLocalizationService {
       conf), new NMTokenSecretManagerInNM(), null,
       new ApplicationACLsManager(conf), new NMNullStateStoreService(), false,
           conf);
+    metrics = mock(NodeManagerMetrics.class);
   }
 
   @After
@@ -225,7 +227,7 @@ public class TestResourceLocalizationService {
 
     ResourceLocalizationService locService =
       spy(new ResourceLocalizationService(dispatcher, exec, delService,
-                                          diskhandler, nmContext));
+            diskhandler, nmContext, metrics));
     doReturn(lfs)
       .when(locService).getLocalFileContext(isA(Configuration.class));
     try {
@@ -286,7 +288,7 @@ public class TestResourceLocalizationService {
 
     ResourceLocalizationService locService =
         spy(new ResourceLocalizationService(dispatcher, exec, delService,
-            diskhandler,nmContext));
+            diskhandler, nmContext, metrics));
     doReturn(lfs)
         .when(locService).getLocalFileContext(isA(Configuration.class));
     try {
@@ -357,7 +359,7 @@ public class TestResourceLocalizationService {
 
     ResourceLocalizationService rawService =
       new ResourceLocalizationService(dispatcher, exec, delService,
-                                      dirsHandler, nmContext);
+            dirsHandler, nmContext, metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker(
@@ -757,7 +759,7 @@ public class TestResourceLocalizationService {
 
     ResourceLocalizationService rawService =
         new ResourceLocalizationService(dispatcher, exec, delService,
-        dirsHandlerSpy, nmContext);
+            dirsHandlerSpy, nmContext, metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     try {
@@ -847,7 +849,7 @@ public class TestResourceLocalizationService {
 
     ResourceLocalizationService rawService =
       new ResourceLocalizationService(dispatcher, exec, delService,
-                                      dirsHandler, nmContext);
+            dirsHandler, nmContext, metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
@@ -1143,7 +1145,8 @@ public class TestResourceLocalizationService {
 
     DrainDispatcher dispatcher = getDispatcher(conf);
     ResourceLocalizationService rawService = new ResourceLocalizationService(
-        dispatcher, exec, delService, dirsHandler, nmContext);
+        dispatcher, exec, delService, dirsHandler, nmContext, metrics);
+
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(lfs).when(spyService).getLocalFileContext(isA(Configuration.class));
@@ -1452,7 +1455,7 @@ public class TestResourceLocalizationService {
     try {
       ResourceLocalizationService rawService =
           new ResourceLocalizationService(dispatcher, exec, delService,
-              dirsHandler, spyContext);
+              dirsHandler, spyContext, metrics);
       ResourceLocalizationService spyService = spy(rawService);
       doReturn(mockServer).when(spyService).createServer();
       doReturn(lfs).when(spyService).getLocalFileContext(
@@ -1547,7 +1550,8 @@ public class TestResourceLocalizationService {
     dirsHandler.init(conf);
     // Start resource localization service.
     ResourceLocalizationService rawService = new ResourceLocalizationService(
-        dispatcher, exec, mock(DeletionService.class), dirsHandler, nmContext);
+        dispatcher, exec, mock(DeletionService.class), dirsHandler, nmContext,
+        metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(lfs).when(spyService).
@@ -1666,7 +1670,7 @@ public class TestResourceLocalizationService {
     try {
       ResourceLocalizationService rawService =
           new ResourceLocalizationService(dispatcher, exec, delService,
-                                        dirsHandler, nmContext);
+              dirsHandler, nmContext, metrics);
       ResourceLocalizationService spyService = spy(rawService);
       doReturn(mockServer).when(spyService).createServer();
       doReturn(lfs).when(spyService).getLocalFileContext(
@@ -1775,7 +1779,7 @@ public class TestResourceLocalizationService {
     try {
       ResourceLocalizationService rawService =
           new ResourceLocalizationService(dispatcher, exec, delService,
-            dirsHandlerSpy, nmContext);
+              dirsHandlerSpy, nmContext, metrics);
       ResourceLocalizationService spyService = spy(rawService);
       doReturn(mockServer).when(spyService).createServer();
       doReturn(lfs).when(spyService).getLocalFileContext(
@@ -1907,7 +1911,7 @@ public class TestResourceLocalizationService {
 
       ResourceLocalizationService rls =
           new ResourceLocalizationService(dispatcher1, exec, delService,
-            localDirHandler, nmContext);
+              localDirHandler, nmContext, metrics);
       dispatcher1.register(LocalizationEventType.class, rls);
       rls.init(conf);
 
@@ -2060,7 +2064,7 @@ public class TestResourceLocalizationService {
 
       ResourceLocalizationService rls =
           new ResourceLocalizationService(dispatcher1, exec, delService,
-            localDirHandler, nmContext);
+              localDirHandler, nmContext, metrics);
       dispatcher1.register(LocalizationEventType.class, rls);
       rls.init(conf);
 
@@ -2226,7 +2230,7 @@ public class TestResourceLocalizationService {
       // it as otherwise it will remove requests from pending queue.
       ResourceLocalizationService rawService =
           new ResourceLocalizationService(dispatcher1, exec, delService,
-            dirsHandler, nmContext);
+              dirsHandler, nmContext, metrics);
       ResourceLocalizationService spyService = spy(rawService);
       dispatcher1.register(LocalizationEventType.class, spyService);
       spyService.init(conf);
@@ -2532,7 +2536,7 @@ public class TestResourceLocalizationService {
           new ApplicationACLsManager(conf), stateStore, false, conf);
     ResourceLocalizationService rawService =
       new ResourceLocalizationService(dispatcher, exec, delService,
-                                      dirsHandler, nmContext);
+            dirsHandler, nmContext, metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(mockLocalizerTracker).when(spyService).createLocalizerTracker(
@@ -2596,7 +2600,7 @@ public class TestResourceLocalizationService {
     // setup mocks
     ResourceLocalizationService rawService =
         new ResourceLocalizationService(dispatcher, exec, delService,
-          mockDirsHandler, nmContext);
+            mockDirsHandler, nmContext, metrics);
     ResourceLocalizationService spyService = spy(rawService);
     doReturn(mockServer).when(spyService).createServer();
     doReturn(mockLocallilzerTracker).when(spyService).createLocalizerTracker(


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[15/50] [abbrv] hadoop git commit: HADOOP-14267. Make DistCpOptions immutable. Contributed by Mingliang Liu

Posted by in...@apache.org.
HADOOP-14267. Make DistCpOptions immutable. Contributed by Mingliang Liu


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

Branch: refs/heads/HDFS-10467
Commit: b1543f9cba0bfcf7caf535b49c122a59ade9cdb3
Parents: 3422a3d
Author: Mingliang Liu <li...@apache.org>
Authored: Thu Jun 23 00:21:49 2016 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/tools/CopyListing.java    |  38 +-
 .../java/org/apache/hadoop/tools/DistCp.java    | 106 +--
 .../org/apache/hadoop/tools/DistCpContext.java  | 198 ++++
 .../apache/hadoop/tools/DistCpOptionSwitch.java |   2 +-
 .../org/apache/hadoop/tools/DistCpOptions.java  | 925 +++++++++----------
 .../org/apache/hadoop/tools/DistCpSync.java     |  42 +-
 .../hadoop/tools/FileBasedCopyListing.java      |  12 +-
 .../apache/hadoop/tools/GlobbedCopyListing.java |  17 +-
 .../org/apache/hadoop/tools/OptionsParser.java  | 299 ++----
 .../apache/hadoop/tools/SimpleCopyListing.java  | 115 +--
 .../hadoop/tools/mapred/CopyCommitter.java      |  15 +-
 .../apache/hadoop/tools/util/DistCpUtils.java   |   8 +-
 .../apache/hadoop/tools/TestCopyListing.java    |  51 +-
 .../apache/hadoop/tools/TestDistCpOptions.java  | 500 ++++++++++
 .../org/apache/hadoop/tools/TestDistCpSync.java |  68 +-
 .../hadoop/tools/TestDistCpSyncReverseBase.java |  44 +-
 .../apache/hadoop/tools/TestDistCpViewFs.java   |  10 +-
 .../hadoop/tools/TestFileBasedCopyListing.java  |   9 +-
 .../hadoop/tools/TestGlobbedCopyListing.java    |  11 +-
 .../apache/hadoop/tools/TestIntegration.java    |  20 +-
 .../apache/hadoop/tools/TestOptionsParser.java  |  81 +-
 .../contract/AbstractContractDistCpTest.java    |   6 +-
 .../hadoop/tools/mapred/TestCopyCommitter.java  |  34 +-
 .../mapred/TestUniformSizeInputFormat.java      |  15 +-
 .../mapred/lib/TestDynamicInputFormat.java      |  17 +-
 25 files changed, 1574 insertions(+), 1069 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
index 9ebf9d2..908b558 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
@@ -77,41 +77,41 @@ public abstract class CopyListing extends Configured {
    * TARGET IS DIR        : Key-"/file1", Value-FileStatus(/tmp/file1)  
    *
    * @param pathToListFile - Output file where the listing would be stored
-   * @param options - Input options to distcp
+   * @param distCpContext - distcp context associated with input options
    * @throws IOException - Exception if any
    */
   public final void buildListing(Path pathToListFile,
-                                 DistCpOptions options) throws IOException {
-    validatePaths(options);
-    doBuildListing(pathToListFile, options);
+      DistCpContext distCpContext) throws IOException {
+    validatePaths(distCpContext);
+    doBuildListing(pathToListFile, distCpContext);
     Configuration config = getConf();
 
     config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, pathToListFile.toString());
     config.setLong(DistCpConstants.CONF_LABEL_TOTAL_BYTES_TO_BE_COPIED, getBytesToCopy());
     config.setLong(DistCpConstants.CONF_LABEL_TOTAL_NUMBER_OF_RECORDS, getNumberOfPaths());
 
-    validateFinalListing(pathToListFile, options);
+    validateFinalListing(pathToListFile, distCpContext);
     LOG.info("Number of paths in the copy list: " + this.getNumberOfPaths());
   }
 
   /**
    * Validate input and output paths
    *
-   * @param options - Input options
+   * @param distCpContext - Distcp context
    * @throws InvalidInputException If inputs are invalid
    * @throws IOException any Exception with FS
    */
-  protected abstract void validatePaths(DistCpOptions options)
+  protected abstract void validatePaths(DistCpContext distCpContext)
       throws IOException, InvalidInputException;
 
   /**
    * The interface to be implemented by sub-classes, to create the source/target file listing.
    * @param pathToListFile Path on HDFS where the listing file is written.
-   * @param options Input Options for DistCp (indicating source/target paths.)
+   * @param distCpContext - Distcp context
    * @throws IOException Thrown on failure to create the listing file.
    */
   protected abstract void doBuildListing(Path pathToListFile,
-                                         DistCpOptions options) throws IOException;
+      DistCpContext distCpContext) throws IOException;
 
   /**
    * Return the total bytes that distCp should copy for the source paths
@@ -135,17 +135,17 @@ public abstract class CopyListing extends Configured {
    * If preserving XAttrs, checks that file system can support XAttrs.
    *
    * @param pathToListFile - path listing build by doBuildListing
-   * @param options - Input options to distcp
+   * @param context - Distcp context with associated input options
    * @throws IOException - Any issues while checking for duplicates and throws
    * @throws DuplicateFileException - if there are duplicates
    */
-  private void validateFinalListing(Path pathToListFile, DistCpOptions options)
+  private void validateFinalListing(Path pathToListFile, DistCpContext context)
       throws DuplicateFileException, IOException {
 
     Configuration config = getConf();
     FileSystem fs = pathToListFile.getFileSystem(config);
 
-    final boolean splitLargeFile = options.splitLargeFile();
+    final boolean splitLargeFile = context.splitLargeFile();
 
     // When splitLargeFile is enabled, we don't randomize the copylist
     // earlier, so we don't do the sorting here. For a file that has
@@ -188,7 +188,7 @@ public abstract class CopyListing extends Configured {
           }
         }
         reader.getCurrentValue(lastFileStatus);
-        if (options.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
+        if (context.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
           FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config);
           URI lastFsUri = lastFs.getUri();
           if (!aclSupportCheckFsSet.contains(lastFsUri)) {
@@ -196,7 +196,7 @@ public abstract class CopyListing extends Configured {
             aclSupportCheckFsSet.add(lastFsUri);
           }
         }
-        if (options.shouldPreserve(DistCpOptions.FileAttribute.XATTR)) {
+        if (context.shouldPreserve(DistCpOptions.FileAttribute.XATTR)) {
           FileSystem lastFs = lastFileStatus.getPath().getFileSystem(config);
           URI lastFsUri = lastFs.getUri();
           if (!xAttrSupportCheckFsSet.contains(lastFsUri)) {
@@ -210,7 +210,7 @@ public abstract class CopyListing extends Configured {
           lastChunkOffset = lastFileStatus.getChunkOffset();
           lastChunkLength = lastFileStatus.getChunkLength();
         }
-        if (options.shouldUseDiff() && LOG.isDebugEnabled()) {
+        if (context.shouldUseDiff() && LOG.isDebugEnabled()) {
           LOG.debug("Copy list entry " + idx + ": " +
                   lastFileStatus.getPath().toUri().getPath());
           idx++;
@@ -253,14 +253,12 @@ public abstract class CopyListing extends Configured {
    * Public Factory method with which the appropriate CopyListing implementation may be retrieved.
    * @param configuration The input configuration.
    * @param credentials Credentials object on which the FS delegation tokens are cached
-   * @param options The input Options, to help choose the appropriate CopyListing Implementation.
+   * @param context Distcp context with associated input options
    * @return An instance of the appropriate CopyListing implementation.
    * @throws java.io.IOException - Exception if any
    */
   public static CopyListing getCopyListing(Configuration configuration,
-                                           Credentials credentials,
-                                           DistCpOptions options)
-      throws IOException {
+      Credentials credentials, DistCpContext context) throws IOException {
     String copyListingClassName = configuration.get(DistCpConstants.
         CONF_LABEL_COPY_LISTING_CLASS, "");
     Class<? extends CopyListing> copyListingClass;
@@ -270,7 +268,7 @@ public abstract class CopyListing extends Configured {
             CONF_LABEL_COPY_LISTING_CLASS, GlobbedCopyListing.class,
             CopyListing.class);
       } else {
-        if (options.getSourceFileListing() == null) {
+        if (context.getSourceFileListing() == null) {
             copyListingClass = GlobbedCopyListing.class;
         } else {
             copyListingClass = FileBasedCopyListing.class;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
index 8c2fa24..df9c328 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
@@ -21,6 +21,7 @@ package org.apache.hadoop.tools;
 import java.io.IOException;
 import java.util.Random;
 
+import com.google.common.base.Preconditions;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience;
@@ -35,7 +36,6 @@ import org.apache.hadoop.mapreduce.Cluster;
 import org.apache.hadoop.mapreduce.Job;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobSubmissionFiles;
-import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.CopyListing.*;
 import org.apache.hadoop.tools.mapred.CopyMapper;
 import org.apache.hadoop.tools.mapred.CopyOutputFormat;
@@ -66,7 +66,9 @@ public class DistCp extends Configured implements Tool {
 
   static final Log LOG = LogFactory.getLog(DistCp.class);
 
-  private DistCpOptions inputOptions;
+  @VisibleForTesting
+  DistCpContext context;
+
   private Path metaFolder;
 
   private static final String PREFIX = "_distcp";
@@ -79,15 +81,14 @@ public class DistCp extends Configured implements Tool {
   private FileSystem jobFS;
 
   private void prepareFileListing(Job job) throws Exception {
-    if (inputOptions.shouldUseSnapshotDiff()) {
+    if (context.shouldUseSnapshotDiff()) {
       // When "-diff" or "-rdiff" is passed, do sync() first, then
       // create copyListing based on snapshot diff.
-      DistCpSync distCpSync = new DistCpSync(inputOptions, getConf());
+      DistCpSync distCpSync = new DistCpSync(context, getConf());
       if (distCpSync.sync()) {
         createInputFileListingWithDiff(job, distCpSync);
       } else {
-        throw new Exception("DistCp sync failed, input options: "
-            + inputOptions);
+        throw new Exception("DistCp sync failed, input options: " + context);
       }
     } else {
       // When no "-diff" or "-rdiff" is passed, create copyListing
@@ -99,16 +100,19 @@ public class DistCp extends Configured implements Tool {
   /**
    * Public Constructor. Creates DistCp object with specified input-parameters.
    * (E.g. source-paths, target-location, etc.)
-   * @param inputOptions Options (indicating source-paths, target-location.)
-   * @param configuration The Hadoop configuration against which the Copy-mapper must run.
+   * @param configuration configuration against which the Copy-mapper must run
+   * @param inputOptions Immutable options
    * @throws Exception
    */
-  public DistCp(Configuration configuration, DistCpOptions inputOptions) throws Exception {
+  public DistCp(Configuration configuration, DistCpOptions inputOptions)
+      throws Exception {
     Configuration config = new Configuration(configuration);
     config.addResource(DISTCP_DEFAULT_XML);
     config.addResource(DISTCP_SITE_XML);
     setConf(config);
-    this.inputOptions = inputOptions;
+    if (inputOptions != null) {
+      this.context = new DistCpContext(inputOptions);
+    }
     this.metaFolder   = createMetaFolderPath();
   }
 
@@ -134,10 +138,10 @@ public class DistCp extends Configured implements Tool {
     }
     
     try {
-      inputOptions = (OptionsParser.parse(argv));
-      setOptionsForSplitLargeFile();
+      context = new DistCpContext(OptionsParser.parse(argv));
+      checkSplitLargeFile();
       setTargetPathExists();
-      LOG.info("Input Options: " + inputOptions);
+      LOG.info("Input Options: " + context);
     } catch (Throwable e) {
       LOG.error("Invalid arguments: ", e);
       System.err.println("Invalid arguments: " + e.getMessage());
@@ -173,9 +177,11 @@ public class DistCp extends Configured implements Tool {
    * @throws Exception
    */
   public Job execute() throws Exception {
+    Preconditions.checkState(context != null,
+        "The DistCpContext should have been created before running DistCp!");
     Job job = createAndSubmitJob();
 
-    if (inputOptions.shouldBlock()) {
+    if (context.shouldBlock()) {
       waitForJobCompletion(job);
     }
     return job;
@@ -186,7 +192,7 @@ public class DistCp extends Configured implements Tool {
    * @return The mapreduce job object that has been submitted
    */
   public Job createAndSubmitJob() throws Exception {
-    assert inputOptions != null;
+    assert context != null;
     assert getConf() != null;
     Job job = null;
     try {
@@ -230,53 +236,36 @@ public class DistCp extends Configured implements Tool {
    * for the benefit of CopyCommitter
    */
   private void setTargetPathExists() throws IOException {
-    Path target = inputOptions.getTargetPath();
+    Path target = context.getTargetPath();
     FileSystem targetFS = target.getFileSystem(getConf());
     boolean targetExists = targetFS.exists(target);
-    inputOptions.setTargetPathExists(targetExists);
+    context.setTargetPathExists(targetExists);
     getConf().setBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, 
         targetExists);
   }
 
   /**
-   * Check if concat is supported by fs.
-   * Throws UnsupportedOperationException if not.
+   * Check splitting large files is supported and populate configs.
    */
-  private void checkConcatSupport(FileSystem fs) {
+  private void checkSplitLargeFile() throws IOException {
+    if (!context.splitLargeFile()) {
+      return;
+    }
+
+    final Path target = context.getTargetPath();
+    final FileSystem targetFS = target.getFileSystem(getConf());
     try {
       Path[] src = null;
       Path tgt = null;
-      fs.concat(tgt, src);
+      targetFS.concat(tgt, src);
     } catch (UnsupportedOperationException use) {
       throw new UnsupportedOperationException(
           DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() +
-          " is not supported since the target file system doesn't" +
-          " support concat.", use);
+              " is not supported since the target file system doesn't" +
+              " support concat.", use);
     } catch (Exception e) {
       // Ignore other exception
     }
-  }
-
-  /**
-   * Set up needed options for splitting large files.
-   */
-  private void setOptionsForSplitLargeFile() throws IOException {
-    if (!inputOptions.splitLargeFile()) {
-      return;
-    }
-    Path target = inputOptions.getTargetPath();
-    FileSystem targetFS = target.getFileSystem(getConf());
-    checkConcatSupport(targetFS);
-
-    LOG.info("Enabling preserving blocksize since "
-        + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " is passed.");
-    inputOptions.preserve(FileAttribute.BLOCKSIZE);
-
-    LOG.info("Set " +
-        DistCpOptionSwitch.APPEND.getSwitch()
-        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
-        + " is passed.");
-    inputOptions.setAppend(false);
 
     LOG.info("Set " +
         DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES
@@ -286,7 +275,6 @@ public class DistCp extends Configured implements Tool {
         DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES, false);
   }
 
-
   /**
    * Create Job object for submitting it, with all the configuration
    *
@@ -300,7 +288,7 @@ public class DistCp extends Configured implements Tool {
       jobName += ": " + userChosenName;
     Job job = Job.getInstance(getConf());
     job.setJobName(jobName);
-    job.setInputFormatClass(DistCpUtils.getStrategy(getConf(), inputOptions));
+    job.setInputFormatClass(DistCpUtils.getStrategy(getConf(), context));
     job.setJarByClass(CopyMapper.class);
     configureOutputFormat(job);
 
@@ -311,9 +299,9 @@ public class DistCp extends Configured implements Tool {
     job.setOutputFormatClass(CopyOutputFormat.class);
     job.getConfiguration().set(JobContext.MAP_SPECULATIVE, "false");
     job.getConfiguration().set(JobContext.NUM_MAPS,
-                  String.valueOf(inputOptions.getMaxMaps()));
+                  String.valueOf(context.getMaxMaps()));
 
-    inputOptions.appendToConf(job.getConfiguration());
+    context.appendToConf(job.getConfiguration());
     return job;
   }
 
@@ -325,18 +313,20 @@ public class DistCp extends Configured implements Tool {
    */
   private void configureOutputFormat(Job job) throws IOException {
     final Configuration configuration = job.getConfiguration();
-    Path targetPath = inputOptions.getTargetPath();
+    Path targetPath = context.getTargetPath();
     FileSystem targetFS = targetPath.getFileSystem(configuration);
     targetPath = targetPath.makeQualified(targetFS.getUri(),
                                           targetFS.getWorkingDirectory());
-    if (inputOptions.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
+    if (context.shouldPreserve(
+        DistCpOptions.FileAttribute.ACL)) {
       DistCpUtils.checkFileSystemAclSupport(targetFS);
     }
-    if (inputOptions.shouldPreserve(DistCpOptions.FileAttribute.XATTR)) {
+    if (context.shouldPreserve(
+        DistCpOptions.FileAttribute.XATTR)) {
       DistCpUtils.checkFileSystemXAttrSupport(targetFS);
     }
-    if (inputOptions.shouldAtomicCommit()) {
-      Path workDir = inputOptions.getAtomicWorkPath();
+    if (context.shouldAtomicCommit()) {
+      Path workDir = context.getAtomicWorkPath();
       if (workDir == null) {
         workDir = targetPath.getParent();
       }
@@ -353,7 +343,7 @@ public class DistCp extends Configured implements Tool {
     }
     CopyOutputFormat.setCommitDirectory(job, targetPath);
 
-    Path logPath = inputOptions.getLogPath();
+    Path logPath = context.getLogPath();
     if (logPath == null) {
       logPath = new Path(metaFolder, "_logs");
     } else {
@@ -374,8 +364,8 @@ public class DistCp extends Configured implements Tool {
   protected Path createInputFileListing(Job job) throws IOException {
     Path fileListingPath = getFileListingPath();
     CopyListing copyListing = CopyListing.getCopyListing(job.getConfiguration(),
-        job.getCredentials(), inputOptions);
-    copyListing.buildListing(fileListingPath, inputOptions);
+        job.getCredentials(), context);
+    copyListing.buildListing(fileListingPath, context);
     return fileListingPath;
   }
 
@@ -391,7 +381,7 @@ public class DistCp extends Configured implements Tool {
     Path fileListingPath = getFileListingPath();
     CopyListing copyListing = new SimpleCopyListing(job.getConfiguration(),
         job.getCredentials(), distCpSync);
-    copyListing.buildListing(fileListingPath, inputOptions);
+    copyListing.buildListing(fileListingPath, context);
     return fileListingPath;
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpContext.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpContext.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpContext.java
new file mode 100644
index 0000000..c34005e
--- /dev/null
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpContext.java
@@ -0,0 +1,198 @@
+/**
+ * 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.tools;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This is the context of the distcp at runtime.
+ *
+ * It has the immutable {@link DistCpOptions} and mutable runtime status.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Evolving
+public class DistCpContext {
+  private final DistCpOptions options;
+
+  /** The source paths can be set at runtime via snapshots. */
+  private List<Path> sourcePaths;
+
+  /** This is a derived field, it's initialized in the beginning of distcp. */
+  private boolean targetPathExists = true;
+
+  /** Indicate that raw.* xattrs should be preserved if true. */
+  private boolean preserveRawXattrs = false;
+
+  public DistCpContext(DistCpOptions options) {
+    this.options = options;
+    this.sourcePaths = options.getSourcePaths();
+  }
+
+  public void setSourcePaths(List<Path> sourcePaths) {
+    this.sourcePaths = sourcePaths;
+  }
+
+  /**
+   * @return the sourcePaths. Please note this method does not directly delegate
+   * to the {@link #options}.
+   */
+  public List<Path> getSourcePaths() {
+    return sourcePaths;
+  }
+
+  public Path getSourceFileListing() {
+    return options.getSourceFileListing();
+  }
+
+  public Path getTargetPath() {
+    return options.getTargetPath();
+  }
+
+  public boolean shouldAtomicCommit() {
+    return options.shouldAtomicCommit();
+  }
+
+  public boolean shouldSyncFolder() {
+    return options.shouldSyncFolder();
+  }
+
+  public boolean shouldDeleteMissing() {
+    return options.shouldDeleteMissing();
+  }
+
+  public boolean shouldIgnoreFailures() {
+    return options.shouldIgnoreFailures();
+  }
+
+  public boolean shouldOverwrite() {
+    return options.shouldOverwrite();
+  }
+
+  public boolean shouldAppend() {
+    return options.shouldAppend();
+  }
+
+  public boolean shouldSkipCRC() {
+    return options.shouldSkipCRC();
+  }
+
+  public boolean shouldBlock() {
+    return options.shouldBlock();
+  }
+
+  public boolean shouldUseDiff() {
+    return options.shouldUseDiff();
+  }
+
+  public boolean shouldUseRdiff() {
+    return options.shouldUseRdiff();
+  }
+
+  public boolean shouldUseSnapshotDiff() {
+    return options.shouldUseSnapshotDiff();
+  }
+
+  public String getFromSnapshot() {
+    return options.getFromSnapshot();
+  }
+
+  public String getToSnapshot() {
+    return options.getToSnapshot();
+  }
+
+  public final String getFiltersFile() {
+    return options.getFiltersFile();
+  }
+
+  public int getNumListstatusThreads() {
+    return options.getNumListstatusThreads();
+  }
+
+  public int getMaxMaps() {
+    return options.getMaxMaps();
+  }
+
+  public float getMapBandwidth() {
+    return options.getMapBandwidth();
+  }
+
+  public Set<FileAttribute> getPreserveAttributes() {
+    return options.getPreserveAttributes();
+  }
+
+  public boolean shouldPreserve(FileAttribute attribute) {
+    return options.shouldPreserve(attribute);
+  }
+
+  public boolean shouldPreserveRawXattrs() {
+    return preserveRawXattrs;
+  }
+
+  public void setPreserveRawXattrs(boolean preserveRawXattrs) {
+    this.preserveRawXattrs = preserveRawXattrs;
+  }
+
+  public Path getAtomicWorkPath() {
+    return options.getAtomicWorkPath();
+  }
+
+  public Path getLogPath() {
+    return options.getLogPath();
+  }
+
+  public String getCopyStrategy() {
+    return options.getCopyStrategy();
+  }
+
+  public int getBlocksPerChunk() {
+    return options.getBlocksPerChunk();
+  }
+
+  public final boolean splitLargeFile() {
+    return options.getBlocksPerChunk() > 0;
+  }
+
+  public void setTargetPathExists(boolean targetPathExists) {
+    this.targetPathExists = targetPathExists;
+  }
+
+  public boolean isTargetPathExists() {
+    return targetPathExists;
+  }
+
+  public void appendToConf(Configuration conf) {
+    options.appendToConf(conf);
+  }
+
+  @Override
+  public String toString() {
+    return options.toString() +
+        ", sourcePaths=" + sourcePaths +
+        ", targetPathExists=" + targetPathExists +
+        ", preserveRawXattrs" + preserveRawXattrs;
+  }
+
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
index ced9b54..81abb7d 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
@@ -81,7 +81,7 @@ public enum DistCpOptionSwitch {
   NUM_LISTSTATUS_THREADS(DistCpConstants.CONF_LABEL_LISTSTATUS_THREADS,
       new Option("numListstatusThreads", true, "Number of threads to " +
           "use for building file listing (max " +
-          DistCpOptions.maxNumListstatusThreads + ").")),
+          DistCpOptions.MAX_NUM_LISTSTATUS_THREADS + ").")),
   /**
    * Max number of maps to use during copy. DistCp will split work
    * as equally as possible among these maps

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/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 9822d83..97ae0c4 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
@@ -18,43 +18,88 @@
 
 package org.apache.hadoop.tools;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
 import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.tools.util.DistCpUtils;
 
+import java.util.Collections;
 import java.util.EnumSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.NoSuchElementException;
+import java.util.Set;
 
 /**
  * The Options class encapsulates all DistCp options.
- * These may be set from command-line (via the OptionsParser)
- * or may be set manually.
+ *
+ * When you add a new option, please:
+ *  - Add the field along with javadoc in DistCpOptions and its Builder
+ *  - Add setter method in the {@link Builder} class
+ *
+ * This class is immutable.
  */
-public class DistCpOptions {
-
-  private boolean atomicCommit = false;
-  private boolean syncFolder = false;
-  private boolean deleteMissing = false;
-  private boolean ignoreFailures = false;
-  private boolean overwrite = false;
-  private boolean append = false;
-  private boolean skipCRC = false;
-  private boolean blocking = true;
+public final class DistCpOptions {
+  private static final Logger LOG = LoggerFactory.getLogger(Builder.class);
+  public static final int MAX_NUM_LISTSTATUS_THREADS = 40;
+
+  /** File path (hdfs:// or file://) that contains the list of actual files to
+   * copy.
+   */
+  private final Path sourceFileListing;
+
+  /** List of source-paths (including wildcards) to be copied to target. */
+  private final List<Path> sourcePaths;
+
+  /** Destination path for the dist-copy. */
+  private final Path targetPath;
+
+  /** Whether data need to be committed automatically. */
+  private final boolean atomicCommit;
+
+  /** the work path for atomic commit. If null, the work
+   * path would be parentOf(targetPath) + "/._WIP_" + nameOf(targetPath). */
+  private final Path atomicWorkPath;
+
+  /** Whether source and target folder contents be sync'ed up. */
+  private final boolean syncFolder;
+
+  /** Whether files only present in target should be deleted. */
+  private boolean deleteMissing;
+
+  /** Whether failures during copy be ignored. */
+  private final boolean ignoreFailures;
+
+  /** Whether files should always be overwritten on target. */
+  private final boolean overwrite;
+
+  /** Whether we want to append new data to target files. This is valid only
+   * with update option and CRC is not skipped. */
+  private final boolean append;
+
+  /** Whether checksum comparison should be skipped while determining if source
+   * and destination files are identical. */
+  private final boolean skipCRC;
+
+  /** Whether to run blocking or non-blocking. */
+  private final boolean blocking;
+
   // When "-diff s1 s2 src tgt" is passed, apply forward snapshot diff (from s1
   // to s2) of source cluster to the target cluster to sync target cluster with
   // the source cluster. Referred to as "Fdiff" in the code.
   // It's required that s2 is newer than s1.
-  private boolean useDiff = false;
+  private final boolean useDiff;
 
   // When "-rdiff s2 s1 src tgt" is passed, apply reversed snapshot diff (from
   // s2 to s1) of target cluster to the target cluster, so to make target
   // cluster go back to s1. Referred to as "Rdiff" in the code.
   // It's required that s2 is newer than s1, and src and tgt have exact same
   // content at their s1, if src is not the same as tgt.
-  private boolean useRdiff = false;
+  private final boolean useRdiff;
 
   // For both -diff and -rdiff, given the example command line switches, two
   // steps are taken:
@@ -66,44 +111,53 @@ public class DistCpOptions {
   //          could be the tgt itself (HDFS-9820).
   //
 
-  public static final int maxNumListstatusThreads = 40;
-  private int numListstatusThreads = 0;  // Indicates that flag is not set.
-  private int maxMaps = DistCpConstants.DEFAULT_MAPS;
-  private float mapBandwidth = 0;  // Indicates that we should use the default.
-
-  private String copyStrategy = DistCpConstants.UNIFORMSIZE;
+  private final String fromSnapshot;
+  private final String toSnapshot;
 
-  private EnumSet<FileAttribute> preserveStatus = EnumSet.noneOf(FileAttribute.class);
+  /** The path to a file containing a list of paths to filter out of copy. */
+  private final String filtersFile;
 
-  private boolean preserveRawXattrs;
+  /** Path where output logs are stored. If not specified, it will use the
+   * default value JobStagingDir/_logs and delete upon job completion. */
+  private final Path logPath;
 
-  private Path atomicWorkPath;
+  /** Set the copy strategy to use. Should map to a strategy implementation
+   * in distp-default.xml. */
+  private final String copyStrategy;
 
-  private Path logPath;
+  /** per map bandwidth in MB. */
+  private final float mapBandwidth;
 
-  private Path sourceFileListing;
-  private List<Path> sourcePaths;
+  /** The number of threads to use for listStatus. We allow max
+   * {@link #MAX_NUM_LISTSTATUS_THREADS} threads. Setting numThreads to zero
+   * signify we should use the value from conf properties. */
+  private final int numListstatusThreads;
 
-  private String fromSnapshot;
-  private String toSnapshot;
+  /** The max number of maps to use for copy. */
+  private final int maxMaps;
 
-  private Path targetPath;
-
-  /**
-   * The path to a file containing a list of paths to filter out of the copy.
-   */
-  private String filtersFile;
-
-  // targetPathExist is a derived field, it's initialized in the
-  // beginning of distcp.
-  private boolean targetPathExists = true;
+  /** File attributes that need to be preserved. */
+  private final EnumSet<FileAttribute> preserveStatus;
 
   // Size of chunk in number of blocks when splitting large file into chunks
   // to copy in parallel. Default is 0 and file are not splitted.
-  private int blocksPerChunk = 0;
+  private final int blocksPerChunk;
 
-  public static enum FileAttribute{
-    REPLICATION, BLOCKSIZE, USER, GROUP, PERMISSION, CHECKSUMTYPE, ACL, XATTR, TIMES;
+  /**
+   * File attributes for preserve.
+   *
+   * Each enum entry uses the first char as its symbol.
+   */
+  public enum FileAttribute {
+    REPLICATION,    // R
+    BLOCKSIZE,      // B
+    USER,           // U
+    GROUP,          // G
+    PERMISSION,     // P
+    CHECKSUMTYPE,   // C
+    ACL,            // A
+    XATTR,          // X
+    TIMES;          // T
 
     public static FileAttribute getAttribute(char symbol) {
       for (FileAttribute attribute : values()) {
@@ -115,187 +169,86 @@ public class DistCpOptions {
     }
   }
 
-  /**
-   * Constructor, to initialize source/target paths.
-   * @param sourcePaths List of source-paths (including wildcards)
-   *                     to be copied to target.
-   * @param targetPath Destination path for the dist-copy.
-   */
-  public DistCpOptions(List<Path> sourcePaths, Path targetPath) {
-    assert sourcePaths != null && !sourcePaths.isEmpty() : "Invalid source paths";
-    assert targetPath != null : "Invalid Target path";
+  private DistCpOptions(Builder builder) {
+    this.sourceFileListing = builder.sourceFileListing;
+    this.sourcePaths = builder.sourcePaths;
+    this.targetPath = builder.targetPath;
+
+    this.atomicCommit = builder.atomicCommit;
+    this.atomicWorkPath = builder.atomicWorkPath;
+    this.syncFolder = builder.syncFolder;
+    this.deleteMissing = builder.deleteMissing;
+    this.ignoreFailures = builder.ignoreFailures;
+    this.overwrite = builder.overwrite;
+    this.append = builder.append;
+    this.skipCRC = builder.skipCRC;
+    this.blocking = builder.blocking;
+
+    this.useDiff = builder.useDiff;
+    this.useRdiff = builder.useRdiff;
+    this.fromSnapshot = builder.fromSnapshot;
+    this.toSnapshot = builder.toSnapshot;
 
-    this.sourcePaths = sourcePaths;
-    this.targetPath = targetPath;
+    this.filtersFile = builder.filtersFile;
+    this.logPath = builder.logPath;
+    this.copyStrategy = builder.copyStrategy;
+
+    this.mapBandwidth = builder.mapBandwidth;
+    this.numListstatusThreads = builder.numListstatusThreads;
+    this.maxMaps = builder.maxMaps;
+
+    this.preserveStatus = builder.preserveStatus;
+
+    this.blocksPerChunk = builder.blocksPerChunk;
   }
 
-  /**
-   * Constructor, to initialize source/target paths.
-   * @param sourceFileListing File containing list of source paths
-   * @param targetPath Destination path for the dist-copy.
-   */
-  public DistCpOptions(Path sourceFileListing, Path targetPath) {
-    assert sourceFileListing != null : "Invalid source paths";
-    assert targetPath != null : "Invalid Target path";
+  public Path getSourceFileListing() {
+    return sourceFileListing;
+  }
 
-    this.sourceFileListing = sourceFileListing;
-    this.targetPath = targetPath;
+  public List<Path> getSourcePaths() {
+    return sourcePaths == null ?
+        null : Collections.unmodifiableList(sourcePaths);
   }
 
-  /**
-   * Copy constructor.
-   * @param that DistCpOptions being copied from.
-   */
-  public DistCpOptions(DistCpOptions that) {
-    if (this != that && that != null) {
-      this.atomicCommit = that.atomicCommit;
-      this.syncFolder = that.syncFolder;
-      this.deleteMissing = that.deleteMissing;
-      this.ignoreFailures = that.ignoreFailures;
-      this.overwrite = that.overwrite;
-      this.skipCRC = that.skipCRC;
-      this.blocking = that.blocking;
-      this.useDiff = that.useDiff;
-      this.useRdiff = that.useRdiff;
-      this.numListstatusThreads = that.numListstatusThreads;
-      this.maxMaps = that.maxMaps;
-      this.mapBandwidth = that.mapBandwidth;
-      this.copyStrategy = that.copyStrategy;
-      this.preserveStatus = that.preserveStatus;
-      this.preserveRawXattrs = that.preserveRawXattrs;
-      this.atomicWorkPath = that.getAtomicWorkPath();
-      this.logPath = that.getLogPath();
-      this.sourceFileListing = that.getSourceFileListing();
-      this.sourcePaths = that.getSourcePaths();
-      this.targetPath = that.getTargetPath();
-      this.targetPathExists = that.getTargetPathExists();
-      this.filtersFile = that.getFiltersFile();
-      this.blocksPerChunk = that.blocksPerChunk;
-    }
+  public Path getTargetPath() {
+    return targetPath;
   }
 
-  /**
-   * Should the data be committed atomically?
-   *
-   * @return true if data should be committed automically. false otherwise
-   */
   public boolean shouldAtomicCommit() {
     return atomicCommit;
   }
 
-  /**
-   * Set if data need to be committed automatically
-   *
-   * @param atomicCommit - boolean switch
-   */
-  public void setAtomicCommit(boolean atomicCommit) {
-    this.atomicCommit = atomicCommit;
+  public Path getAtomicWorkPath() {
+    return atomicWorkPath;
   }
 
-  /**
-   * Should the data be sync'ed between source and target paths?
-   *
-   * @return true if data should be sync'ed up. false otherwise
-   */
   public boolean shouldSyncFolder() {
     return syncFolder;
   }
 
-  /**
-   * Set if source and target folder contents be sync'ed up
-   *
-   * @param syncFolder - boolean switch
-   */
-  public void setSyncFolder(boolean syncFolder) {
-    this.syncFolder = syncFolder;
-  }
-
-  /**
-   * Should target files missing in source should be deleted?
-   *
-   * @return true if zoombie target files to be removed. false otherwise
-   */
   public boolean shouldDeleteMissing() {
     return deleteMissing;
   }
 
-  /**
-   * Set if files only present in target should be deleted
-   *
-   * @param deleteMissing - boolean switch
-   */
-  public void setDeleteMissing(boolean deleteMissing) {
-    this.deleteMissing = deleteMissing;
-  }
-
-  /**
-   * Should failures be logged and ignored during copy?
-   *
-   * @return true if failures are to be logged and ignored. false otherwise
-   */
   public boolean shouldIgnoreFailures() {
     return ignoreFailures;
   }
 
-  /**
-   * Set if failures during copy be ignored
-   *
-   * @param ignoreFailures - boolean switch
-   */
-  public void setIgnoreFailures(boolean ignoreFailures) {
-    this.ignoreFailures = ignoreFailures;
-  }
-
-  /**
-   * Should DistCp be running in blocking mode
-   *
-   * @return true if should run in blocking, false otherwise
-   */
-  public boolean shouldBlock() {
-    return blocking;
-  }
-
-  /**
-   * Set if Disctp should run blocking or non-blocking
-   *
-   * @param blocking - boolean switch
-   */
-  public void setBlocking(boolean blocking) {
-    this.blocking = blocking;
-  }
-
-  /**
-   * Should files be overwritten always?
-   *
-   * @return true if files in target that may exist before distcp, should always
-   *         be overwritten. false otherwise
-   */
   public boolean shouldOverwrite() {
     return overwrite;
   }
 
-  /**
-   * Set if files should always be overwritten on target
-   *
-   * @param overwrite - boolean switch
-   */
-  public void setOverwrite(boolean overwrite) {
-    this.overwrite = overwrite;
-  }
-
-  /**
-   * @return whether we can append new data to target files
-   */
   public boolean shouldAppend() {
     return append;
   }
 
-  /**
-   * Set if we want to append new data to target files. This is valid only with
-   * update option and CRC is not skipped.
-   */
-  public void setAppend(boolean append) {
-    this.append = append;
+  public boolean shouldSkipCRC() {
+    return skipCRC;
+  }
+
+  public boolean shouldBlock() {
+    return blocking;
   }
 
   public boolean shouldUseDiff() {
@@ -318,104 +271,34 @@ public class DistCpOptions {
     return this.toSnapshot;
   }
 
-  public void setUseDiff(String fromSS, String toSS) {
-    this.useDiff = true;
-    this.fromSnapshot = fromSS;
-    this.toSnapshot = toSS;
-  }
-
-  public void setUseRdiff(String fromSS, String toSS) {
-    this.useRdiff = true;
-    this.fromSnapshot = fromSS;
-    this.toSnapshot = toSS;
+  public String getFiltersFile() {
+    return filtersFile;
   }
 
-  /**
-   * Should CRC/checksum check be skipped while checking files are identical
-   *
-   * @return true if checksum check should be skipped while checking files are
-   *         identical. false otherwise
-   */
-  public boolean shouldSkipCRC() {
-    return skipCRC;
+  public Path getLogPath() {
+    return logPath;
   }
 
-  /**
-   * Set if checksum comparison should be skipped while determining if
-   * source and destination files are identical
-   *
-   * @param skipCRC - boolean switch
-   */
-  public void setSkipCRC(boolean skipCRC) {
-    this.skipCRC = skipCRC;
+  public String getCopyStrategy() {
+    return copyStrategy;
   }
 
-  /** Get the number of threads to use for listStatus
-   *
-   * @return Number of threads to do listStatus
-   */
   public int getNumListstatusThreads() {
     return numListstatusThreads;
   }
 
-  /** Set the number of threads to use for listStatus. We allow max 40
-   *  threads. Setting numThreads to zero signify we should use the value
-   *  from conf properties.
-   *
-   * @param numThreads - Number of threads
-   */
-  public void setNumListstatusThreads(int numThreads) {
-    if (numThreads > maxNumListstatusThreads) {
-      this.numListstatusThreads = maxNumListstatusThreads;
-    } else if (numThreads > 0) {
-      this.numListstatusThreads = numThreads;
-    } else {
-      this.numListstatusThreads = 0;
-    }
-  }
-
-  /** Get the max number of maps to use for this copy
-   *
-   * @return Max number of maps
-   */
   public int getMaxMaps() {
     return maxMaps;
   }
 
-  /**
-   * Set the max number of maps to use for copy
-   *
-   * @param maxMaps - Number of maps
-   */
-  public void setMaxMaps(int maxMaps) {
-    this.maxMaps = Math.max(maxMaps, 1);
-  }
-
-  /** Get the map bandwidth in MB
-   *
-   * @return Bandwidth in MB
-   */
   public float getMapBandwidth() {
     return mapBandwidth;
   }
 
-  /**
-   * Set per map bandwidth
-   *
-   * @param mapBandwidth - per map bandwidth
-   */
-  public void setMapBandwidth(float mapBandwidth) {
-    assert mapBandwidth > 0 : "Bandwidth " + mapBandwidth + " is invalid (should be > 0)";
-    this.mapBandwidth = mapBandwidth;
-  }
-
-  /**
-   * Returns an iterator with the list of file attributes to preserve
-   *
-   * @return iterator of file attributes to preserve
-   */
-  public Iterator<FileAttribute> preserveAttributes() {
-    return preserveStatus.iterator();
+  public Set<FileAttribute> getPreserveAttributes() {
+    return (preserveStatus == null)
+        ? null
+        : Collections.unmodifiableSet(preserveStatus);
   }
 
   /**
@@ -428,230 +311,10 @@ public class DistCpOptions {
     return preserveStatus.contains(attribute);
   }
 
-  /**
-   * Add file attributes that need to be preserved. This method may be
-   * called multiple times to add attributes.
-   *
-   * @param fileAttribute - Attribute to add, one at a time
-   */
-  public void preserve(FileAttribute fileAttribute) {
-    for (FileAttribute attribute : preserveStatus) {
-      if (attribute.equals(fileAttribute)) {
-        return;
-      }
-    }
-    preserveStatus.add(fileAttribute);
-  }
-
-  /**
-   * Return true if raw.* xattrs should be preserved.
-   * @return true if raw.* xattrs should be preserved.
-   */
-  public boolean shouldPreserveRawXattrs() {
-    return preserveRawXattrs;
-  }
-
-  /**
-   * Indicate that raw.* xattrs should be preserved
-   */
-  public void preserveRawXattrs() {
-    preserveRawXattrs = true;
-  }
-
-  /** Get work path for atomic commit. If null, the work
-   * path would be parentOf(targetPath) + "/._WIP_" + nameOf(targetPath)
-   *
-   * @return Atomic work path on the target cluster. Null if not set
-   */
-  public Path getAtomicWorkPath() {
-    return atomicWorkPath;
-  }
-
-  /**
-   * Set the work path for atomic commit
-   *
-   * @param atomicWorkPath - Path on the target cluster
-   */
-  public void setAtomicWorkPath(Path atomicWorkPath) {
-    this.atomicWorkPath = atomicWorkPath;
-  }
-
-  /** Get output directory for writing distcp logs. Otherwise logs
-   * are temporarily written to JobStagingDir/_logs and deleted
-   * upon job completion
-   *
-   * @return Log output path on the cluster where distcp job is run
-   */
-  public Path getLogPath() {
-    return logPath;
-  }
-
-  /**
-   * Set the log path where distcp output logs are stored
-   * Uses JobStagingDir/_logs by default
-   *
-   * @param logPath - Path where logs will be saved
-   */
-  public void setLogPath(Path logPath) {
-    this.logPath = logPath;
-  }
-
-  /**
-   * Get the copy strategy to use. Uses appropriate input format
-   *
-   * @return copy strategy to use
-   */
-  public String getCopyStrategy() {
-    return copyStrategy;
-  }
-
-  /**
-   * Set the copy strategy to use. Should map to a strategy implementation
-   * in distp-default.xml
-   *
-   * @param copyStrategy - copy Strategy to use
-   */
-  public void setCopyStrategy(String copyStrategy) {
-    this.copyStrategy = copyStrategy;
-  }
-
-  /**
-   * File path (hdfs:// or file://) that contains the list of actual
-   * files to copy
-   *
-   * @return - Source listing file path
-   */
-  public Path getSourceFileListing() {
-    return sourceFileListing;
-  }
-
-  /**
-   * Getter for sourcePaths.
-   * @return List of source-paths.
-   */
-  public List<Path> getSourcePaths() {
-    return sourcePaths;
-  }
-
-  /**
-   * Setter for sourcePaths.
-   * @param sourcePaths The new list of source-paths.
-   */
-  public void setSourcePaths(List<Path> sourcePaths) {
-    assert sourcePaths != null && sourcePaths.size() != 0;
-    this.sourcePaths = sourcePaths;
-  }
-
-  /**
-   * Getter for the targetPath.
-   * @return The target-path.
-   */
-  public Path getTargetPath() {
-    return targetPath;
-  }
-
-  /**
-   * Getter for the targetPathExists.
-   * @return The target-path.
-   */
-  public boolean getTargetPathExists() {
-    return targetPathExists;
-  }
-  
-  /**
-   * Set targetPathExists.
-   * @param targetPathExists Whether the target path of distcp exists.
-   */
-  public boolean setTargetPathExists(boolean targetPathExists) {
-    return this.targetPathExists = targetPathExists;
-  }
-
-  /**
-   * File path that contains the list of patterns
-   * for paths to be filtered from the file copy.
-   * @return - Filter  file path.
-   */
-  public final String getFiltersFile() {
-    return filtersFile;
-  }
-
-  /**
-   * Set filtersFile.
-   * @param filtersFilename The path to a list of patterns to exclude from copy.
-   */
-  public final void setFiltersFile(String filtersFilename) {
-    this.filtersFile = filtersFilename;
-  }
-
-  public final void setBlocksPerChunk(int csize) {
-    this.blocksPerChunk = csize;
-  }
-
-  public final int getBlocksPerChunk() {
+  public int getBlocksPerChunk() {
     return blocksPerChunk;
   }
 
-  public final boolean splitLargeFile() {
-    return blocksPerChunk > 0;
-  }
-
-  void validate() {
-    if ((useDiff || useRdiff) && deleteMissing) {
-      // -delete and -diff/-rdiff are mutually exclusive. For backward
-      // compatibility, we ignore the -delete option here, instead of throwing
-      // an IllegalArgumentException. See HDFS-10397 for more discussion.
-      OptionsParser.LOG.warn(
-          "-delete and -diff/-rdiff are mutually exclusive. " +
-          "The -delete option will be ignored.");
-      setDeleteMissing(false);
-    }
-
-    if (syncFolder && atomicCommit) {
-      throw new IllegalArgumentException("Atomic commit can't be used with " +
-          "sync folder or overwrite options");
-    }
-
-    if (deleteMissing && !(overwrite || syncFolder)) {
-      throw new IllegalArgumentException("Delete missing is applicable " +
-          "only with update or overwrite options");
-    }
-
-    if (overwrite && syncFolder) {
-      throw new IllegalArgumentException("Overwrite and update options are " +
-          "mutually exclusive");
-    }
-
-    if (!syncFolder && skipCRC) {
-      throw new IllegalArgumentException("Skip CRC is valid only with update options");
-    }
-
-    if (!syncFolder && append) {
-      throw new IllegalArgumentException(
-          "Append is valid only with update options");
-    }
-    if (skipCRC && append) {
-      throw new IllegalArgumentException(
-          "Append is disallowed when skipping CRC");
-    }
-    if (!syncFolder && (useDiff || useRdiff)) {
-      throw new IllegalArgumentException(
-          "-diff/-rdiff is valid only with -update option");
-    }
-
-    if (useDiff || useRdiff) {
-      if (StringUtils.isBlank(fromSnapshot) ||
-          StringUtils.isBlank(toSnapshot)) {
-        throw new IllegalArgumentException(
-            "Must provide both the starting and ending " +
-            "snapshot names for -diff/-rdiff");
-      }
-    }
-    if (useDiff && useRdiff) {
-      throw new IllegalArgumentException(
-          "-diff and -rdiff are mutually exclusive");
-    }
-  }
-
   /**
    * Add options to configuration. These will be used in the Mapper/committer
    *
@@ -715,20 +378,292 @@ public class DistCpOptions {
         ", mapBandwidth=" + mapBandwidth +
         ", copyStrategy='" + copyStrategy + '\'' +
         ", preserveStatus=" + preserveStatus +
-        ", preserveRawXattrs=" + preserveRawXattrs +
         ", atomicWorkPath=" + atomicWorkPath +
         ", logPath=" + logPath +
         ", sourceFileListing=" + sourceFileListing +
         ", sourcePaths=" + sourcePaths +
         ", targetPath=" + targetPath +
-        ", targetPathExists=" + targetPathExists +
         ", filtersFile='" + filtersFile + '\'' +
         ", blocksPerChunk=" + blocksPerChunk +
         '}';
   }
 
-  @Override
-  protected DistCpOptions clone() throws CloneNotSupportedException {
-    return (DistCpOptions) super.clone();
+  /**
+   * The builder of the {@link DistCpOptions}.
+   *
+   * This is designed to be the only public interface to create a
+   * {@link DistCpOptions} object for users. It follows a simple Builder design
+   * pattern.
+   */
+  public static class Builder {
+    private Path sourceFileListing;
+    private List<Path> sourcePaths;
+    private Path targetPath;
+
+    private boolean atomicCommit = false;
+    private Path atomicWorkPath;
+    private boolean syncFolder = false;
+    private boolean deleteMissing = false;
+    private boolean ignoreFailures = false;
+    private boolean overwrite = false;
+    private boolean append = false;
+    private boolean skipCRC = false;
+    private boolean blocking = true;
+
+    private boolean useDiff = false;
+    private boolean useRdiff = false;
+    private String fromSnapshot;
+    private String toSnapshot;
+
+    private String filtersFile;
+
+    private Path logPath;
+    private String copyStrategy = DistCpConstants.UNIFORMSIZE;
+
+    private int numListstatusThreads = 0;  // 0 indicates that flag is not set.
+    private int maxMaps = DistCpConstants.DEFAULT_MAPS;
+    private float mapBandwidth = 0; // 0 indicates we should use the default
+
+    private EnumSet<FileAttribute> preserveStatus =
+        EnumSet.noneOf(FileAttribute.class);
+
+    private int blocksPerChunk = 0;
+
+    public Builder(List<Path> sourcePaths, Path targetPath) {
+      Preconditions.checkArgument(sourcePaths != null && !sourcePaths.isEmpty(),
+          "Source paths should not be null or empty!");
+      Preconditions.checkArgument(targetPath != null,
+          "Target path should not be null!");
+      this.sourcePaths = sourcePaths;
+      this.targetPath = targetPath;
+    }
+
+    public Builder(Path sourceFileListing, Path targetPath) {
+      Preconditions.checkArgument(sourceFileListing != null,
+          "Source file listing should not be null!");
+      Preconditions.checkArgument(targetPath != null,
+          "Target path should not be null!");
+
+      this.sourceFileListing = sourceFileListing;
+      this.targetPath = targetPath;
+    }
+
+    /**
+     * This is the single entry point for constructing DistCpOptions objects.
+     *
+     * Before a new DistCpOptions object is returned, it will set the dependent
+     * options, validate the option combinations. After constructing, the
+     * DistCpOptions instance is immutable.
+     */
+    public DistCpOptions build() {
+      setOptionsForSplitLargeFile();
+
+      validate();
+
+      return new DistCpOptions(this);
+    }
+
+    /**
+     * Override options for split large files.
+     */
+    private void setOptionsForSplitLargeFile() {
+      if (blocksPerChunk <= 0) {
+        return;
+      }
+
+      LOG.info("Enabling preserving blocksize since "
+          + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " is passed.");
+      preserve(FileAttribute.BLOCKSIZE);
+
+      LOG.info("Set " + DistCpOptionSwitch.APPEND.getSwitch()
+          + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
+          + " is passed.");
+      this.append = false;
+    }
+
+    private void validate() {
+      if ((useDiff || useRdiff) && deleteMissing) {
+        // -delete and -diff/-rdiff are mutually exclusive.
+        throw new IllegalArgumentException("-delete and -diff/-rdiff are "
+            + "mutually exclusive. The -delete option will be ignored.");
+      }
+
+      if (!atomicCommit && atomicWorkPath != null) {
+        throw new IllegalArgumentException(
+            "-tmp work-path can only be specified along with -atomic");
+      }
+
+      if (syncFolder && atomicCommit) {
+        throw new IllegalArgumentException("Atomic commit can't be used with "
+            + "sync folder or overwrite options");
+      }
+
+      if (deleteMissing && !(overwrite || syncFolder)) {
+        throw new IllegalArgumentException("Delete missing is applicable "
+            + "only with update or overwrite options");
+      }
+
+      if (overwrite && syncFolder) {
+        throw new IllegalArgumentException("Overwrite and update options are "
+            + "mutually exclusive");
+      }
+
+      if (!syncFolder && skipCRC) {
+        throw new IllegalArgumentException(
+            "Skip CRC is valid only with update options");
+      }
+
+      if (!syncFolder && append) {
+        throw new IllegalArgumentException(
+            "Append is valid only with update options");
+      }
+      if (skipCRC && append) {
+        throw new IllegalArgumentException(
+            "Append is disallowed when skipping CRC");
+      }
+      if (!syncFolder && (useDiff || useRdiff)) {
+        throw new IllegalArgumentException(
+            "-diff/-rdiff is valid only with -update option");
+      }
+
+      if (useDiff || useRdiff) {
+        if (StringUtils.isBlank(fromSnapshot) ||
+            StringUtils.isBlank(toSnapshot)) {
+          throw new IllegalArgumentException(
+              "Must provide both the starting and ending " +
+                  "snapshot names for -diff/-rdiff");
+        }
+      }
+      if (useDiff && useRdiff) {
+        throw new IllegalArgumentException(
+            "-diff and -rdiff are mutually exclusive");
+      }
+    }
+
+    @VisibleForTesting
+    Builder withSourcePaths(List<Path> newSourcePaths) {
+      this.sourcePaths = newSourcePaths;
+      return this;
+    }
+
+    public Builder withAtomicCommit(boolean newAtomicCommit) {
+      this.atomicCommit = newAtomicCommit;
+      return this;
+    }
+
+    public Builder withAtomicWorkPath(Path newAtomicWorkPath) {
+      this.atomicWorkPath = newAtomicWorkPath;
+      return this;
+    }
+
+    public Builder withSyncFolder(boolean newSyncFolder) {
+      this.syncFolder = newSyncFolder;
+      return this;
+    }
+
+    public Builder withDeleteMissing(boolean newDeleteMissing) {
+      this.deleteMissing = newDeleteMissing;
+      return this;
+    }
+
+    public Builder withIgnoreFailures(boolean newIgnoreFailures) {
+      this.ignoreFailures = newIgnoreFailures;
+      return this;
+    }
+
+    public Builder withOverwrite(boolean newOverwrite) {
+      this.overwrite = newOverwrite;
+      return this;
+    }
+
+    public Builder withAppend(boolean newAppend) {
+      this.append = newAppend;
+      return this;
+    }
+
+    public Builder withCRC(boolean newSkipCRC) {
+      this.skipCRC = newSkipCRC;
+      return this;
+    }
+
+    public Builder withBlocking(boolean newBlocking) {
+      this.blocking = newBlocking;
+      return this;
+    }
+
+    public Builder withUseDiff(String newFromSnapshot,  String newToSnapshot) {
+      this.useDiff = true;
+      this.fromSnapshot = newFromSnapshot;
+      this.toSnapshot = newToSnapshot;
+      return this;
+    }
+
+    public Builder withUseRdiff(String newFromSnapshot, String newToSnapshot) {
+      this.useRdiff = true;
+      this.fromSnapshot = newFromSnapshot;
+      this.toSnapshot = newToSnapshot;
+      return this;
+    }
+
+    public Builder withFiltersFile(String newFiletersFile) {
+      this.filtersFile = newFiletersFile;
+      return this;
+    }
+
+    public Builder withLogPath(Path newLogPath) {
+      this.logPath = newLogPath;
+      return this;
+    }
+
+    public Builder withCopyStrategy(String newCopyStrategy) {
+      this.copyStrategy = newCopyStrategy;
+      return this;
+    }
+
+    public Builder withMapBandwidth(float newMapBandwidth) {
+      Preconditions.checkArgument(newMapBandwidth > 0,
+          "Bandwidth " + newMapBandwidth + " is invalid (should be > 0)");
+      this.mapBandwidth = newMapBandwidth;
+      return this;
+    }
+
+    public Builder withNumListstatusThreads(int newNumListstatusThreads) {
+      if (newNumListstatusThreads > MAX_NUM_LISTSTATUS_THREADS) {
+        this.numListstatusThreads = MAX_NUM_LISTSTATUS_THREADS;
+      } else if (newNumListstatusThreads > 0) {
+        this.numListstatusThreads = newNumListstatusThreads;
+      } else {
+        this.numListstatusThreads = 0;
+      }
+      return this;
+    }
+
+    public Builder maxMaps(int newMaxMaps) {
+      this.maxMaps = Math.max(newMaxMaps, 1);
+      return this;
+    }
+
+    public Builder preserve(String attributes) {
+      if (attributes == null || attributes.isEmpty()) {
+        preserveStatus = EnumSet.allOf(FileAttribute.class);
+      } else {
+        for (int index = 0; index < attributes.length(); index++) {
+          preserveStatus.add(FileAttribute.
+              getAttribute(attributes.charAt(index)));
+        }
+      }
+      return this;
+    }
+
+    public Builder preserve(FileAttribute attribute) {
+      preserveStatus.add(attribute);
+      return this;
+    }
+
+    public Builder withBlocksPerChunk(int newBlocksPerChunk) {
+      this.blocksPerChunk = newBlocksPerChunk;
+      return this;
+    }
   }
+
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpSync.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpSync.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpSync.java
index bcae96a..a78320b 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpSync.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpSync.java
@@ -48,7 +48,7 @@ import java.util.HashSet;
  * source.s1
  */
 class DistCpSync {
-  private DistCpOptions inputOptions;
+  private DistCpContext context;
   private Configuration conf;
   // diffMap maps snapshot diff op type to a list of diff ops.
   // It's initially created based on the snapshot diff. Then the individual
@@ -58,13 +58,13 @@ class DistCpSync {
   private EnumMap<SnapshotDiffReport.DiffType, List<DiffInfo>> diffMap;
   private DiffInfo[] renameDiffs;
 
-  DistCpSync(DistCpOptions options, Configuration conf) {
-    this.inputOptions = options;
+  DistCpSync(DistCpContext context, Configuration conf) {
+    this.context = context;
     this.conf = conf;
   }
 
   private boolean isRdiff() {
-    return inputOptions.shouldUseRdiff();
+    return context.shouldUseRdiff();
   }
 
   /**
@@ -77,14 +77,14 @@ class DistCpSync {
    *  default distcp if the third condition isn't met.
    */
   private boolean preSyncCheck() throws IOException {
-    List<Path> sourcePaths = inputOptions.getSourcePaths();
+    List<Path> sourcePaths = context.getSourcePaths();
     if (sourcePaths.size() != 1) {
       // we only support one source dir which must be a snapshottable directory
       throw new IllegalArgumentException(sourcePaths.size()
           + " source paths are provided");
     }
     final Path sourceDir = sourcePaths.get(0);
-    final Path targetDir = inputOptions.getTargetPath();
+    final Path targetDir = context.getTargetPath();
 
     final FileSystem srcFs = sourceDir.getFileSystem(conf);
     final FileSystem tgtFs = targetDir.getFileSystem(conf);
@@ -104,13 +104,15 @@ class DistCpSync {
     // make sure targetFS has no change between from and the current states
     if (!checkNoChange(targetFs, targetDir)) {
       // set the source path using the snapshot path
-      inputOptions.setSourcePaths(Arrays.asList(getSnapshotPath(sourceDir,
-          inputOptions.getToSnapshot())));
+      context.setSourcePaths(Arrays.asList(getSnapshotPath(sourceDir,
+          context.getToSnapshot())));
       return false;
     }
 
-    final String from = getSnapshotName(inputOptions.getFromSnapshot());
-    final String to = getSnapshotName(inputOptions.getToSnapshot());
+    final String from = getSnapshotName(
+        context.getFromSnapshot());
+    final String to = getSnapshotName(
+        context.getToSnapshot());
 
     try {
       final FileStatus fromSnapshotStat =
@@ -152,9 +154,9 @@ class DistCpSync {
       return false;
     }
 
-    List<Path> sourcePaths = inputOptions.getSourcePaths();
+    List<Path> sourcePaths = context.getSourcePaths();
     final Path sourceDir = sourcePaths.get(0);
-    final Path targetDir = inputOptions.getTargetPath();
+    final Path targetDir = context.getTargetPath();
     final FileSystem tfs = targetDir.getFileSystem(conf);
     final DistributedFileSystem targetFs = (DistributedFileSystem) tfs;
 
@@ -175,8 +177,8 @@ class DistCpSync {
       deleteTargetTmpDir(targetFs, tmpDir);
       // TODO: since we have tmp directory, we can support "undo" with failures
       // set the source path using the snapshot path
-      inputOptions.setSourcePaths(Arrays.asList(getSnapshotPath(sourceDir,
-          inputOptions.getToSnapshot())));
+      context.setSourcePaths(Arrays.asList(getSnapshotPath(sourceDir,
+          context.getToSnapshot())));
     }
   }
 
@@ -187,13 +189,13 @@ class DistCpSync {
    */
   private boolean getAllDiffs() throws IOException {
     Path ssDir = isRdiff()?
-        inputOptions.getTargetPath() : inputOptions.getSourcePaths().get(0);
+        context.getTargetPath() : context.getSourcePaths().get(0);
 
     try {
       DistributedFileSystem fs =
           (DistributedFileSystem) ssDir.getFileSystem(conf);
-      final String from = getSnapshotName(inputOptions.getFromSnapshot());
-      final String to = getSnapshotName(inputOptions.getToSnapshot());
+      final String from = getSnapshotName(context.getFromSnapshot());
+      final String to = getSnapshotName(context.getToSnapshot());
       SnapshotDiffReport report = fs.getSnapshotDiffReport(ssDir,
           from, to);
       this.diffMap = new EnumMap<>(SnapshotDiffReport.DiffType.class);
@@ -273,19 +275,19 @@ class DistCpSync {
    */
   private boolean checkNoChange(DistributedFileSystem fs, Path path) {
     try {
-      final String from = getSnapshotName(inputOptions.getFromSnapshot());
+      final String from = getSnapshotName(context.getFromSnapshot());
       SnapshotDiffReport targetDiff =
           fs.getSnapshotDiffReport(path, from, "");
       if (!targetDiff.getDiffList().isEmpty()) {
         DistCp.LOG.warn("The target has been modified since snapshot "
-            + inputOptions.getFromSnapshot());
+            + context.getFromSnapshot());
         return false;
       } else {
         return true;
       }
     } catch (IOException e) {
       DistCp.LOG.warn("Failed to compute snapshot diff on " + path
-          + " at snapshot " + inputOptions.getFromSnapshot(), e);
+          + " at snapshot " + context.getFromSnapshot(), e);
     }
     return false;
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/FileBasedCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/FileBasedCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/FileBasedCopyListing.java
index 2bc343e..c356edd 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/FileBasedCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/FileBasedCopyListing.java
@@ -52,7 +52,7 @@ public class FileBasedCopyListing extends CopyListing {
 
   /** {@inheritDoc} */
   @Override
-  protected void validatePaths(DistCpOptions options)
+  protected void validatePaths(DistCpContext context)
       throws IOException, InvalidInputException {
   }
 
@@ -60,14 +60,14 @@ public class FileBasedCopyListing extends CopyListing {
    * Implementation of CopyListing::buildListing().
    *   Iterates over all source paths mentioned in the input-file.
    * @param pathToListFile Path on HDFS where the listing file is written.
-   * @param options Input Options for DistCp (indicating source/target paths.)
+   * @param context Distcp context with associated input options.
    * @throws IOException
    */
   @Override
-  public void doBuildListing(Path pathToListFile, DistCpOptions options) throws IOException {
-    DistCpOptions newOption = new DistCpOptions(options);
-    newOption.setSourcePaths(fetchFileList(options.getSourceFileListing()));
-    globbedListing.buildListing(pathToListFile, newOption);
+  public void doBuildListing(Path pathToListFile, DistCpContext context)
+      throws IOException {
+    context.setSourcePaths(fetchFileList(context.getSourceFileListing()));
+    globbedListing.buildListing(pathToListFile, context);
   }
 
   private List<Path> fetchFileList(Path sourceListing) throws IOException {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/GlobbedCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/GlobbedCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/GlobbedCopyListing.java
index 27330b7..63c6f43 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/GlobbedCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/GlobbedCopyListing.java
@@ -51,7 +51,7 @@ public class GlobbedCopyListing extends CopyListing {
 
   /** {@inheritDoc} */
   @Override
-  protected void validatePaths(DistCpOptions options)
+  protected void validatePaths(DistCpContext context)
       throws IOException, InvalidInputException {
   }
 
@@ -60,19 +60,19 @@ public class GlobbedCopyListing extends CopyListing {
    * Creates the copy listing by "globbing" all source-paths.
    * @param pathToListingFile The location at which the copy-listing file
    *                           is to be created.
-   * @param options Input Options for DistCp (indicating source/target paths.)
+   * @param context The distcp context with associated input options.
    * @throws IOException
    */
   @Override
-  public void doBuildListing(Path pathToListingFile,
-                             DistCpOptions options) throws IOException {
+  public void doBuildListing(Path pathToListingFile, DistCpContext context)
+      throws IOException {
 
     List<Path> globbedPaths = new ArrayList<Path>();
-    if (options.getSourcePaths().isEmpty()) {
+    if (context.getSourcePaths().isEmpty()) {
       throw new InvalidInputException("Nothing to process. Source paths::EMPTY");  
     }
 
-    for (Path p : options.getSourcePaths()) {
+    for (Path p : context.getSourcePaths()) {
       FileSystem fs = p.getFileSystem(getConf());
       FileStatus[] inputs = fs.globStatus(p);
 
@@ -85,9 +85,8 @@ public class GlobbedCopyListing extends CopyListing {
       }
     }
 
-    DistCpOptions optionsGlobbed = new DistCpOptions(options);
-    optionsGlobbed.setSourcePaths(globbedPaths);
-    simpleListing.buildListing(pathToListingFile, optionsGlobbed);
+    context.setSourcePaths(globbedPaths);
+    simpleListing.buildListing(pathToListingFile, context);
   }
 
   /** {@inheritDoc} */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b1543f9c/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
index 8881264..21ff0f8 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
@@ -32,7 +32,6 @@ import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 
 import com.google.common.base.Preconditions;
 
@@ -95,253 +94,126 @@ public class OptionsParser {
         Arrays.toString(args), e);
     }
 
-    DistCpOptions option = parseSourceAndTargetPaths(command);
-
-    option.setIgnoreFailures(
-        command.hasOption(DistCpOptionSwitch.IGNORE_FAILURES.getSwitch()));
-
-    option.setAtomicCommit(
-        command.hasOption(DistCpOptionSwitch.ATOMIC_COMMIT.getSwitch()));
-
-    option.setSyncFolder(
-        command.hasOption(DistCpOptionSwitch.SYNC_FOLDERS.getSwitch()));
-
-    option.setOverwrite(
-        command.hasOption(DistCpOptionSwitch.OVERWRITE.getSwitch()));
-
-    option.setAppend(
-        command.hasOption(DistCpOptionSwitch.APPEND.getSwitch()));
-
-    option.setDeleteMissing(
-        command.hasOption(DistCpOptionSwitch.DELETE_MISSING.getSwitch()));
-
-    option.setSkipCRC(
-        command.hasOption(DistCpOptionSwitch.SKIP_CRC.getSwitch()));
-
-    if (command.hasOption(DistCpOptionSwitch.WORK_PATH.getSwitch()) &&
-        option.shouldAtomicCommit()) {
-      String workPath = getVal(command, DistCpOptionSwitch.WORK_PATH.getSwitch());
-      if (workPath != null && !workPath.isEmpty()) {
-        option.setAtomicWorkPath(new Path(workPath));
-      }
-    } else if (command.hasOption(DistCpOptionSwitch.WORK_PATH.getSwitch())) {
-      throw new IllegalArgumentException("-tmp work-path can only be specified along with -atomic");
-    }
-
-    if (command.hasOption(DistCpOptionSwitch.LOG_PATH.getSwitch())) {
-      option.setLogPath(new Path(getVal(command, DistCpOptionSwitch.LOG_PATH.getSwitch())));
-    }
-
-
-    if (command.hasOption(DistCpOptionSwitch.BLOCKING.getSwitch())) {
-      option.setBlocking(false);
-    }
-
-    parseBandwidth(command, option);
-
-    parseNumListStatusThreads(command, option);
-
-    parseMaxMaps(command, option);
-
-    if (command.hasOption(DistCpOptionSwitch.COPY_STRATEGY.getSwitch())) {
-      option.setCopyStrategy(
-            getVal(command, DistCpOptionSwitch.COPY_STRATEGY.getSwitch()));
-    }
-
-    parsePreserveStatus(command, option);
+    DistCpOptions.Builder builder = parseSourceAndTargetPaths(command);
+    builder
+        .withAtomicCommit(
+            command.hasOption(DistCpOptionSwitch.ATOMIC_COMMIT.getSwitch()))
+        .withSyncFolder(
+            command.hasOption(DistCpOptionSwitch.SYNC_FOLDERS.getSwitch()))
+        .withDeleteMissing(
+            command.hasOption(DistCpOptionSwitch.DELETE_MISSING.getSwitch()))
+        .withIgnoreFailures(
+            command.hasOption(DistCpOptionSwitch.IGNORE_FAILURES.getSwitch()))
+        .withOverwrite(
+            command.hasOption(DistCpOptionSwitch.OVERWRITE.getSwitch()))
+        .withAppend(
+            command.hasOption(DistCpOptionSwitch.APPEND.getSwitch()))
+        .withCRC(
+            command.hasOption(DistCpOptionSwitch.SKIP_CRC.getSwitch()))
+        .withBlocking(
+            !command.hasOption(DistCpOptionSwitch.BLOCKING.getSwitch()));
 
     if (command.hasOption(DistCpOptionSwitch.DIFF.getSwitch())) {
       String[] snapshots = getVals(command,
           DistCpOptionSwitch.DIFF.getSwitch());
       checkSnapshotsArgs(snapshots);
-      option.setUseDiff(snapshots[0], snapshots[1]);
+      builder.withUseDiff(snapshots[0], snapshots[1]);
     }
     if (command.hasOption(DistCpOptionSwitch.RDIFF.getSwitch())) {
       String[] snapshots = getVals(command,
           DistCpOptionSwitch.RDIFF.getSwitch());
       checkSnapshotsArgs(snapshots);
-      option.setUseRdiff(snapshots[0], snapshots[1]);
+      builder.withUseRdiff(snapshots[0], snapshots[1]);
     }
 
-    parseFileLimit(command);
-
-    parseSizeLimit(command);
-
     if (command.hasOption(DistCpOptionSwitch.FILTERS.getSwitch())) {
-      option.setFiltersFile(getVal(command,
-          DistCpOptionSwitch.FILTERS.getSwitch()));
+      builder.withFiltersFile(
+          getVal(command, DistCpOptionSwitch.FILTERS.getSwitch()));
     }
 
-    parseBlocksPerChunk(command, option);
-
-    option.validate();
-
-    return option;
-  }
-
-
-  /**
-   * A helper method to parse chunk size in number of blocks.
-   * Used when breaking large file into chunks to copy in parallel.
-   *
-   * @param command command line arguments
-   */
-  private static void parseBlocksPerChunk(CommandLine command,
-      DistCpOptions option) {
-    boolean hasOption =
-        command.hasOption(DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch());
-    LOG.info("parseChunkSize: " +
-        DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " " + hasOption);
-    if (hasOption) {
-      String chunkSizeString = getVal(command,
-          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch().trim());
-      try {
-        int csize = Integer.parseInt(chunkSizeString);
-        if (csize < 0) {
-          csize = 0;
-        }
-        LOG.info("Set distcp blocksPerChunk to " + csize);
-        option.setBlocksPerChunk(csize);
-      }
-      catch (NumberFormatException e) {
-        throw new IllegalArgumentException("blocksPerChunk is invalid: "
-            + chunkSizeString, e);
-      }
+    if (command.hasOption(DistCpOptionSwitch.LOG_PATH.getSwitch())) {
+      builder.withLogPath(
+          new Path(getVal(command, DistCpOptionSwitch.LOG_PATH.getSwitch())));
     }
-  }
 
-  /**
-   * parseSizeLimit is a helper method for parsing the deprecated
-   * argument SIZE_LIMIT.
-   *
-   * @param command command line arguments
-   */
-  private static void parseSizeLimit(CommandLine command) {
-    if (command.hasOption(DistCpOptionSwitch.SIZE_LIMIT.getSwitch())) {
-      String sizeLimitString = getVal(command,
-                              DistCpOptionSwitch.SIZE_LIMIT.getSwitch().trim());
-      try {
-        Long.parseLong(sizeLimitString);
-      }
-      catch (NumberFormatException e) {
-        throw new IllegalArgumentException("Size-limit is invalid: "
-                                            + sizeLimitString, e);
+    if (command.hasOption(DistCpOptionSwitch.WORK_PATH.getSwitch())) {
+      final String workPath = getVal(command,
+          DistCpOptionSwitch.WORK_PATH.getSwitch());
+      if (workPath != null && !workPath.isEmpty()) {
+        builder.withAtomicWorkPath(new Path(workPath));
       }
-      LOG.warn(DistCpOptionSwitch.SIZE_LIMIT.getSwitch() + " is a deprecated" +
-              " option. Ignoring.");
     }
-  }
 
-  /**
-   * parseFileLimit is a helper method for parsing the deprecated
-   * argument FILE_LIMIT.
-   *
-   * @param command command line arguments
-   */
-  private static void parseFileLimit(CommandLine command) {
-    if (command.hasOption(DistCpOptionSwitch.FILE_LIMIT.getSwitch())) {
-      String fileLimitString = getVal(command,
-                              DistCpOptionSwitch.FILE_LIMIT.getSwitch().trim());
+    if (command.hasOption(DistCpOptionSwitch.BANDWIDTH.getSwitch())) {
       try {
-        Integer.parseInt(fileLimitString);
+        final Float mapBandwidth = Float.parseFloat(
+            getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()));
+        builder.withMapBandwidth(mapBandwidth);
       } catch (NumberFormatException e) {
-        throw new IllegalArgumentException("File-limit is invalid: "
-                                            + fileLimitString, e);
+        throw new IllegalArgumentException("Bandwidth specified is invalid: " +
+            getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()), e);
       }
-      LOG.warn(DistCpOptionSwitch.FILE_LIMIT.getSwitch() + " is a deprecated" +
-          " option. Ignoring.");
     }
-  }
 
-  /**
-   * parsePreserveStatus is a helper method for parsing PRESERVE_STATUS.
-   *
-   * @param command command line arguments
-   * @param option  parsed distcp options
-   */
-  private static void parsePreserveStatus(CommandLine command,
-                                          DistCpOptions option) {
-    if (command.hasOption(DistCpOptionSwitch.PRESERVE_STATUS.getSwitch())) {
-      String attributes =
-          getVal(command, DistCpOptionSwitch.PRESERVE_STATUS.getSwitch());
-      if (attributes == null || attributes.isEmpty()) {
-        for (FileAttribute attribute : FileAttribute.values()) {
-          option.preserve(attribute);
-        }
-      } else {
-        for (int index = 0; index < attributes.length(); index++) {
-          option.preserve(FileAttribute.
-              getAttribute(attributes.charAt(index)));
-        }
+    if (command.hasOption(
+        DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch())) {
+      try {
+        final Integer numThreads = Integer.parseInt(getVal(command,
+            DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch()));
+        builder.withNumListstatusThreads(numThreads);
+      } catch (NumberFormatException e) {
+        throw new IllegalArgumentException(
+            "Number of liststatus threads is invalid: " + getVal(command,
+                DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch()), e);
       }
     }
-  }
 
-  /**
-   * parseMaxMaps is a helper method for parsing MAX_MAPS.
-   *
-   * @param command command line arguments
-   * @param option  parsed distcp options
-   */
-  private static void parseMaxMaps(CommandLine command,
-                                   DistCpOptions option) {
     if (command.hasOption(DistCpOptionSwitch.MAX_MAPS.getSwitch())) {
       try {
-        Integer maps = Integer.parseInt(
-            getVal(command, DistCpOptionSwitch.MAX_MAPS.getSwitch()).trim());
-        option.setMaxMaps(maps);
+        final Integer maps = Integer.parseInt(
+            getVal(command, DistCpOptionSwitch.MAX_MAPS.getSwitch()));
+        builder.maxMaps(maps);
       } catch (NumberFormatException e) {
         throw new IllegalArgumentException("Number of maps is invalid: " +
             getVal(command, DistCpOptionSwitch.MAX_MAPS.getSwitch()), e);
       }
     }
-  }
 
-  /**
-   * parseNumListStatusThreads is a helper method for parsing
-   * NUM_LISTSTATUS_THREADS.
-   *
-   * @param command command line arguments
-   * @param option  parsed distcp options
-   */
-  private static void parseNumListStatusThreads(CommandLine command,
-                                                DistCpOptions option) {
-    if (command.hasOption(
-        DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch())) {
-      try {
-        Integer numThreads = Integer.parseInt(getVal(command,
-              DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch()).trim());
-        option.setNumListstatusThreads(numThreads);
-      } catch (NumberFormatException e) {
-        throw new IllegalArgumentException(
-            "Number of liststatus threads is invalid: " + getVal(command,
-                DistCpOptionSwitch.NUM_LISTSTATUS_THREADS.getSwitch()), e);
-      }
+    if (command.hasOption(DistCpOptionSwitch.COPY_STRATEGY.getSwitch())) {
+      builder.withCopyStrategy(
+            getVal(command, DistCpOptionSwitch.COPY_STRATEGY.getSwitch()));
     }
-  }
 
-  /**
-   * parseBandwidth is a helper method for parsing BANDWIDTH.
-   *
-   * @param command command line arguments
-   * @param option  parsed distcp options
-   */
-  private static void parseBandwidth(CommandLine command,
-                                     DistCpOptions option) {
-    if (command.hasOption(DistCpOptionSwitch.BANDWIDTH.getSwitch())) {
+    if (command.hasOption(DistCpOptionSwitch.PRESERVE_STATUS.getSwitch())) {
+      builder.preserve(
+          getVal(command, DistCpOptionSwitch.PRESERVE_STATUS.getSwitch()));
+    }
+
+    if (command.hasOption(DistCpOptionSwitch.FILE_LIMIT.getSwitch())) {
+      LOG.warn(DistCpOptionSwitch.FILE_LIMIT.getSwitch() + " is a deprecated" +
+          " option. Ignoring.");
+    }
+
+    if (command.hasOption(DistCpOptionSwitch.SIZE_LIMIT.getSwitch())) {
+      LOG.warn(DistCpOptionSwitch.SIZE_LIMIT.getSwitch() + " is a deprecated" +
+          " option. Ignoring.");
+    }
+
+    if (command.hasOption(DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch())) {
+      final String chunkSizeStr = getVal(command,
+          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch().trim());
       try {
-        Float mapBandwidth = Float.parseFloat(
-            getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()).trim());
-        if (mapBandwidth <= 0) {
-          throw new IllegalArgumentException("Bandwidth specified is not " +
-              "positive: " + mapBandwidth);
-        }
-        option.setMapBandwidth(mapBandwidth);
+        int csize = Integer.parseInt(chunkSizeStr);
+        csize = csize > 0 ? csize : 0;
+        LOG.info("Set distcp blocksPerChunk to " + csize);
+        builder.withBlocksPerChunk(csize);
       } catch (NumberFormatException e) {
-        throw new IllegalArgumentException("Bandwidth specified is invalid: " +
-            getVal(command, DistCpOptionSwitch.BANDWIDTH.getSwitch()), e);
+        throw new IllegalArgumentException("blocksPerChunk is invalid: "
+            + chunkSizeStr, e);
       }
     }
+
+    return builder.build();
   }
 
   /**
@@ -351,9 +223,8 @@ public class OptionsParser {
    * @param command command line arguments
    * @return        DistCpOptions
    */
-  private static DistCpOptions parseSourceAndTargetPaths(
+  private static DistCpOptions.Builder parseSourceAndTargetPaths(
       CommandLine command) {
-    DistCpOptions option;
     Path targetPath;
     List<Path> sourcePaths = new ArrayList<Path>();
 
@@ -378,20 +249,22 @@ public class OptionsParser {
         throw new IllegalArgumentException("Both source file listing and " +
             "source paths present");
       }
-      option = new DistCpOptions(new Path(getVal(command, DistCpOptionSwitch.
-          SOURCE_FILE_LISTING.getSwitch())), targetPath);
+      return new DistCpOptions.Builder(new Path(getVal(command,
+          DistCpOptionSwitch.SOURCE_FILE_LISTING.getSwitch())), targetPath);
     } else {
       if (sourcePaths.isEmpty()) {
         throw new IllegalArgumentException("Neither source file listing nor " +
             "source paths present");
       }
-      option = new DistCpOptions(sourcePaths, targetPath);
+      return new DistCpOptions.Builder(sourcePaths, targetPath);
     }
-    return option;
   }
 
   private static String getVal(CommandLine command, String swtch) {
-    String optionValue = command.getOptionValue(swtch);
+    if (swtch == null) {
+      return null;
+    }
+    String optionValue = command.getOptionValue(swtch.trim());
     if (optionValue == null) {
       return null;
     } else {


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[04/50] [abbrv] hadoop git commit: HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen.

Posted by in...@apache.org.
HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen.


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

Branch: refs/heads/HDFS-10467
Commit: 92421f27929388af769ca978c317c01597fdac91
Parents: df919ee
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Thu Mar 30 17:01:15 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:19 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSTestUtil.java     |  22 +-
 .../org/apache/hadoop/tools/CopyListing.java    |  37 +-
 .../hadoop/tools/CopyListingFileStatus.java     |  87 ++++-
 .../java/org/apache/hadoop/tools/DistCp.java    |  52 +++
 .../apache/hadoop/tools/DistCpOptionSwitch.java |  10 +
 .../org/apache/hadoop/tools/DistCpOptions.java  |  22 +-
 .../org/apache/hadoop/tools/OptionsParser.java  |  36 +-
 .../apache/hadoop/tools/SimpleCopyListing.java  |  83 +++--
 .../hadoop/tools/mapred/CopyCommitter.java      | 174 ++++++++-
 .../apache/hadoop/tools/mapred/CopyMapper.java  |  40 +-
 .../tools/mapred/RetriableFileCopyCommand.java  |  26 +-
 .../tools/mapred/UniformSizeInputFormat.java    |   5 +-
 .../apache/hadoop/tools/util/DistCpUtils.java   | 111 +++++-
 .../src/site/markdown/DistCp.md.vm              |   1 +
 .../apache/hadoop/tools/TestDistCpSystem.java   | 368 +++++++++++++++++--
 .../apache/hadoop/tools/TestOptionsParser.java  |   2 +-
 .../hadoop/tools/mapred/TestCopyCommitter.java  |   5 +-
 17 files changed, 971 insertions(+), 110 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
index 1329195..9b782f3 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
@@ -862,7 +862,27 @@ public class DFSTestUtil {
       out.write(toAppend);
     }
   }
-  
+
+  /**
+   * Append specified length of bytes to a given file, starting with new block.
+   * @param fs The file system
+   * @param p Path of the file to append
+   * @param length Length of bytes to append to the file
+   * @throws IOException
+   */
+  public static void appendFileNewBlock(DistributedFileSystem fs,
+      Path p, int length) throws IOException {
+    assert fs.exists(p);
+    assert length >= 0;
+    byte[] toAppend = new byte[length];
+    Random random = new Random();
+    random.nextBytes(toAppend);
+    try (FSDataOutputStream out = fs.append(p,
+        EnumSet.of(CreateFlag.APPEND, CreateFlag.NEW_BLOCK), 4096, null)) {
+      out.write(toAppend);
+    }
+  }
+
   /**
    * @return url content as string (UTF-8 encoding assumed)
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
index 481aa61..9ebf9d2 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
@@ -145,12 +145,22 @@ public abstract class CopyListing extends Configured {
     Configuration config = getConf();
     FileSystem fs = pathToListFile.getFileSystem(config);
 
-    Path sortedList = DistCpUtils.sortListing(fs, config, pathToListFile);
+    final boolean splitLargeFile = options.splitLargeFile();
+
+    // When splitLargeFile is enabled, we don't randomize the copylist
+    // earlier, so we don't do the sorting here. For a file that has
+    // multiple entries due to split, we check here that their
+    // <chunkOffset, chunkLength> is continuous.
+    //
+    Path checkPath = splitLargeFile?
+        pathToListFile : DistCpUtils.sortListing(fs, config, pathToListFile);
 
     SequenceFile.Reader reader = new SequenceFile.Reader(
-                          config, SequenceFile.Reader.file(sortedList));
+                          config, SequenceFile.Reader.file(checkPath));
     try {
       Text lastKey = new Text("*"); //source relative path can never hold *
+      long lastChunkOffset = -1;
+      long lastChunkLength = -1;
       CopyListingFileStatus lastFileStatus = new CopyListingFileStatus();
 
       Text currentKey = new Text();
@@ -161,8 +171,21 @@ public abstract class CopyListing extends Configured {
         if (currentKey.equals(lastKey)) {
           CopyListingFileStatus currentFileStatus = new CopyListingFileStatus();
           reader.getCurrentValue(currentFileStatus);
-          throw new DuplicateFileException("File " + lastFileStatus.getPath() + " and " +
-              currentFileStatus.getPath() + " would cause duplicates. Aborting");
+          if (!splitLargeFile) {
+            throw new DuplicateFileException("File " + lastFileStatus.getPath()
+                + " and " + currentFileStatus.getPath()
+                + " would cause duplicates. Aborting");
+          } else {
+            if (lastChunkOffset + lastChunkLength !=
+                currentFileStatus.getChunkOffset()) {
+              throw new InvalidInputException("File " + lastFileStatus.getPath()
+                  + " " + lastChunkOffset + "," + lastChunkLength
+                  + " and " + currentFileStatus.getPath()
+                  + " " + currentFileStatus.getChunkOffset() + ","
+                  + currentFileStatus.getChunkLength()
+                  + " are not continuous. Aborting");
+            }
+          }
         }
         reader.getCurrentValue(lastFileStatus);
         if (options.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
@@ -181,8 +204,12 @@ public abstract class CopyListing extends Configured {
             xAttrSupportCheckFsSet.add(lastFsUri);
           }
         }
-        lastKey.set(currentKey);
 
+        lastKey.set(currentKey);
+        if (splitLargeFile) {
+          lastChunkOffset = lastFileStatus.getChunkOffset();
+          lastChunkLength = lastFileStatus.getChunkLength();
+        }
         if (options.shouldUseDiff() && LOG.isDebugEnabled()) {
           LOG.debug("Copy list entry " + idx + ": " +
                   lastFileStatus.getPath().toUri().getPath());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
index 00d4b32..29c59ac 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
@@ -74,6 +74,14 @@ public final class CopyListingFileStatus implements Writable {
   private List<AclEntry> aclEntries;
   private Map<String, byte[]> xAttrs;
 
+  // <chunkOffset, chunkLength> represents the offset and length of a file
+  // chunk in number of bytes.
+  // used when splitting a large file to chunks to copy in parallel.
+  // If a file is not large enough to split, chunkOffset would be 0 and
+  // chunkLength would be the length of the file.
+  private long chunkOffset = 0;
+  private long chunkLength = Long.MAX_VALUE;
+
   /**
    * Default constructor.
    */
@@ -96,11 +104,32 @@ public final class CopyListingFileStatus implements Writable {
         fileStatus.getPath());
   }
 
+  public CopyListingFileStatus(FileStatus fileStatus,
+      long chunkOffset, long chunkLength) {
+    this(fileStatus.getLen(), fileStatus.isDirectory(),
+        fileStatus.getReplication(), fileStatus.getBlockSize(),
+        fileStatus.getModificationTime(), fileStatus.getAccessTime(),
+        fileStatus.getPermission(), fileStatus.getOwner(),
+        fileStatus.getGroup(),
+        fileStatus.getPath());
+    this.chunkOffset = chunkOffset;
+    this.chunkLength = chunkLength;
+  }
+
   @SuppressWarnings("checkstyle:parameternumber")
   public CopyListingFileStatus(long length, boolean isdir,
       int blockReplication, long blocksize, long modificationTime,
       long accessTime, FsPermission permission, String owner, String group,
       Path path) {
+    this(length, isdir, blockReplication, blocksize, modificationTime,
+        accessTime, permission, owner, group, path, 0, Long.MAX_VALUE);
+  }
+
+  @SuppressWarnings("checkstyle:parameternumber")
+  public CopyListingFileStatus(long length, boolean isdir,
+      int blockReplication, long blocksize, long modificationTime,
+      long accessTime, FsPermission permission, String owner, String group,
+      Path path, long chunkOffset, long chunkLength) {
     this.length = length;
     this.isdir = isdir;
     this.blockReplication = (short)blockReplication;
@@ -117,6 +146,23 @@ public final class CopyListingFileStatus implements Writable {
     this.owner = (owner == null) ? "" : owner;
     this.group = (group == null) ? "" : group;
     this.path = path;
+    this.chunkOffset = chunkOffset;
+    this.chunkLength = chunkLength;
+  }
+
+  public CopyListingFileStatus(CopyListingFileStatus other) {
+    this.length = other.length;
+    this.isdir = other.isdir;
+    this.blockReplication = other.blockReplication;
+    this.blocksize = other.blocksize;
+    this.modificationTime = other.modificationTime;
+    this.accessTime = other.accessTime;
+    this.permission = other.permission;
+    this.owner = other.owner;
+    this.group = other.group;
+    this.path = new Path(other.path.toUri());
+    this.chunkOffset = other.chunkOffset;
+    this.chunkLength = other.chunkLength;
   }
 
   public Path getPath() {
@@ -200,6 +246,31 @@ public final class CopyListingFileStatus implements Writable {
     this.xAttrs = xAttrs;
   }
 
+  public long getChunkOffset() {
+    return chunkOffset;
+  }
+
+  public void setChunkOffset(long offset) {
+    this.chunkOffset = offset;
+  }
+
+  public long getChunkLength() {
+    return chunkLength;
+  }
+
+  public void setChunkLength(long chunkLength) {
+    this.chunkLength = chunkLength;
+  }
+
+  public boolean isSplit() {
+    return getChunkLength() != Long.MAX_VALUE &&
+        getChunkLength() != getLen();
+  }
+
+  public long getSizeToCopy() {
+    return isSplit()? getChunkLength() : getLen();
+  }
+
   @Override
   public void write(DataOutput out) throws IOException {
     Text.writeString(out, getPath().toString(), Text.DEFAULT_MAX_LEN);
@@ -244,6 +315,9 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       out.writeInt(NO_XATTRS);
     }
+
+    out.writeLong(chunkOffset);
+    out.writeLong(chunkLength);
   }
 
   @Override
@@ -292,6 +366,9 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       xAttrs = null;
     }
+
+    chunkOffset = in.readLong();
+    chunkLength = in.readLong();
   }
 
   @Override
@@ -317,8 +394,14 @@ public final class CopyListingFileStatus implements Writable {
   public String toString() {
     StringBuilder sb = new StringBuilder(super.toString());
     sb.append('{');
-    sb.append("aclEntries = " + aclEntries);
-    sb.append(", xAttrs = " + xAttrs);
+    sb.append(this.getPath().toString());
+    sb.append(" length = ").append(this.getLen());
+    sb.append(" aclEntries = ").append(aclEntries);
+    sb.append(", xAttrs = ").append(xAttrs);
+    if (isSplit()) {
+      sb.append(", chunkOffset = ").append(this.getChunkOffset());
+      sb.append(", chunkLength = ").append(this.getChunkLength());
+    }
     sb.append('}');
     return sb.toString();
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
index ab58e9c..8c2fa24 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
@@ -35,6 +35,7 @@ import org.apache.hadoop.mapreduce.Cluster;
 import org.apache.hadoop.mapreduce.Job;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobSubmissionFiles;
+import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.CopyListing.*;
 import org.apache.hadoop.tools.mapred.CopyMapper;
 import org.apache.hadoop.tools.mapred.CopyOutputFormat;
@@ -134,6 +135,7 @@ public class DistCp extends Configured implements Tool {
     
     try {
       inputOptions = (OptionsParser.parse(argv));
+      setOptionsForSplitLargeFile();
       setTargetPathExists();
       LOG.info("Input Options: " + inputOptions);
     } catch (Throwable e) {
@@ -235,6 +237,56 @@ public class DistCp extends Configured implements Tool {
     getConf().setBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, 
         targetExists);
   }
+
+  /**
+   * Check if concat is supported by fs.
+   * Throws UnsupportedOperationException if not.
+   */
+  private void checkConcatSupport(FileSystem fs) {
+    try {
+      Path[] src = null;
+      Path tgt = null;
+      fs.concat(tgt, src);
+    } catch (UnsupportedOperationException use) {
+      throw new UnsupportedOperationException(
+          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() +
+          " is not supported since the target file system doesn't" +
+          " support concat.", use);
+    } catch (Exception e) {
+      // Ignore other exception
+    }
+  }
+
+  /**
+   * Set up needed options for splitting large files.
+   */
+  private void setOptionsForSplitLargeFile() throws IOException {
+    if (!inputOptions.splitLargeFile()) {
+      return;
+    }
+    Path target = inputOptions.getTargetPath();
+    FileSystem targetFS = target.getFileSystem(getConf());
+    checkConcatSupport(targetFS);
+
+    LOG.info("Enabling preserving blocksize since "
+        + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " is passed.");
+    inputOptions.preserve(FileAttribute.BLOCKSIZE);
+
+    LOG.info("Set " +
+        DistCpOptionSwitch.APPEND.getSwitch()
+        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
+        + " is passed.");
+    inputOptions.setAppend(false);
+
+    LOG.info("Set " +
+        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES
+        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
+        + " is passed.");
+    getConf().setBoolean(
+        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES, false);
+  }
+
+
   /**
    * Create Job object for submitting it, with all the configuration
    *

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
index fb47d76..ced9b54 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
@@ -169,6 +169,16 @@ public enum DistCpOptionSwitch {
       new Option("sizelimit", true, "(Deprecated!) Limit number of files " +
               "copied to <= n bytes")),
 
+  BLOCKS_PER_CHUNK("",
+      new Option("blocksperchunk", true, "If set to a positive value, files"
+          + "with more blocks than this value will be split into chunks of "
+          + "<blocksperchunk> blocks to be transferred in parallel, and "
+          + "reassembled on the destination. By default, <blocksperchunk> is "
+          + "0 and the files will be transmitted in their entirety without "
+          + "splitting. This switch is only applicable when the source file "
+          + "system implements getBlockLocations method and the target file "
+          + "system implements concat method")),
+
   /**
    * Specify bandwidth per map in MB, accepts bandwidth as a fraction
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/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 8c37ff3..9822d83 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
@@ -97,7 +97,11 @@ public class DistCpOptions {
   // targetPathExist is a derived field, it's initialized in the
   // beginning of distcp.
   private boolean targetPathExists = true;
-  
+
+  // Size of chunk in number of blocks when splitting large file into chunks
+  // to copy in parallel. Default is 0 and file are not splitted.
+  private int blocksPerChunk = 0;
+
   public static enum FileAttribute{
     REPLICATION, BLOCKSIZE, USER, GROUP, PERMISSION, CHECKSUMTYPE, ACL, XATTR, TIMES;
 
@@ -166,6 +170,7 @@ public class DistCpOptions {
       this.targetPath = that.getTargetPath();
       this.targetPathExists = that.getTargetPathExists();
       this.filtersFile = that.getFiltersFile();
+      this.blocksPerChunk = that.blocksPerChunk;
     }
   }
 
@@ -578,6 +583,18 @@ public class DistCpOptions {
     this.filtersFile = filtersFilename;
   }
 
+  public final void setBlocksPerChunk(int csize) {
+    this.blocksPerChunk = csize;
+  }
+
+  public final int getBlocksPerChunk() {
+    return blocksPerChunk;
+  }
+
+  public final boolean splitLargeFile() {
+    return blocksPerChunk > 0;
+  }
+
   void validate() {
     if ((useDiff || useRdiff) && deleteMissing) {
       // -delete and -diff/-rdiff are mutually exclusive. For backward
@@ -669,6 +686,8 @@ public class DistCpOptions {
       DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.FILTERS,
           filtersFile);
     }
+    DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.BLOCKS_PER_CHUNK,
+        String.valueOf(blocksPerChunk));
   }
 
   /**
@@ -704,6 +723,7 @@ public class DistCpOptions {
         ", targetPath=" + targetPath +
         ", targetPathExists=" + targetPathExists +
         ", filtersFile='" + filtersFile + '\'' +
+        ", blocksPerChunk=" + blocksPerChunk +
         '}';
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
index d0f82ca..8881264 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
@@ -172,11 +172,44 @@ public class OptionsParser {
           DistCpOptionSwitch.FILTERS.getSwitch()));
     }
 
+    parseBlocksPerChunk(command, option);
+
     option.validate();
 
     return option;
   }
 
+
+  /**
+   * A helper method to parse chunk size in number of blocks.
+   * Used when breaking large file into chunks to copy in parallel.
+   *
+   * @param command command line arguments
+   */
+  private static void parseBlocksPerChunk(CommandLine command,
+      DistCpOptions option) {
+    boolean hasOption =
+        command.hasOption(DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch());
+    LOG.info("parseChunkSize: " +
+        DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " " + hasOption);
+    if (hasOption) {
+      String chunkSizeString = getVal(command,
+          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch().trim());
+      try {
+        int csize = Integer.parseInt(chunkSizeString);
+        if (csize < 0) {
+          csize = 0;
+        }
+        LOG.info("Set distcp blocksPerChunk to " + csize);
+        option.setBlocksPerChunk(csize);
+      }
+      catch (NumberFormatException e) {
+        throw new IllegalArgumentException("blocksPerChunk is invalid: "
+            + chunkSizeString, e);
+      }
+    }
+  }
+
   /**
    * parseSizeLimit is a helper method for parsing the deprecated
    * argument SIZE_LIMIT.
@@ -211,8 +244,7 @@ public class OptionsParser {
                               DistCpOptionSwitch.FILE_LIMIT.getSwitch().trim());
       try {
         Integer.parseInt(fileLimitString);
-      }
-      catch (NumberFormatException e) {
+      } catch (NumberFormatException e) {
         throw new IllegalArgumentException("File-limit is invalid: "
                                             + fileLimitString, e);
       }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
index 105e4f2..af91347 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
@@ -19,6 +19,7 @@
 package org.apache.hadoop.tools;
 
 import com.google.common.collect.Lists;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.Path;
@@ -47,6 +48,7 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Random;
+import java.util.LinkedList;
 
 import static org.apache.hadoop.tools.DistCpConstants
         .HDFS_RESERVED_RAW_DIRECTORY_NAME;
@@ -240,10 +242,10 @@ public class SimpleCopyListing extends CopyListing {
     final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
     final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
     final boolean preserveRawXAttrs = options.shouldPreserveRawXattrs();
-    CopyListingFileStatus fileCopyListingStatus =
+    LinkedList<CopyListingFileStatus> fileCopyListingStatus =
         DistCpUtils.toCopyListingFileStatus(sourceFS, fileStatus,
-            preserveAcls, preserveXAttrs, preserveRawXAttrs);
-
+            preserveAcls, preserveXAttrs, preserveRawXAttrs,
+            options.getBlocksPerChunk());
     writeToFileListingRoot(fileListWriter, fileCopyListingStatus,
         sourceRoot, options);
   }
@@ -348,9 +350,10 @@ public class SimpleCopyListing extends CopyListing {
         FileStatus[] sourceFiles = sourceFS.listStatus(path);
         boolean explore = (sourceFiles != null && sourceFiles.length > 0);
         if (!explore || rootStatus.isDirectory()) {
-          CopyListingFileStatus rootCopyListingStatus =
-            DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
-                preserveAcls, preserveXAttrs, preserveRawXAttrs);
+          LinkedList<CopyListingFileStatus> rootCopyListingStatus =
+              DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
+                  preserveAcls, preserveXAttrs, preserveRawXAttrs,
+                  options.getBlocksPerChunk());
           writeToFileListingRoot(fileListWriter, rootCopyListingStatus,
               sourcePathRoot, options);
         }
@@ -360,20 +363,20 @@ public class SimpleCopyListing extends CopyListing {
             if (LOG.isDebugEnabled()) {
               LOG.debug("Recording source-path: " + sourceStatus.getPath() + " for copy.");
             }
-            CopyListingFileStatus sourceCopyListingStatus =
-              DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
-                  preserveAcls && sourceStatus.isDirectory(),
-                  preserveXAttrs && sourceStatus.isDirectory(),
-                  preserveRawXAttrs && sourceStatus.isDirectory());
-            if (randomizeFileListing) {
-              addToFileListing(statusList,
-                  new FileStatusInfo(sourceCopyListingStatus, sourcePathRoot),
-                  fileListWriter);
-            } else {
-              writeToFileListing(fileListWriter, sourceCopyListingStatus,
-                  sourcePathRoot);
+            LinkedList<CopyListingFileStatus> sourceCopyListingStatus =
+                DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
+                    preserveAcls && sourceStatus.isDirectory(),
+                    preserveXAttrs && sourceStatus.isDirectory(),
+                    preserveRawXAttrs && sourceStatus.isDirectory(),
+                    options.getBlocksPerChunk());
+            for (CopyListingFileStatus fs : sourceCopyListingStatus) {
+              if (randomizeFileListing) {
+                addToFileListing(statusList,
+                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
+              } else {
+                writeToFileListing(fileListWriter, fs, sourcePathRoot);
+              }
             }
-
             if (sourceStatus.isDirectory()) {
               if (LOG.isDebugEnabled()) {
                 LOG.debug("Adding source dir for traverse: " + sourceStatus.getPath());
@@ -641,18 +644,20 @@ public class SimpleCopyListing extends CopyListing {
             LOG.debug("Recording source-path: " + child.getPath() + " for copy.");
           }
           if (workResult.getSuccess()) {
-            CopyListingFileStatus childCopyListingStatus =
+            LinkedList<CopyListingFileStatus> childCopyListingStatus =
               DistCpUtils.toCopyListingFileStatus(sourceFS, child,
                 preserveAcls && child.isDirectory(),
                 preserveXAttrs && child.isDirectory(),
-                preserveRawXattrs && child.isDirectory());
-            if (randomizeFileListing) {
-              addToFileListing(fileStatuses,
-                  new FileStatusInfo(childCopyListingStatus, sourcePathRoot),
-                  fileListWriter);
-            } else {
-              writeToFileListing(fileListWriter, childCopyListingStatus,
-                  sourcePathRoot);
+                preserveRawXattrs && child.isDirectory(),
+                options.getBlocksPerChunk());
+
+            for (CopyListingFileStatus fs : childCopyListingStatus) {
+              if (randomizeFileListing) {
+                addToFileListing(fileStatuses,
+                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
+              } else {
+                writeToFileListing(fileListWriter, fs, sourcePathRoot);
+              }
             }
           }
           if (retry < maxRetries) {
@@ -675,19 +680,21 @@ public class SimpleCopyListing extends CopyListing {
   }
 
   private void writeToFileListingRoot(SequenceFile.Writer fileListWriter,
-      CopyListingFileStatus fileStatus, Path sourcePathRoot,
+      LinkedList<CopyListingFileStatus> fileStatus, Path sourcePathRoot,
       DistCpOptions options) throws IOException {
     boolean syncOrOverwrite = options.shouldSyncFolder() ||
         options.shouldOverwrite();
-    if (fileStatus.getPath().equals(sourcePathRoot) && 
-        fileStatus.isDirectory() && syncOrOverwrite) {
-      // Skip the root-paths when syncOrOverwrite
-      if (LOG.isDebugEnabled()) {
-        LOG.debug("Skip " + fileStatus.getPath());
-      }      
-      return;
+    for (CopyListingFileStatus fs : fileStatus) {
+      if (fs.getPath().equals(sourcePathRoot) &&
+          fs.isDirectory() && syncOrOverwrite) {
+        // Skip the root-paths when syncOrOverwrite
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Skip " + fs.getPath());
+        }
+        return;
+      }
+      writeToFileListing(fileListWriter, fs, sourcePathRoot);
     }
-    writeToFileListing(fileListWriter, fileStatus, sourcePathRoot);
   }
 
   private void writeToFileListing(SequenceFile.Writer fileListWriter,
@@ -707,7 +714,7 @@ public class SimpleCopyListing extends CopyListing {
     fileListWriter.sync();
 
     if (!fileStatus.isDirectory()) {
-      totalBytesToCopy += fileStatus.getLen();
+      totalBytesToCopy += fileStatus.getSizeToCopy();
     } else {
       totalDirs++;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
index 75cefb4..6ddaab9 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
@@ -27,6 +27,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
+import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobStatus;
 import org.apache.hadoop.mapreduce.TaskAttemptContext;
@@ -34,14 +35,17 @@ import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
 import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.CopyListingFileStatus;
 import org.apache.hadoop.tools.DistCpConstants;
+import org.apache.hadoop.tools.DistCpOptionSwitch;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.GlobbedCopyListing;
 import org.apache.hadoop.tools.util.DistCpUtils;
 
+import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.EnumSet;
+import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -63,7 +67,8 @@ public class CopyCommitter extends FileOutputCommitter {
   private boolean syncFolder = false;
   private boolean overwrite = false;
   private boolean targetPathExists = true;
-  
+  private boolean ignoreFailures = false;
+
   /**
    * Create a output committer
    *
@@ -82,8 +87,13 @@ public class CopyCommitter extends FileOutputCommitter {
     Configuration conf = jobContext.getConfiguration();
     syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false);
     overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false);
-    targetPathExists = conf.getBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
-    
+    targetPathExists = conf.getBoolean(
+        DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
+    ignoreFailures = conf.getBoolean(
+        DistCpOptionSwitch.IGNORE_FAILURES.getConfigLabel(), false);
+
+    concatFileChunks(conf);
+
     super.commitJob(jobContext);
 
     cleanupTempFiles(jobContext);
@@ -169,9 +179,112 @@ public class CopyCommitter extends FileOutputCommitter {
     }
   }
 
+  private boolean isFileNotFoundException(IOException e) {
+    if (e instanceof FileNotFoundException) {
+      return true;
+    }
+
+    if (e instanceof RemoteException) {
+      return ((RemoteException)e).unwrapRemoteException()
+          instanceof FileNotFoundException;
+    }
+
+    return false;
+  }
+
+  /**
+   * Concat chunk files for the same file into one.
+   * Iterate through copy listing, identify chunk files for the same file,
+   * concat them into one.
+   */
+  private void concatFileChunks(Configuration conf) throws IOException {
+
+    LOG.info("concat file chunks ...");
+
+    String spath = conf.get(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH);
+    if (spath == null || spath.isEmpty()) {
+      return;
+    }
+    Path sourceListing = new Path(spath);
+    SequenceFile.Reader sourceReader = new SequenceFile.Reader(conf,
+                                      SequenceFile.Reader.file(sourceListing));
+    Path targetRoot =
+        new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
+
+    try {
+      CopyListingFileStatus srcFileStatus = new CopyListingFileStatus();
+      Text srcRelPath = new Text();
+      CopyListingFileStatus lastFileStatus = null;
+      LinkedList<Path> allChunkPaths = new LinkedList<Path>();
+
+      // Iterate over every source path that was copied.
+      while (sourceReader.next(srcRelPath, srcFileStatus)) {
+        if (srcFileStatus.isDirectory()) {
+          continue;
+        }
+        Path targetFile = new Path(targetRoot.toString() + "/" + srcRelPath);
+        Path targetFileChunkPath =
+            DistCpUtils.getSplitChunkPath(targetFile, srcFileStatus);
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("  add " + targetFileChunkPath + " to concat.");
+        }
+        allChunkPaths.add(targetFileChunkPath);
+        if (srcFileStatus.getChunkOffset() + srcFileStatus.getChunkLength()
+            == srcFileStatus.getLen()) {
+          // This is the last chunk of the splits, consolidate allChunkPaths
+          try {
+            concatFileChunks(conf, targetFile, allChunkPaths);
+          } catch (IOException e) {
+            // If the concat failed because a chunk file doesn't exist,
+            // then we assume that the CopyMapper has skipped copying this
+            // file, and we ignore the exception here.
+            // If a chunk file should have been created but it was not, then
+            // the CopyMapper would have failed.
+            if (!isFileNotFoundException(e)) {
+              String emsg = "Failed to concat chunk files for " + targetFile;
+              if (!ignoreFailures) {
+                throw new IOException(emsg, e);
+              } else {
+                LOG.warn(emsg, e);
+              }
+            }
+          }
+          allChunkPaths.clear();
+          lastFileStatus = null;
+        } else {
+          if (lastFileStatus == null) {
+            lastFileStatus = new CopyListingFileStatus(srcFileStatus);
+          } else {
+            // Two neighboring chunks have to be consecutive ones for the same
+            // file, for them to be merged
+            if (!srcFileStatus.getPath().equals(lastFileStatus.getPath()) ||
+                srcFileStatus.getChunkOffset() !=
+                (lastFileStatus.getChunkOffset() +
+                lastFileStatus.getChunkLength())) {
+              String emsg = "Inconsistent sequence file: current " +
+                  "chunk file " + srcFileStatus + " doesnt match prior " +
+                  "entry " + lastFileStatus;
+              if (!ignoreFailures) {
+                throw new IOException(emsg);
+              } else {
+                LOG.warn(emsg + ", skipping concat this set.");
+              }
+            } else {
+              lastFileStatus.setChunkOffset(srcFileStatus.getChunkOffset());
+              lastFileStatus.setChunkLength(srcFileStatus.getChunkLength());
+            }
+          }
+        }
+      }
+    } finally {
+      IOUtils.closeStream(sourceReader);
+    }
+  }
+
   // This method changes the target-directories' file-attributes (owner,
   // user/group permissions, etc.) based on the corresponding source directories.
-  private void preserveFileAttributesForDirectories(Configuration conf) throws IOException {
+  private void preserveFileAttributesForDirectories(Configuration conf)
+      throws IOException {
     String attrSymbols = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS);
     final boolean syncOrOverwrite = syncFolder || overwrite;
 
@@ -325,4 +438,57 @@ public class CopyCommitter extends FileOutputCommitter {
         ", Unable to move to " + finalDir);
     }
   }
+
+  /**
+   * Concat the passed chunk files into one and rename it the targetFile.
+   */
+  private void concatFileChunks(Configuration conf, Path targetFile,
+      LinkedList<Path> allChunkPaths) throws IOException {
+    if (allChunkPaths.size() == 1) {
+      return;
+    }
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat " + targetFile + " allChunkSize+ "
+          + allChunkPaths.size());
+    }
+    FileSystem dstfs = targetFile.getFileSystem(conf);
+
+    Path firstChunkFile = allChunkPaths.removeFirst();
+    Path[] restChunkFiles = new Path[allChunkPaths.size()];
+    allChunkPaths.toArray(restChunkFiles);
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat: firstchunk: " + dstfs.getFileStatus(firstChunkFile));
+      int i = 0;
+      for (Path f : restChunkFiles) {
+        LOG.debug("concat: other chunk: " + i + ": " + dstfs.getFileStatus(f));
+        ++i;
+      }
+    }
+    dstfs.concat(firstChunkFile, restChunkFiles);
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("concat: result: " + dstfs.getFileStatus(firstChunkFile));
+    }
+    rename(dstfs, firstChunkFile, targetFile);
+  }
+
+  /**
+   * Rename tmp to dst on destFileSys.
+   * @param destFileSys the file ssystem
+   * @param tmp the source path
+   * @param dst the destination path
+   * @throws IOException if renaming failed
+   */
+  private static void rename(FileSystem destFileSys, Path tmp, Path dst)
+      throws IOException {
+    try {
+      if (destFileSys.exists(dst)) {
+        destFileSys.delete(dst, true);
+      }
+      destFileSys.rename(tmp, dst);
+    } catch (IOException ioe) {
+      throw new IOException("Fail to rename tmp file (=" + tmp
+          + ") to destination file (=" + dst + ")", ioe);
+    }
+  }
+
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
index e1873f1..d6b3ba8 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
@@ -156,10 +156,12 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         sourceFS = sourcePath.getFileSystem(conf);
         final boolean preserveXAttrs =
             fileAttributes.contains(FileAttribute.XATTR);
-        sourceCurrStatus = DistCpUtils.toCopyListingFileStatus(sourceFS,
-          sourceFS.getFileStatus(sourcePath),
-          fileAttributes.contains(FileAttribute.ACL), 
-          preserveXAttrs, preserveRawXattrs);
+        sourceCurrStatus = DistCpUtils.toCopyListingFileStatusHelper(sourceFS,
+            sourceFS.getFileStatus(sourcePath),
+            fileAttributes.contains(FileAttribute.ACL),
+            preserveXAttrs, preserveRawXattrs,
+            sourceFileStatus.getChunkOffset(),
+            sourceFileStatus.getChunkLength());
       } catch (FileNotFoundException e) {
         throw new IOException(new RetriableFileCopyCommand.CopyReadException(e));
       }
@@ -173,7 +175,8 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
           LOG.debug("Path could not be found: " + target, ignore);
       }
 
-      if (targetStatus != null && (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
+      if (targetStatus != null &&
+          (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
         throw new IOException("Can't replace " + target + ". Target is " +
             getFileType(targetStatus) + ", Source is " + getFileType(sourceCurrStatus));
       }
@@ -183,19 +186,28 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         return;
       }
 
-      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target, targetStatus);
+      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target,
+          targetStatus);
+
+      Path tmpTarget = target;
       if (action == FileAction.SKIP) {
         LOG.info("Skipping copy of " + sourceCurrStatus.getPath()
                  + " to " + target);
         updateSkipCounters(context, sourceCurrStatus);
         context.write(null, new Text("SKIP: " + sourceCurrStatus.getPath()));
+
       } else {
-        copyFileWithRetry(description, sourceCurrStatus, target, context,
+        if (sourceCurrStatus.isSplit()) {
+          tmpTarget = DistCpUtils.getSplitChunkPath(target, sourceCurrStatus);
+        }
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("copying " + sourceCurrStatus + " " + tmpTarget);
+        }
+        copyFileWithRetry(description, sourceCurrStatus, tmpTarget, context,
             action, fileAttributes);
       }
-
-      DistCpUtils.preserve(target.getFileSystem(conf), target, sourceCurrStatus,
-          fileAttributes, preserveRawXattrs);
+      DistCpUtils.preserve(target.getFileSystem(conf), tmpTarget,
+          sourceCurrStatus, fileAttributes, preserveRawXattrs);
     } catch (IOException exception) {
       handleFailures(exception, sourceFileStatus, target, context);
     }
@@ -261,8 +273,12 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
   private void handleFailures(IOException exception,
       CopyListingFileStatus sourceFileStatus, Path target, Context context)
       throws IOException, InterruptedException {
-    LOG.error("Failure in copying " + sourceFileStatus.getPath() + " to " +
-                target, exception);
+    LOG.error("Failure in copying " + sourceFileStatus.getPath() +
+        (sourceFileStatus.isSplit()? ","
+            + " offset=" + sourceFileStatus.getChunkOffset()
+            + " chunkLength=" + sourceFileStatus.getChunkLength()
+            : "") +
+        " to " + target, exception);
 
     if (ignoreFailures &&
         ExceptionUtils.indexOfType(exception, CopyReadException.class) != -1) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
index 06acd78..2c17fef 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
@@ -118,17 +118,21 @@ public class RetriableFileCopyCommand extends RetriableCommand {
           .contains(FileAttribute.CHECKSUMTYPE) ? sourceFS
           .getFileChecksum(sourcePath) : null;
 
-      final long offset = action == FileAction.APPEND ? targetFS.getFileStatus(
-          target).getLen() : 0;
+      long offset = (action == FileAction.APPEND) ?
+          targetFS.getFileStatus(target).getLen() : source.getChunkOffset();
       long bytesRead = copyToFile(targetPath, targetFS, source,
           offset, context, fileAttributes, sourceChecksum);
 
-      compareFileLengths(source, targetPath, configuration, bytesRead
-          + offset);
+      if (!source.isSplit()) {
+        compareFileLengths(source, targetPath, configuration, bytesRead
+            + offset);
+      }
       //At this point, src&dest lengths are same. if length==0, we skip checksum
       if ((bytesRead != 0) && (!skipCrc)) {
-        compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
-            targetFS, targetPath);
+        if (!source.isSplit()) {
+          compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
+              targetFS, targetPath);
+        }
       }
       // it's not append case, thus we first write to a temporary file, rename
       // it to the target path.
@@ -249,16 +253,26 @@ public class RetriableFileCopyCommand extends RetriableCommand {
     ThrottledInputStream inStream = null;
     long totalBytesRead = 0;
 
+    long chunkLength = source2.getChunkLength();
+    boolean finished = false;
     try {
       inStream = getInputStream(source, context.getConfiguration());
       int bytesRead = readBytes(inStream, buf, sourceOffset);
       while (bytesRead >= 0) {
+        if (chunkLength > 0 &&
+            (totalBytesRead + bytesRead) >= chunkLength) {
+          bytesRead = (int)(chunkLength - totalBytesRead);
+          finished = true;
+        }
         totalBytesRead += bytesRead;
         if (action == FileAction.APPEND) {
           sourceOffset += bytesRead;
         }
         outStream.write(buf, 0, bytesRead);
         updateContextStatus(totalBytesRead, context, source2);
+        if (finished) {
+          break;
+        }
         bytesRead = readBytes(inStream, buf, sourceOffset);
       }
       outStream.close();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
index 3e86d09..d1c18ea 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
@@ -99,7 +99,8 @@ public class UniformSizeInputFormat
       while (reader.next(srcRelPath, srcFileStatus)) {
         // If adding the current file would cause the bytes per map to exceed
         // limit. Add the current file to new split
-        if (currentSplitSize + srcFileStatus.getLen() > nBytesPerSplit && lastPosition != 0) {
+        if (currentSplitSize + srcFileStatus.getChunkLength() > nBytesPerSplit
+            && lastPosition != 0) {
           FileSplit split = new FileSplit(listingFilePath, lastSplitStart,
               lastPosition - lastSplitStart, null);
           if (LOG.isDebugEnabled()) {
@@ -109,7 +110,7 @@ public class UniformSizeInputFormat
           lastSplitStart = lastPosition;
           currentSplitSize = 0;
         }
-        currentSplitSize += srcFileStatus.getLen();
+        currentSplitSize += srcFileStatus.getChunkLength();
         lastPosition = reader.getPosition();
       }
       if (lastPosition > lastSplitStart) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
index 76bc4c5..e315b84 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
@@ -19,9 +19,11 @@
 package org.apache.hadoop.tools.util;
 
 import com.google.common.collect.Maps;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.FileChecksum;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
@@ -30,6 +32,7 @@ import org.apache.hadoop.fs.XAttr;
 import org.apache.hadoop.fs.permission.AclEntry;
 import org.apache.hadoop.fs.permission.AclUtil;
 import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.mapreduce.InputFormat;
@@ -44,6 +47,7 @@ import org.apache.hadoop.util.StringUtils;
 import java.io.IOException;
 import java.text.DecimalFormat;
 import java.util.EnumSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -116,7 +120,7 @@ public class DistCpUtils {
    * @return Class implementing the strategy specified in options.
    */
   public static Class<? extends InputFormat> getStrategy(Configuration conf,
-                                                                 DistCpOptions options) {
+      DistCpOptions options) {
     String confLabel = "distcp."
         + StringUtils.toLowerCase(options.getCopyStrategy())
         + ".strategy" + ".impl";
@@ -298,6 +302,86 @@ public class DistCpUtils {
   }
 
   /**
+   * Converts FileStatus to a list of CopyListingFileStatus.
+   * The resulted list contains either one CopyListingFileStatus per chunk of
+   * file-blocks (if file-size exceeds blockSize * blocksPerChunk, and there
+   * are more blocks in the file than blocksperChunk), or a single
+   * CopyListingFileStatus for the entire file (if file-size is too small to
+   * split).
+   * If preserving ACLs, populates the CopyListingFileStatus with the ACLs.
+   * If preserving XAttrs, populates the CopyListingFileStatus with the XAttrs.
+   *
+   * @param fileSystem FileSystem containing the file
+   * @param fileStatus FileStatus of file
+   * @param preserveAcls boolean true if preserving ACLs
+   * @param preserveXAttrs boolean true if preserving XAttrs
+   * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
+   * @param blocksPerChunk size of chunks when copying chunks in parallel
+   * @return list of CopyListingFileStatus
+   * @throws IOException if there is an I/O error
+   */
+  public static LinkedList<CopyListingFileStatus> toCopyListingFileStatus(
+      FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls,
+      boolean preserveXAttrs, boolean preserveRawXAttrs, int blocksPerChunk)
+          throws IOException {
+    LinkedList<CopyListingFileStatus> copyListingFileStatus =
+        new LinkedList<CopyListingFileStatus>();
+
+    final CopyListingFileStatus clfs = toCopyListingFileStatusHelper(
+        fileSystem, fileStatus, preserveAcls,
+        preserveXAttrs, preserveRawXAttrs,
+        0, fileStatus.getLen());
+    final long blockSize = fileStatus.getBlockSize();
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("toCopyListing: " + fileStatus + " chunkSize: "
+          + blocksPerChunk + " isDFS: " +
+          (fileSystem instanceof DistributedFileSystem));
+    }
+    if ((blocksPerChunk > 0) &&
+        !fileStatus.isDirectory() &&
+        (fileStatus.getLen() > blockSize * blocksPerChunk)) {
+      // split only when the file size is larger than the intended chunk size
+      final BlockLocation[] blockLocations;
+      blockLocations = fileSystem.getFileBlockLocations(fileStatus, 0,
+            fileStatus.getLen());
+
+      int numBlocks = blockLocations.length;
+      long curPos = 0;
+      if (numBlocks <= blocksPerChunk) {
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("  add file " + clfs);
+        }
+        copyListingFileStatus.add(clfs);
+      } else {
+        int i = 0;
+        while (i < numBlocks) {
+          long curLength = 0;
+          for (int j = 0; j < blocksPerChunk && i < numBlocks; ++j, ++i) {
+            curLength += blockLocations[i].getLength();
+          }
+          if (curLength > 0) {
+            CopyListingFileStatus clfs1 = new CopyListingFileStatus(clfs);
+            clfs1.setChunkOffset(curPos);
+            clfs1.setChunkLength(curLength);
+            if (LOG.isDebugEnabled()) {
+              LOG.debug("  add file chunk " + clfs1);
+            }
+            copyListingFileStatus.add(clfs1);
+            curPos += curLength;
+          }
+        }
+      }
+    } else {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("  add file/dir " + clfs);
+      }
+      copyListingFileStatus.add(clfs);
+    }
+
+    return copyListingFileStatus;
+  }
+
+  /**
    * Converts a FileStatus to a CopyListingFileStatus.  If preserving ACLs,
    * populates the CopyListingFileStatus with the ACLs. If preserving XAttrs,
    * populates the CopyListingFileStatus with the XAttrs.
@@ -307,13 +391,17 @@ public class DistCpUtils {
    * @param preserveAcls boolean true if preserving ACLs
    * @param preserveXAttrs boolean true if preserving XAttrs
    * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
+   * @param chunkOffset chunk offset in bytes
+   * @param chunkLength chunk length in bytes
+   * @return CopyListingFileStatus
    * @throws IOException if there is an I/O error
    */
-  public static CopyListingFileStatus toCopyListingFileStatus(
+  public static CopyListingFileStatus toCopyListingFileStatusHelper(
       FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls, 
-      boolean preserveXAttrs, boolean preserveRawXAttrs) throws IOException {
+      boolean preserveXAttrs, boolean preserveRawXAttrs,
+      long chunkOffset, long chunkLength) throws IOException {
     CopyListingFileStatus copyListingFileStatus =
-      new CopyListingFileStatus(fileStatus);
+        new CopyListingFileStatus(fileStatus, chunkOffset, chunkLength);
     if (preserveAcls) {
       FsPermission perm = fileStatus.getPermission();
       if (perm.getAclBit()) {
@@ -470,4 +558,19 @@ public class DistCpUtils {
     return (sourceChecksum == null || targetChecksum == null ||
             sourceChecksum.equals(targetChecksum));
   }
+
+  /*
+   * Return the Path for a given chunk.
+   * Used when splitting large file into chunks to copy in parallel.
+   * @param targetFile path to target file
+   * @param srcFileStatus source file status in copy listing
+   * @return path to the chunk specified by the parameters to store
+   * in target cluster temporarily
+   */
+  public static Path getSplitChunkPath(Path targetFile,
+      CopyListingFileStatus srcFileStatus) {
+    return new Path(targetFile.toString()
+        + ".____distcpSplit____" + srcFileStatus.getChunkOffset()
+        + "." + srcFileStatus.getChunkLength());
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
index 41a6e94..a77deb2 100644
--- a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
+++ b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
@@ -237,6 +237,7 @@ Flag              | Description                          | Notes
 `-rdiff <newSnapshot> <oldSnapshot>` | Use snapshot diff report between given two snapshots to identify what has been changed on the target since the snapshot `<oldSnapshot>` was created on the target, and apply the diff reversely to the target, and copy modified files from the source's `<oldSnapshot>`, to make the target the same as `<oldSnapshot>`. | This option is valid only with `-update` option and the following conditions should be satisfied. <ol><li>Both the source and the target FileSystem must be DistributedFileSystem. The source and the target can be two different clusters/paths, or they can be exactly the same cluster/path. In the latter case, modified files are copied from target's `<oldSnapshot>` to target's current state).</li>  <li> Two snapshots `<newSnapshot>` and `<oldSnapshot>` have been created on the target FS, and `<oldSnapshot>` is older than `<newSnapshot>`. No change has been made on target since `<newSnapshot>` was created on the target. </li> <li> The sour
 ce has the same snapshot `<oldSnapshot>`, which has the same content as the `<oldSnapshot>` on the target. All the files/directories in the target's `<oldSnapshot>` are the same with source's `<oldSnapshot>`.</li> </ol> |
 `-numListstatusThreads` | Number of threads to use for building file listing | At most 40 threads.
 `-skipcrccheck` | Whether to skip CRC checks between source and target paths. |
+`-blocksperchunk <blocksperchunk>` | Number of blocks per chunk. When specified, split files into chunks to copy in parallel | If set to a positive value, files with more blocks than this value will be split into chunks of `<blocksperchunk>` blocks to be transferred in parallel, and reassembled on the destination. By default, `<blocksperchunk>` is 0 and the files will be transmitted in their entirety without splitting. This switch is only applicable when the source file system implements getBlockLocations method and the target file system implements concat method. |
 
 Architecture of DistCp
 ----------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
index e3018a0..b2266b3 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
@@ -23,17 +23,27 @@ import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.OutputStream;
+import java.io.PrintStream;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Random;
 
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.FsShell;
 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.MiniDFSCluster;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.util.ToolRunner;
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -47,11 +57,15 @@ import org.junit.rules.Timeout;
  */
 
 public class TestDistCpSystem {
+  private static final Log LOG =
+      LogFactory.getLog(TestDistCpSystem.class);
+
   @Rule
   public Timeout globalTimeout = new Timeout(30000);
 
   private static final String SRCDAT = "srcdat";
   private static final String DSTDAT = "dstdat";
+  private static final long BLOCK_SIZE = 1024;
 
   private static MiniDFSCluster cluster;
   private static Configuration conf;
@@ -63,27 +77,76 @@ public class TestDistCpSystem {
       this.path = path;
       this.isDir = isDir;
     }
-    String getPath() { return path; }
-    boolean isDirectory() { return isDir; }
+
+    String getPath() {
+      return path;
+    }
+
+    boolean isDirectory() {
+      return isDir;
+    }
+  }
+
+  @BeforeClass
+  public static void beforeClass() throws IOException {
+    conf = new Configuration();
+    conf.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, BLOCK_SIZE);
+    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
+    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
+    cluster.waitActive();
+  }
+
+  @AfterClass
+  public static void afterClass() throws IOException {
+    if (cluster != null) {
+      cluster.shutdown();
+    }
+  }
+
+  static String execCmd(FsShell shell, String... args) throws Exception {
+    ByteArrayOutputStream baout = new ByteArrayOutputStream();
+    PrintStream out = new PrintStream(baout, true);
+    PrintStream old = System.out;
+    System.setOut(out);
+    shell.run(args);
+    out.close();
+    System.setOut(old);
+    return baout.toString();
   }
   
-  private void createFiles(FileSystem fs, String topdir,
-      FileEntry[] entries) throws IOException {
+  private void createFiles(DistributedFileSystem fs, String topdir,
+      FileEntry[] entries, long chunkSize) throws IOException {
+    long seed = System.currentTimeMillis();
+    Random rand = new Random(seed);
+    short replicationFactor = 2;
     for (FileEntry entry : entries) {
-      Path newpath = new Path(topdir + "/" + entry.getPath());
+      Path newPath = new Path(topdir + "/" + entry.getPath());
       if (entry.isDirectory()) {
-        fs.mkdirs(newpath);
+        fs.mkdirs(newPath);
       } else {
-        OutputStream out = fs.create(newpath);
-        try {
-          out.write((topdir + "/" + entry).getBytes());
-          out.write("\n".getBytes());
-        } finally {
-          out.close();
+        long fileSize = BLOCK_SIZE *100;
+        int bufSize = 128;
+        if (chunkSize == -1) {
+          DFSTestUtil.createFile(fs, newPath, bufSize,
+              fileSize, BLOCK_SIZE, replicationFactor, seed);
+        } else {
+          // Create a variable length block file, by creating
+          // one block of half block size at the chunk boundary
+          long seg1 = chunkSize * BLOCK_SIZE - BLOCK_SIZE / 2;
+          long seg2 = fileSize - seg1;
+          DFSTestUtil.createFile(fs, newPath, bufSize,
+              seg1, BLOCK_SIZE, replicationFactor, seed);
+          DFSTestUtil.appendFileNewBlock(fs, newPath, (int)seg2);
         }
       }
+      seed = System.currentTimeMillis() + rand.nextLong();
     }
   }
+
+  private void createFiles(DistributedFileSystem fs, String topdir,
+      FileEntry[] entries) throws IOException {
+    createFiles(fs, topdir, entries, -1);
+  }
    
   private static FileStatus[] getFileStatus(FileSystem fs,
       String topdir, FileEntry[] files) throws IOException {
@@ -104,18 +167,19 @@ public class TestDistCpSystem {
   }
 
   private void testPreserveUserHelper(String testRoot,
-                                      FileEntry[] srcEntries,
-                                      FileEntry[] dstEntries,
-                                      boolean createSrcDir,
-                                      boolean createTgtDir,
-                                      boolean update) throws Exception {
+      FileEntry[] srcEntries,
+      FileEntry[] dstEntries,
+      boolean createSrcDir,
+      boolean createTgtDir,
+      boolean update) throws Exception {
     final String testSrcRel = SRCDAT;
     final String testSrc = testRoot + "/" + testSrcRel;
     final String testDstRel = DSTDAT;
     final String testDst = testRoot + "/" + testDstRel;
 
     String nnUri = FileSystem.getDefaultUri(conf).toString();
-    FileSystem fs = FileSystem.get(URI.create(nnUri), conf);
+    DistributedFileSystem fs = (DistributedFileSystem)
+        FileSystem.get(URI.create(nnUri), conf);
     fs.mkdirs(new Path(testRoot));
     if (createSrcDir) {
       fs.mkdirs(new Path(testSrc));
@@ -129,8 +193,8 @@ public class TestDistCpSystem {
     for(int i = 0; i < srcEntries.length; i++) {
       fs.setOwner(srcstats[i].getPath(), "u" + i, null);
     }
-    String[] args = update? new String[]{"-pu", "-update", nnUri+testSrc,
-        nnUri+testDst} : new String[]{"-pu", nnUri+testSrc, nnUri+testDst};
+    String[] args = update? new String[]{"-pub", "-update", nnUri+testSrc,
+        nnUri+testDst} : new String[]{"-pub", nnUri+testSrc, nnUri+testDst};
 
     ToolRunner.run(conf, new DistCp(), args);
 
@@ -145,20 +209,263 @@ public class TestDistCpSystem {
     deldir(fs, testRoot);
   }
 
-  @BeforeClass
-  public static void beforeClass() throws IOException {
-    conf = new Configuration();
-    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
-    cluster.waitActive();
+  private void compareFiles(FileSystem fs, FileStatus srcStat,
+      FileStatus dstStat) throws Exception {
+    LOG.info("Comparing " + srcStat + " and " + dstStat);
+    assertEquals(srcStat.isDirectory(), dstStat.isDirectory());
+    assertEquals(srcStat.getReplication(), dstStat.getReplication());
+    assertEquals("File POSIX permission should match",
+        srcStat.getPermission(), dstStat.getPermission());
+    assertEquals("File user ownership should match",
+        srcStat.getOwner(), dstStat.getOwner());
+    assertEquals("File group ownership should match",
+        srcStat.getGroup(), dstStat.getGroup());
+    // TODO; check ACL attributes
+
+    if (srcStat.isDirectory()) {
+      return;
+    }
+
+    assertEquals("File length should match (" + srcStat.getPath() + ")",
+        srcStat.getLen(), dstStat.getLen());
+
+    FSDataInputStream srcIn = fs.open(srcStat.getPath());
+    FSDataInputStream dstIn = fs.open(dstStat.getPath());
+    try {
+      byte[] readSrc = new byte[(int)
+                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
+      byte[] readDst = new byte[(int)
+                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
+
+      int srcBytesRead = 0, tgtBytesRead = 0;
+      int srcIdx = 0, tgtIdx = 0;
+      long totalComparedBytes = 0;
+      while (true) {
+        if (srcBytesRead == 0) {
+          srcBytesRead = srcIn.read(readSrc);
+          srcIdx = 0;
+        }
+        if (tgtBytesRead == 0) {
+          tgtBytesRead = dstIn.read(readDst);
+          tgtIdx = 0;
+        }
+        if (srcBytesRead == 0 || tgtBytesRead == 0) {
+          LOG.info("______ compared src and dst files for "
+              + totalComparedBytes + " bytes, content match.");
+          if (srcBytesRead != tgtBytesRead) {
+            Assert.fail("Read mismatching size, compared "
+                + totalComparedBytes + " bytes between src and dst file "
+                + srcStat + " and " + dstStat);
+          }
+          if (totalComparedBytes != srcStat.getLen()) {
+            Assert.fail("Only read/compared " + totalComparedBytes +
+                " bytes between src and dst file " + srcStat +
+                " and " + dstStat);
+          } else {
+            // success
+            break;
+          }
+        }
+        for (; srcIdx < srcBytesRead && tgtIdx < tgtBytesRead;
+            ++srcIdx, ++tgtIdx) {
+          if (readSrc[srcIdx] != readDst[tgtIdx]) {
+            Assert.fail("src and dst file does not match at "
+                + totalComparedBytes + " between "
+                + srcStat + " and " + dstStat);
+          }
+          ++totalComparedBytes;
+        }
+        LOG.info("______ compared src and dst files for "
+            + totalComparedBytes + " bytes, content match. FileLength: "
+            + srcStat.getLen());
+        if (totalComparedBytes == srcStat.getLen()) {
+          LOG.info("______ Final:" + srcIdx + " "
+              + srcBytesRead + " " + tgtIdx + " " + tgtBytesRead);
+          break;
+        }
+        if (srcIdx == srcBytesRead) {
+          srcBytesRead = 0;
+        }
+        if (tgtIdx == tgtBytesRead) {
+          tgtBytesRead = 0;
+        }
+      }
+    } finally {
+      if (srcIn != null) {
+        srcIn.close();
+      }
+      if (dstIn != null) {
+        dstIn.close();
+      }
+    }
   }
 
-  @AfterClass
-  public static void afterClass() throws IOException {
-    if (cluster != null) {
-      cluster.shutdown();
+  // WC: needed because the current distcp does not create target dirs
+  private void createDestDir(FileSystem fs, String testDst,
+      FileStatus[] srcStats, FileEntry[] srcFiles) throws IOException {
+    fs.mkdirs(new Path(testDst));
+
+    for (int i=0; i<srcStats.length; i++) {
+      FileStatus srcStat = srcStats[i];
+      if (srcStat.isDirectory()) {
+        Path dstPath = new Path(testDst, srcFiles[i].getPath());
+        fs.mkdirs(dstPath);
+        fs.setOwner(dstPath, srcStat.getOwner(), srcStat.getGroup());
+      }
+    }
+  }
+
+  private void copyAndVerify(final DistributedFileSystem fs,
+      final FileEntry[] srcFiles, final FileStatus[] srcStats,
+      final String testDst,
+      final String[] args) throws Exception {
+    final String testRoot = "/testdir";
+    FsShell shell = new FsShell(fs.getConf());
+
+    LOG.info("ls before distcp");
+    LOG.info(execCmd(shell, "-lsr", testRoot));
+
+    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
+    ToolRunner.run(conf, new DistCp(), args);
+
+    LOG.info("ls after distcp");
+    LOG.info(execCmd(shell, "-lsr", testRoot));
+
+    FileStatus[] dstStat = getFileStatus(fs, testDst, srcFiles);
+    for (int i=0; i< dstStat.length; i++) {
+      compareFiles(fs, srcStats[i], dstStat[i]);
     }
   }
 
+  private void chunkCopy(FileEntry[] srcFiles) throws Exception {
+    final String testRoot = "/testdir";
+    final String testSrcRel = SRCDAT;
+    final String testSrc = testRoot + "/" + testSrcRel;
+    final String testDstRel = DSTDAT;
+    final String testDst = testRoot + "/" + testDstRel;
+    long chunkSize = 8;
+
+    String nnUri = FileSystem.getDefaultUri(conf).toString();
+    DistributedFileSystem fs = (DistributedFileSystem)
+        FileSystem.get(URI.create(nnUri), conf);
+
+    createFiles(fs, testRoot, srcFiles, chunkSize);
+
+    FileStatus[] srcStats = getFileStatus(fs, testRoot, srcFiles);
+    for (int i = 0; i < srcFiles.length; i++) {
+      fs.setOwner(srcStats[i].getPath(), "u" + i,  "g" + i);
+    }
+    // get file status after updating owners
+    srcStats = getFileStatus(fs, testRoot, srcFiles);
+
+    createDestDir(fs, testDst, srcStats, srcFiles);
+
+    String[] args = new String[] {"-pugp", "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc, nnUri + testDst};
+
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+    // Do it again
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+
+    // modify last file and rerun distcp with -update option
+    LOG.info("Modify a file and copy again");
+    for(int i=srcFiles.length-1; i >=0; --i) {
+      if (!srcFiles[i].isDirectory()) {
+        LOG.info("Modifying " + srcStats[i].getPath());
+        DFSTestUtil.appendFileNewBlock(fs, srcStats[i].getPath(),
+            (int)BLOCK_SIZE * 3);
+        break;
+      }
+    }
+    // get file status after modifying file
+    srcStats = getFileStatus(fs, testRoot, srcFiles);
+
+    args = new String[] {"-pugp", "-update", "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc, nnUri + testDst + "/" + testSrcRel};
+
+    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
+
+    deldir(fs, testRoot);
+  }
+
+  @Test
+  public void testRecursiveChunkCopy() throws Exception {
+    FileEntry[] srcFiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file0", false),
+        new FileEntry(SRCDAT + "/dir1", true),
+        new FileEntry(SRCDAT + "/dir2", true),
+        new FileEntry(SRCDAT + "/dir1/file1", false)
+    };
+    chunkCopy(srcFiles);
+  }
+
+  @Test
+  public void testChunkCopyOneFile() throws Exception {
+    FileEntry[] srcFiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file0", false)
+    };
+    chunkCopy(srcFiles);
+  }
+
+  @Test
+  public void testDistcpLargeFile() throws Exception {
+    FileEntry[] srcfiles = {
+        new FileEntry(SRCDAT, true),
+        new FileEntry(SRCDAT + "/file", false)
+    };
+
+    final String testRoot = "/testdir";
+    final String testSrcRel = SRCDAT;
+    final String testSrc = testRoot + "/" + testSrcRel;
+    final String testDstRel = DSTDAT;
+    final String testDst = testRoot + "/" + testDstRel;
+
+    String nnUri = FileSystem.getDefaultUri(conf).toString();
+    DistributedFileSystem fs =
+        (DistributedFileSystem) FileSystem.get(URI.create(nnUri), conf);
+    fs.mkdirs(new Path(testRoot));
+    fs.mkdirs(new Path(testSrc));
+    fs.mkdirs(new Path(testDst));
+    long chunkSize = 6;
+    createFiles(fs, testRoot, srcfiles, chunkSize);
+
+    String srcFileName = testRoot + Path.SEPARATOR + srcfiles[1].getPath();
+    Path srcfile = new Path(srcFileName);
+
+    if(!cluster.getFileSystem().exists(srcfile)){
+      throw new Exception("src not exist");
+    }
+
+    final long srcLen = fs.getFileStatus(srcfile).getLen();
+
+    FileStatus[] srcstats = getFileStatus(fs, testRoot, srcfiles);
+    for (int i = 0; i < srcfiles.length; i++) {
+      fs.setOwner(srcstats[i].getPath(), "u" + i, null);
+    }
+    String[] args = new String[] {
+        "-blocksperchunk",
+        String.valueOf(chunkSize),
+        nnUri + testSrc,
+        nnUri + testDst
+    };
+
+    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
+    ToolRunner.run(conf, new DistCp(), args);
+
+    String realTgtPath = testDst;
+    FileStatus[] dststat = getFileStatus(fs, realTgtPath, srcfiles);
+    assertEquals("File length should match", srcLen,
+        dststat[dststat.length - 1].getLen());
+
+    this.compareFiles(fs,  srcstats[srcstats.length-1],
+        dststat[dststat.length-1]);
+    deldir(fs, testRoot);
+  }
+
   @Test
   public void testPreserveUseNonEmptyDir() throws Exception {
     String testRoot = "/testdir." + getMethodName();
@@ -180,7 +487,6 @@ public class TestDistCpSystem {
     testPreserveUserHelper(testRoot, srcfiles, dstfiles, false, false, false);
   }
 
-
   @Test
   public void testPreserveUserEmptyDir() throws Exception {
     String testRoot = "/testdir." + getMethodName();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/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 efe4627..f94ba97 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
@@ -394,7 +394,7 @@ public class TestOptionsParser {
         + "copyStrategy='uniformsize', preserveStatus=[], "
         + "preserveRawXattrs=false, atomicWorkPath=null, logPath=null, "
         + "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, "
-        + "targetPathExists=true, filtersFile='null'}";
+        + "targetPathExists=true, filtersFile='null', blocksPerChunk=0}";
     String optionString = option.toString();
     Assert.assertEquals(val, optionString);
     Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),

http://git-wip-us.apache.org/repos/asf/hadoop/blob/92421f27/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
index 2e9a350..2452d6f 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
@@ -81,6 +81,10 @@ public class TestCopyCommitter {
   @Before
   public void createMetaFolder() {
     config.set(DistCpConstants.CONF_LABEL_META_FOLDER, "/meta");
+    // Unset listing file path since the config is shared by
+    // multiple tests, and some test doesn't set it, such as
+    // testNoCommitAction, but the distcp code will check it.
+    config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, "");
     Path meta = new Path("/meta");
     try {
       cluster.getFileSystem().mkdirs(meta);
@@ -326,7 +330,6 @@ public class TestCopyCommitter {
       committer.commitJob(jobContext);
       Assert.assertFalse(fs.exists(new Path(workPath)));
       Assert.assertTrue(fs.exists(new Path(finalPath)));
-
     } catch (IOException e) {
       LOG.error("Exception encountered while testing for preserve status", e);
       Assert.fail("Atomic commit failure");


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[32/50] [abbrv] hadoop git commit: HDFS-11538. Move ClientProtocol HA proxies into hadoop-hdfs-client. Contributed by Huafeng Wang.

Posted by in...@apache.org.
HDFS-11538. Move ClientProtocol HA proxies into hadoop-hdfs-client. Contributed by Huafeng Wang.


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

Branch: refs/heads/HDFS-10467
Commit: c58c01fe043c0cf7182eccef1b7205adfa091201
Parents: 11406a4
Author: Andrew Wang <wa...@apache.org>
Authored: Tue Apr 4 23:05:24 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSUtilClient.java   |  13 +
 .../org/apache/hadoop/hdfs/HAUtilClient.java    |  55 +++
 .../hadoop/hdfs/NameNodeProxiesClient.java      |  15 +-
 .../hdfs/client/HdfsClientConfigKeys.java       |   1 +
 .../namenode/ha/ClientHAProxyFactory.java       |  44 ++
 .../ha/ConfiguredFailoverProxyProvider.java     | 183 +++++++
 .../hdfs/server/namenode/ha/HAProxyFactory.java |  44 ++
 .../namenode/ha/IPFailoverProxyProvider.java    | 126 +++++
 .../ha/RequestHedgingProxyProvider.java         | 234 +++++++++
 .../ha/TestRequestHedgingProxyProvider.java     | 476 +++++++++++++++++++
 .../org/apache/hadoop/hdfs/DFSConfigKeys.java   |   3 +-
 .../java/org/apache/hadoop/hdfs/DFSUtil.java    |  15 +-
 .../java/org/apache/hadoop/hdfs/HAUtil.java     |  57 +--
 .../org/apache/hadoop/hdfs/NameNodeProxies.java |   3 +-
 .../hadoop/hdfs/server/namenode/DfsServlet.java |  29 +-
 .../ha/ConfiguredFailoverProxyProvider.java     | 216 ---------
 .../namenode/ha/IPFailoverProxyProvider.java    | 132 -----
 .../namenode/ha/NameNodeHAProxyFactory.java     |  45 ++
 .../ha/RequestHedgingProxyProvider.java         | 241 ----------
 .../hadoop/hdfs/TestDFSClientFailover.java      |   4 +-
 .../org/apache/hadoop/hdfs/TestDFSUtil.java     |   2 +-
 .../namenode/ha/TestDelegationTokensWithHA.java |   4 +-
 .../ha/TestRequestHedgingProxyProvider.java     | 470 ------------------
 23 files changed, 1247 insertions(+), 1165 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSUtilClient.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSUtilClient.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSUtilClient.java
index f9b2e8d..2e770cc 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSUtilClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSUtilClient.java
@@ -170,6 +170,19 @@ public class DFSUtilClient {
   }
 
   /**
+   * Returns list of InetSocketAddress corresponding to HA NN RPC addresses from
+   * the configuration.
+   *
+   * @param conf configuration
+   * @return list of InetSocketAddresses
+   */
+  public static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses(
+      Configuration conf) {
+    return DFSUtilClient.getAddresses(conf, null,
+      HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
+  }
+
+  /**
    * Returns list of InetSocketAddress corresponding to HA NN HTTP addresses from
    * the configuration.
    *

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java
index 9f28cfc..47288f7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/HAUtilClient.java
@@ -20,15 +20,29 @@ package org.apache.hadoop.hdfs;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
+import org.apache.hadoop.hdfs.protocol.HdfsConstants;
+import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
+import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSelector;
 import org.apache.hadoop.io.Text;
+import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.security.token.Token;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import java.net.InetSocketAddress;
 import java.net.URI;
+import java.util.Collection;
 
 import static org.apache.hadoop.hdfs.protocol.HdfsConstants.HA_DT_SERVICE_PREFIX;
+import static org.apache.hadoop.security.SecurityUtil.buildTokenService;
 
 @InterfaceAudience.Private
 public class HAUtilClient {
+  private static final Logger LOG = LoggerFactory.getLogger(HAUtilClient.class);
+
+  private static final DelegationTokenSelector tokenSelector =
+      new DelegationTokenSelector();
+
   /**
    * @return true if the given nameNodeUri appears to be a logical URI.
    */
@@ -92,4 +106,45 @@ public class HAUtilClient {
   public static boolean isTokenForLogicalUri(Token<?> token) {
     return token.getService().toString().startsWith(HA_DT_SERVICE_PREFIX);
   }
+
+  /**
+   * Locate a delegation token associated with the given HA cluster URI, and if
+   * one is found, clone it to also represent the underlying namenode address.
+   * @param ugi the UGI to modify
+   * @param haUri the logical URI for the cluster
+   * @param nnAddrs collection of NNs in the cluster to which the token
+   * applies
+   */
+  public static void cloneDelegationTokenForLogicalUri(
+      UserGroupInformation ugi, URI haUri,
+      Collection<InetSocketAddress> nnAddrs) {
+    // this cloning logic is only used by hdfs
+    Text haService = HAUtilClient.buildTokenServiceForLogicalUri(haUri,
+        HdfsConstants.HDFS_URI_SCHEME);
+    Token<DelegationTokenIdentifier> haToken =
+        tokenSelector.selectToken(haService, ugi.getTokens());
+    if (haToken != null) {
+      for (InetSocketAddress singleNNAddr : nnAddrs) {
+        // this is a minor hack to prevent physical HA tokens from being
+        // exposed to the user via UGI.getCredentials(), otherwise these
+        // cloned tokens may be inadvertently propagated to jobs
+        Token<DelegationTokenIdentifier> specificToken =
+            haToken.privateClone(buildTokenService(singleNNAddr));
+        Text alias = new Text(
+            HAUtilClient.buildTokenServicePrefixForLogicalUri(
+                HdfsConstants.HDFS_URI_SCHEME)
+                + "//" + specificToken.getService());
+        ugi.addToken(alias, specificToken);
+        if (LOG.isDebugEnabled()) {
+          LOG.debug("Mapped HA service delegation token for logical URI " +
+              haUri + " to namenode " + singleNNAddr);
+        }
+      }
+    } else {
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("No HA service delegation token found for logical URI " +
+            haUri);
+      }
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
index 5ca7030..a092f02 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/NameNodeProxiesClient.java
@@ -28,6 +28,8 @@ import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.hdfs.server.namenode.ha.ClientHAProxyFactory;
+import org.apache.hadoop.hdfs.server.namenode.ha.HAProxyFactory;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -212,6 +214,14 @@ public class NameNodeProxiesClient {
   public static <T> AbstractNNFailoverProxyProvider<T> createFailoverProxyProvider(
       Configuration conf, URI nameNodeUri, Class<T> xface, boolean checkPort,
       AtomicBoolean fallbackToSimpleAuth) throws IOException {
+    return createFailoverProxyProvider(conf, nameNodeUri, xface, checkPort,
+      fallbackToSimpleAuth, new ClientHAProxyFactory<T>());
+  }
+
+  protected static <T> AbstractNNFailoverProxyProvider<T> createFailoverProxyProvider(
+      Configuration conf, URI nameNodeUri, Class<T> xface, boolean checkPort,
+      AtomicBoolean fallbackToSimpleAuth, HAProxyFactory<T> proxyFactory)
+      throws IOException {
     Class<FailoverProxyProvider<T>> failoverProxyProviderClass = null;
     AbstractNNFailoverProxyProvider<T> providerNN;
     try {
@@ -223,9 +233,10 @@ public class NameNodeProxiesClient {
       }
       // Create a proxy provider instance.
       Constructor<FailoverProxyProvider<T>> ctor = failoverProxyProviderClass
-          .getConstructor(Configuration.class, URI.class, Class.class);
+          .getConstructor(Configuration.class, URI.class,
+              Class.class, HAProxyFactory.class);
       FailoverProxyProvider<T> provider = ctor.newInstance(conf, nameNodeUri,
-          xface);
+          xface, proxyFactory);
 
       // If the proxy provider is of an old implementation, wrap it.
       if (!(provider instanceof AbstractNNFailoverProxyProvider)) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/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 1a38806..c152a4b 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
@@ -67,6 +67,7 @@ public interface HdfsClientConfigKeys {
 
   String PREFIX = "dfs.client.";
   String  DFS_NAMESERVICES = "dfs.nameservices";
+  String DFS_NAMENODE_RPC_ADDRESS_KEY = "dfs.namenode.rpc-address";
   int     DFS_NAMENODE_HTTP_PORT_DEFAULT = 9870;
   String  DFS_NAMENODE_HTTP_ADDRESS_KEY = "dfs.namenode.http-address";
   int     DFS_NAMENODE_HTTPS_PORT_DEFAULT = 9871;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ClientHAProxyFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ClientHAProxyFactory.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ClientHAProxyFactory.java
new file mode 100644
index 0000000..b887d87
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ClientHAProxyFactory.java
@@ -0,0 +1,44 @@
+/**
+ * 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.namenode.ha;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.NameNodeProxiesClient;
+import org.apache.hadoop.security.UserGroupInformation;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class ClientHAProxyFactory<T> implements HAProxyFactory<T> {
+  @Override
+  @SuppressWarnings("unchecked")
+  public T createProxy(Configuration conf, InetSocketAddress nnAddr,
+      Class<T> xface, UserGroupInformation ugi, boolean withRetries,
+      AtomicBoolean fallbackToSimpleAuth) throws IOException {
+    return (T) NameNodeProxiesClient.createNonHAProxyWithClientProtocol(
+      nnAddr, conf, ugi, false, fallbackToSimpleAuth);
+  }
+
+  @Override
+  public T createProxy(Configuration conf, InetSocketAddress nnAddr,
+      Class<T> xface, UserGroupInformation ugi, boolean withRetries)
+      throws IOException {
+    return createProxy(conf, nnAddr, xface, ugi, withRetries, null);
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
new file mode 100644
index 0000000..e9c8791
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
@@ -0,0 +1,183 @@
+/**
+ * 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.namenode.ha;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.hdfs.DFSUtilClient;
+import org.apache.hadoop.hdfs.HAUtilClient;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
+import org.apache.hadoop.ipc.RPC;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A FailoverProxyProvider implementation which allows one to configure
+ * multiple URIs to connect to during fail-over. A random configured address is
+ * tried first, and on a fail-over event the other addresses are tried
+ * sequentially in a random order.
+ */
+public class ConfiguredFailoverProxyProvider<T> extends
+    AbstractNNFailoverProxyProvider<T> {
+
+  private static final Logger LOG =
+      LoggerFactory.getLogger(ConfiguredFailoverProxyProvider.class);
+
+  protected final Configuration conf;
+  protected final List<AddressRpcProxyPair<T>> proxies =
+      new ArrayList<AddressRpcProxyPair<T>>();
+  private final UserGroupInformation ugi;
+  protected final Class<T> xface;
+
+  private int currentProxyIndex = 0;
+  private final HAProxyFactory<T> factory;
+
+  public ConfiguredFailoverProxyProvider(Configuration conf, URI uri,
+      Class<T> xface, HAProxyFactory<T> factory) {
+    this.xface = xface;
+    this.conf = new Configuration(conf);
+    int maxRetries = this.conf.getInt(
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_KEY,
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_DEFAULT);
+    this.conf.setInt(
+        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY,
+        maxRetries);
+
+    int maxRetriesOnSocketTimeouts = this.conf.getInt(
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT);
+    this.conf.setInt(
+            CommonConfigurationKeysPublic
+                    .IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
+            maxRetriesOnSocketTimeouts);
+
+    try {
+      ugi = UserGroupInformation.getCurrentUser();
+
+      Map<String, Map<String, InetSocketAddress>> map =
+          DFSUtilClient.getHaNnRpcAddresses(conf);
+      Map<String, InetSocketAddress> addressesInNN = map.get(uri.getHost());
+
+      if (addressesInNN == null || addressesInNN.size() == 0) {
+        throw new RuntimeException("Could not find any configured addresses " +
+            "for URI " + uri);
+      }
+
+      Collection<InetSocketAddress> addressesOfNns = addressesInNN.values();
+      for (InetSocketAddress address : addressesOfNns) {
+        proxies.add(new AddressRpcProxyPair<T>(address));
+      }
+      // Randomize the list to prevent all clients pointing to the same one
+      boolean randomized = conf.getBoolean(
+          HdfsClientConfigKeys.Failover.RANDOM_ORDER,
+          HdfsClientConfigKeys.Failover.RANDOM_ORDER_DEFAULT);
+      if (randomized) {
+        Collections.shuffle(proxies);
+      }
+
+      // The client may have a delegation token set for the logical
+      // URI of the cluster. Clone this token to apply to each of the
+      // underlying IPC addresses so that the IPC code can find it.
+      HAUtilClient.cloneDelegationTokenForLogicalUri(ugi, uri, addressesOfNns);
+      this.factory = factory;
+    } catch (IOException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  @Override
+  public Class<T> getInterface() {
+    return xface;
+  }
+
+  /**
+   * Lazily initialize the RPC proxy object.
+   */
+  @Override
+  public synchronized ProxyInfo<T> getProxy() {
+    AddressRpcProxyPair<T> current = proxies.get(currentProxyIndex);
+    if (current.namenode == null) {
+      try {
+        current.namenode = factory.createProxy(conf,
+            current.address, xface, ugi, false, getFallbackToSimpleAuth());
+      } catch (IOException e) {
+        LOG.error("Failed to create RPC proxy to NameNode", e);
+        throw new RuntimeException(e);
+      }
+    }
+    return new ProxyInfo<T>(current.namenode, current.address.toString());
+  }
+
+  @Override
+  public  void performFailover(T currentProxy) {
+    incrementProxyIndex();
+  }
+
+  synchronized void incrementProxyIndex() {
+    currentProxyIndex = (currentProxyIndex + 1) % proxies.size();
+  }
+
+  /**
+   * A little pair object to store the address and connected RPC proxy object to
+   * an NN. Note that {@link AddressRpcProxyPair#namenode} may be null.
+   */
+  private static class AddressRpcProxyPair<T> {
+    public final InetSocketAddress address;
+    public T namenode;
+
+    public AddressRpcProxyPair(InetSocketAddress address) {
+      this.address = address;
+    }
+  }
+
+  /**
+   * Close all the proxy objects which have been opened over the lifetime of
+   * this proxy provider.
+   */
+  @Override
+  public synchronized void close() throws IOException {
+    for (AddressRpcProxyPair<T> proxy : proxies) {
+      if (proxy.namenode != null) {
+        if (proxy.namenode instanceof Closeable) {
+          ((Closeable)proxy.namenode).close();
+        } else {
+          RPC.stopProxy(proxy.namenode);
+        }
+      }
+    }
+  }
+
+  /**
+   * Logical URI is required for this failover proxy provider.
+   */
+  @Override
+  public boolean useLogicalURI() {
+    return true;
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/HAProxyFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/HAProxyFactory.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/HAProxyFactory.java
new file mode 100644
index 0000000..f92a74f
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/HAProxyFactory.java
@@ -0,0 +1,44 @@
+/**
+ * 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.namenode.ha;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.security.UserGroupInformation;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * This interface aims to decouple the proxy creation implementation that used
+ * in {@link AbstractNNFailoverProxyProvider}. Client side can use
+ * {@link org.apache.hadoop.hdfs.protocol.ClientProtocol} to initialize the
+ * proxy while the server side can use NamenodeProtocols
+ */
+@InterfaceAudience.Private
+public interface HAProxyFactory<T> {
+
+  T createProxy(Configuration conf, InetSocketAddress nnAddr, Class<T> xface,
+      UserGroupInformation ugi, boolean withRetries,
+      AtomicBoolean fallbackToSimpleAuth) throws IOException;
+
+  T createProxy(Configuration conf, InetSocketAddress nnAddr, Class<T> xface,
+      UserGroupInformation ugi, boolean withRetries) throws IOException;
+
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
new file mode 100644
index 0000000..ed250a0
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
@@ -0,0 +1,126 @@
+/**
+ * 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.namenode.ha;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.hdfs.DFSUtilClient;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
+import org.apache.hadoop.ipc.RPC;
+import org.apache.hadoop.security.UserGroupInformation;
+
+/**
+ * A NNFailoverProxyProvider implementation which works on IP failover setup.
+ * Only one proxy is used to connect to both servers and switching between
+ * the servers is done by the environment/infrastructure, which guarantees
+ * clients can consistently reach only one node at a time.
+ *
+ * Clients with a live connection will likely get connection reset after an
+ * IP failover. This case will be handled by the
+ * FailoverOnNetworkExceptionRetry retry policy. I.e. if the call is
+ * not idempotent, it won't get retried.
+ *
+ * A connection reset while setting up a connection (i.e. before sending a
+ * request) will be handled in ipc client.
+ *
+ * The namenode URI must contain a resolvable host name.
+ */
+public class IPFailoverProxyProvider<T> extends
+    AbstractNNFailoverProxyProvider<T> {
+  private final Configuration conf;
+  private final Class<T> xface;
+  private final URI nameNodeUri;
+  private final HAProxyFactory<T> factory;
+  private ProxyInfo<T> nnProxyInfo = null;
+
+  public IPFailoverProxyProvider(Configuration conf, URI uri,
+      Class<T> xface, HAProxyFactory<T> factory) {
+    this.xface = xface;
+    this.nameNodeUri = uri;
+    this.factory = factory;
+
+    this.conf = new Configuration(conf);
+    int maxRetries = this.conf.getInt(
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_KEY,
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_DEFAULT);
+    this.conf.setInt(
+        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY,
+        maxRetries);
+
+    int maxRetriesOnSocketTimeouts = this.conf.getInt(
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
+        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT);
+    this.conf.setInt(
+        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
+        maxRetriesOnSocketTimeouts);
+  }
+
+  @Override
+  public Class<T> getInterface() {
+    return xface;
+  }
+
+  @Override
+  public synchronized ProxyInfo<T> getProxy() {
+    // Create a non-ha proxy if not already created.
+    if (nnProxyInfo == null) {
+      try {
+        // Create a proxy that is not wrapped in RetryProxy
+        InetSocketAddress nnAddr = DFSUtilClient.getNNAddress(nameNodeUri);
+        nnProxyInfo = new ProxyInfo<T>(factory.createProxy(conf, nnAddr, xface,
+          UserGroupInformation.getCurrentUser(), false), nnAddr.toString());
+      } catch (IOException ioe) {
+        throw new RuntimeException(ioe);
+      }
+    }
+    return nnProxyInfo;
+  }
+
+  /** Nothing to do for IP failover */
+  @Override
+  public void performFailover(T currentProxy) {
+  }
+
+  /**
+   * Close the proxy,
+   */
+  @Override
+  public synchronized void close() throws IOException {
+    if (nnProxyInfo == null) {
+      return;
+    }
+    if (nnProxyInfo.proxy instanceof Closeable) {
+      ((Closeable)nnProxyInfo.proxy).close();
+    } else {
+      RPC.stopProxy(nnProxyInfo.proxy);
+    }
+  }
+
+  /**
+   * Logical URI is not used for IP failover.
+   */
+  @Override
+  public boolean useLogicalURI() {
+    return false;
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
new file mode 100644
index 0000000..b94e94d
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/RequestHedgingProxyProvider.java
@@ -0,0 +1,234 @@
+/**
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.namenode.ha;
+
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletionService;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.ipc.RemoteException;
+import org.apache.hadoop.ipc.StandbyException;
+
+import org.apache.hadoop.io.retry.MultiException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A FailoverProxyProvider implementation that technically does not "failover"
+ * per-se. It constructs a wrapper proxy that sends the request to ALL
+ * underlying proxies simultaneously. It assumes the in an HA setup, there will
+ * be only one Active, and the active should respond faster than any configured
+ * standbys. Once it receive a response from any one of the configred proxies,
+ * outstanding requests to other proxies are immediately cancelled.
+ */
+public class RequestHedgingProxyProvider<T> extends
+        ConfiguredFailoverProxyProvider<T> {
+
+  public static final Logger LOG =
+      LoggerFactory.getLogger(RequestHedgingProxyProvider.class);
+
+  class RequestHedgingInvocationHandler implements InvocationHandler {
+
+    final Map<String, ProxyInfo<T>> targetProxies;
+
+    public RequestHedgingInvocationHandler(
+            Map<String, ProxyInfo<T>> targetProxies) {
+      this.targetProxies = new HashMap<>(targetProxies);
+    }
+
+    /**
+     * Creates a Executor and invokes all proxies concurrently. This
+     * implementation assumes that Clients have configured proper socket
+     * timeouts, else the call can block forever.
+     *
+     * @param proxy
+     * @param method
+     * @param args
+     * @return
+     * @throws Throwable
+     */
+    @Override
+    public Object
+    invoke(Object proxy, final Method method, final Object[] args)
+            throws Throwable {
+      Map<Future<Object>, ProxyInfo<T>> proxyMap = new HashMap<>();
+      int numAttempts = 0;
+
+      ExecutorService executor = null;
+      CompletionService<Object> completionService;
+      try {
+        // Optimization : if only 2 proxies are configured and one had failed
+        // over, then we dont need to create a threadpool etc.
+        targetProxies.remove(toIgnore);
+        if (targetProxies.size() == 1) {
+          ProxyInfo<T> proxyInfo = targetProxies.values().iterator().next();
+          Object retVal = method.invoke(proxyInfo.proxy, args);
+          successfulProxy = proxyInfo;
+          return retVal;
+        }
+        executor = Executors.newFixedThreadPool(proxies.size());
+        completionService = new ExecutorCompletionService<>(executor);
+        for (final Map.Entry<String, ProxyInfo<T>> pEntry :
+                targetProxies.entrySet()) {
+          Callable<Object> c = new Callable<Object>() {
+            @Override
+            public Object call() throws Exception {
+              LOG.trace("Invoking method {} on proxy {}", method,
+                  pEntry.getValue().proxyInfo);
+              return method.invoke(pEntry.getValue().proxy, args);
+            }
+          };
+          proxyMap.put(completionService.submit(c), pEntry.getValue());
+          numAttempts++;
+        }
+
+        Map<String, Exception> badResults = new HashMap<>();
+        while (numAttempts > 0) {
+          Future<Object> callResultFuture = completionService.take();
+          Object retVal;
+          try {
+            retVal = callResultFuture.get();
+            successfulProxy = proxyMap.get(callResultFuture);
+            LOG.debug("Invocation successful on [{}]",
+                successfulProxy.proxyInfo);
+            return retVal;
+          } catch (Exception ex) {
+            ProxyInfo<T> tProxyInfo = proxyMap.get(callResultFuture);
+            logProxyException(ex, tProxyInfo.proxyInfo);
+            badResults.put(tProxyInfo.proxyInfo, unwrapException(ex));
+            LOG.trace("Unsuccessful invocation on [{}]", tProxyInfo.proxyInfo);
+            numAttempts--;
+          }
+        }
+
+        // At this point we should have All bad results (Exceptions)
+        // Or should have returned with successful result.
+        if (badResults.size() == 1) {
+          throw badResults.values().iterator().next();
+        } else {
+          throw new MultiException(badResults);
+        }
+      } finally {
+        if (executor != null) {
+          LOG.trace("Shutting down threadpool executor");
+          executor.shutdownNow();
+        }
+      }
+    }
+  }
+
+
+  private volatile ProxyInfo<T> successfulProxy = null;
+  private volatile String toIgnore = null;
+
+  public RequestHedgingProxyProvider(Configuration conf, URI uri,
+      Class<T> xface, HAProxyFactory<T> proxyFactory) {
+    super(conf, uri, xface, proxyFactory);
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public synchronized ProxyInfo<T> getProxy() {
+    if (successfulProxy != null) {
+      return successfulProxy;
+    }
+    Map<String, ProxyInfo<T>> targetProxyInfos = new HashMap<>();
+    StringBuilder combinedInfo = new StringBuilder("[");
+    for (int i = 0; i < proxies.size(); i++) {
+      ProxyInfo<T> pInfo = super.getProxy();
+      incrementProxyIndex();
+      targetProxyInfos.put(pInfo.proxyInfo, pInfo);
+      combinedInfo.append(pInfo.proxyInfo).append(',');
+    }
+    combinedInfo.append(']');
+    T wrappedProxy = (T) Proxy.newProxyInstance(
+            RequestHedgingInvocationHandler.class.getClassLoader(),
+            new Class<?>[]{xface},
+            new RequestHedgingInvocationHandler(targetProxyInfos));
+    return new ProxyInfo<T>(wrappedProxy, combinedInfo.toString());
+  }
+
+  @Override
+  public synchronized void performFailover(T currentProxy) {
+    toIgnore = successfulProxy.proxyInfo;
+    successfulProxy = null;
+  }
+
+  /**
+   * Check the exception returned by the proxy log a warning message if it's
+   * not a StandbyException (expected exception).
+   * @param ex Exception to evaluate.
+   * @param proxyInfo Information of the proxy reporting the exception.
+   */
+  private void logProxyException(Exception ex, String proxyInfo) {
+    if (isStandbyException(ex)) {
+      LOG.debug("Invocation returned standby exception on [{}]", proxyInfo);
+    } else {
+      LOG.warn("Invocation returned exception on [{}]", proxyInfo);
+    }
+  }
+
+  /**
+   * Check if the returned exception is caused by an standby namenode.
+   * @param ex Exception to check.
+   * @return If the exception is caused by an standby namenode.
+   */
+  private boolean isStandbyException(Exception ex) {
+    Exception exception = unwrapException(ex);
+    if (exception instanceof RemoteException) {
+      return ((RemoteException) exception).unwrapRemoteException()
+          instanceof StandbyException;
+    }
+    return false;
+  }
+
+  /**
+   * Unwraps the exception. <p>
+   * Example:
+   * <blockquote><pre>
+   * if ex is
+   * ExecutionException(InvocationTargetExeption(SomeException))
+   * returns SomeException
+   * </pre></blockquote>
+   *
+   * @return unwrapped exception
+   */
+  private Exception unwrapException(Exception ex) {
+    if (ex != null) {
+      Throwable cause = ex.getCause();
+      if (cause instanceof Exception) {
+        Throwable innerCause = cause.getCause();
+        if (innerCause instanceof Exception) {
+          return (Exception) innerCause;
+        }
+        return (Exception) cause;
+      }
+    }
+    return ex;
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
new file mode 100644
index 0000000..724b5f0
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRequestHedgingProxyProvider.java
@@ -0,0 +1,476 @@
+/**
+ * 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.namenode.ha;
+
+import java.io.EOFException;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Iterator;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
+import org.apache.hadoop.hdfs.protocol.ClientProtocol;
+import org.apache.hadoop.io.retry.MultiException;
+import org.apache.hadoop.ipc.RemoteException;
+import org.apache.hadoop.ipc.StandbyException;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.apache.hadoop.test.GenericTestUtils;
+import org.apache.hadoop.util.Time;
+import org.apache.log4j.Level;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.mockito.Matchers;
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import com.google.common.collect.Lists;
+
+public class TestRequestHedgingProxyProvider {
+
+  private Configuration conf;
+  private URI nnUri;
+  private String ns;
+
+  @BeforeClass
+  public static void setupClass() throws Exception {
+    GenericTestUtils.setLogLevel(RequestHedgingProxyProvider.LOG, Level.TRACE);
+  }
+
+  @Before
+  public void setup() throws URISyntaxException {
+    ns = "mycluster-" + Time.monotonicNow();
+    nnUri = new URI("hdfs://" + ns);
+    conf = new Configuration();
+    conf.set(HdfsClientConfigKeys.DFS_NAMESERVICES, ns);
+    conf.set(
+        HdfsClientConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + ns, "nn1,nn2");
+    conf.set(
+        HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn1",
+        "machine1.foo.bar:9820");
+    conf.set(
+        HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn2",
+        "machine2.foo.bar:9820");
+  }
+
+  @Test
+  public void testHedgingWhenOneFails() throws Exception {
+    final ClientProtocol goodMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        Thread.sleep(1000);
+        return new long[]{1};
+      }
+    });
+    final ClientProtocol badMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri, ClientProtocol.class,
+            createFactory(badMock, goodMock));
+    long[] stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Mockito.verify(badMock).getStats();
+    Mockito.verify(goodMock).getStats();
+  }
+
+  @Test
+  public void testHedgingWhenOneIsSlow() throws Exception {
+    final ClientProtocol goodMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        Thread.sleep(1000);
+        return new long[]{1};
+      }
+    });
+    final ClientProtocol badMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri, ClientProtocol.class,
+            createFactory(goodMock, badMock));
+    long[] stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(1, stats[0]);
+    Mockito.verify(badMock).getStats();
+    Mockito.verify(goodMock).getStats();
+  }
+
+  @Test
+  public void testHedgingWhenBothFail() throws Exception {
+    ClientProtocol badMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(badMock.getStats()).thenThrow(new IOException("Bad mock !!"));
+    ClientProtocol worseMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(worseMock.getStats()).thenThrow(
+            new IOException("Worse mock !!"));
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri, ClientProtocol.class,
+            createFactory(badMock, worseMock));
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since both namenodes throw IOException !!");
+    } catch (Exception e) {
+      Assert.assertTrue(e instanceof MultiException);
+    }
+    Mockito.verify(badMock).getStats();
+    Mockito.verify(worseMock).getStats();
+  }
+
+  @Test
+  public void testPerformFailover() throws Exception {
+    final AtomicInteger counter = new AtomicInteger(0);
+    final int[] isGood = {1};
+    final ClientProtocol goodMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        counter.incrementAndGet();
+        if (isGood[0] == 1) {
+          Thread.sleep(1000);
+          return new long[]{1};
+        }
+        throw new IOException("Was Good mock !!");
+      }
+    });
+    final ClientProtocol badMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(badMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        counter.incrementAndGet();
+        if (isGood[0] == 2) {
+          Thread.sleep(1000);
+          return new long[]{2};
+        }
+        throw new IOException("Bad mock !!");
+      }
+    });
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+            new RequestHedgingProxyProvider<>(conf, nnUri, ClientProtocol.class,
+                    createFactory(goodMock, badMock));
+    long[] stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(1, stats[0]);
+    Assert.assertEquals(2, counter.get());
+    Mockito.verify(badMock).getStats();
+    Mockito.verify(goodMock).getStats();
+
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(1, stats[0]);
+    // Ensure only the previous successful one is invoked
+    Mockito.verifyNoMoreInteractions(badMock);
+    Assert.assertEquals(3, counter.get());
+
+    // Flip to standby.. so now this should fail
+    isGood[0] = 2;
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since previously successful proxy now fails ");
+    } catch (Exception ex) {
+      Assert.assertTrue(ex instanceof IOException);
+    }
+
+    Assert.assertEquals(4, counter.get());
+
+    provider.performFailover(provider.getProxy().proxy);
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(2, stats[0]);
+
+    // Counter should update only once
+    Assert.assertEquals(5, counter.get());
+
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(2, stats[0]);
+
+    // Counter updates only once now
+    Assert.assertEquals(6, counter.get());
+
+    // Flip back to old active.. so now this should fail
+    isGood[0] = 1;
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since previously successful proxy now fails ");
+    } catch (Exception ex) {
+      Assert.assertTrue(ex instanceof IOException);
+    }
+
+    Assert.assertEquals(7, counter.get());
+
+    provider.performFailover(provider.getProxy().proxy);
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    // Ensure correct proxy was called
+    Assert.assertEquals(1, stats[0]);
+  }
+
+  @Test
+  public void testPerformFailoverWith3Proxies() throws Exception {
+    conf.set(HdfsClientConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX + "." + ns,
+            "nn1,nn2,nn3");
+    conf.set(HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY + "." + ns + ".nn3",
+            "machine3.foo.bar:9820");
+
+    final AtomicInteger counter = new AtomicInteger(0);
+    final int[] isGood = {1};
+    final ClientProtocol goodMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(goodMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        counter.incrementAndGet();
+        if (isGood[0] == 1) {
+          Thread.sleep(1000);
+          return new long[]{1};
+        }
+        throw new IOException("Was Good mock !!");
+      }
+    });
+    final ClientProtocol badMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(badMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        counter.incrementAndGet();
+        if (isGood[0] == 2) {
+          Thread.sleep(1000);
+          return new long[]{2};
+        }
+        throw new IOException("Bad mock !!");
+      }
+    });
+    final ClientProtocol worseMock = Mockito.mock(ClientProtocol.class);
+    Mockito.when(worseMock.getStats()).thenAnswer(new Answer<long[]>() {
+      @Override
+      public long[] answer(InvocationOnMock invocation) throws Throwable {
+        counter.incrementAndGet();
+        if (isGood[0] == 3) {
+          Thread.sleep(1000);
+          return new long[]{3};
+        }
+        throw new IOException("Worse mock !!");
+      }
+    });
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+            new RequestHedgingProxyProvider<>(conf, nnUri, ClientProtocol.class,
+                    createFactory(goodMock, badMock, worseMock));
+    long[] stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(1, stats[0]);
+    Assert.assertEquals(3, counter.get());
+    Mockito.verify(badMock).getStats();
+    Mockito.verify(goodMock).getStats();
+    Mockito.verify(worseMock).getStats();
+
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(1, stats[0]);
+    // Ensure only the previous successful one is invoked
+    Mockito.verifyNoMoreInteractions(badMock);
+    Mockito.verifyNoMoreInteractions(worseMock);
+    Assert.assertEquals(4, counter.get());
+
+    // Flip to standby.. so now this should fail
+    isGood[0] = 2;
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since previously successful proxy now fails ");
+    } catch (Exception ex) {
+      Assert.assertTrue(ex instanceof IOException);
+    }
+
+    Assert.assertEquals(5, counter.get());
+
+    provider.performFailover(provider.getProxy().proxy);
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(2, stats[0]);
+
+    // Counter updates twice since both proxies are tried on failure
+    Assert.assertEquals(7, counter.get());
+
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(2, stats[0]);
+
+    // Counter updates only once now
+    Assert.assertEquals(8, counter.get());
+
+    // Flip to Other standby.. so now this should fail
+    isGood[0] = 3;
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since previously successful proxy now fails ");
+    } catch (Exception ex) {
+      Assert.assertTrue(ex instanceof IOException);
+    }
+
+    // Counter should ipdate only 1 time
+    Assert.assertEquals(9, counter.get());
+
+    provider.performFailover(provider.getProxy().proxy);
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+
+    // Ensure correct proxy was called
+    Assert.assertEquals(3, stats[0]);
+
+    // Counter updates twice since both proxies are tried on failure
+    Assert.assertEquals(11, counter.get());
+
+    stats = provider.getProxy().proxy.getStats();
+    Assert.assertTrue(stats.length == 1);
+    Assert.assertEquals(3, stats[0]);
+
+    // Counter updates only once now
+    Assert.assertEquals(12, counter.get());
+  }
+
+  @Test
+  public void testHedgingWhenFileNotFoundException() throws Exception {
+    ClientProtocol active = Mockito.mock(ClientProtocol.class);
+    Mockito
+        .when(active.getBlockLocations(Matchers.anyString(),
+            Matchers.anyLong(), Matchers.anyLong()))
+        .thenThrow(new RemoteException("java.io.FileNotFoundException",
+            "File does not exist!"));
+
+    ClientProtocol standby = Mockito.mock(ClientProtocol.class);
+    Mockito
+        .when(standby.getBlockLocations(Matchers.anyString(),
+            Matchers.anyLong(), Matchers.anyLong()))
+        .thenThrow(
+            new RemoteException("org.apache.hadoop.ipc.StandbyException",
+            "Standby NameNode"));
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri,
+          ClientProtocol.class, createFactory(active, standby));
+    try {
+      provider.getProxy().proxy.getBlockLocations("/tmp/test.file", 0L, 20L);
+      Assert.fail("Should fail since the active namenode throws"
+          + " FileNotFoundException!");
+    } catch (MultiException me) {
+      for (Exception ex : me.getExceptions().values()) {
+        Exception rEx = ((RemoteException) ex).unwrapRemoteException();
+        if (rEx instanceof StandbyException) {
+          continue;
+        }
+        Assert.assertTrue(rEx instanceof FileNotFoundException);
+      }
+    }
+    Mockito.verify(active).getBlockLocations(Matchers.anyString(),
+        Matchers.anyLong(), Matchers.anyLong());
+    Mockito.verify(standby).getBlockLocations(Matchers.anyString(),
+        Matchers.anyLong(), Matchers.anyLong());
+  }
+
+  @Test
+  public void testHedgingWhenConnectException() throws Exception {
+    ClientProtocol active = Mockito.mock(ClientProtocol.class);
+    Mockito.when(active.getStats()).thenThrow(new ConnectException());
+
+    ClientProtocol standby = Mockito.mock(ClientProtocol.class);
+    Mockito.when(standby.getStats())
+        .thenThrow(
+            new RemoteException("org.apache.hadoop.ipc.StandbyException",
+            "Standby NameNode"));
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri,
+          ClientProtocol.class, createFactory(active, standby));
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since the active namenode throws"
+          + " ConnectException!");
+    } catch (MultiException me) {
+      for (Exception ex : me.getExceptions().values()) {
+        if (ex instanceof RemoteException) {
+          Exception rEx = ((RemoteException) ex)
+              .unwrapRemoteException();
+          Assert.assertTrue("Unexpected RemoteException: " + rEx.getMessage(),
+              rEx instanceof StandbyException);
+        } else {
+          Assert.assertTrue(ex instanceof ConnectException);
+        }
+      }
+    }
+    Mockito.verify(active).getStats();
+    Mockito.verify(standby).getStats();
+  }
+
+  @Test
+  public void testHedgingWhenConnectAndEOFException() throws Exception {
+    ClientProtocol active = Mockito.mock(ClientProtocol.class);
+    Mockito.when(active.getStats()).thenThrow(new EOFException());
+
+    ClientProtocol standby = Mockito.mock(ClientProtocol.class);
+    Mockito.when(standby.getStats()).thenThrow(new ConnectException());
+
+    RequestHedgingProxyProvider<ClientProtocol> provider =
+        new RequestHedgingProxyProvider<>(conf, nnUri,
+          ClientProtocol.class, createFactory(active, standby));
+    try {
+      provider.getProxy().proxy.getStats();
+      Assert.fail("Should fail since both active and standby namenodes throw"
+          + " Exceptions!");
+    } catch (MultiException me) {
+      for (Exception ex : me.getExceptions().values()) {
+        if (!(ex instanceof ConnectException) &&
+            !(ex instanceof EOFException)) {
+          Assert.fail("Unexpected Exception " + ex.getMessage());
+        }
+      }
+    }
+    Mockito.verify(active).getStats();
+    Mockito.verify(standby).getStats();
+  }
+
+  private HAProxyFactory<ClientProtocol> createFactory(
+      ClientProtocol... protos) {
+    final Iterator<ClientProtocol> iterator =
+        Lists.newArrayList(protos).iterator();
+    return new HAProxyFactory<ClientProtocol>() {
+      @Override
+      public ClientProtocol createProxy(Configuration conf,
+          InetSocketAddress nnAddr, Class<ClientProtocol> xface,
+          UserGroupInformation ugi, boolean withRetries,
+          AtomicBoolean fallbackToSimpleAuth) throws IOException {
+        return iterator.next();
+      }
+
+      @Override
+      public ClientProtocol createProxy(Configuration conf,
+          InetSocketAddress nnAddr, Class<ClientProtocol> xface,
+          UserGroupInformation ugi, boolean withRetries) throws IOException {
+        return iterator.next();
+      }
+    };
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/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 8fea41f..58a2823 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
@@ -142,7 +142,8 @@ public class DFSConfigKeys extends CommonConfigurationKeys {
       HdfsClientConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY;
   public static final String  DFS_NAMENODE_HTTP_ADDRESS_DEFAULT = "0.0.0.0:" + DFS_NAMENODE_HTTP_PORT_DEFAULT;
   public static final String  DFS_NAMENODE_HTTP_BIND_HOST_KEY = "dfs.namenode.http-bind-host";
-  public static final String  DFS_NAMENODE_RPC_ADDRESS_KEY = "dfs.namenode.rpc-address";
+  public static final String  DFS_NAMENODE_RPC_ADDRESS_KEY =
+      HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY;
   public static final String  DFS_NAMENODE_RPC_BIND_HOST_KEY = "dfs.namenode.rpc-bind-host";
   public static final String  DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY = "dfs.namenode.servicerpc-address";
   public static final String  DFS_NAMENODE_SERVICE_RPC_BIND_HOST_KEY = "dfs.namenode.servicerpc-bind-host";

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/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 23166e2..47e1c0d 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
@@ -450,19 +450,6 @@ public class DFSUtil {
   }
 
   /**
-   * Returns list of InetSocketAddress corresponding to HA NN RPC addresses from
-   * the configuration.
-   * 
-   * @param conf configuration
-   * @return list of InetSocketAddresses
-   */
-  public static Map<String, Map<String, InetSocketAddress>> getHaNnRpcAddresses(
-      Configuration conf) {
-    return DFSUtilClient.getAddresses(conf, null,
-                                      DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY);
-  }
-
-  /**
    * Returns list of InetSocketAddress corresponding to  backup node rpc 
    * addresses from the configuration.
    * 
@@ -693,7 +680,7 @@ public class DFSUtil {
   
   public static String nnAddressesAsString(Configuration conf) {
     Map<String, Map<String, InetSocketAddress>> addresses =
-      getHaNnRpcAddresses(conf);
+        DFSUtilClient.getHaNnRpcAddresses(conf);
     return addressMapToString(addresses);
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HAUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HAUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HAUtil.java
index ea535e9..3556086 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HAUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/HAUtil.java
@@ -29,7 +29,6 @@ import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RPC_BIND_HOST_KE
 import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY;
 import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_BIND_HOST_KEY;
 import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY;
-import static org.apache.hadoop.security.SecurityUtil.buildTokenService;
 
 import java.io.IOException;
 import java.net.InetSocketAddress;
@@ -39,8 +38,6 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.HadoopIllegalArgumentException;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.conf.Configuration;
@@ -48,17 +45,12 @@ import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hdfs.NameNodeProxiesClient.ProxyAndInfo;
 import org.apache.hadoop.hdfs.protocol.ClientProtocol;
-import org.apache.hadoop.hdfs.protocol.HdfsConstants;
-import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
-import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSelector;
 import org.apache.hadoop.hdfs.server.namenode.NameNode;
 import org.apache.hadoop.hdfs.server.namenode.ha.AbstractNNFailoverProxyProvider;
-import org.apache.hadoop.io.Text;
 import org.apache.hadoop.ipc.RPC;
 import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.ipc.StandbyException;
 import org.apache.hadoop.security.UserGroupInformation;
-import org.apache.hadoop.security.token.Token;
 
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
@@ -67,12 +59,6 @@ import com.google.common.collect.Lists;
 @InterfaceAudience.Private
 public class HAUtil {
   
-  private static final Log LOG = 
-    LogFactory.getLog(HAUtil.class);
-  
-  private static final DelegationTokenSelector tokenSelector =
-      new DelegationTokenSelector();
-
   private static final String[] HA_SPECIAL_INDEPENDENT_KEYS = new String[]{
     DFS_NAMENODE_RPC_ADDRESS_KEY,
     DFS_NAMENODE_RPC_BIND_HOST_KEY,
@@ -97,7 +83,7 @@ public class HAUtil {
    */
   public static boolean isHAEnabled(Configuration conf, String nsId) {
     Map<String, Map<String, InetSocketAddress>> addresses =
-      DFSUtil.getHaNnRpcAddresses(conf);
+        DFSUtilClient.getHaNnRpcAddresses(conf);
     if (addresses == null) return false;
     Map<String, InetSocketAddress> nnMap = addresses.get(nsId);
     return nnMap != null && nnMap.size() > 1;
@@ -260,47 +246,6 @@ public class HAUtil {
   }
 
   /**
-   * Locate a delegation token associated with the given HA cluster URI, and if
-   * one is found, clone it to also represent the underlying namenode address.
-   * @param ugi the UGI to modify
-   * @param haUri the logical URI for the cluster
-   * @param nnAddrs collection of NNs in the cluster to which the token
-   * applies
-   */
-  public static void cloneDelegationTokenForLogicalUri(
-      UserGroupInformation ugi, URI haUri,
-      Collection<InetSocketAddress> nnAddrs) {
-    // this cloning logic is only used by hdfs
-    Text haService = HAUtilClient.buildTokenServiceForLogicalUri(haUri,
-                                                                 HdfsConstants.HDFS_URI_SCHEME);
-    Token<DelegationTokenIdentifier> haToken =
-        tokenSelector.selectToken(haService, ugi.getTokens());
-    if (haToken != null) {
-      for (InetSocketAddress singleNNAddr : nnAddrs) {
-        // this is a minor hack to prevent physical HA tokens from being
-        // exposed to the user via UGI.getCredentials(), otherwise these
-        // cloned tokens may be inadvertently propagated to jobs
-        Token<DelegationTokenIdentifier> specificToken =
-            haToken.privateClone(buildTokenService(singleNNAddr));
-        Text alias = new Text(
-            HAUtilClient.buildTokenServicePrefixForLogicalUri(
-                HdfsConstants.HDFS_URI_SCHEME)
-                + "//" + specificToken.getService());
-        ugi.addToken(alias, specificToken);
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("Mapped HA service delegation token for logical URI " +
-              haUri + " to namenode " + singleNNAddr);
-        }
-      }
-    } else {
-      if (LOG.isDebugEnabled()) {
-        LOG.debug("No HA service delegation token found for logical URI " +
-            haUri);
-      }
-    }
-  }
-
-  /**
    * Get the internet address of the currently-active NN. This should rarely be
    * used, since callers of this method who connect directly to the NN using the
    * resulting InetSocketAddress will not be able to connect to the active NN if

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java
index 61d701d..d556c90 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java
@@ -36,6 +36,7 @@ import org.apache.hadoop.hdfs.protocolPB.JournalProtocolTranslatorPB;
 import org.apache.hadoop.hdfs.protocolPB.NamenodeProtocolPB;
 import org.apache.hadoop.hdfs.protocolPB.NamenodeProtocolTranslatorPB;
 import org.apache.hadoop.hdfs.server.namenode.ha.AbstractNNFailoverProxyProvider;
+import org.apache.hadoop.hdfs.server.namenode.ha.NameNodeHAProxyFactory;
 import org.apache.hadoop.hdfs.server.protocol.JournalProtocol;
 import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
 import org.apache.hadoop.io.Text;
@@ -112,7 +113,7 @@ public class NameNodeProxies {
       throws IOException {
     AbstractNNFailoverProxyProvider<T> failoverProxyProvider =
         NameNodeProxiesClient.createFailoverProxyProvider(conf, nameNodeUri,
-            xface, true, fallbackToSimpleAuth);
+            xface, true, fallbackToSimpleAuth, new NameNodeHAProxyFactory<T>());
 
     if (failoverProxyProvider == null) {
       return createNonHAProxy(conf, DFSUtilClient.getNNAddress(nameNodeUri),

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/DfsServlet.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/DfsServlet.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/DfsServlet.java
index 8edaed6..6b489fc 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/DfsServlet.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/DfsServlet.java
@@ -17,19 +17,13 @@
  */
 package org.apache.hadoop.hdfs.server.namenode;
 
-import java.io.IOException;
-import java.net.InetSocketAddress;
-
-import javax.servlet.ServletContext;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
+import java.io.IOException;
+
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.hdfs.DFSUtilClient;
-import org.apache.hadoop.hdfs.HdfsConfiguration;
-import org.apache.hadoop.hdfs.NameNodeProxies;
-import org.apache.hadoop.hdfs.protocol.ClientProtocol;
 import org.apache.hadoop.hdfs.server.common.JspHelper;
 import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.security.UserGroupInformation;
@@ -63,25 +57,6 @@ abstract class DfsServlet extends HttpServlet {
     doc.endTag();
   }
 
-  /**
-   * Create a {@link NameNode} proxy from the current {@link ServletContext}. 
-   */
-  protected ClientProtocol createNameNodeProxy() throws IOException {
-    ServletContext context = getServletContext();
-    // if we are running in the Name Node, use it directly rather than via 
-    // rpc
-    NameNode nn = NameNodeHttpServer.getNameNodeFromContext(context);
-    if (nn != null) {
-      return nn.getRpcServer();
-    }
-    InetSocketAddress nnAddr =
-      NameNodeHttpServer.getNameNodeAddressFromContext(context);
-    Configuration conf = new HdfsConfiguration(
-        NameNodeHttpServer.getConfFromContext(context));
-    return NameNodeProxies.createProxy(conf, DFSUtilClient.getNNUri(nnAddr),
-        ClientProtocol.class).getProxy();
-  }
-
   protected UserGroupInformation getUGI(HttpServletRequest request,
                                         Configuration conf) throws IOException {
     return JspHelper.getUGI(getServletContext(), request, conf);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
deleted file mode 100644
index 0e8fa44..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ConfiguredFailoverProxyProvider.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * 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.namenode.ha;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
-import org.apache.hadoop.hdfs.DFSUtil;
-import org.apache.hadoop.hdfs.HAUtil;
-import org.apache.hadoop.hdfs.NameNodeProxies;
-import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
-import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
-import org.apache.hadoop.ipc.RPC;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-
-/**
- * A FailoverProxyProvider implementation which allows one to configure
- * multiple URIs to connect to during fail-over. A random configured address is
- * tried first, and on a fail-over event the other addresses are tried
- * sequentially in a random order.
- */
-public class ConfiguredFailoverProxyProvider<T> extends
-    AbstractNNFailoverProxyProvider<T> {
-  
-  private static final Log LOG =
-      LogFactory.getLog(ConfiguredFailoverProxyProvider.class);
-  
-  interface ProxyFactory<T> {
-    T createProxy(Configuration conf, InetSocketAddress nnAddr, Class<T> xface,
-        UserGroupInformation ugi, boolean withRetries,
-        AtomicBoolean fallbackToSimpleAuth) throws IOException;
-  }
-
-  static class DefaultProxyFactory<T> implements ProxyFactory<T> {
-    @Override
-    public T createProxy(Configuration conf, InetSocketAddress nnAddr,
-        Class<T> xface, UserGroupInformation ugi, boolean withRetries,
-        AtomicBoolean fallbackToSimpleAuth) throws IOException {
-      return NameNodeProxies.createNonHAProxy(conf,
-          nnAddr, xface, ugi, false, fallbackToSimpleAuth).getProxy();
-    }
-  }
-
-  protected final Configuration conf;
-  protected final List<AddressRpcProxyPair<T>> proxies =
-      new ArrayList<AddressRpcProxyPair<T>>();
-  private final UserGroupInformation ugi;
-  protected final Class<T> xface;
-
-  private int currentProxyIndex = 0;
-  private final ProxyFactory<T> factory;
-
-  public ConfiguredFailoverProxyProvider(Configuration conf, URI uri,
-      Class<T> xface) {
-    this(conf, uri, xface, new DefaultProxyFactory<T>());
-  }
-
-  @VisibleForTesting
-  ConfiguredFailoverProxyProvider(Configuration conf, URI uri,
-      Class<T> xface, ProxyFactory<T> factory) {
-
-    Preconditions.checkArgument(
-        xface.isAssignableFrom(NamenodeProtocols.class),
-        "Interface class %s is not a valid NameNode protocol!");
-    this.xface = xface;
-    
-    this.conf = new Configuration(conf);
-    int maxRetries = this.conf.getInt(
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_KEY,
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_DEFAULT);
-    this.conf.setInt(
-        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY,
-        maxRetries);
-    
-    int maxRetriesOnSocketTimeouts = this.conf.getInt(
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT);
-    this.conf.setInt(
-            CommonConfigurationKeysPublic
-                    .IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
-            maxRetriesOnSocketTimeouts);
-
-    try {
-      ugi = UserGroupInformation.getCurrentUser();
-      
-      Map<String, Map<String, InetSocketAddress>> map = DFSUtil.getHaNnRpcAddresses(
-          conf);
-      Map<String, InetSocketAddress> addressesInNN = map.get(uri.getHost());
-      
-      if (addressesInNN == null || addressesInNN.size() == 0) {
-        throw new RuntimeException("Could not find any configured addresses " +
-            "for URI " + uri);
-      }
-      
-      Collection<InetSocketAddress> addressesOfNns = addressesInNN.values();
-      for (InetSocketAddress address : addressesOfNns) {
-        proxies.add(new AddressRpcProxyPair<T>(address));
-      }
-      // Randomize the list to prevent all clients pointing to the same one
-      boolean randomized = conf.getBoolean(
-          HdfsClientConfigKeys.Failover.RANDOM_ORDER,
-          HdfsClientConfigKeys.Failover.RANDOM_ORDER_DEFAULT);
-      if (randomized) {
-        Collections.shuffle(proxies);
-      }
-
-      // The client may have a delegation token set for the logical
-      // URI of the cluster. Clone this token to apply to each of the
-      // underlying IPC addresses so that the IPC code can find it.
-      HAUtil.cloneDelegationTokenForLogicalUri(ugi, uri, addressesOfNns);
-      this.factory = factory;
-    } catch (IOException e) {
-      throw new RuntimeException(e);
-    }
-  }
-    
-  @Override
-  public Class<T> getInterface() {
-    return xface;
-  }
-
-  /**
-   * Lazily initialize the RPC proxy object.
-   */
-  @Override
-  public synchronized ProxyInfo<T> getProxy() {
-    AddressRpcProxyPair<T> current = proxies.get(currentProxyIndex);
-    if (current.namenode == null) {
-      try {
-        current.namenode = factory.createProxy(conf,
-            current.address, xface, ugi, false, getFallbackToSimpleAuth());
-      } catch (IOException e) {
-        LOG.error("Failed to create RPC proxy to NameNode", e);
-        throw new RuntimeException(e);
-      }
-    }
-    return new ProxyInfo<T>(current.namenode, current.address.toString());
-  }
-
-  @Override
-  public  void performFailover(T currentProxy) {
-    incrementProxyIndex();
-  }
-
-  synchronized void incrementProxyIndex() {
-    currentProxyIndex = (currentProxyIndex + 1) % proxies.size();
-  }
-
-  /**
-   * A little pair object to store the address and connected RPC proxy object to
-   * an NN. Note that {@link AddressRpcProxyPair#namenode} may be null.
-   */
-  private static class AddressRpcProxyPair<T> {
-    public final InetSocketAddress address;
-    public T namenode;
-    
-    public AddressRpcProxyPair(InetSocketAddress address) {
-      this.address = address;
-    }
-  }
-
-  /**
-   * Close all the proxy objects which have been opened over the lifetime of
-   * this proxy provider.
-   */
-  @Override
-  public synchronized void close() throws IOException {
-    for (AddressRpcProxyPair<T> proxy : proxies) {
-      if (proxy.namenode != null) {
-        if (proxy.namenode instanceof Closeable) {
-          ((Closeable)proxy.namenode).close();
-        } else {
-          RPC.stopProxy(proxy.namenode);
-        }
-      }
-    }
-  }
-
-  /**
-   * Logical URI is required for this failover proxy provider.
-   */
-  @Override
-  public boolean useLogicalURI() {
-    return true;
-  }
-}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
deleted file mode 100644
index 4e1cb9e..0000000
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/IPFailoverProxyProvider.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * 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.namenode.ha;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.URI;
-
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
-import org.apache.hadoop.hdfs.DFSUtilClient;
-import org.apache.hadoop.hdfs.NameNodeProxies;
-import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
-import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
-import org.apache.hadoop.ipc.RPC;
-import org.apache.hadoop.security.UserGroupInformation;
-
-import com.google.common.base.Preconditions;
-
-/**
- * A NNFailoverProxyProvider implementation which works on IP failover setup.
- * Only one proxy is used to connect to both servers and switching between
- * the servers is done by the environment/infrastructure, which guarantees
- * clients can consistently reach only one node at a time.
- *
- * Clients with a live connection will likely get connection reset after an
- * IP failover. This case will be handled by the 
- * FailoverOnNetworkExceptionRetry retry policy. I.e. if the call is
- * not idempotent, it won't get retried.
- *
- * A connection reset while setting up a connection (i.e. before sending a
- * request) will be handled in ipc client.
- *
- * The namenode URI must contain a resolvable host name.
- */
-public class IPFailoverProxyProvider<T> extends
-    AbstractNNFailoverProxyProvider<T> {
-  private final Configuration conf;
-  private final Class<T> xface;
-  private final URI nameNodeUri;
-  private ProxyInfo<T> nnProxyInfo = null;
-  
-  public IPFailoverProxyProvider(Configuration conf, URI uri,
-      Class<T> xface) {
-    Preconditions.checkArgument(
-        xface.isAssignableFrom(NamenodeProtocols.class),
-        "Interface class %s is not a valid NameNode protocol!");
-    this.xface = xface;
-    this.nameNodeUri = uri;
-
-    this.conf = new Configuration(conf);
-    int maxRetries = this.conf.getInt(
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_KEY,
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_DEFAULT);
-    this.conf.setInt(
-        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_KEY,
-        maxRetries);
-    
-    int maxRetriesOnSocketTimeouts = this.conf.getInt(
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
-        HdfsClientConfigKeys.Failover.CONNECTION_RETRIES_ON_SOCKET_TIMEOUTS_DEFAULT);
-    this.conf.setInt(
-        CommonConfigurationKeysPublic.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SOCKET_TIMEOUTS_KEY,
-        maxRetriesOnSocketTimeouts);
-  }
-    
-  @Override
-  public Class<T> getInterface() {
-    return xface;
-  }
-
-  @Override
-  public synchronized ProxyInfo<T> getProxy() {
-    // Create a non-ha proxy if not already created.
-    if (nnProxyInfo == null) {
-      try {
-        // Create a proxy that is not wrapped in RetryProxy
-        InetSocketAddress nnAddr = DFSUtilClient.getNNAddress(nameNodeUri);
-        nnProxyInfo = new ProxyInfo<T>(NameNodeProxies.createNonHAProxy(
-            conf, nnAddr, xface, UserGroupInformation.getCurrentUser(), 
-            false).getProxy(), nnAddr.toString());
-      } catch (IOException ioe) {
-        throw new RuntimeException(ioe);
-      }
-    }
-    return nnProxyInfo;
-  }
-
-  /** Nothing to do for IP failover */
-  @Override
-  public void performFailover(T currentProxy) {
-  }
-
-  /**
-   * Close the proxy,
-   */
-  @Override
-  public synchronized void close() throws IOException {
-    if (nnProxyInfo == null) {
-      return;
-    }
-    if (nnProxyInfo.proxy instanceof Closeable) {
-      ((Closeable)nnProxyInfo.proxy).close();
-    } else {
-      RPC.stopProxy(nnProxyInfo.proxy);
-    }
-  }
-
-  /**
-   * Logical URI is not used for IP failover.
-   */
-  @Override
-  public boolean useLogicalURI() {
-    return false;
-  }
-}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/c58c01fe/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/NameNodeHAProxyFactory.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/NameNodeHAProxyFactory.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/NameNodeHAProxyFactory.java
new file mode 100644
index 0000000..036b6eb
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/NameNodeHAProxyFactory.java
@@ -0,0 +1,45 @@
+/**
+ * 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.namenode.ha;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.NameNodeProxies;
+import org.apache.hadoop.security.UserGroupInformation;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class NameNodeHAProxyFactory<T> implements HAProxyFactory<T> {
+
+  @Override
+  public T createProxy(Configuration conf, InetSocketAddress nnAddr,
+      Class<T> xface, UserGroupInformation ugi, boolean withRetries,
+      AtomicBoolean fallbackToSimpleAuth) throws IOException {
+    return NameNodeProxies.createNonHAProxy(conf, nnAddr, xface,
+      ugi, withRetries, fallbackToSimpleAuth).getProxy();
+  }
+
+  @Override
+  public T createProxy(Configuration conf, InetSocketAddress nnAddr,
+      Class<T> xface, UserGroupInformation ugi, boolean withRetries)
+      throws IOException {
+    return NameNodeProxies.createNonHAProxy(conf, nnAddr, xface,
+      ugi, withRetries).getProxy();
+  }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[33/50] [abbrv] hadoop git commit: YARN-6403. Invalid local resource request can raise NPE and make NM exit. Contributed by Tao Yang

Posted by in...@apache.org.
YARN-6403. Invalid local resource request can raise NPE and make NM exit. Contributed by Tao Yang


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

Branch: refs/heads/HDFS-10467
Commit: 939320941ad870adacc26fe096b278cf63529312
Parents: ca33197
Author: Jason Lowe <jl...@yahoo-inc.com>
Authored: Wed Apr 5 12:30:45 2017 -0500
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../impl/pb/ContainerLaunchContextPBImpl.java   | 13 ++++++
 .../TestApplicationClientProtocolRecords.java   | 29 +++++++++++++
 .../containermanager/ContainerManagerImpl.java  | 10 +++++
 .../TestContainerManagerWithLCE.java            | 11 +++++
 .../containermanager/TestContainerManager.java  | 45 ++++++++++++++++++++
 5 files changed, 108 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/93932094/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ContainerLaunchContextPBImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ContainerLaunchContextPBImpl.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ContainerLaunchContextPBImpl.java
index 1f76c34..f07a9d6 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ContainerLaunchContextPBImpl.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/records/impl/pb/ContainerLaunchContextPBImpl.java
@@ -208,11 +208,24 @@ extends ContainerLaunchContext {
       final Map<String, LocalResource> localResources) {
     if (localResources == null)
       return;
+    checkLocalResources(localResources);
     initLocalResources();
     this.localResources.clear();
     this.localResources.putAll(localResources);
   }
   
+  private void checkLocalResources(Map<String, LocalResource> localResources) {
+    for (Map.Entry<String, LocalResource> rsrcEntry : localResources
+        .entrySet()) {
+      if (rsrcEntry.getValue() == null
+          || rsrcEntry.getValue().getResource() == null) {
+        throw new NullPointerException(
+            "Null resource URL for local resource " + rsrcEntry.getKey() + " : "
+                + rsrcEntry.getValue());
+      }
+    }
+  }
+
   private void addLocalResourcesToProto() {
     maybeInitBuilder();
     builder.clearLocalResources();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/93932094/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/records/impl/pb/TestApplicationClientProtocolRecords.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/records/impl/pb/TestApplicationClientProtocolRecords.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/records/impl/pb/TestApplicationClientProtocolRecords.java
index 0294ad1..8773d11 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/records/impl/pb/TestApplicationClientProtocolRecords.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/records/impl/pb/TestApplicationClientProtocolRecords.java
@@ -30,6 +30,10 @@ import org.apache.hadoop.security.Credentials;
 import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
 import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
 import org.apache.hadoop.yarn.api.records.LocalResource;
+import org.apache.hadoop.yarn.api.records.LocalResourceType;
+import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
+import org.apache.hadoop.yarn.factories.RecordFactory;
+import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
 import org.junit.Assert;
 import org.junit.Test;
 
@@ -66,4 +70,29 @@ public class TestApplicationClientProtocolRecords {
         clcProto.getEnvironment().get("testCLCPBImplNullEnv"));
 
   }
+
+  /*
+   * This test validates the scenario in which the client sets a null value for
+   * local resource URL.
+   */
+  @Test
+  public void testCLCPBImplNullResourceURL() throws IOException {
+    RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null);
+    try {
+      LocalResource rsrc_alpha = recordFactory.newRecordInstance(LocalResource.class);
+      rsrc_alpha.setResource(null);
+      rsrc_alpha.setSize(-1);
+      rsrc_alpha.setVisibility(LocalResourceVisibility.APPLICATION);
+      rsrc_alpha.setType(LocalResourceType.FILE);
+      rsrc_alpha.setTimestamp(System.currentTimeMillis());
+      Map<String, LocalResource> localResources =
+          new HashMap<String, LocalResource>();
+      localResources.put("null_url_resource", rsrc_alpha);
+      ContainerLaunchContext containerLaunchContext = recordFactory.newRecordInstance(ContainerLaunchContext.class);
+      containerLaunchContext.setLocalResources(localResources);
+      Assert.fail("Setting an invalid local resource should be an error!");
+    } catch (NullPointerException e) {
+      Assert.assertTrue(e.getMessage().contains("Null resource URL for local resource"));
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/93932094/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 f3fe8cc..85dc5fc 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
@@ -64,6 +64,7 @@ import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
 import org.apache.hadoop.yarn.api.records.ContainerState;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
+import org.apache.hadoop.yarn.api.records.LocalResource;
 import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
 import org.apache.hadoop.yarn.api.records.LogAggregationContext;
 import org.apache.hadoop.yarn.api.records.NodeId;
@@ -996,6 +997,15 @@ public class ContainerManagerImpl extends CompositeService implements
 
     ContainerLaunchContext launchContext = request.getContainerLaunchContext();
 
+    // Sanity check for local resources
+    for (Map.Entry<String, LocalResource> rsrc : launchContext
+        .getLocalResources().entrySet()) {
+      if (rsrc.getValue() == null || rsrc.getValue().getResource() == null) {
+        throw new YarnException(
+            "Null resource URL for local resource " + rsrc.getKey() + " : " + rsrc.getValue());
+      }
+    }
+
     Credentials credentials =
         YarnServerSecurityUtils.parseCredentials(launchContext);
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/93932094/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.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/TestContainerManagerWithLCE.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
index 8221827..5dc4717 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/TestContainerManagerWithLCE.java
@@ -364,6 +364,17 @@ public class TestContainerManagerWithLCE extends TestContainerManager {
     super.testContainerRestart();
   }
 
+  @Override
+  public void testStartContainerFailureWithInvalidLocalResource() throws Exception {
+    // Don't run the test if the binary is not available.
+    if (!shouldRunTest()) {
+      LOG.info("LCE binary path is not passed. Not running the test");
+      return;
+    }
+    LOG.info("Running testStartContainerFailureWithInvalidLocalResource");
+    super.testStartContainerFailureWithInvalidLocalResource();
+  }
+
   private boolean shouldRunTest() {
     return System
         .getProperty(YarnConfiguration.NM_LINUX_CONTAINER_EXECUTOR_PATH) != null;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/93932094/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.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/TestContainerManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
index 66686a5..6fead7e 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestContainerManager.java
@@ -1859,4 +1859,49 @@ public class TestContainerManager extends BaseContainerManagerTest {
       Assert.assertEquals(signal, signalContext.getSignal());
     }
   }
+
+  @Test
+  public void testStartContainerFailureWithInvalidLocalResource()
+      throws Exception {
+    containerManager.start();
+    LocalResource rsrc_alpha =
+        recordFactory.newRecordInstance(LocalResource.class);
+    rsrc_alpha.setResource(null);
+    rsrc_alpha.setSize(-1);
+    rsrc_alpha.setVisibility(LocalResourceVisibility.APPLICATION);
+    rsrc_alpha.setType(LocalResourceType.FILE);
+    rsrc_alpha.setTimestamp(System.currentTimeMillis());
+    Map<String, LocalResource> localResources =
+        new HashMap<String, LocalResource>();
+    localResources.put("invalid_resource", rsrc_alpha);
+    ContainerLaunchContext containerLaunchContext =
+        recordFactory.newRecordInstance(ContainerLaunchContext.class);
+    ContainerLaunchContext spyContainerLaunchContext =
+        Mockito.spy(containerLaunchContext);
+    Mockito.when(spyContainerLaunchContext.getLocalResources())
+        .thenReturn(localResources);
+
+    ContainerId cId = createContainerId(0);
+    String user = "start_container_fail";
+    Token containerToken =
+        createContainerToken(cId, DUMMY_RM_IDENTIFIER, context.getNodeId(),
+            user, context.getContainerTokenSecretManager());
+    StartContainerRequest request = StartContainerRequest
+        .newInstance(spyContainerLaunchContext, containerToken);
+
+    // start containers
+    List<StartContainerRequest> startRequest =
+        new ArrayList<StartContainerRequest>();
+    startRequest.add(request);
+    StartContainersRequest requestList =
+        StartContainersRequest.newInstance(startRequest);
+
+    StartContainersResponse response =
+        containerManager.startContainers(requestList);
+    Assert.assertTrue(response.getFailedRequests().size() == 1);
+    Assert.assertTrue(response.getSuccessfullyStartedContainers().size() == 0);
+    Assert.assertTrue(response.getFailedRequests().containsKey(cId));
+    Assert.assertTrue(response.getFailedRequests().get(cId).getMessage()
+        .contains("Null resource URL for local resource"));
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[35/50] [abbrv] hadoop git commit: YARN-6406. Remove SchedulerRequestKeys when no more pending ResourceRequest. (Arun Suresh via wangda)

Posted by in...@apache.org.
YARN-6406. Remove SchedulerRequestKeys when no more pending ResourceRequest. (Arun Suresh via wangda)


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

Branch: refs/heads/HDFS-10467
Commit: 55285272c6d3ac4b24748138eed442560f33717a
Parents: 9393209
Author: Wangda Tan <wa...@apache.org>
Authored: Tue Apr 4 14:43:58 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../scheduler/AppSchedulingInfo.java            |  47 ++----
 .../LocalitySchedulingPlacementSet.java         |   8 +-
 .../capacity/TestCapacityScheduler.java         | 159 +++++++++++++++++++
 .../scheduler/capacity/TestLeafQueue.java       |   8 +-
 .../webapp/TestRMWebServicesApps.java           | 123 ++++++++++----
 5 files changed, 266 insertions(+), 79 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/55285272/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.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/AppSchedulingInfo.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java
index bff9c41..4de5eac 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/AppSchedulingInfo.java
@@ -25,12 +25,8 @@ import org.apache.hadoop.classification.InterfaceStability.Unstable;
 import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.api.records.Container;
-import org.apache.hadoop.yarn.api.records.ContainerId;
-import org.apache.hadoop.yarn.api.records.NodeId;
 import org.apache.hadoop.yarn.api.records.Resource;
 import org.apache.hadoop.yarn.api.records.ResourceRequest;
-import org.apache.hadoop.yarn.exceptions.YarnException;
-import org.apache.hadoop.yarn.server.resourcemanager.RMServerUtils;
 import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer;
 import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainerState;
@@ -51,9 +47,8 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.TreeMap;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.ConcurrentSkipListSet;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -86,8 +81,8 @@ public class AppSchedulingInfo {
 
   private Set<String> requestedPartitions = new HashSet<>();
 
-  private final ConcurrentSkipListMap<SchedulerRequestKey, Integer>
-      schedulerKeys = new ConcurrentSkipListMap<>();
+  private final ConcurrentSkipListSet<SchedulerRequestKey>
+      schedulerKeys = new ConcurrentSkipListSet<>();
   final Map<SchedulerRequestKey, SchedulingPlacementSet<SchedulerNode>>
       schedulerKeyToPlacementSets = new ConcurrentHashMap<>();
 
@@ -156,29 +151,6 @@ public class AppSchedulingInfo {
     LOG.info("Application " + applicationId + " requests cleared");
   }
 
-
-  private void incrementSchedulerKeyReference(
-      SchedulerRequestKey schedulerKey) {
-    Integer schedulerKeyCount = schedulerKeys.get(schedulerKey);
-    if (schedulerKeyCount == null) {
-      schedulerKeys.put(schedulerKey, 1);
-    } else {
-      schedulerKeys.put(schedulerKey, schedulerKeyCount + 1);
-    }
-  }
-
-  public void decrementSchedulerKeyReference(
-      SchedulerRequestKey schedulerKey) {
-    Integer schedulerKeyCount = schedulerKeys.get(schedulerKey);
-    if (schedulerKeyCount != null) {
-      if (schedulerKeyCount > 1) {
-        schedulerKeys.put(schedulerKey, schedulerKeyCount - 1);
-      } else {
-        schedulerKeys.remove(schedulerKey);
-      }
-    }
-  }
-
   public ContainerUpdateContext getUpdateContext() {
     return updateContext;
   }
@@ -230,6 +202,10 @@ public class AppSchedulingInfo {
     }
   }
 
+  public void removePlacementSets(SchedulerRequestKey schedulerRequestKey) {
+    schedulerKeyToPlacementSets.remove(schedulerRequestKey);
+  }
+
   boolean addToPlacementSets(
       boolean recoverPreemptedRequestForAContainer,
       Map<SchedulerRequestKey, Map<String, ResourceRequest>> dedupRequests) {
@@ -268,7 +244,8 @@ public class AppSchedulingInfo {
         (lastRequest != null) ? lastRequest.getNumContainers() : 0;
     if (request.getNumContainers() <= 0) {
       if (lastRequestContainers >= 0) {
-        decrementSchedulerKeyReference(schedulerKey);
+        schedulerKeys.remove(schedulerKey);
+        schedulerKeyToPlacementSets.remove(schedulerKey);
       }
       LOG.info("checking for deactivate of application :"
           + this.applicationId);
@@ -276,7 +253,7 @@ public class AppSchedulingInfo {
     } else {
       // Activate application. Metrics activation is done here.
       if (lastRequestContainers <= 0) {
-        incrementSchedulerKeyReference(schedulerKey);
+        schedulerKeys.add(schedulerKey);
         abstractUsersManager.activateApplication(user, applicationId);
       }
     }
@@ -366,7 +343,7 @@ public class AppSchedulingInfo {
   }
 
   public Collection<SchedulerRequestKey> getSchedulerKeys() {
-    return schedulerKeys.keySet();
+    return schedulerKeys;
   }
 
   /**
@@ -389,7 +366,7 @@ public class AppSchedulingInfo {
   public PendingAsk getNextPendingAsk() {
     try {
       readLock.lock();
-      SchedulerRequestKey firstRequestKey = schedulerKeys.firstKey();
+      SchedulerRequestKey firstRequestKey = schedulerKeys.first();
       return getPendingAsk(firstRequestKey, ResourceRequest.ANY);
     } finally {
       readLock.unlock();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/55285272/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/LocalitySchedulingPlacementSet.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/placement/LocalitySchedulingPlacementSet.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/LocalitySchedulingPlacementSet.java
index c32246d..6cc8cc7 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/LocalitySchedulingPlacementSet.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/placement/LocalitySchedulingPlacementSet.java
@@ -204,15 +204,17 @@ public class LocalitySchedulingPlacementSet<N extends SchedulerNode>
   private void decrementOutstanding(SchedulerRequestKey schedulerRequestKey,
       ResourceRequest offSwitchRequest) {
     int numOffSwitchContainers = offSwitchRequest.getNumContainers() - 1;
-
-    // Do not remove ANY
     offSwitchRequest.setNumContainers(numOffSwitchContainers);
 
     // Do we have any outstanding requests?
     // If there is nothing, we need to deactivate this application
     if (numOffSwitchContainers == 0) {
-      appSchedulingInfo.decrementSchedulerKeyReference(schedulerRequestKey);
+      appSchedulingInfo.getSchedulerKeys().remove(schedulerRequestKey);
       appSchedulingInfo.checkForDeactivation();
+      resourceRequestMap.remove(ResourceRequest.ANY);
+      if (resourceRequestMap.isEmpty()) {
+        appSchedulingInfo.removePlacementSets(schedulerRequestKey);
+      }
     }
 
     appSchedulingInfo.decPendingResource(

http://git-wip-us.apache.org/repos/asf/hadoop/blob/55285272/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 e2f456c..447ee3d 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
@@ -31,6 +31,7 @@ import java.net.InetSocketAddress;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
@@ -63,6 +64,7 @@ import org.apache.hadoop.yarn.api.records.ContainerState;
 import org.apache.hadoop.yarn.api.records.ContainerStatus;
 import org.apache.hadoop.yarn.api.records.ContainerUpdateType;
 import org.apache.hadoop.yarn.api.records.ExecutionType;
+import org.apache.hadoop.yarn.api.records.ExecutionTypeRequest;
 import org.apache.hadoop.yarn.api.records.NodeId;
 import org.apache.hadoop.yarn.api.records.NodeState;
 import org.apache.hadoop.yarn.api.records.Priority;
@@ -86,6 +88,7 @@ import org.apache.hadoop.yarn.ipc.YarnRPC;
 import org.apache.hadoop.yarn.server.api.protocolrecords.UpdateNodeResourceRequest;
 import org.apache.hadoop.yarn.server.resourcemanager.AdminService;
 import org.apache.hadoop.yarn.server.resourcemanager.Application;
+import org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService;
 import org.apache.hadoop.yarn.server.resourcemanager.MockAM;
 import org.apache.hadoop.yarn.server.resourcemanager.MockNM;
 import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
@@ -2947,6 +2950,162 @@ public class TestCapacityScheduler {
   }
 
   @Test
+  public void testSchedulerKeyGarbageCollection() throws Exception {
+    YarnConfiguration conf =
+        new YarnConfiguration(new CapacitySchedulerConfiguration());
+    conf.setBoolean(CapacitySchedulerConfiguration.ENABLE_USER_METRICS, true);
+
+    MemoryRMStateStore memStore = new MemoryRMStateStore();
+    memStore.init(conf);
+    MockRM rm = new MockRM(conf, memStore);
+    rm.start();
+
+    HashMap<NodeId, MockNM> nodes = new HashMap<>();
+    MockNM nm1 = new MockNM("h1:1234", 4096, rm.getResourceTrackerService());
+    nodes.put(nm1.getNodeId(), nm1);
+    MockNM nm2 = new MockNM("h2:1234", 4096, rm.getResourceTrackerService());
+    nodes.put(nm2.getNodeId(), nm2);
+    MockNM nm3 = new MockNM("h3:1234", 4096, rm.getResourceTrackerService());
+    nodes.put(nm3.getNodeId(), nm3);
+    MockNM nm4 = new MockNM("h4:1234", 4096, rm.getResourceTrackerService());
+    nodes.put(nm4.getNodeId(), nm4);
+    nm1.registerNode();
+    nm2.registerNode();
+    nm3.registerNode();
+    nm4.registerNode();
+
+    RMApp app1 = rm.submitApp(1 * GB, "app", "user", null, "default");
+    ApplicationAttemptId attemptId =
+        app1.getCurrentAppAttempt().getAppAttemptId();
+    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, nm2);
+    ResourceScheduler scheduler = rm.getResourceScheduler();
+
+    // All nodes 1 - 4 will be applicable for scheduling.
+    nm1.nodeHeartbeat(true);
+    nm2.nodeHeartbeat(true);
+    nm3.nodeHeartbeat(true);
+    nm4.nodeHeartbeat(true);
+
+    Thread.sleep(1000);
+
+    AllocateResponse allocateResponse = am1.allocate(
+        Arrays.asList(
+            newResourceRequest(1, 1, ResourceRequest.ANY,
+                Resources.createResource(3 * GB), 1, true,
+                ExecutionType.GUARANTEED),
+            newResourceRequest(2, 2, ResourceRequest.ANY,
+                Resources.createResource(3 * GB), 1, true,
+                ExecutionType.GUARANTEED),
+            newResourceRequest(3, 3, ResourceRequest.ANY,
+                Resources.createResource(3 * GB), 1, true,
+                ExecutionType.GUARANTEED),
+            newResourceRequest(4, 4, ResourceRequest.ANY,
+                Resources.createResource(3 * GB), 1, true,
+                ExecutionType.GUARANTEED)
+        ),
+        null);
+    List<Container> allocatedContainers = allocateResponse
+        .getAllocatedContainers();
+    Assert.assertEquals(0, allocatedContainers.size());
+
+    Collection<SchedulerRequestKey> schedulerKeys =
+        ((CapacityScheduler) scheduler).getApplicationAttempt(attemptId)
+            .getAppSchedulingInfo().getSchedulerKeys();
+    Assert.assertEquals(4, schedulerKeys.size());
+
+    // Get a Node to HB... at which point 1 container should be
+    // allocated
+    nm1.nodeHeartbeat(true);
+    Thread.sleep(200);
+    allocateResponse =  am1.allocate(new ArrayList<>(), new ArrayList<>());
+    allocatedContainers = allocateResponse.getAllocatedContainers();
+    Assert.assertEquals(1, allocatedContainers.size());
+
+    // Verify 1 outstanding schedulerKey is removed
+    Assert.assertEquals(3, schedulerKeys.size());
+
+    List <ResourceRequest> resReqs =
+        ((CapacityScheduler) scheduler).getApplicationAttempt(attemptId)
+            .getAppSchedulingInfo().getAllResourceRequests();
+
+    // Verify 1 outstanding schedulerKey is removed from the
+    // rrMap as well
+    Assert.assertEquals(3, resReqs.size());
+
+    // Verify One more container Allocation on node nm2
+    // And ensure the outstanding schedulerKeys go down..
+    nm2.nodeHeartbeat(true);
+    Thread.sleep(200);
+
+    // Update the allocateReq to send 0 numContainer req.
+    // For the satisfied container...
+    allocateResponse =  am1.allocate(Arrays.asList(
+        newResourceRequest(1,
+            allocatedContainers.get(0).getAllocationRequestId(),
+            ResourceRequest.ANY,
+            Resources.createResource(3 * GB), 0, true,
+            ExecutionType.GUARANTEED)
+        ),
+        new ArrayList<>());
+    allocatedContainers = allocateResponse.getAllocatedContainers();
+    Assert.assertEquals(1, allocatedContainers.size());
+
+    // Verify 1 outstanding schedulerKey is removed
+    Assert.assertEquals(2, schedulerKeys.size());
+
+    resReqs = ((CapacityScheduler) scheduler).getApplicationAttempt(attemptId)
+        .getAppSchedulingInfo().getAllResourceRequests();
+    // Verify the map size is not increased due to 0 req
+    Assert.assertEquals(2, resReqs.size());
+
+    // Now Verify that the AM can cancel 1 Ask:
+    SchedulerRequestKey sk = schedulerKeys.iterator().next();
+    am1.allocate(
+        Arrays.asList(
+            newResourceRequest(sk.getPriority().getPriority(),
+                sk.getAllocationRequestId(),
+                ResourceRequest.ANY, Resources.createResource(3 * GB), 0, true,
+                ExecutionType.GUARANTEED)
+        ),
+        null);
+
+    schedulerKeys =
+        ((CapacityScheduler) scheduler).getApplicationAttempt(attemptId)
+            .getAppSchedulingInfo().getSchedulerKeys();
+
+    Thread.sleep(200);
+
+    // Verify 1 outstanding schedulerKey is removed because of the
+    // cancel ask
+    Assert.assertEquals(1, schedulerKeys.size());
+
+    // Now verify that after the next node heartbeat, we allocate
+    // the last schedulerKey
+    nm3.nodeHeartbeat(true);
+    Thread.sleep(200);
+    allocateResponse =  am1.allocate(new ArrayList<>(), new ArrayList<>());
+    allocatedContainers = allocateResponse.getAllocatedContainers();
+    Assert.assertEquals(1, allocatedContainers.size());
+
+    // Verify no more outstanding schedulerKeys..
+    Assert.assertEquals(0, schedulerKeys.size());
+    resReqs =
+        ((CapacityScheduler) scheduler).getApplicationAttempt(attemptId)
+            .getAppSchedulingInfo().getAllResourceRequests();
+    Assert.assertEquals(0, resReqs.size());
+  }
+
+  private static ResourceRequest newResourceRequest(int priority,
+      long allocReqId, String rName, Resource resource, int numContainers,
+      boolean relaxLoc, ExecutionType eType) {
+    ResourceRequest rr = ResourceRequest.newInstance(
+        Priority.newInstance(priority), rName, resource, numContainers,
+        relaxLoc, null, ExecutionTypeRequest.newInstance(eType, true));
+    rr.setAllocationRequestId(allocReqId);
+    return rr;
+  }
+
+  @Test
   public void testHierarchyQueuesCurrentLimits() throws Exception {
     /*
      * Queue tree:

http://git-wip-us.apache.org/repos/asf/hadoop/blob/55285272/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestLeafQueue.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/TestLeafQueue.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/TestLeafQueue.java
index 1162b9f..252666d 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/TestLeafQueue.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/TestLeafQueue.java
@@ -1059,13 +1059,9 @@ public class TestLeafQueue {
     //test case 3
     qb.finishApplication(app_0.getApplicationId(), user_0);
     qb.finishApplication(app_2.getApplicationId(), user_1);
-    qb.releaseResource(clusterResource, app_0,
-        app_0.getAppSchedulingInfo().getPendingAsk(u0SchedKey)
-            .getPerAllocationResource(),
+    qb.releaseResource(clusterResource, app_0, Resource.newInstance(4*GB, 1),
         null, null);
-    qb.releaseResource(clusterResource, app_2,
-        app_2.getAppSchedulingInfo().getPendingAsk(u1SchedKey)
-            .getPerAllocationResource(),
+    qb.releaseResource(clusterResource, app_2, Resource.newInstance(4*GB, 1),
         null, null);
 
     qb.setUserLimit(50);

http://git-wip-us.apache.org/repos/asf/hadoop/blob/55285272/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesApps.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/webapp/TestRMWebServicesApps.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesApps.java
index fb9e8ed..aab9bee 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesApps.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/TestRMWebServicesApps.java
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.StringReader;
+import java.util.ArrayList;
 import java.util.Collection;
 
 import javax.ws.rs.core.MediaType;
@@ -46,6 +47,8 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppState;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptState;
+
+import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler;
 import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppInfo;
@@ -169,7 +172,38 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     assertEquals("incorrect number of elements", 1, nodesApps.getLength());
     NodeList nodes = dom.getElementsByTagName("app");
     assertEquals("incorrect number of elements", 1, nodes.getLength());
-    verifyAppsXML(nodes, app1);
+    verifyAppsXML(nodes, app1, false);
+    rm.stop();
+  }
+
+  @Test
+  public void testRunningApp() throws JSONException, Exception {
+    rm.start();
+    MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
+    RMApp app1 = rm.submitApp(CONTAINER_MB, "testwordcount", "user1");
+    MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, amNodeManager);
+    am1.allocate("*", 4096, 1, new ArrayList<>());
+    amNodeManager.nodeHeartbeat(true);
+
+    WebResource r = resource();
+    ClientResponse response = r.path("ws").path("v1").path("cluster")
+        .path("apps").accept(MediaType.APPLICATION_XML)
+        .get(ClientResponse.class);
+    assertEquals(MediaType.APPLICATION_XML_TYPE + "; " + JettyUtils.UTF_8,
+        response.getType().toString());
+    String xml = response.getEntity(String.class);
+    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+    DocumentBuilder db = dbf.newDocumentBuilder();
+    InputSource is = new InputSource();
+    is.setCharacterStream(new StringReader(xml));
+    Document dom = db.parse(is);
+    NodeList nodesApps = dom.getElementsByTagName("apps");
+    assertEquals("incorrect number of elements", 1, nodesApps.getLength());
+    NodeList nodes = dom.getElementsByTagName("app");
+    assertEquals("incorrect number of elements", 1, nodes.getLength());
+    verifyAppsXML(nodes, app1, true);
+
+    testAppsHelper("apps/", app1, MediaType.APPLICATION_JSON, true);
     rm.stop();
   }
 
@@ -203,6 +237,11 @@ public class TestRMWebServicesApps extends JerseyTestBase {
 
   public void testAppsHelper(String path, RMApp app, String media)
       throws JSONException, Exception {
+    testAppsHelper(path, app, media, false);
+  }
+
+  public void testAppsHelper(String path, RMApp app, String media,
+      boolean hasResourceReq) throws JSONException, Exception {
     WebResource r = resource();
 
     ClientResponse response = r.path("ws").path("v1").path("cluster")
@@ -215,7 +254,7 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     assertEquals("incorrect number of elements", 1, apps.length());
     JSONArray array = apps.getJSONArray("app");
     assertEquals("incorrect number of elements", 1, array.length());
-    verifyAppInfo(array.getJSONObject(0), app);
+    verifyAppInfo(array.getJSONObject(0), app, hasResourceReq);
 
   }
 
@@ -239,7 +278,7 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     assertEquals("incorrect number of elements", 1, apps.length());
     JSONArray array = apps.getJSONArray("app");
     assertEquals("incorrect number of elements", 1, array.length());
-    verifyAppInfo(array.getJSONObject(0), app1);
+    verifyAppInfo(array.getJSONObject(0), app1, false);
     rm.stop();
   }
 
@@ -483,7 +522,7 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     assertEquals("incorrect number of elements", 1, apps.length());
     JSONArray array = apps.getJSONArray("app");
     assertEquals("incorrect number of elements", 1, array.length());
-    verifyAppInfo(array.getJSONObject(0), app1);
+    verifyAppInfo(array.getJSONObject(0), app1, false);
     rm.stop();
   }
 
@@ -1327,7 +1366,7 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     JSONObject json = response.getEntity(JSONObject.class);
 
     assertEquals("incorrect number of elements", 1, json.length());
-    verifyAppInfo(json.getJSONObject("app"), app);
+    verifyAppInfo(json.getJSONObject("app"), app, false);
   }
 
   @Test
@@ -1351,11 +1390,11 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     Document dom = db.parse(is);
     NodeList nodes = dom.getElementsByTagName("app");
     assertEquals("incorrect number of elements", 1, nodes.getLength());
-    verifyAppsXML(nodes, app1);
+    verifyAppsXML(nodes, app1, false);
     rm.stop();
   }
 
-  public void verifyAppsXML(NodeList nodes, RMApp app)
+  public void verifyAppsXML(NodeList nodes, RMApp app, boolean hasResourceReq)
       throws JSONException, Exception {
 
     for (int i = 0; i < nodes.getLength(); i++) {
@@ -1394,32 +1433,38 @@ public class TestRMWebServicesApps extends JerseyTestBase {
           WebServicesTestUtils.getXmlString(element, "amNodeLabelExpression"),
           WebServicesTestUtils.getXmlString(element, "amRPCAddress"));
 
-      assertEquals(element.getElementsByTagName("resourceRequests").getLength(),
-          1);
-      Element resourceRequests =
-          (Element) element.getElementsByTagName("resourceRequests").item(0);
-      Element capability =
-          (Element) resourceRequests.getElementsByTagName("capability").item(0);
-
-      verifyResourceRequestsGeneric(app,
-          WebServicesTestUtils.getXmlString(resourceRequests,
-              "nodeLabelExpression"),
-          WebServicesTestUtils.getXmlInt(resourceRequests, "numContainers"),
-          WebServicesTestUtils.getXmlBoolean(resourceRequests, "relaxLocality"),
-          WebServicesTestUtils.getXmlInt(resourceRequests, "priority"),
-          WebServicesTestUtils.getXmlString(resourceRequests, "resourceName"),
-          WebServicesTestUtils.getXmlLong(capability, "memory"),
-          WebServicesTestUtils.getXmlLong(capability, "vCores"),
-          WebServicesTestUtils.getXmlString(resourceRequests, "executionType"),
-          WebServicesTestUtils.getXmlBoolean(resourceRequests,
-              "enforceExecutionType"));
+      if (hasResourceReq) {
+        assertEquals(element.getElementsByTagName("resourceRequests").getLength(),
+            1);
+        Element resourceRequests =
+            (Element) element.getElementsByTagName("resourceRequests").item(0);
+        Element capability =
+            (Element) resourceRequests.getElementsByTagName("capability").item(0);
+        ResourceRequest rr =
+            ((AbstractYarnScheduler)rm.getRMContext().getScheduler())
+                .getApplicationAttempt(
+                    app.getCurrentAppAttempt().getAppAttemptId())
+                .getAppSchedulingInfo().getAllResourceRequests().get(0);
+        verifyResourceRequestsGeneric(rr,
+            WebServicesTestUtils.getXmlString(resourceRequests,
+                "nodeLabelExpression"),
+            WebServicesTestUtils.getXmlInt(resourceRequests, "numContainers"),
+            WebServicesTestUtils.getXmlBoolean(resourceRequests, "relaxLocality"),
+            WebServicesTestUtils.getXmlInt(resourceRequests, "priority"),
+            WebServicesTestUtils.getXmlString(resourceRequests, "resourceName"),
+            WebServicesTestUtils.getXmlLong(capability, "memory"),
+            WebServicesTestUtils.getXmlLong(capability, "vCores"),
+            WebServicesTestUtils.getXmlString(resourceRequests, "executionType"),
+            WebServicesTestUtils.getXmlBoolean(resourceRequests,
+                "enforceExecutionType"));
+      }
     }
   }
 
-  public void verifyAppInfo(JSONObject info, RMApp app) throws JSONException,
-      Exception {
+  public void verifyAppInfo(JSONObject info, RMApp app, boolean hasResourceReqs)
+      throws JSONException, Exception {
 
-    int expectedNumberOfElements = 35;
+    int expectedNumberOfElements = 34 + (hasResourceReqs ? 2 : 0);
     String appNodeLabelExpression = null;
     String amNodeLabelExpression = null;
     if (app.getApplicationSubmissionContext()
@@ -1461,7 +1506,9 @@ public class TestRMWebServicesApps extends JerseyTestBase {
         amNodeLabelExpression,
         amRPCAddress);
 
-    verifyResourceRequests(info.getJSONArray("resourceRequests"), app);
+    if (hasResourceReqs) {
+      verifyResourceRequests(info.getJSONArray("resourceRequests"), app);
+    }
   }
 
   public void verifyAppInfoGeneric(RMApp app, String id, String user,
@@ -1490,8 +1537,10 @@ public class TestRMWebServicesApps extends JerseyTestBase {
     WebServicesTestUtils.checkStringMatch("finalStatus", app
         .getFinalApplicationStatus().toString(), finalStatus);
     assertEquals("progress doesn't match", 0, progress, 0.0);
-    WebServicesTestUtils.checkStringMatch("trackingUI", "UNASSIGNED",
-        trackingUI);
+    if ("UNASSIGNED".equals(trackingUI)) {
+      WebServicesTestUtils.checkStringMatch("trackingUI", "UNASSIGNED",
+          trackingUI);
+    }
     WebServicesTestUtils.checkStringEqual("diagnostics",
         app.getDiagnostics().toString(), diagnostics);
     assertEquals("clusterId doesn't match",
@@ -1544,7 +1593,12 @@ public class TestRMWebServicesApps extends JerseyTestBase {
   public void verifyResourceRequests(JSONArray resourceRequest, RMApp app)
       throws JSONException {
     JSONObject requestInfo = resourceRequest.getJSONObject(0);
-    verifyResourceRequestsGeneric(app,
+    ResourceRequest rr =
+        ((AbstractYarnScheduler) rm.getRMContext().getScheduler())
+            .getApplicationAttempt(
+                app.getCurrentAppAttempt().getAppAttemptId())
+            .getAppSchedulingInfo().getAllResourceRequests().get(0);
+    verifyResourceRequestsGeneric(rr,
         requestInfo.getString("nodeLabelExpression"),
         requestInfo.getInt("numContainers"),
         requestInfo.getBoolean("relaxLocality"), requestInfo.getInt("priority"),
@@ -1557,11 +1611,10 @@ public class TestRMWebServicesApps extends JerseyTestBase {
             .getBoolean("enforceExecutionType"));
   }
 
-  public void verifyResourceRequestsGeneric(RMApp app,
+  public void verifyResourceRequestsGeneric(ResourceRequest request,
       String nodeLabelExpression, int numContainers, boolean relaxLocality,
       int priority, String resourceName, long memory, long vCores,
       String executionType, boolean enforceExecutionType) {
-    ResourceRequest request = app.getAMResourceRequests().get(0);
     assertEquals("nodeLabelExpression doesn't match",
         request.getNodeLabelExpression(), nodeLabelExpression);
     assertEquals("numContainers doesn't match", request.getNumContainers(),


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[29/50] [abbrv] hadoop git commit: YARN-6420. RM startup failure due to wrong order in nodelabel editlog (Bibin A Chundatt via Varun Saxena)

Posted by in...@apache.org.
YARN-6420. RM startup failure due to wrong order in nodelabel editlog (Bibin A Chundatt via Varun Saxena)


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

Branch: refs/heads/HDFS-10467
Commit: 11406a44b3e40e4d20bd4628d392afafee126e3c
Parents: 8c69f5a
Author: Varun Saxena <va...@apache.org>
Authored: Wed Apr 5 09:16:35 2017 +0530
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 .../resourcemanager/nodelabels/RMNodeLabelsManager.java | 12 ++++++++++++
 1 file changed, 12 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/11406a44/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.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/nodelabels/RMNodeLabelsManager.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java
index effe422..79b25ed 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/nodelabels/RMNodeLabelsManager.java
@@ -34,6 +34,7 @@ import java.util.concurrent.ConcurrentMap;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hadoop.yarn.api.records.NodeId;
+import org.apache.hadoop.yarn.api.records.NodeLabel;
 import org.apache.hadoop.yarn.api.records.Resource;
 import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager;
 import org.apache.hadoop.yarn.nodelabels.RMNodeLabel;
@@ -134,6 +135,17 @@ public class RMNodeLabelsManager extends CommonNodeLabelsManager {
   }
 
   @Override
+  public void addToCluserNodeLabels(Collection<NodeLabel> labels)
+      throws IOException {
+    try {
+      writeLock.lock();
+      super.addToCluserNodeLabels(labels);
+    } finally {
+      writeLock.unlock();
+    }
+  }
+
+  @Override
   public void
       removeLabelsFromNode(Map<NodeId, Set<String>> removeLabelsFromNode)
           throws IOException {


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[16/50] [abbrv] hadoop git commit: HDFS-11560. Expose slow disks via NameNode JMX. Contributed by Hanisha Koneru.

Posted by in...@apache.org.
HDFS-11560. Expose slow disks via NameNode JMX. Contributed by Hanisha Koneru.


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

Branch: refs/heads/HDFS-10467
Commit: 3422a3ddf02695df5b2db196d04299d9a8f68a04
Parents: 7070895
Author: Hanisha Koneru <ha...@apache.org>
Authored: Fri Mar 31 13:50:29 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../server/blockmanagement/DatanodeManager.java |  9 +++
 .../server/blockmanagement/SlowDiskTracker.java |  3 +
 .../hadoop/hdfs/server/namenode/NameNode.java   |  6 ++
 .../server/namenode/NameNodeStatusMXBean.java   |  8 +++
 .../blockmanagement/TestSlowDiskTracker.java    | 13 +----
 .../namenode/TestNameNodeStatusMXBean.java      | 59 +++++++++++++++++++-
 6 files changed, 85 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/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 18135a8..c7bdca9 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
@@ -1907,5 +1907,14 @@ public class DatanodeManager {
   public SlowDiskTracker getSlowDiskTracker() {
     return slowDiskTracker;
   }
+  /**
+   * Retrieve information about slow disks as a JSON.
+   * Returns null if we are not tracking slow disks.
+   * @return
+   */
+  public String getSlowDisksReport() {
+    return slowDiskTracker != null ?
+        slowDiskTracker.getSlowDiskReportAsJsonString() : null;
+  }
 }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
index 25920a2..52fce5d 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/SlowDiskTracker.java
@@ -256,6 +256,9 @@ public class SlowDiskTracker {
   public String getSlowDiskReportAsJsonString() {
     ObjectMapper objectMapper = new ObjectMapper();
     try {
+      if (slowDisksReport.isEmpty()) {
+        return null;
+      }
       return objectMapper.writeValueAsString(slowDisksReport);
     } catch (JsonProcessingException e) {
       // Failed to serialize. Don't log the exception call stack.

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/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 e7841f0..32d268a 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
@@ -1826,6 +1826,12 @@ public class NameNode extends ReconfigurableBase implements
         .getSlowPeersReport();
   }
 
+  @Override //NameNodeStatusMXBean
+  public String getSlowDisksReport() {
+    return namesystem.getBlockManager().getDatanodeManager()
+        .getSlowDisksReport();
+  }
+
   /**
    * Shutdown the NN immediately in an ungraceful way. Used when it would be
    * unsafe for the NN to continue operating, e.g. during a failed HA state

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeStatusMXBean.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeStatusMXBean.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeStatusMXBean.java
index f46b9ae..ed1b96b 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeStatusMXBean.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/NameNodeStatusMXBean.java
@@ -75,4 +75,12 @@ public interface NameNodeStatusMXBean {
    * enabled. The report is in a JSON format.
    */
   String getSlowPeersReport();
+
+
+  /**
+   *  Gets the topN slow disks in the cluster, if the feature is enabled.
+   *
+   *  @return JSON string of list of diskIDs and latencies
+   */
+  String getSlowDisksReport();
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
index e96b96a..16dfab2 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestSlowDiskTracker.java
@@ -393,18 +393,9 @@ public class TestSlowDiskTracker {
     timer.advance(reportValidityMs);
 
     tracker.updateSlowDiskReportAsync(timer.monotonicNow());
+    Thread.sleep(OUTLIERS_REPORT_INTERVAL*2);
 
-    GenericTestUtils.waitFor(new Supplier<Boolean>() {
-      @Override
-      public Boolean get() {
-        return tracker.getSlowDiskReportAsJsonString() != null;
-      }
-    }, 500, 5000);
-
-    ArrayList<DiskLatency> jsonReport = getAndDeserializeJson(
-        tracker.getSlowDiskReportAsJsonString());
-
-    assertTrue(jsonReport.isEmpty());
+    assertTrue(tracker.getSlowDiskReportAsJsonString() == null);
   }
 
   private boolean isDiskInReports(ArrayList<DiskLatency> reports,

http://git-wip-us.apache.org/repos/asf/hadoop/blob/3422a3dd/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeStatusMXBean.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeStatusMXBean.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeStatusMXBean.java
index c03dc20..8fe734e 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeStatusMXBean.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestNameNodeStatusMXBean.java
@@ -17,17 +17,23 @@
  */
 package org.apache.hadoop.hdfs.server.namenode;
 
+import com.google.common.base.Supplier;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
+import org.apache.hadoop.hdfs.server.datanode.DataNode;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
-import org.apache.hadoop.hdfs.server.datanode.TestDataNodeMXBean;
+import org.apache.hadoop.test.GenericTestUtils;
 import org.junit.Assert;
 import org.junit.Test;
 
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
 import java.lang.management.ManagementFactory;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 /**
  * Class for testing {@link NameNodeStatusMXBean} implementation.
@@ -38,7 +44,7 @@ public class TestNameNodeStatusMXBean {
       TestNameNodeStatusMXBean.class);
 
   @Test(timeout = 120000L)
-  public void testDataNodeMXBean() throws Exception {
+  public void testNameNodeStatusMXBean() throws Exception {
     Configuration conf = new Configuration();
     MiniDFSCluster cluster = null;
 
@@ -84,6 +90,55 @@ public class TestNameNodeStatusMXBean {
       String slowPeersReport = (String)mbs.getAttribute(mxbeanName,
           "SlowPeersReport");
       Assert.assertEquals(nn.getSlowPeersReport(), slowPeersReport);
+
+      // Get attribute "SlowDisksReport"
+      String slowDisksReport = (String)mbs.getAttribute(mxbeanName,
+          "SlowDisksReport");
+      Assert.assertEquals(nn.getSlowDisksReport(), slowDisksReport);
+    } finally {
+      if (cluster != null) {
+        cluster.shutdown();
+      }
+    }
+  }
+
+  @Test
+  public void testNameNodeMXBeanSlowDisksEnabled() throws Exception {
+    Configuration conf = new Configuration();
+    conf.setDouble(
+        DFSConfigKeys.DFS_DATANODE_FILEIO_PROFILING_SAMPLING_FRACTION_KEY, 1.0);
+    conf.setTimeDuration(
+        DFSConfigKeys.DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY,
+        1000, TimeUnit.MILLISECONDS);
+    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build();
+
+    try {
+      List<DataNode> datanodes = cluster.getDataNodes();
+      Assert.assertEquals(datanodes.size(), 1);
+      DataNode datanode = datanodes.get(0);
+      String slowDiskPath = "test/data1/slowVolume";
+      datanode.getDiskMetrics().addSlowDiskForTesting(slowDiskPath, null);
+
+      NameNode nn = cluster.getNameNode();
+      DatanodeManager datanodeManager = nn.getNamesystem().getBlockManager()
+          .getDatanodeManager();
+
+      MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
+      ObjectName mxbeanName = new ObjectName(
+          "Hadoop:service=NameNode,name=NameNodeStatus");
+
+      GenericTestUtils.waitFor(new Supplier<Boolean>() {
+        @Override
+        public Boolean get() {
+          return (datanodeManager.getSlowDisksReport() != null);
+        }
+      }, 1000, 100000);
+
+      String slowDisksReport = (String)mbs.getAttribute(
+          mxbeanName, "SlowDisksReport");
+      Assert.assertEquals(datanodeManager.getSlowDisksReport(),
+          slowDisksReport);
+      Assert.assertTrue(slowDisksReport.contains(slowDiskPath));
     } finally {
       if (cluster != null) {
         cluster.shutdown();


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[19/50] [abbrv] hadoop git commit: HADOOP-14271. Correct spelling of 'occurred' and variants. Contributed by Yeliang Cang

Posted by in...@apache.org.
HADOOP-14271. Correct spelling of 'occurred' and variants. Contributed by Yeliang Cang


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

Branch: refs/heads/HDFS-10467
Commit: 53a513f17ae2e4ce251a4674215f79fac0936ad5
Parents: aeb249e
Author: Chris Douglas <cd...@apache.org>
Authored: Mon Apr 3 20:13:14 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/util/Progressable.java    |  2 +-
 .../apache/hadoop/util/UTF8ByteArrayUtils.java  |  4 +--
 .../src/main/native/gtest/gtest-all.cc          |  2 +-
 .../src/main/native/gtest/include/gtest/gtest.h |  2 +-
 .../hadoop/test/MultithreadedTestUtil.java      |  2 +-
 .../org/apache/hadoop/hdfs/DFSInputStream.java  |  2 +-
 .../hadoop/hdfs/DFSStripedInputStream.java      |  2 +-
 .../hadoop/fs/http/server/FSOperations.java     | 34 ++++++++++----------
 .../datanode/fsdataset/impl/BlockPoolSlice.java |  2 +-
 .../datanode/fsdataset/impl/FsVolumeImpl.java   |  2 +-
 .../mapreduce/lib/jobcontrol/JobControl.java    |  2 +-
 .../hadoop/fs/azure/BlockBlobAppendStream.java  |  2 +-
 .../hadoop/streaming/StreamKeyValUtil.java      |  8 ++---
 .../distributedshell/TestDistributedShell.java  | 30 ++++++++---------
 .../launcher/TestContainerLaunch.java           | 12 +++----
 .../scheduler/capacity/TestParentQueue.java     | 18 +++++------
 16 files changed, 63 insertions(+), 63 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Progressable.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Progressable.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Progressable.java
index 495ca82..201ee5c 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Progressable.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Progressable.java
@@ -28,7 +28,7 @@ import org.apache.hadoop.classification.InterfaceStability;
  * to explicitly report progress to the Hadoop framework. This is especially
  * important for operations which take significant amount of time since,
  * in-lieu of the reported progress, the framework has to assume that an error
- * has occured and time-out the operation.</p>
+ * has occurred and time-out the operation.</p>
  */
 @InterfaceAudience.Public
 @InterfaceStability.Stable

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/UTF8ByteArrayUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/UTF8ByteArrayUtils.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/UTF8ByteArrayUtils.java
index 2a804c6..069494f 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/UTF8ByteArrayUtils.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/UTF8ByteArrayUtils.java
@@ -30,7 +30,7 @@ public class UTF8ByteArrayUtils {
    * @param start starting offset
    * @param end ending position
    * @param b the byte to find
-   * @return position that first byte occures otherwise -1
+   * @return position that first byte occurs, otherwise -1
    */
   public static int findByte(byte [] utf, int start, int end, byte b) {
     for(int i=start; i<end; i++) {
@@ -47,7 +47,7 @@ public class UTF8ByteArrayUtils {
    * @param start starting offset
    * @param end ending position
    * @param b the bytes to find
-   * @return position that first byte occures otherwise -1
+   * @return position that first byte occurs, otherwise -1
    */
   public static int findBytes(byte [] utf, int start, int end, byte[] b) {
     int matchEnd = end - b.length;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-common-project/hadoop-common/src/main/native/gtest/gtest-all.cc
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/native/gtest/gtest-all.cc b/hadoop-common-project/hadoop-common/src/main/native/gtest/gtest-all.cc
index 4f8c08a..fb6ddbc 100644
--- a/hadoop-common-project/hadoop-common/src/main/native/gtest/gtest-all.cc
+++ b/hadoop-common-project/hadoop-common/src/main/native/gtest/gtest-all.cc
@@ -8298,7 +8298,7 @@ FilePath FilePath::RemoveExtension(const char* extension) const {
   return *this;
 }
 
-// Returns a pointer to the last occurence of a valid path separator in
+// Returns a pointer to the last occurrence of a valid path separator in
 // the FilePath. On Windows, for example, both '/' and '\' are valid path
 // separators. Returns NULL if no path separator was found.
 const char* FilePath::FindLastPathSeparator() const {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-common-project/hadoop-common/src/main/native/gtest/include/gtest/gtest.h
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/native/gtest/include/gtest/gtest.h b/hadoop-common-project/hadoop-common/src/main/native/gtest/include/gtest/gtest.h
index c04205d..3d795bf 100644
--- a/hadoop-common-project/hadoop-common/src/main/native/gtest/include/gtest/gtest.h
+++ b/hadoop-common-project/hadoop-common/src/main/native/gtest/include/gtest/gtest.h
@@ -4457,7 +4457,7 @@ class GTEST_API_ FilePath {
 
   void Normalize();
 
-  // Returns a pointer to the last occurence of a valid path separator in
+  // Returns a pointer to the last occurrence of a valid path separator in
   // the FilePath. On Windows, for example, both '/' and '\' are valid path
   // separators. Returns NULL if no path separator was found.
   const char* FindLastPathSeparator() const;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/MultithreadedTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/MultithreadedTestUtil.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/MultithreadedTestUtil.java
index e0bc136..b51329f 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/MultithreadedTestUtil.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/MultithreadedTestUtil.java
@@ -225,7 +225,7 @@ public abstract class MultithreadedTestUtil {
 
     /**
      * User method for any code to test repeating behavior of (as threads).
-     * @throws Exception throw an exception if a failure has occured.
+     * @throws Exception throw an exception if a failure has occurred.
      */
     public abstract void doAnAction() throws Exception;
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSInputStream.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSInputStream.java b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSInputStream.java
index 39d0eed..d388d00 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSInputStream.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/DFSInputStream.java
@@ -777,7 +777,7 @@ public class DFSInputStream extends FSInputStream
           }
         } finally {
           // Check if need to report block replicas corruption either read
-          // was successful or ChecksumException occured.
+          // was successful or ChecksumException occurred.
           reportCheckSumFailure(corruptedBlocks,
               currentLocatedBlock.getLocations().length, false);
         }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/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 07e6609..75ad022 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
@@ -394,7 +394,7 @@ public class DFSStripedInputStream extends DFSInputStream {
         return result;
       } finally {
         // Check if need to report block replicas corruption either read
-        // was successful or ChecksumException occured.
+        // was successful or ChecksumException occurred.
         reportCheckSumFailure(corruptedBlocks,
             currentLocatedBlock.getLocations().length, true);
       }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
index 5ff42a4..3373582 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/server/FSOperations.java
@@ -333,7 +333,7 @@ public class FSOperations {
      *
      * @return void.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -377,7 +377,7 @@ public class FSOperations {
      *
      * @return void.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -418,7 +418,7 @@ public class FSOperations {
      *         wait for it to complete before proceeding with further file 
      *         updates.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public JSONObject execute(FileSystem fs) throws IOException {
@@ -452,7 +452,7 @@ public class FSOperations {
      *
      * @return a Map object (JSON friendly) with the content-summary.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Map execute(FileSystem fs) throws IOException {
@@ -501,7 +501,7 @@ public class FSOperations {
      *
      * @return The URI of the created file.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -549,7 +549,7 @@ public class FSOperations {
      * @return <code>true</code> if the delete operation was successful,
      *         <code>false</code> otherwise.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public JSONObject execute(FileSystem fs) throws IOException {
@@ -583,7 +583,7 @@ public class FSOperations {
      *
      * @return a Map object (JSON friendly) with the file checksum.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Map execute(FileSystem fs) throws IOException {
@@ -640,7 +640,7 @@ public class FSOperations {
      *
      * @return a JSON object with the user home directory.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     @SuppressWarnings("unchecked")
@@ -765,7 +765,7 @@ public class FSOperations {
      * @return <code>true</code> if the mkdirs operation was successful,
      *         <code>false</code> otherwise.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public JSONObject execute(FileSystem fs) throws IOException {
@@ -799,7 +799,7 @@ public class FSOperations {
      *
      * @return The inputstream of the file.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public InputStream execute(FileSystem fs) throws IOException {
@@ -837,7 +837,7 @@ public class FSOperations {
      * @return <code>true</code> if the rename operation was successful,
      *         <code>false</code> otherwise.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public JSONObject execute(FileSystem fs) throws IOException {
@@ -876,7 +876,7 @@ public class FSOperations {
      *
      * @return void.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -913,7 +913,7 @@ public class FSOperations {
      *
      * @return void.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -1186,7 +1186,7 @@ public class FSOperations {
      * @return <code>true</code> if the replication value was set,
      *         <code>false</code> otherwise.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     @SuppressWarnings("unchecked")
@@ -1228,7 +1228,7 @@ public class FSOperations {
      *
      * @return void.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Void execute(FileSystem fs) throws IOException {
@@ -1314,7 +1314,7 @@ public class FSOperations {
      *
      * @return Map a map object (JSON friendly) with the xattr names.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Map execute(FileSystem fs) throws IOException {
@@ -1353,7 +1353,7 @@ public class FSOperations {
      *
      * @return Map a map object (JSON friendly) with the xattrs.
      *
-     * @throws IOException thrown if an IO error occured.
+     * @throws IOException thrown if an IO error occurred.
      */
     @Override
     public Map execute(FileSystem fs) throws IOException {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/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 c8df300..c17ef36 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
@@ -822,7 +822,7 @@ class BlockPoolSlice {
     } catch (Exception e) {
       // Any exception we need to revert back to read from disk
       // Log the error and return false
-      LOG.info("Exception occured while reading the replicas cache file: "
+      LOG.info("Exception occurred while reading the replicas cache file: "
           + replicaFile.getPath(), e );
       return false;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/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 f6e6a59..b948fb7 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
@@ -1323,7 +1323,7 @@ public class FsVolumeImpl implements FsVolumeSpi {
       fileNames = fileIoProvider.listDirectory(
           this, dir, BlockDirFilter.INSTANCE);
     } catch (IOException ioe) {
-      LOG.warn("Exception occured while compiling report: ", ioe);
+      LOG.warn("Exception occurred while compiling report: ", ioe);
       // Volume error check moved to FileIoProvider.
       // Ignore this directory and proceed.
       return report;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.java
index b0b7a3c..e5399b5 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/jobcontrol/JobControl.java
@@ -276,7 +276,7 @@ public class JobControl implements Runnable {
   }
 
   synchronized private void failAllJobs(Throwable t) {
-    String message = "Unexpected System Error Occured: "+
+    String message = "Unexpected System Error Occurred: "+
     StringUtils.stringifyException(t);
     Iterator<ControlledJob> it = jobsInProgress.iterator();
     while(it.hasNext()) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/BlockBlobAppendStream.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/BlockBlobAppendStream.java b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/BlockBlobAppendStream.java
index a7e286c..afb9379 100644
--- a/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/BlockBlobAppendStream.java
+++ b/hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/BlockBlobAppendStream.java
@@ -346,7 +346,7 @@ public class BlockBlobAppendStream extends OutputStream {
 
     try {
       if (!ioThreadPool.awaitTermination(10, TimeUnit.MINUTES)) {
-        LOG.error("Time out occured while waiting for IO request to finish in append"
+        LOG.error("Time out occurred while waiting for IO request to finish in append"
             + " for blob : {}", key);
         NativeAzureFileSystemHelper.logAllLiveStackTraces();
         throw new IOException("Timed out waiting for IO requests to finish");

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamKeyValUtil.java b/hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
index 75e05dc..fba45b1 100644
--- a/hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
+++ b/hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamKeyValUtil.java
@@ -26,11 +26,11 @@ import org.apache.hadoop.util.LineReader;
 public class StreamKeyValUtil {
 
   /**
-   * Find the first occured tab in a UTF-8 encoded string
+   * Find the first occurred tab in a UTF-8 encoded string
    * @param utf a byte array containing a UTF-8 encoded string
    * @param start starting offset
    * @param length no. of bytes
-   * @return position that first tab occures otherwise -1
+   * @return position that first tab occurres otherwise -1
    */
   public static int findTab(byte [] utf, int start, int length) {
     for(int i=start; i<(start+length); i++) {
@@ -41,9 +41,9 @@ public class StreamKeyValUtil {
     return -1;      
   }
   /**
-   * Find the first occured tab in a UTF-8 encoded string
+   * Find the first occurred tab in a UTF-8 encoded string
    * @param utf a byte array containing a UTF-8 encoded string
-   * @return position that first tab occures otherwise -1
+   * @return position that first tab occurres otherwise -1
    */
   public static int findTab(byte [] utf) {
     return org.apache.hadoop.util.UTF8ByteArrayUtils.findNthByte(utf, 0, 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java
----------------------------------------------------------------------
diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java
index 300ea67..ef21c87 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDistributedShell.java
@@ -544,17 +544,17 @@ public class TestDistributedShell {
       Assert.assertEquals(
           "Container created event needs to be published atleast once",
           1,
-          getNumOfStringOccurences(containerEntityFile,
+          getNumOfStringOccurrences(containerEntityFile,
               ContainerMetricsConstants.CREATED_EVENT_TYPE));
 
       // to avoid race condition of testcase, atleast check 4 times with sleep
       // of 500ms
-      long numOfContainerFinishedOccurences = 0;
+      long numOfContainerFinishedOccurrences = 0;
       for (int i = 0; i < 4; i++) {
-        numOfContainerFinishedOccurences =
-            getNumOfStringOccurences(containerEntityFile,
+        numOfContainerFinishedOccurrences =
+            getNumOfStringOccurrences(containerEntityFile,
                 ContainerMetricsConstants.FINISHED_EVENT_TYPE);
-        if (numOfContainerFinishedOccurences > 0) {
+        if (numOfContainerFinishedOccurrences > 0) {
           break;
         } else {
           Thread.sleep(500L);
@@ -563,7 +563,7 @@ public class TestDistributedShell {
       Assert.assertEquals(
           "Container finished event needs to be published atleast once",
           1,
-          numOfContainerFinishedOccurences);
+          numOfContainerFinishedOccurrences);
 
       // Verify RM posting Application life cycle Events are getting published
       String appMetricsTimestampFileName =
@@ -576,17 +576,17 @@ public class TestDistributedShell {
       Assert.assertEquals(
           "Application created event should be published atleast once",
           1,
-          getNumOfStringOccurences(appEntityFile,
+          getNumOfStringOccurrences(appEntityFile,
               ApplicationMetricsConstants.CREATED_EVENT_TYPE));
 
       // to avoid race condition of testcase, atleast check 4 times with sleep
       // of 500ms
-      long numOfStringOccurences = 0;
+      long numOfStringOccurrences = 0;
       for (int i = 0; i < 4; i++) {
-        numOfStringOccurences =
-            getNumOfStringOccurences(appEntityFile,
+        numOfStringOccurrences =
+            getNumOfStringOccurrences(appEntityFile,
                 ApplicationMetricsConstants.FINISHED_EVENT_TYPE);
-        if (numOfStringOccurences > 0) {
+        if (numOfStringOccurrences > 0) {
           break;
         } else {
           Thread.sleep(500L);
@@ -595,7 +595,7 @@ public class TestDistributedShell {
       Assert.assertEquals(
           "Application finished event should be published atleast once",
           1,
-          numOfStringOccurences);
+          numOfStringOccurrences);
 
       // Verify RM posting AppAttempt life cycle Events are getting published
       String appAttemptMetricsTimestampFileName =
@@ -609,13 +609,13 @@ public class TestDistributedShell {
       Assert.assertEquals(
           "AppAttempt register event should be published atleast once",
           1,
-          getNumOfStringOccurences(appAttemptEntityFile,
+          getNumOfStringOccurrences(appAttemptEntityFile,
               AppAttemptMetricsConstants.REGISTERED_EVENT_TYPE));
 
       Assert.assertEquals(
           "AppAttempt finished event should be published atleast once",
           1,
-          getNumOfStringOccurences(appAttemptEntityFile,
+          getNumOfStringOccurrences(appAttemptEntityFile,
               AppAttemptMetricsConstants.FINISHED_EVENT_TYPE));
     } finally {
       FileUtils.deleteDirectory(tmpRootFolder.getParentFile());
@@ -636,7 +636,7 @@ public class TestDistributedShell {
     return entityFile;
   }
 
-  private long getNumOfStringOccurences(File entityFile, String searchString)
+  private long getNumOfStringOccurrences(File entityFile, String searchString)
       throws IOException {
     BufferedReader reader = null;
     String strLine;

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.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/launcher/TestContainerLaunch.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
index 23b99d9..8dcf4be 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunch.java
@@ -641,8 +641,8 @@ public class TestContainerLaunch extends BaseContainerManagerTest {
     ContainerLaunch launch = new ContainerLaunch(context, conf, dispatcher,
         exec, app, container, dirsHandler, containerManager);
     launch.call();
-    Assert.assertTrue("ContainerExitEvent should have occured",
-        eventHandler.isContainerExitEventOccured());
+    Assert.assertTrue("ContainerExitEvent should have occurred",
+        eventHandler.isContainerExitEventOccurred());
   }
 
   private static class ContainerExitHandler implements EventHandler<Event> {
@@ -652,15 +652,15 @@ public class TestContainerLaunch extends BaseContainerManagerTest {
       this.testForMultiFile = testForMultiFile;
     }
 
-    boolean containerExitEventOccured = false;
+    boolean containerExitEventOccurred = false;
 
-    public boolean isContainerExitEventOccured() {
-      return containerExitEventOccured;
+    public boolean isContainerExitEventOccurred() {
+      return containerExitEventOccurred;
     }
 
     public void handle(Event event) {
       if (event instanceof ContainerExitEvent) {
-        containerExitEventOccured = true;
+        containerExitEventOccurred = true;
         ContainerExitEvent exitEvent = (ContainerExitEvent) event;
         Assert.assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_FAILURE,
             exitEvent.getType());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/53a513f1/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/TestParentQueue.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/TestParentQueue.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/TestParentQueue.java
index c4b7a0d..cdbbc51 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/TestParentQueue.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/TestParentQueue.java
@@ -343,43 +343,43 @@ public class TestParentQueue {
     csConf.setCapacity(Q_B, 70.5F);
 
     Map<String, CSQueue> queues = new HashMap<String, CSQueue>();
-    boolean exceptionOccured = false;
+    boolean exceptionOccurred = false;
     try {
       CapacitySchedulerQueueManager.parseQueue(csContext, csConf, null,
           CapacitySchedulerConfiguration.ROOT, queues, queues,
           TestUtils.spyHook);
     } catch (IllegalArgumentException ie) {
-      exceptionOccured = true;
+      exceptionOccurred = true;
     }
-    if (!exceptionOccured) {
+    if (!exceptionOccurred) {
       Assert.fail("Capacity is more then 100% so should be failed.");
     }
     csConf.setCapacity(Q_A, 30);
     csConf.setCapacity(Q_B, 70);
-    exceptionOccured = false;
+    exceptionOccurred = false;
     queues.clear();
     try {
       CapacitySchedulerQueueManager.parseQueue(csContext, csConf, null,
           CapacitySchedulerConfiguration.ROOT, queues, queues,
           TestUtils.spyHook);
     } catch (IllegalArgumentException ie) {
-      exceptionOccured = true;
+      exceptionOccurred = true;
     }
-    if (exceptionOccured) {
+    if (exceptionOccurred) {
       Assert.fail("Capacity is 100% so should not be failed.");
     }
     csConf.setCapacity(Q_A, 30);
     csConf.setCapacity(Q_B, 70.005F);
-    exceptionOccured = false;
+    exceptionOccurred = false;
     queues.clear();
     try {
       CapacitySchedulerQueueManager.parseQueue(csContext, csConf, null,
           CapacitySchedulerConfiguration.ROOT, queues, queues,
           TestUtils.spyHook);
     } catch (IllegalArgumentException ie) {
-      exceptionOccured = true;
+      exceptionOccurred = true;
     }
-    if (exceptionOccured) {
+    if (exceptionOccurred) {
       Assert
           .fail("Capacity is under PRECISION which is .05% so should not be failed.");
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[09/50] [abbrv] hadoop git commit: YARN-6354. LeveldbRMStateStore can parse invalid keys when recovering reservations. Contributed by Jason Lowe

Posted by in...@apache.org.
YARN-6354. LeveldbRMStateStore can parse invalid keys when recovering reservations. Contributed by Jason Lowe


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

Branch: refs/heads/HDFS-10467
Commit: 98c25b72992b4fdb57814fccb3065c2aaedd9d9a
Parents: a0db5dd
Author: Eric Payne <ep...@apache.org>
Authored: Fri Mar 31 12:30:35 2017 -0500
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:20 2017 -0700

----------------------------------------------------------------------
 .../recovery/LeveldbRMStateStore.java            |  8 ++++++++
 .../recovery/TestLeveldbRMStateStore.java        | 19 +++++++++++++++----
 2 files changed, 23 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/98c25b72/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.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/recovery/LeveldbRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java
index 02f90dd..2ca53db 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/LeveldbRMStateStore.java
@@ -214,6 +214,11 @@ public class LeveldbRMStateStore extends RMStateStore {
     return db == null;
   }
 
+  @VisibleForTesting
+  DB getDatabase() {
+    return db;
+  }
+
   @Override
   protected Version loadVersion() throws Exception {
     Version version = null;
@@ -284,6 +289,9 @@ public class LeveldbRMStateStore extends RMStateStore {
       while (iter.hasNext()) {
         Entry<byte[],byte[]> entry = iter.next();
         String key = asString(entry.getKey());
+        if (!key.startsWith(RM_RESERVATION_KEY_PREFIX)) {
+          break;
+        }
 
         String planReservationString =
             key.substring(RM_RESERVATION_KEY_PREFIX.length());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/98c25b72/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestLeveldbRMStateStore.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/recovery/TestLeveldbRMStateStore.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestLeveldbRMStateStore.java
index 4297e73..51adbe1 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestLeveldbRMStateStore.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/recovery/TestLeveldbRMStateStore.java
@@ -31,6 +31,7 @@ import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.records.Version;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMApp;
 import org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttempt;
+import org.fusesource.leveldbjni.JniDBFactory;
 import org.iq80.leveldb.DB;
 import org.junit.After;
 import org.junit.Before;
@@ -125,17 +126,27 @@ public class TestLeveldbRMStateStore extends RMStateStoreTestBase {
   public void testCompactionCycle() throws Exception {
     final DB mockdb = mock(DB.class);
     conf.setLong(YarnConfiguration.RM_LEVELDB_COMPACTION_INTERVAL_SECS, 1);
-    LeveldbRMStateStore store = new LeveldbRMStateStore() {
+    stateStore = new LeveldbRMStateStore() {
       @Override
       protected DB openDatabase() throws Exception {
         return mockdb;
       }
     };
-    store.init(conf);
-    store.start();
+    stateStore.init(conf);
+    stateStore.start();
     verify(mockdb, timeout(10000)).compactRange(
         (byte[]) isNull(), (byte[]) isNull());
-    store.close();
+  }
+
+  @Test
+  public void testBadKeyIteration() throws Exception {
+    stateStore = new LeveldbRMStateStore();
+    stateStore.init(conf);
+    stateStore.start();
+    DB db = stateStore.getDatabase();
+    // add an entry that appears at the end of the database when iterating
+    db.put(JniDBFactory.bytes("zzz"), JniDBFactory.bytes("z"));
+    stateStore.loadState();
   }
 
   class LeveldbStateStoreTester implements RMStateStoreHelper {


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[50/50] [abbrv] hadoop git commit: HDFS-10882. Federation State Store Interface API. Contributed by Jason Kace and Inigo Goiri.

Posted by in...@apache.org.
HDFS-10882. Federation State Store Interface API. Contributed by Jason Kace and Inigo Goiri.


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

Branch: refs/heads/HDFS-10467
Commit: 0e4661f7fe6b29b13c8c2d74ee70e8d6dd7ab3de
Parents: 83b1d22
Author: Inigo <in...@apache.org>
Authored: Thu Apr 6 19:18:52 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 19:18:52 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSConfigKeys.java   |  11 ++
 .../server/federation/store/RecordStore.java    | 100 ++++++++++++++++
 .../store/driver/StateStoreSerializer.java      | 119 +++++++++++++++++++
 .../driver/impl/StateStoreSerializerPBImpl.java | 115 ++++++++++++++++++
 .../store/records/impl/pb/PBRecord.java         |  47 ++++++++
 .../store/records/impl/pb/package-info.java     |  29 +++++
 .../src/main/resources/hdfs-default.xml         |   8 ++
 7 files changed, 429 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/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 58a2823..07c2adf 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
@@ -25,6 +25,7 @@ import org.apache.hadoop.hdfs.protocol.HdfsConstants;
 import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyDefault;
 import org.apache.hadoop.hdfs.server.blockmanagement.BlockPlacementPolicyRackFaultTolerant;
 import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.RamDiskReplicaLruTracker;
+import org.apache.hadoop.hdfs.server.federation.store.driver.impl.StateStoreSerializerPBImpl;
 import org.apache.hadoop.http.HttpConfig;
 
 /** 
@@ -1097,6 +1098,16 @@ public class DFSConfigKeys extends CommonConfigurationKeys {
   public static final String FEDERATION_NAMENODE_RESOLVER_CLIENT_CLASS_DEFAULT =
       "org.apache.hadoop.hdfs.server.federation.MockResolver";
 
+  // HDFS Router-based federation State Store
+  public static final String FEDERATION_STORE_PREFIX =
+      FEDERATION_ROUTER_PREFIX + "store.";
+
+  public static final String FEDERATION_STORE_SERIALIZER_CLASS =
+      DFSConfigKeys.FEDERATION_STORE_PREFIX + "serializer";
+  public static final Class<StateStoreSerializerPBImpl>
+      FEDERATION_STORE_SERIALIZER_CLASS_DEFAULT =
+          StateStoreSerializerPBImpl.class;
+
   // dfs.client.retry confs are moved to HdfsClientConfigKeys.Retry 
   @Deprecated
   public static final String  DFS_CLIENT_RETRY_POLICY_ENABLED_KEY

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/RecordStore.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/RecordStore.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/RecordStore.java
new file mode 100644
index 0000000..524f432
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/RecordStore.java
@@ -0,0 +1,100 @@
+/**
+ * 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.federation.store;
+
+import java.lang.reflect.Constructor;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.hadoop.hdfs.server.federation.store.driver.StateStoreDriver;
+import org.apache.hadoop.hdfs.server.federation.store.records.BaseRecord;
+
+/**
+ * Store records in the State Store. Subclasses provide interfaces to operate on
+ * those records.
+ *
+ * @param <R> Record to store by this interface.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Evolving
+public abstract class RecordStore<R extends BaseRecord> {
+
+  private static final Log LOG = LogFactory.getLog(RecordStore.class);
+
+
+  /** Class of the record stored in this State Store. */
+  private final Class<R> recordClass;
+
+  /** State store driver backed by persistent storage. */
+  private final StateStoreDriver driver;
+
+
+  /**
+   * Create a new store for records.
+   *
+   * @param clazz Class of the record to store.
+   * @param stateStoreDriver Driver for the State Store.
+   */
+  protected RecordStore(Class<R> clazz, StateStoreDriver stateStoreDriver) {
+    this.recordClass = clazz;
+    this.driver = stateStoreDriver;
+  }
+
+  /**
+   * Report a required record to the data store. The data store uses this to
+   * create/maintain storage for the record.
+   *
+   * @return The class of the required record or null if no record is required
+   *         for this interface.
+   */
+  public Class<R> getRecordClass() {
+    return this.recordClass;
+  }
+
+  /**
+   * Get the State Store driver.
+   *
+   * @return State Store driver.
+   */
+  protected StateStoreDriver getDriver() {
+    return this.driver;
+  }
+
+  /**
+   * Build a state store API implementation interface.
+   *
+   * @param interfaceClass The specific interface implementation to create
+   * @param driver The {@link StateStoreDriver} implementation in use.
+   * @return An initialized instance of the specified state store API
+   *         implementation.
+   */
+  public static <T extends RecordStore<?>> T newInstance(
+      final Class<T> clazz, final StateStoreDriver driver) {
+
+    try {
+      Constructor<T> constructor = clazz.getConstructor(StateStoreDriver.class);
+      T recordStore = constructor.newInstance(driver);
+      return recordStore;
+    } catch (Exception e) {
+      LOG.error("Cannot create new instance for " + clazz, e);
+      return null;
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/StateStoreSerializer.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/StateStoreSerializer.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/StateStoreSerializer.java
new file mode 100644
index 0000000..8540405
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/StateStoreSerializer.java
@@ -0,0 +1,119 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hadoop.hdfs.server.federation.store.driver;
+
+import java.io.IOException;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.server.federation.store.records.BaseRecord;
+import org.apache.hadoop.util.ReflectionUtils;
+
+/**
+ * Serializer to store and retrieve data in the State Store.
+ */
+public abstract class StateStoreSerializer {
+
+  /** Singleton for the serializer instance. */
+  private static StateStoreSerializer defaultSerializer;
+
+  /**
+   * Get the default serializer based.
+   * @return Singleton serializer.
+   */
+  public static StateStoreSerializer getSerializer() {
+    return getSerializer(null);
+  }
+
+  /**
+   * Get a serializer based on the provided configuration.
+   * @param conf Configuration. Default if null.
+   * @return Singleton serializer.
+   */
+  public static StateStoreSerializer getSerializer(Configuration conf) {
+    if (conf == null) {
+      synchronized (StateStoreSerializer.class) {
+        if (defaultSerializer == null) {
+          conf = new Configuration();
+          defaultSerializer = newSerializer(conf);
+        }
+      }
+      return defaultSerializer;
+    } else {
+      return newSerializer(conf);
+    }
+  }
+
+  private static StateStoreSerializer newSerializer(final Configuration conf) {
+    Class<? extends StateStoreSerializer> serializerName = conf.getClass(
+        DFSConfigKeys.FEDERATION_STORE_SERIALIZER_CLASS,
+        DFSConfigKeys.FEDERATION_STORE_SERIALIZER_CLASS_DEFAULT,
+        StateStoreSerializer.class);
+    return ReflectionUtils.newInstance(serializerName, conf);
+  }
+
+  /**
+   * Create a new record.
+   * @param clazz Class of the new record.
+   * @return New record.
+   */
+  public static <T> T newRecord(Class<T> clazz) {
+    return getSerializer(null).newRecordInstance(clazz);
+  }
+
+  /**
+   * Create a new record.
+   * @param clazz Class of the new record.
+   * @return New record.
+   */
+  public abstract <T> T newRecordInstance(Class<T> clazz);
+
+  /**
+   * Serialize a record into a byte array.
+   * @param record Record to serialize.
+   * @return Byte array with the serialized record.
+   */
+  public abstract byte[] serialize(BaseRecord record);
+
+  /**
+   * Serialize a record into a string.
+   * @param record Record to serialize.
+   * @return String with the serialized record.
+   */
+  public abstract String serializeString(BaseRecord record);
+
+  /**
+   * Deserialize a bytes array into a record.
+   * @param byteArray Byte array to deserialize.
+   * @param clazz Class of the record.
+   * @return New record.
+   * @throws IOException If it cannot deserialize the record.
+   */
+  public abstract <T extends BaseRecord> T deserialize(
+      byte[] byteArray, Class<T> clazz) throws IOException;
+
+  /**
+   * Deserialize a string into a record.
+   * @param data String with the data to deserialize.
+   * @param clazz Class of the record.
+   * @return New record.
+   * @throws IOException If it cannot deserialize the record.
+   */
+  public abstract <T extends BaseRecord> T deserialize(
+      String data, Class<T> clazz) throws IOException;
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/impl/StateStoreSerializerPBImpl.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/impl/StateStoreSerializerPBImpl.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/impl/StateStoreSerializerPBImpl.java
new file mode 100644
index 0000000..45c5dd6
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/driver/impl/StateStoreSerializerPBImpl.java
@@ -0,0 +1,115 @@
+/**
+ * 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.federation.store.driver.impl;
+
+import java.io.IOException;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.codec.binary.StringUtils;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hdfs.server.federation.store.driver.StateStoreSerializer;
+import org.apache.hadoop.hdfs.server.federation.store.records.BaseRecord;
+import org.apache.hadoop.hdfs.server.federation.store.records.impl.pb.PBRecord;
+import org.apache.hadoop.util.ReflectionUtils;
+
+import com.google.protobuf.Message;
+
+/**
+ * Protobuf implementation of the State Store serializer.
+ */
+public final class StateStoreSerializerPBImpl extends StateStoreSerializer {
+
+  private static final String PB_IMPL_PACKAGE_SUFFIX = "impl.pb";
+  private static final String PB_IMPL_CLASS_SUFFIX = "PBImpl";
+
+  private Configuration localConf = new Configuration();
+
+
+  private StateStoreSerializerPBImpl() {
+  }
+
+  @Override
+  @SuppressWarnings("unchecked")
+  public <T> T newRecordInstance(Class<T> clazz) {
+    try {
+      String clazzPBImpl = getPBImplClassName(clazz);
+      Class<?> pbClazz = localConf.getClassByName(clazzPBImpl);
+      Object retObject = ReflectionUtils.newInstance(pbClazz, localConf);
+      return (T)retObject;
+    } catch (ClassNotFoundException e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  private String getPBImplClassName(Class<?> clazz) {
+    String srcPackagePart = getPackageName(clazz);
+    String srcClassName = getClassName(clazz);
+    String destPackagePart = srcPackagePart + "." + PB_IMPL_PACKAGE_SUFFIX;
+    String destClassPart = srcClassName + PB_IMPL_CLASS_SUFFIX;
+    return destPackagePart + "." + destClassPart;
+  }
+
+  private String getClassName(Class<?> clazz) {
+    String fqName = clazz.getName();
+    return (fqName.substring(fqName.lastIndexOf(".") + 1, fqName.length()));
+  }
+
+  private String getPackageName(Class<?> clazz) {
+    return clazz.getPackage().getName();
+  }
+
+  @Override
+  public byte[] serialize(BaseRecord record) {
+    byte[] byteArray64 = null;
+    if (record instanceof PBRecord) {
+      PBRecord recordPB = (PBRecord) record;
+      Message msg = recordPB.getProto();
+      byte[] byteArray = msg.toByteArray();
+      byteArray64 = Base64.encodeBase64(byteArray, false);
+    }
+    return byteArray64;
+  }
+
+  @Override
+  public String serializeString(BaseRecord record) {
+    byte[] byteArray64 = serialize(record);
+    String base64Encoded = StringUtils.newStringUtf8(byteArray64);
+    return base64Encoded;
+  }
+
+  @Override
+  public <T extends BaseRecord> T deserialize(
+      byte[] byteArray, Class<T> clazz) throws IOException {
+
+    T record = newRecord(clazz);
+    if (record instanceof PBRecord) {
+      PBRecord pbRecord = (PBRecord) record;
+      byte[] byteArray64 = Base64.encodeBase64(byteArray, false);
+      String base64Encoded = StringUtils.newStringUtf8(byteArray64);
+      pbRecord.readInstance(base64Encoded);
+    }
+    return record;
+  }
+
+  @Override
+  public <T extends BaseRecord> T deserialize(String data, Class<T> clazz)
+      throws IOException {
+    byte[] byteArray64 = Base64.decodeBase64(data);
+    return deserialize(byteArray64, clazz);
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/PBRecord.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/PBRecord.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/PBRecord.java
new file mode 100644
index 0000000..c369275
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/PBRecord.java
@@ -0,0 +1,47 @@
+/**
+ * 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.federation.store.records.impl.pb;
+
+import java.io.IOException;
+
+import com.google.protobuf.Message;
+
+/**
+ * A record implementation using Protobuf.
+ */
+public interface PBRecord {
+
+  /**
+   * Get the protocol for the record.
+   * @return The protocol for this record.
+   */
+  Message getProto();
+
+  /**
+   * Set the protocol for the record.
+   * @param proto Protocol for this record.
+   */
+  void setProto(Message proto);
+
+  /**
+   * Populate this record with serialized data.
+   * @param base64String Serialized data in base64.
+   * @throws IOException If it cannot read the data.
+   */
+  void readInstance(String base64String) throws IOException;
+}

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/package-info.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/package-info.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/package-info.java
new file mode 100644
index 0000000..b329732
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/federation/store/records/impl/pb/package-info.java
@@ -0,0 +1,29 @@
+/**
+ * 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.
+ */
+
+/**
+ * The protobuf implementations of state store data records defined in the
+ * org.apache.hadoop.hdfs.server.federation.store.records package. Each
+ * implementation wraps an associated protobuf proto definition.
+ */
+@InterfaceAudience.Private
+@InterfaceStability.Evolving
+package org.apache.hadoop.hdfs.server.federation.store.records.impl.pb;
+
+import org.apache.hadoop.classification.InterfaceAudience;
+import org.apache.hadoop.classification.InterfaceStability;
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0e4661f7/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 0df91f2..d56a3b2 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
@@ -4489,4 +4489,12 @@
     </description>
   </property>
 
+  <property>
+    <name>dfs.federation.router.store.serializer</name>
+    <value>org.apache.hadoop.hdfs.server.federation.store.driver.impl.StateStoreSerializerPBImpl</value>
+    <description>
+      Class to serialize State Store records.
+    </description>
+  </property>
+
 </configuration>


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[22/50] [abbrv] hadoop git commit: YARN-6109. Add an ability to convert ChildQueue to ParentQueue. (Xuan Gong via wangda)

Posted by in...@apache.org.
YARN-6109. Add an ability to convert ChildQueue to ParentQueue. (Xuan Gong via wangda)


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

Branch: refs/heads/HDFS-10467
Commit: f9544fac483678dc6df7f3116fb89b1e41b3c7ba
Parents: b8a0b18
Author: Wangda Tan <wa...@apache.org>
Authored: Tue Apr 4 14:38:45 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:21 2017 -0700

----------------------------------------------------------------------
 .../capacity/CapacitySchedulerQueueManager.java |  13 +++
 .../scheduler/capacity/ParentQueue.java         |  17 ++-
 .../capacity/TestCapacityScheduler.java         | 103 +++++++++++++++++++
 3 files changed, 132 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/f9544fac/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerQueueManager.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/CapacitySchedulerQueueManager.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/CapacitySchedulerQueueManager.java
index 76cb5d6..c92c343 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/CapacitySchedulerQueueManager.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/CapacitySchedulerQueueManager.java
@@ -264,6 +264,8 @@ public class CapacitySchedulerQueueManager implements SchedulerQueueManager<
   /**
    * Ensure all existing queues are present. Queues cannot be deleted if its not
    * in Stopped state, Queue's cannot be moved from one hierarchy to other also.
+   * Previous child queue could be converted into parent queue if it is in
+   * STOPPED state.
    *
    * @param queues existing queues
    * @param newQueues new queues
@@ -292,6 +294,17 @@ public class CapacitySchedulerQueueManager implements SchedulerQueueManager<
           throw new IOException(queueName + " is moved from:"
               + oldQueue.getQueuePath() + " to:" + newQueue.getQueuePath()
               + " after refresh, which is not allowed.");
+        } else  if (oldQueue instanceof LeafQueue
+            && newQueue instanceof ParentQueue) {
+          if (oldQueue.getState() == QueueState.STOPPED) {
+            LOG.info("Converting the leaf queue: " + oldQueue.getQueuePath()
+                + " to parent queue.");
+          } else {
+            throw new IOException("Can not convert the leaf queue: "
+                + oldQueue.getQueuePath() + " to parent queue since "
+                + "it is not yet in stopped state. Current State : "
+                + oldQueue.getState());
+          }
         }
       }
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/f9544fac/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/ParentQueue.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/ParentQueue.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/ParentQueue.java
index f84b7a4..1579472 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/ParentQueue.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/ParentQueue.java
@@ -315,7 +315,22 @@ public class ParentQueue extends AbstractCSQueue {
 
         // Check if the child-queue already exists
         if (childQueue != null) {
-          // Re-init existing child queues
+          // Check if the child-queue has been converted into parent queue.
+          // The CS has already checked to ensure that this child-queue is in
+          // STOPPED state.
+          if (childQueue instanceof LeafQueue
+              && newChildQueue instanceof ParentQueue) {
+            // We would convert this LeafQueue to ParentQueue, consider this
+            // as the combination of DELETE then ADD.
+            newChildQueue.setParent(this);
+            currentChildQueues.put(newChildQueueName, newChildQueue);
+            // inform CapacitySchedulerQueueManager
+            CapacitySchedulerQueueManager queueManager = this.csContext
+                .getCapacitySchedulerQueueManager();
+            queueManager.addQueue(newChildQueueName, newChildQueue);
+            continue;
+          }
+          // Re-init existing queues
           childQueue.reinitialize(newChildQueue, clusterResource);
           LOG.info(getQueueName() + ": re-configured queue: " + childQueue);
         } else{

http://git-wip-us.apache.org/repos/asf/hadoop/blob/f9544fac/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 ff0f7cf..e2f456c 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
@@ -474,6 +474,52 @@ public class TestCapacityScheduler {
 
   /**
    * @param conf, to be modified
+   * @return, CS configuration which has converted b1 to parent queue
+   *           root
+   *          /     \
+   *        a        b
+   *       / \    /  |  \
+   *      a1  a2 b1  b2  b3
+   *              |
+   *             b11
+   */
+  private CapacitySchedulerConfiguration
+      setupQueueConfigurationWithB1AsParentQueue(
+          CapacitySchedulerConfiguration conf) {
+
+    // Define top-level queues
+    conf.setQueues(CapacitySchedulerConfiguration.ROOT,
+        new String[] { "a", "b" });
+
+    conf.setCapacity(A, A_CAPACITY);
+    conf.setCapacity(B, B_CAPACITY);
+
+    // Define 2nd-level queues
+    conf.setQueues(A, new String[] { "a1", "a2" });
+    conf.setCapacity(A1, A1_CAPACITY);
+    conf.setUserLimitFactor(A1, 100.0f);
+    conf.setCapacity(A2, A2_CAPACITY);
+    conf.setUserLimitFactor(A2, 100.0f);
+
+    conf.setQueues(B, new String[] {"b1","b2", "b3"});
+    conf.setCapacity(B1, B1_CAPACITY);
+    conf.setUserLimitFactor(B1, 100.0f);
+    conf.setCapacity(B2, B2_CAPACITY);
+    conf.setUserLimitFactor(B2, 100.0f);
+    conf.setCapacity(B3, B3_CAPACITY);
+    conf.setUserLimitFactor(B3, 100.0f);
+
+    // Set childQueue for B1
+    conf.setQueues(B1, new String[] {"b11"});
+    String B11 = B1 + ".b11";
+    conf.setCapacity(B11, 100.0f);
+    conf.setUserLimitFactor(B11, 100.0f);
+
+    return conf;
+  }
+
+  /**
+   * @param conf, to be modified
    * @return, CS configuration which has deleted a
    *          Parent queue(b)
    */
@@ -4142,4 +4188,61 @@ public class TestCapacityScheduler {
 
     cs.stop();
   }
+
+  /**
+   * Test if we can convert a leaf queue to a parent queue
+   * @throws Exception
+   */
+  @Test (timeout = 10000)
+  public void testConvertLeafQueueToParentQueue() throws Exception {
+    CapacityScheduler cs = new CapacityScheduler();
+    CapacitySchedulerConfiguration conf = new CapacitySchedulerConfiguration();
+    RMContextImpl rmContext = new RMContextImpl(null, null, null, null, null,
+        null, new RMContainerTokenSecretManager(conf),
+        new NMTokenSecretManagerInRM(conf),
+        new ClientToAMTokenSecretManagerInRM(), null);
+    setupQueueConfiguration(conf);
+    cs.setConf(new YarnConfiguration());
+    cs.setRMContext(resourceManager.getRMContext());
+    cs.init(conf);
+    cs.start();
+    cs.reinitialize(conf, rmContext);
+    checkQueueCapacities(cs, A_CAPACITY, B_CAPACITY);
+
+    String targetQueue = "b1";
+    CSQueue b1 = cs.getQueue(targetQueue);
+    Assert.assertEquals(b1.getState(), QueueState.RUNNING);
+
+    // test if we can convert a leaf queue which is in RUNNING state
+    conf = new CapacitySchedulerConfiguration();
+    setupQueueConfigurationWithB1AsParentQueue(conf);
+    try {
+      cs.reinitialize(conf, mockContext);
+      fail("Expected to throw exception when refresh queue tries to convert"
+          + " a child queue to a parent queue.");
+    } catch (IOException e) {
+      // ignore
+    }
+
+    // now set queue state for b1 to STOPPED
+    conf = new CapacitySchedulerConfiguration();
+    setupQueueConfiguration(conf);
+    conf.set("yarn.scheduler.capacity.root.b.b1.state", "STOPPED");
+    cs.reinitialize(conf, mockContext);
+    Assert.assertEquals(b1.getState(), QueueState.STOPPED);
+
+    // test if we can convert a leaf queue which is in STOPPED state
+    conf = new CapacitySchedulerConfiguration();
+    setupQueueConfigurationWithB1AsParentQueue(conf);
+    try {
+      cs.reinitialize(conf, mockContext);
+    } catch (IOException e) {
+      fail("Expected to NOT throw exception when refresh queue tries"
+          + " to convert a leaf queue WITHOUT running apps");
+    }
+    b1 = cs.getQueue(targetQueue);
+    Assert.assertTrue(b1 instanceof ParentQueue);
+    Assert.assertEquals(b1.getState(), QueueState.RUNNING);
+    Assert.assertTrue(!b1.getChildQueues().isEmpty());
+  }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[46/50] [abbrv] hadoop git commit: YARN-6448. Continuous scheduling thread crashes while sorting nodes. (Yufei Gu via kasha)

Posted by in...@apache.org.
YARN-6448. Continuous scheduling thread crashes while sorting nodes. (Yufei Gu via kasha)


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

Branch: refs/heads/HDFS-10467
Commit: e054888da14060bf1fdf5be1808f154dd523dc66
Parents: 6b8607d
Author: Karthik Kambatla <ka...@apache.org>
Authored: Wed Apr 5 15:42:55 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../scheduler/SchedulerNode.java                |  4 ++-
 .../scheduler/fair/FairScheduler.java           |  8 +++--
 .../fair/TestContinuousScheduling.java          | 36 ++++++++++++++++++++
 3 files changed, 45 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/e054888d/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerNode.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/SchedulerNode.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerNode.java
index db17b42..af4a001 100644
--- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerNode.java
+++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/SchedulerNode.java
@@ -25,6 +25,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import com.google.common.annotations.VisibleForTesting;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.classification.InterfaceAudience.Private;
@@ -286,7 +287,8 @@ public abstract class SchedulerNode {
    * container.
    * @param resource Resources to deduct.
    */
-  private synchronized void deductUnallocatedResource(Resource resource) {
+  @VisibleForTesting
+  public synchronized void deductUnallocatedResource(Resource resource) {
     if (resource == null) {
       LOG.error("Invalid deduction of null resource for "
           + rmNode.getNodeAddress());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e054888d/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 f3fde76..98c14ac 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
@@ -913,8 +913,12 @@ public class FairScheduler extends
 
   void continuousSchedulingAttempt() throws InterruptedException {
     long start = getClock().getTime();
-    List<FSSchedulerNode> nodeIdList =
-        nodeTracker.sortedNodeList(nodeAvailableResourceComparator);
+    List<FSSchedulerNode> nodeIdList;
+    // Hold a lock to prevent comparator order changes due to changes of node
+    // unallocated resources
+    synchronized (this) {
+      nodeIdList = nodeTracker.sortedNodeList(nodeAvailableResourceComparator);
+    }
 
     // iterate all nodes
     for (FSSchedulerNode node : nodeIdList) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/e054888d/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestContinuousScheduling.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/TestContinuousScheduling.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/TestContinuousScheduling.java
index 1ea0032..9efa83d 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/TestContinuousScheduling.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/TestContinuousScheduling.java
@@ -23,6 +23,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
 import org.apache.hadoop.yarn.api.records.ContainerId;
 import org.apache.hadoop.yarn.api.records.NodeId;
 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.event.AsyncDispatcher;
 import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
@@ -30,6 +31,7 @@ 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.ClusterNodeTracker;
 import org.apache.hadoop.yarn.server.scheduler.SchedulerRequestKey;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.TestUtils;
 import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
@@ -57,6 +59,7 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ThreadLocalRandom;
 
 public class TestContinuousScheduling extends FairSchedulerTestBase {
   private ControlledClock mockClock;
@@ -303,6 +306,39 @@ public class TestContinuousScheduling extends FairSchedulerTestBase {
   }
 
   @Test
+  public void TestNodeAvailableResourceComparatorTransitivity() {
+    ClusterNodeTracker<FSSchedulerNode> clusterNodeTracker =
+        scheduler.getNodeTracker();
+
+    List<RMNode> rmNodes =
+        MockNodes.newNodes(2, 4000, Resource.newInstance(4096, 4));
+    for (RMNode rmNode : rmNodes) {
+      clusterNodeTracker.addNode(new FSSchedulerNode(rmNode, false));
+    }
+
+    // To simulate unallocated resource changes
+    new Thread() {
+      @Override
+      public void run() {
+        for (int j = 0; j < 100; j++) {
+          for (FSSchedulerNode node : clusterNodeTracker.getAllNodes()) {
+            int i = ThreadLocalRandom.current().nextInt(-30, 30);
+            synchronized (scheduler) {
+              node.deductUnallocatedResource(Resource.newInstance(i * 1024, i));
+            }
+          }
+        }
+      }
+    }.start();
+
+    try {
+      scheduler.continuousSchedulingAttempt();
+    } catch (Exception e) {
+      fail(e.getMessage());
+    }
+  }
+
+  @Test
   public void testFairSchedulerContinuousSchedulingInitTime() throws Exception {
     scheduler.start();
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[43/50] [abbrv] hadoop git commit: MAPREDUCE-6846. Fragments specified for libjar paths are not handled correctly (Contributed by Chris Trezzo via Daniel Templeton)

Posted by in...@apache.org.
MAPREDUCE-6846. Fragments specified for libjar paths are not handled correctly
(Contributed by Chris Trezzo via Daniel Templeton)


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

Branch: refs/heads/HDFS-10467
Commit: 4db939daf5e052e6a9ff604a8e7150b89176faad
Parents: 8bbd335
Author: Daniel Templeton <te...@apache.org>
Authored: Wed Apr 5 17:24:09 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:23 2017 -0700

----------------------------------------------------------------------
 .../hadoop/mapreduce/JobResourceUploader.java   | 103 +++-
 .../mapreduce/TestJobResourceUploader.java      | 481 ++++++++++++++++---
 2 files changed, 492 insertions(+), 92 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/4db939da/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobResourceUploader.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobResourceUploader.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobResourceUploader.java
index 085c966..f1cad57 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobResourceUploader.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/JobResourceUploader.java
@@ -23,6 +23,7 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.LinkedList;
 import java.util.Map;
 
 import org.apache.commons.logging.Log;
@@ -91,7 +92,7 @@ class JobResourceUploader {
     submitJobDir = new Path(submitJobDir.toUri().getPath());
     FsPermission mapredSysPerms =
         new FsPermission(JobSubmissionFiles.JOB_DIR_PERMISSION);
-    FileSystem.mkdirs(jtFs, submitJobDir, mapredSysPerms);
+    mkdirs(jtFs, submitJobDir, mapredSysPerms);
 
     Collection<String> files = conf.getStringCollection("tmpfiles");
     Collection<String> libjars = conf.getStringCollection("tmpjars");
@@ -116,18 +117,20 @@ class JobResourceUploader {
         job.getCredentials());
   }
 
-  private void uploadFiles(Configuration conf, Collection<String> files,
+  @VisibleForTesting
+  void uploadFiles(Configuration conf, Collection<String> files,
       Path submitJobDir, FsPermission mapredSysPerms, short submitReplication)
       throws IOException {
     Path filesDir = JobSubmissionFiles.getJobDistCacheFiles(submitJobDir);
     if (!files.isEmpty()) {
-      FileSystem.mkdirs(jtFs, filesDir, mapredSysPerms);
+      mkdirs(jtFs, filesDir, mapredSysPerms);
       for (String tmpFile : files) {
         URI tmpURI = null;
         try {
           tmpURI = new URI(tmpFile);
         } catch (URISyntaxException e) {
-          throw new IllegalArgumentException(e);
+          throw new IllegalArgumentException("Error parsing files argument."
+              + " Argument must be a valid URI: " + tmpFile, e);
         }
         Path tmp = new Path(tmpURI);
         Path newPath = copyRemoteFiles(filesDir, tmp, conf, submitReplication);
@@ -136,50 +139,83 @@ class JobResourceUploader {
           DistributedCache.addCacheFile(pathURI, conf);
         } catch (URISyntaxException ue) {
           // should not throw a uri exception
-          throw new IOException("Failed to create uri for " + tmpFile, ue);
+          throw new IOException(
+              "Failed to create a URI (URISyntaxException) for the remote path "
+                  + newPath + ". This was based on the files parameter: "
+                  + tmpFile,
+              ue);
         }
       }
     }
   }
 
-  private void uploadLibJars(Configuration conf, Collection<String> libjars,
+  // Suppress warning for use of DistributedCache (it is everywhere).
+  @SuppressWarnings("deprecation")
+  @VisibleForTesting
+  void uploadLibJars(Configuration conf, Collection<String> libjars,
       Path submitJobDir, FsPermission mapredSysPerms, short submitReplication)
       throws IOException {
     Path libjarsDir = JobSubmissionFiles.getJobDistCacheLibjars(submitJobDir);
     if (!libjars.isEmpty()) {
-      FileSystem.mkdirs(jtFs, libjarsDir, mapredSysPerms);
+      mkdirs(jtFs, libjarsDir, mapredSysPerms);
+      Collection<URI> libjarURIs = new LinkedList<>();
+      boolean foundFragment = false;
       for (String tmpjars : libjars) {
-        Path tmp = new Path(tmpjars);
+        URI tmpURI = null;
+        try {
+          tmpURI = new URI(tmpjars);
+        } catch (URISyntaxException e) {
+          throw new IllegalArgumentException("Error parsing libjars argument."
+              + " Argument must be a valid URI: " + tmpjars, e);
+        }
+        Path tmp = new Path(tmpURI);
         Path newPath =
             copyRemoteFiles(libjarsDir, tmp, conf, submitReplication);
-
-        // Add each file to the classpath
-        DistributedCache.addFileToClassPath(
-            new Path(newPath.toUri().getPath()), conf, jtFs, !useWildcard);
+        try {
+          URI pathURI = getPathURI(newPath, tmpURI.getFragment());
+          if (!foundFragment) {
+            foundFragment = pathURI.getFragment() != null;
+          }
+          DistributedCache.addFileToClassPath(new Path(pathURI.getPath()), conf,
+              jtFs, false);
+          libjarURIs.add(pathURI);
+        } catch (URISyntaxException ue) {
+          // should not throw a uri exception
+          throw new IOException(
+              "Failed to create a URI (URISyntaxException) for the remote path "
+                  + newPath + ". This was based on the libjar parameter: "
+                  + tmpjars,
+              ue);
+        }
       }
 
-      if (useWildcard) {
-        // Add the whole directory to the cache
+      if (useWildcard && !foundFragment) {
+        // Add the whole directory to the cache using a wild card
         Path libJarsDirWildcard =
             jtFs.makeQualified(new Path(libjarsDir, DistributedCache.WILDCARD));
-
         DistributedCache.addCacheFile(libJarsDirWildcard.toUri(), conf);
+      } else {
+        for (URI uri : libjarURIs) {
+          DistributedCache.addCacheFile(uri, conf);
+        }
       }
     }
   }
 
-  private void uploadArchives(Configuration conf, Collection<String> archives,
+  @VisibleForTesting
+  void uploadArchives(Configuration conf, Collection<String> archives,
       Path submitJobDir, FsPermission mapredSysPerms, short submitReplication)
       throws IOException {
     Path archivesDir = JobSubmissionFiles.getJobDistCacheArchives(submitJobDir);
     if (!archives.isEmpty()) {
-      FileSystem.mkdirs(jtFs, archivesDir, mapredSysPerms);
+      mkdirs(jtFs, archivesDir, mapredSysPerms);
       for (String tmpArchives : archives) {
         URI tmpURI;
         try {
           tmpURI = new URI(tmpArchives);
         } catch (URISyntaxException e) {
-          throw new IllegalArgumentException(e);
+          throw new IllegalArgumentException("Error parsing archives argument."
+              + " Argument must be a valid URI: " + tmpArchives, e);
         }
         Path tmp = new Path(tmpURI);
         Path newPath =
@@ -189,13 +225,18 @@ class JobResourceUploader {
           DistributedCache.addCacheArchive(pathURI, conf);
         } catch (URISyntaxException ue) {
           // should not throw an uri excpetion
-          throw new IOException("Failed to create uri for " + tmpArchives, ue);
+          throw new IOException(
+              "Failed to create a URI (URISyntaxException) for the remote path"
+                  + newPath + ". This was based on the archive parameter: "
+                  + tmpArchives,
+              ue);
         }
       }
     }
   }
 
-  private void uploadJobJar(Job job, String jobJar, Path submitJobDir,
+  @VisibleForTesting
+  void uploadJobJar(Job job, String jobJar, Path submitJobDir,
       short submitReplication) throws IOException {
     if (jobJar != null) { // copy jar to JobTracker's fs
       // use jar name if job is not named.
@@ -273,7 +314,8 @@ class JobResourceUploader {
       URI uri = new URI(s);
       return new Path(uri.getScheme(), uri.getAuthority(), uri.getPath());
     } catch (URISyntaxException e) {
-      throw new IllegalArgumentException(e);
+      throw new IllegalArgumentException(
+          "Error parsing argument." + " Argument must be a valid URI: " + s, e);
     }
   }
 
@@ -380,9 +422,20 @@ class JobResourceUploader {
     return status;
   }
 
+  /**
+   * Create a new directory in the passed filesystem. This wrapper method exists
+   * so that it can be overridden/stubbed during testing.
+   */
+  @VisibleForTesting
+  boolean mkdirs(FileSystem fs, Path dir, FsPermission permission)
+      throws IOException {
+    return FileSystem.mkdirs(fs, dir, permission);
+  }
+
   // copies a file to the jobtracker filesystem and returns the path where it
   // was copied to
-  private Path copyRemoteFiles(Path parentDir, Path originalPath,
+  @VisibleForTesting
+  Path copyRemoteFiles(Path parentDir, Path originalPath,
       Configuration conf, short replication) throws IOException {
     // check if we do not need to copy the files
     // is jt using the same file system.
@@ -400,10 +453,12 @@ class JobResourceUploader {
     Path newPath = new Path(parentDir, originalPath.getName());
     FileUtil.copy(remoteFs, originalPath, jtFs, newPath, false, conf);
     jtFs.setReplication(newPath, replication);
+    jtFs.makeQualified(newPath);
     return newPath;
   }
 
-  private void copyJar(Path originalJarPath, Path submitJarFile,
+  @VisibleForTesting
+  void copyJar(Path originalJarPath, Path submitJarFile,
       short replication) throws IOException {
     jtFs.copyFromLocalFile(originalJarPath, submitJarFile);
     jtFs.setReplication(submitJarFile, replication);
@@ -427,7 +482,7 @@ class JobResourceUploader {
     URI pathURI = destPath.toUri();
     if (pathURI.getFragment() == null) {
       if (fragment == null) {
-        pathURI = new URI(pathURI.toString() + "#" + destPath.getName());
+        // no fragment, just return existing pathURI from destPath
       } else {
         pathURI = new URI(pathURI.toString() + "#" + fragment);
       }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/4db939da/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestJobResourceUploader.java
----------------------------------------------------------------------
diff --git a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestJobResourceUploader.java b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestJobResourceUploader.java
index 8ba50a6..20b7b7d 100644
--- a/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestJobResourceUploader.java
+++ b/hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestJobResourceUploader.java
@@ -23,13 +23,19 @@ import static org.mockito.Mockito.when;
 
 import java.io.IOException;
 import java.net.URI;
+import java.util.Arrays;
+import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.permission.FsPermission;
 import org.apache.hadoop.mapred.JobConf;
 import org.junit.Assert;
 import org.junit.Test;
@@ -69,13 +75,13 @@ public class TestJobResourceUploader {
 
   @Test
   public void testAllDefaults() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     runLimitsTest(b.build(), true, null);
   }
 
   @Test
   public void testNoLimitsWithResources() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(1);
     b.setNumOfTmpArchives(10);
@@ -88,7 +94,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testAtResourceLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(1);
     b.setNumOfTmpArchives(1);
@@ -101,7 +107,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testOverResourceLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(1);
     b.setNumOfTmpArchives(1);
@@ -114,7 +120,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testAtResourcesMBLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(1);
     b.setNumOfTmpArchives(1);
@@ -128,7 +134,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testOverResourcesMBLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(2);
     b.setNumOfTmpArchives(1);
@@ -142,7 +148,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testAtSingleResourceMBLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(2);
     b.setNumOfTmpArchives(1);
@@ -156,7 +162,7 @@ public class TestJobResourceUploader {
 
   @Test
   public void testOverSingleResourceMBLimit() throws IOException {
-    ResourceLimitsConf.Builder b = new ResourceLimitsConf.Builder();
+    ResourceConf.Builder b = new ResourceConf.Builder();
     b.setNumOfDCArchives(1);
     b.setNumOfDCFiles(2);
     b.setNumOfTmpArchives(1);
@@ -168,20 +174,263 @@ public class TestJobResourceUploader {
     runLimitsTest(b.build(), false, ResourceViolation.SINGLE_RESOURCE_SIZE);
   }
 
+  private String destinationPathPrefix = "hdfs:///destinationPath/";
+  private String[] expectedFilesNoFrags =
+      { destinationPathPrefix + "tmpFiles0.txt",
+          destinationPathPrefix + "tmpFiles1.txt",
+          destinationPathPrefix + "tmpFiles2.txt",
+          destinationPathPrefix + "tmpFiles3.txt",
+          destinationPathPrefix + "tmpFiles4.txt",
+          destinationPathPrefix + "tmpjars0.jar",
+          destinationPathPrefix + "tmpjars1.jar" };
+
+  private String[] expectedFilesWithFrags =
+      { destinationPathPrefix + "tmpFiles0.txt#tmpFilesfragment0.txt",
+          destinationPathPrefix + "tmpFiles1.txt#tmpFilesfragment1.txt",
+          destinationPathPrefix + "tmpFiles2.txt#tmpFilesfragment2.txt",
+          destinationPathPrefix + "tmpFiles3.txt#tmpFilesfragment3.txt",
+          destinationPathPrefix + "tmpFiles4.txt#tmpFilesfragment4.txt",
+          destinationPathPrefix + "tmpjars0.jar#tmpjarsfragment0.jar",
+          destinationPathPrefix + "tmpjars1.jar#tmpjarsfragment1.jar" };
+
+  // We use the local fs for the submitFS in the StubedUploader, so libjars
+  // should be replaced with a single path.
+  private String[] expectedFilesWithWildcard =
+      { destinationPathPrefix + "tmpFiles0.txt",
+          destinationPathPrefix + "tmpFiles1.txt",
+          destinationPathPrefix + "tmpFiles2.txt",
+          destinationPathPrefix + "tmpFiles3.txt",
+          destinationPathPrefix + "tmpFiles4.txt",
+          "file:///libjars-submit-dir/libjars/*" };
+
+  private String[] expectedArchivesNoFrags =
+      { destinationPathPrefix + "tmpArchives0.tgz",
+          destinationPathPrefix + "tmpArchives1.tgz" };
+
+  private String[] expectedArchivesWithFrags =
+      { destinationPathPrefix + "tmpArchives0.tgz#tmpArchivesfragment0.tgz",
+          destinationPathPrefix + "tmpArchives1.tgz#tmpArchivesfragment1.tgz" };
+
+  private String jobjarSubmitDir = "/jobjar-submit-dir";
+  private String expectedJobJar = jobjarSubmitDir + "/job.jar";
+
+  @Test
+  public void testPathsWithNoFragNoSchemeRelative() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithScheme(false);
+    b.setPathsWithFrags(false);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesNoFrags,
+        expectedArchivesNoFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithNoFragNoSchemeAbsolute() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(false);
+    b.setPathsWithScheme(false);
+    b.setAbsolutePaths(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesNoFrags,
+        expectedArchivesNoFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithFragNoSchemeAbsolute() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(true);
+    b.setPathsWithScheme(false);
+    b.setAbsolutePaths(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesWithFrags,
+        expectedArchivesWithFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithFragNoSchemeRelative() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(true);
+    b.setAbsolutePaths(false);
+    b.setPathsWithScheme(false);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesWithFrags,
+        expectedArchivesWithFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithFragSchemeAbsolute() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(true);
+    b.setAbsolutePaths(true);
+    b.setPathsWithScheme(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesWithFrags,
+        expectedArchivesWithFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithNoFragWithSchemeAbsolute() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(false);
+    b.setPathsWithScheme(true);
+    b.setAbsolutePaths(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesNoFrags,
+        expectedArchivesNoFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithNoFragAndWildCard() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(4);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(false);
+    b.setPathsWithScheme(true);
+    b.setAbsolutePaths(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf, true);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesWithWildcard,
+        expectedArchivesNoFrags, expectedJobJar);
+  }
+
+  @Test
+  public void testPathsWithFragsAndWildCard() throws IOException {
+    ResourceConf.Builder b = new ResourceConf.Builder();
+    b.setNumOfTmpFiles(5);
+    b.setNumOfTmpLibJars(2);
+    b.setNumOfTmpArchives(2);
+    b.setJobJar(true);
+    b.setPathsWithFrags(true);
+    b.setPathsWithScheme(true);
+    b.setAbsolutePaths(true);
+    ResourceConf rConf = b.build();
+    JobConf jConf = new JobConf();
+    JobResourceUploader uploader = new StubedUploader(jConf, true);
+
+    runTmpResourcePathTest(uploader, rConf, jConf, expectedFilesWithFrags,
+        expectedArchivesWithFrags, expectedJobJar);
+  }
+
+  private void runTmpResourcePathTest(JobResourceUploader uploader,
+      ResourceConf rConf, JobConf jConf, String[] expectedFiles,
+      String[] expectedArchives, String expectedJobJar) throws IOException {
+    rConf.setupJobConf(jConf);
+    // We use a pre and post job object here because we need the post job object
+    // to get the new values set during uploadResources, but we need the pre job
+    // to set the job jar because JobResourceUploader#uploadJobJar uses the Job
+    // interface not the JobConf. The post job is automatically created in
+    // validateResourcePaths.
+    Job jobPre = Job.getInstance(jConf);
+    uploadResources(uploader, jConf, jobPre);
+
+    validateResourcePaths(jConf, expectedFiles, expectedArchives,
+        expectedJobJar, jobPre);
+  }
+
+  private void uploadResources(JobResourceUploader uploader, JobConf jConf,
+      Job job) throws IOException {
+    Collection<String> files = jConf.getStringCollection("tmpfiles");
+    Collection<String> libjars = jConf.getStringCollection("tmpjars");
+    Collection<String> archives = jConf.getStringCollection("tmparchives");
+    String jobJar = jConf.getJar();
+    uploader.uploadFiles(jConf, files, new Path("/files-submit-dir"), null,
+        (short) 3);
+    uploader.uploadArchives(jConf, archives, new Path("/archives-submit-dir"),
+        null, (short) 3);
+    uploader.uploadLibJars(jConf, libjars, new Path("/libjars-submit-dir"),
+        null, (short) 3);
+    uploader.uploadJobJar(job, jobJar, new Path(jobjarSubmitDir), (short) 3);
+  }
+
+  private void validateResourcePaths(JobConf jConf, String[] expectedFiles,
+      String[] expectedArchives, String expectedJobJar, Job preJob)
+      throws IOException {
+    Job j = Job.getInstance(jConf);
+    validateResourcePathsSub(j.getCacheFiles(), expectedFiles);
+    validateResourcePathsSub(j.getCacheArchives(), expectedArchives);
+    // We use a different job object here because the jobjar was set on a
+    // different job object
+    Assert.assertEquals("Job jar path is different than expected!",
+        expectedJobJar, preJob.getJar());
+  }
+
+  private void validateResourcePathsSub(URI[] actualURIs,
+      String[] expectedURIs) {
+    List<URI> actualList = Arrays.asList(actualURIs);
+    Set<String> expectedSet = new HashSet<>(Arrays.asList(expectedURIs));
+    if (actualList.size() != expectedSet.size()) {
+      Assert.fail("Expected list of resources (" + expectedSet.size()
+          + ") and actual list of resources (" + actualList.size()
+          + ") are different lengths!");
+    }
+
+    for (URI u : actualList) {
+      if (!expectedSet.contains(u.toString())) {
+        Assert.fail("Resource list contained unexpected path: " + u.toString());
+      }
+    }
+  }
+
   private enum ResourceViolation {
     NUMBER_OF_RESOURCES, TOTAL_RESOURCE_SIZE, SINGLE_RESOURCE_SIZE;
   }
 
-  private void runLimitsTest(ResourceLimitsConf rlConf,
-      boolean checkShouldSucceed, ResourceViolation violation)
-      throws IOException {
+  private void runLimitsTest(ResourceConf rlConf, boolean checkShouldSucceed,
+      ResourceViolation violation) throws IOException {
 
     if (!checkShouldSucceed && violation == null) {
       Assert.fail("Test is misconfigured. checkShouldSucceed is set to false"
           + " and a ResourceViolation is not specified.");
     }
 
-    JobConf conf = setupJobConf(rlConf);
+    JobConf conf = new JobConf();
+    rlConf.setupJobConf(conf);
     JobResourceUploader uploader = new StubedUploader(conf);
     long configuredSizeOfResourceBytes = rlConf.sizeOfResource * 1024 * 1024;
     when(mockedStatus.getLen()).thenReturn(configuredSizeOfResourceBytes);
@@ -230,43 +479,7 @@ public class TestJobResourceUploader {
 
   private final FileStatus mockedStatus = mock(FileStatus.class);
 
-  private JobConf setupJobConf(ResourceLimitsConf rlConf) {
-    JobConf conf = new JobConf();
-    conf.setInt(MRJobConfig.MAX_RESOURCES, rlConf.maxResources);
-    conf.setLong(MRJobConfig.MAX_RESOURCES_MB, rlConf.maxResourcesMB);
-    conf.setLong(MRJobConfig.MAX_SINGLE_RESOURCE_MB,
-        rlConf.maxSingleResourceMB);
-
-    conf.set("tmpfiles",
-        buildPathString("file:///tmpFiles", rlConf.numOfTmpFiles));
-    conf.set("tmpjars",
-        buildPathString("file:///tmpjars", rlConf.numOfTmpLibJars));
-    conf.set("tmparchives",
-        buildPathString("file:///tmpArchives", rlConf.numOfTmpArchives));
-    conf.set(MRJobConfig.CACHE_ARCHIVES,
-        buildPathString("file:///cacheArchives", rlConf.numOfDCArchives));
-    conf.set(MRJobConfig.CACHE_FILES,
-        buildPathString("file:///cacheFiles", rlConf.numOfDCFiles));
-    if (rlConf.jobJar) {
-      conf.setJar("file:///jobjar.jar");
-    }
-    return conf;
-  }
-
-  private String buildPathString(String pathPrefix, int numOfPaths) {
-    if (numOfPaths < 1) {
-      return "";
-    } else {
-      StringBuilder b = new StringBuilder();
-      b.append(pathPrefix + 0);
-      for (int i = 1; i < numOfPaths; i++) {
-        b.append("," + pathPrefix + i);
-      }
-      return b.toString();
-    }
-  }
-
-  final static class ResourceLimitsConf {
+  private static class ResourceConf {
     private final int maxResources;
     private final long maxResourcesMB;
     private final long maxSingleResourceMB;
@@ -277,14 +490,15 @@ public class TestJobResourceUploader {
     private final int numOfDCFiles;
     private final int numOfDCArchives;
     private final long sizeOfResource;
+    private final boolean pathsWithFrags;
+    private final boolean pathsWithScheme;
+    private final boolean absolutePaths;
 
-    static final ResourceLimitsConf DEFAULT = new ResourceLimitsConf();
-
-    private ResourceLimitsConf() {
+    private ResourceConf() {
       this(new Builder());
     }
 
-    private ResourceLimitsConf(Builder builder) {
+    private ResourceConf(Builder builder) {
       this.maxResources = builder.maxResources;
       this.maxResourcesMB = builder.maxResourcesMB;
       this.maxSingleResourceMB = builder.maxSingleResourceMB;
@@ -295,6 +509,9 @@ public class TestJobResourceUploader {
       this.numOfDCFiles = builder.numOfDCFiles;
       this.numOfDCArchives = builder.numOfDCArchives;
       this.sizeOfResource = builder.sizeOfResource;
+      this.pathsWithFrags = builder.pathsWithFrags;
+      this.pathsWithScheme = builder.pathsWithScheme;
+      this.absolutePaths = builder.absolutePaths;
     }
 
     static class Builder {
@@ -309,69 +526,176 @@ public class TestJobResourceUploader {
       private int numOfDCFiles = 0;
       private int numOfDCArchives = 0;
       private long sizeOfResource = 0;
+      private boolean pathsWithFrags = false;
+      private boolean pathsWithScheme = false;
+      private boolean absolutePaths = true;
 
-      Builder() {
+      private Builder() {
       }
 
-      Builder setMaxResources(int max) {
+      private Builder setMaxResources(int max) {
         this.maxResources = max;
         return this;
       }
 
-      Builder setMaxResourcesMB(long max) {
+      private Builder setMaxResourcesMB(long max) {
         this.maxResourcesMB = max;
         return this;
       }
 
-      Builder setMaxSingleResourceMB(long max) {
+      private Builder setMaxSingleResourceMB(long max) {
         this.maxSingleResourceMB = max;
         return this;
       }
 
-      Builder setNumOfTmpFiles(int num) {
+      private Builder setNumOfTmpFiles(int num) {
         this.numOfTmpFiles = num;
         return this;
       }
 
-      Builder setNumOfTmpArchives(int num) {
+      private Builder setNumOfTmpArchives(int num) {
         this.numOfTmpArchives = num;
         return this;
       }
 
-      Builder setNumOfTmpLibJars(int num) {
+      private Builder setNumOfTmpLibJars(int num) {
         this.numOfTmpLibJars = num;
         return this;
       }
 
-      Builder setJobJar(boolean jar) {
+      private Builder setJobJar(boolean jar) {
         this.jobJar = jar;
         return this;
       }
 
-      Builder setNumOfDCFiles(int num) {
+      private Builder setNumOfDCFiles(int num) {
         this.numOfDCFiles = num;
         return this;
       }
 
-      Builder setNumOfDCArchives(int num) {
+      private Builder setNumOfDCArchives(int num) {
         this.numOfDCArchives = num;
         return this;
       }
 
-      Builder setSizeOfResource(long sizeMB) {
+      private Builder setSizeOfResource(long sizeMB) {
         this.sizeOfResource = sizeMB;
         return this;
       }
 
-      ResourceLimitsConf build() {
-        return new ResourceLimitsConf(this);
+      private Builder setPathsWithFrags(boolean fragments) {
+        this.pathsWithFrags = fragments;
+        return this;
+      }
+
+      private Builder setPathsWithScheme(boolean scheme) {
+        this.pathsWithScheme = scheme;
+        return this;
+      }
+
+      private Builder setAbsolutePaths(boolean absolute) {
+        this.absolutePaths = absolute;
+        return this;
+      }
+
+      ResourceConf build() {
+        return new ResourceConf(this);
+      }
+    }
+
+    private void setupJobConf(JobConf conf) {
+      conf.set("tmpfiles",
+          buildPathString("tmpFiles", this.numOfTmpFiles, ".txt"));
+      conf.set("tmpjars",
+          buildPathString("tmpjars", this.numOfTmpLibJars, ".jar"));
+      conf.set("tmparchives",
+          buildPathString("tmpArchives", this.numOfTmpArchives, ".tgz"));
+      conf.set(MRJobConfig.CACHE_ARCHIVES, buildDistributedCachePathString(
+          "cacheArchives", this.numOfDCArchives, ".tgz"));
+      conf.set(MRJobConfig.CACHE_FILES, buildDistributedCachePathString(
+          "cacheFiles", this.numOfDCFiles, ".txt"));
+      if (this.jobJar) {
+        String fragment = "";
+        if (pathsWithFrags) {
+          fragment = "#jobjarfrag.jar";
+        }
+        if (pathsWithScheme) {
+          conf.setJar("file:///jobjar.jar" + fragment);
+        } else {
+          if (absolutePaths) {
+            conf.setJar("/jobjar.jar" + fragment);
+          } else {
+            conf.setJar("jobjar.jar" + fragment);
+          }
+        }
+      }
+      conf.setInt(MRJobConfig.MAX_RESOURCES, this.maxResources);
+      conf.setLong(MRJobConfig.MAX_RESOURCES_MB, this.maxResourcesMB);
+      conf.setLong(MRJobConfig.MAX_SINGLE_RESOURCE_MB,
+          this.maxSingleResourceMB);
+    }
+
+    // We always want absolute paths with a scheme in the DistributedCache, so
+    // we use a separate method to construct the path string.
+    private String buildDistributedCachePathString(String pathPrefix,
+        int numOfPaths, String extension) {
+      if (numOfPaths < 1) {
+        return "";
+      } else {
+        StringBuilder b = new StringBuilder();
+        b.append(buildPathStringSub(pathPrefix, "file:///" + pathPrefix,
+            extension, 0));
+        for (int i = 1; i < numOfPaths; i++) {
+          b.append("," + buildPathStringSub(pathPrefix, "file:///" + pathPrefix,
+              extension, i));
+        }
+        return b.toString();
+      }
+    }
+
+    private String buildPathString(String pathPrefix, int numOfPaths,
+        String extension) {
+      if (numOfPaths < 1) {
+        return "";
+      } else {
+        StringBuilder b = new StringBuilder();
+        String processedPath;
+        if (pathsWithScheme) {
+          processedPath = "file:///" + pathPrefix;
+        } else {
+          if (absolutePaths) {
+            processedPath = "/" + pathPrefix;
+          } else {
+            processedPath = pathPrefix;
+          }
+        }
+        b.append(buildPathStringSub(pathPrefix, processedPath, extension, 0));
+        for (int i = 1; i < numOfPaths; i++) {
+          b.append(","
+              + buildPathStringSub(pathPrefix, processedPath, extension, i));
+        }
+        return b.toString();
+      }
+    }
+
+    private String buildPathStringSub(String pathPrefix, String processedPath,
+        String extension, int num) {
+      if (pathsWithFrags) {
+        return processedPath + num + extension + "#" + pathPrefix + "fragment"
+            + num + extension;
+      } else {
+        return processedPath + num + extension;
       }
     }
   }
 
-  class StubedUploader extends JobResourceUploader {
+  private class StubedUploader extends JobResourceUploader {
     StubedUploader(JobConf conf) throws IOException {
-      super(FileSystem.getLocal(conf), false);
+      this(conf, false);
+    }
+
+    StubedUploader(JobConf conf, boolean useWildcard) throws IOException {
+      super(FileSystem.getLocal(conf), useWildcard);
     }
 
     @Override
@@ -379,5 +703,26 @@ public class TestJobResourceUploader {
         Path p) throws IOException {
       return mockedStatus;
     }
+
+    @Override
+    boolean mkdirs(FileSystem fs, Path dir, FsPermission permission)
+        throws IOException {
+      // Do nothing. Stubbed out to avoid side effects. We don't actually need
+      // to create submit dirs.
+      return true;
+    }
+
+    @Override
+    Path copyRemoteFiles(Path parentDir, Path originalPath, Configuration conf,
+        short replication) throws IOException {
+      return new Path(destinationPathPrefix + originalPath.getName());
+    }
+
+    @Override
+    void copyJar(Path originalJarPath, Path submitJarFile, short replication)
+        throws IOException {
+      // Do nothing. Stubbed out to avoid side effects. We don't actually need
+      // to copy the jar to the remote fs.
+    }
   }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[05/50] [abbrv] hadoop git commit: HDFS-11592. Closing a file has a wasteful preconditions in NameNode. Contributed by Eric Badger

Posted by in...@apache.org.
HDFS-11592. Closing a file has a wasteful preconditions in NameNode. Contributed by Eric Badger


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

Branch: refs/heads/HDFS-10467
Commit: df919ee734289072c42a7133889a3c2005b7ae77
Parents: 2ad28df
Author: Mingliang Liu <li...@apache.org>
Authored: Thu Mar 30 15:44:06 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:19 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/server/namenode/INodeFile.java    | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/df919ee7/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeFile.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeFile.java b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeFile.java
index 2b0e0ad..3da6aa7 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeFile.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/INodeFile.java
@@ -328,9 +328,11 @@ public class INodeFile extends INodeWithAdditionalFields
     for (int i = 0; i < blocks.length; i++) {
       final String err = checkBlockComplete(blocks, i, numCommittedAllowed,
           minReplication);
-      Preconditions.checkState(err == null,
-          "Unexpected block state: %s, file=%s (%s), blocks=%s (i=%s)",
-          err, this, getClass().getSimpleName(), Arrays.asList(blocks), i);
+      if(err != null) {
+        throw new IllegalStateException(String.format("Unexpected block state: " +
+            "%s, file=%s (%s), blocks=%s (i=%s)", err, this,
+            getClass().getSimpleName(), Arrays.asList(blocks), i));
+      }
     }
   }
 


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[48/50] [abbrv] hadoop git commit: HADOOP-14276. Add a nanosecond API to Time/Timer/FakeTimer. Contributed by Erik Krogen.

Posted by in...@apache.org.
HADOOP-14276. Add a nanosecond API to Time/Timer/FakeTimer. Contributed by Erik Krogen.


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

Branch: refs/heads/HDFS-10467
Commit: b2e33d5f7b61c6124837b5cbb3af07e4e15e6163
Parents: 66b8830
Author: Zhe Zhang <zh...@apache.org>
Authored: Thu Apr 6 16:52:22 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:24 2017 -0700

----------------------------------------------------------------------
 .../apache/hadoop/util/LightWeightCache.java    | 20 +++++-----------
 .../main/java/org/apache/hadoop/util/Time.java  | 10 ++++++++
 .../main/java/org/apache/hadoop/util/Timer.java | 10 ++++++++
 .../java/org/apache/hadoop/util/FakeTimer.java  | 24 ++++++++++++++++----
 .../hadoop/util/TestLightWeightCache.java       | 19 ++++++----------
 5 files changed, 52 insertions(+), 31 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/b2e33d5f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightCache.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightCache.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightCache.java
index a0a553a..d79aade 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightCache.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LightWeightCache.java
@@ -76,14 +76,6 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
       return l > r? 1: l < r? -1: 0;
     }
   };
-
-  /** A clock for measuring time so that it can be mocked in unit tests. */
-  static class Clock {
-    /** @return the current time. */
-    long currentTime() {
-      return System.nanoTime();
-    }
-  }
   
   private static int updateRecommendedLength(int recommendedLength,
       int sizeLimit) {
@@ -102,7 +94,7 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
   private final long creationExpirationPeriod;
   private final long accessExpirationPeriod;
   private final int sizeLimit;
-  private final Clock clock;
+  private final Timer timer;
 
   /**
    * @param recommendedLength Recommended size of the internal array.
@@ -120,7 +112,7 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
       final long creationExpirationPeriod,
       final long accessExpirationPeriod) {
     this(recommendedLength, sizeLimit,
-        creationExpirationPeriod, accessExpirationPeriod, new Clock());
+        creationExpirationPeriod, accessExpirationPeriod, new Timer());
   }
 
   @VisibleForTesting
@@ -128,7 +120,7 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
       final int sizeLimit,
       final long creationExpirationPeriod,
       final long accessExpirationPeriod,
-      final Clock clock) {
+      final Timer timer) {
     super(updateRecommendedLength(recommendedLength, sizeLimit));
 
     this.sizeLimit = sizeLimit;
@@ -147,11 +139,11 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
 
     this.queue = new PriorityQueue<Entry>(
         sizeLimit > 0? sizeLimit + 1: 1 << 10, expirationTimeComparator);
-    this.clock = clock;
+    this.timer = timer;
   }
 
   void setExpirationTime(final Entry e, final long expirationPeriod) {
-    e.setExpirationTime(clock.currentTime() + expirationPeriod);
+    e.setExpirationTime(timer.monotonicNowNanos() + expirationPeriod);
   }
 
   boolean isExpired(final Entry e, final long now) {
@@ -168,7 +160,7 @@ public class LightWeightCache<K, E extends K> extends LightWeightGSet<K, E> {
 
   /** Evict expired entries. */
   private void evictExpiredEntries() {
-    final long now = clock.currentTime();
+    final long now = timer.monotonicNowNanos();
     for(int i = 0; i < EVICTION_LIMIT; i++) {
       final Entry peeked = queue.peek();
       if (peeked == null || !isExpired(peeked, now)) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b2e33d5f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Time.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Time.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Time.java
index e96fa77..db5a567 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Time.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Time.java
@@ -66,6 +66,16 @@ public final class Time {
   }
 
   /**
+   * Same as {@link #monotonicNow()} but returns its result in nanoseconds.
+   * Note that this is subject to the same resolution constraints as
+   * {@link System#nanoTime()}.
+   * @return a monotonic clock that counts in nanoseconds.
+   */
+  public static long monotonicNowNanos() {
+    return System.nanoTime();
+  }
+
+  /**
    * Convert time in millisecond to human readable format.
    * @return a human readable string for the input time
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b2e33d5f/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Timer.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Timer.java b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Timer.java
index e1e21a7..3165a9b 100644
--- a/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Timer.java
+++ b/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Timer.java
@@ -48,4 +48,14 @@ public class Timer {
    * @return a monotonic clock that counts in milliseconds.
    */
   public long monotonicNow() { return Time.monotonicNow(); }
+
+  /**
+   * Same as {@link #monotonicNow()} but returns its result in nanoseconds.
+   * Note that this is subject to the same resolution constraints as
+   * {@link System#nanoTime()}.
+   * @return a monotonic clock that counts in nanoseconds.
+   */
+  public long monotonicNowNanos() {
+    return Time.monotonicNowNanos();
+  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b2e33d5f/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/FakeTimer.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/FakeTimer.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/FakeTimer.java
index 66386fd..2b5f850 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/FakeTimer.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/FakeTimer.java
@@ -18,6 +18,7 @@
 
 package org.apache.hadoop.util;
 
+import java.util.concurrent.TimeUnit;
 import org.apache.hadoop.classification.InterfaceAudience;
 import org.apache.hadoop.classification.InterfaceStability;
 
@@ -28,25 +29,38 @@ import org.apache.hadoop.classification.InterfaceStability;
 @InterfaceAudience.Private
 @InterfaceStability.Unstable
 public class FakeTimer extends Timer {
-  private long nowMillis;
+  private long nowNanos;
 
   /** Constructs a FakeTimer with a non-zero value */
   public FakeTimer() {
-    nowMillis = 1000;  // Initialize with a non-trivial value.
+    nowNanos = 1000;  // Initialize with a non-trivial value.
   }
 
   @Override
   public long now() {
-    return nowMillis;
+    return TimeUnit.NANOSECONDS.toMillis(nowNanos);
   }
 
   @Override
   public long monotonicNow() {
-    return nowMillis;
+    return TimeUnit.NANOSECONDS.toMillis(nowNanos);
+  }
+
+  @Override
+  public long monotonicNowNanos() {
+    return nowNanos;
   }
 
   /** Increases the time by milliseconds */
   public void advance(long advMillis) {
-    nowMillis += advMillis;
+    nowNanos += TimeUnit.MILLISECONDS.toNanos(advMillis);
+  }
+
+  /**
+   * Increases the time by nanoseconds.
+   * @param advNanos Nanoseconds to advance by.
+   */
+  public void advanceNanos(long advNanos) {
+    nowNanos += advNanos;
   }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/b2e33d5f/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java
----------------------------------------------------------------------
diff --git a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java
index dff6937..de61818 100644
--- a/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java
+++ b/hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestLightWeightCache.java
@@ -213,7 +213,7 @@ public class TestLightWeightCache {
     int iterate_count = 0;
     int contain_count = 0;
 
-    private long currentTestTime = ran.nextInt();
+    private FakeTimer fakeTimer = new FakeTimer();
 
     LightWeightCacheTestCase(int tablelength, int sizeLimit,
         long creationExpirationPeriod, long accessExpirationPeriod,
@@ -230,12 +230,7 @@ public class TestLightWeightCache {
 
       data = new IntData(datasize, modulus);
       cache = new LightWeightCache<IntEntry, IntEntry>(tablelength, sizeLimit,
-          creationExpirationPeriod, 0, new LightWeightCache.Clock() {
-        @Override
-        long currentTime() {
-          return currentTestTime;
-        }
-      });
+          creationExpirationPeriod, 0, fakeTimer);
 
       Assert.assertEquals(0, cache.size());
     }
@@ -247,7 +242,7 @@ public class TestLightWeightCache {
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, currentTestTime));
+          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -266,7 +261,7 @@ public class TestLightWeightCache {
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, currentTestTime));
+          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -286,7 +281,7 @@ public class TestLightWeightCache {
         final IntEntry h = hashMap.put(entry);
         if (h != null && h != entry) {
           // if h == entry, its expiration time is already updated
-          Assert.assertTrue(cache.isExpired(h, currentTestTime));
+          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -305,7 +300,7 @@ public class TestLightWeightCache {
       } else {
         final IntEntry h = hashMap.remove(key);
         if (h != null) {
-          Assert.assertTrue(cache.isExpired(h, currentTestTime));
+          Assert.assertTrue(cache.isExpired(h, fakeTimer.monotonicNowNanos()));
         }
       }
       return c;
@@ -339,7 +334,7 @@ public class TestLightWeightCache {
     }
 
     void check() {
-      currentTestTime += ran.nextInt() & 0x3;
+      fakeTimer.advanceNanos(ran.nextInt() & 0x3);
 
       //test size
       sizeTest();


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[28/50] [abbrv] hadoop git commit: HDFS-9651. Add missing robots.txt files.

Posted by in...@apache.org.
HDFS-9651. Add missing robots.txt files.


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

Branch: refs/heads/HDFS-10467
Commit: 8c69f5a7981904e0f4153dc692fd430c3eeb8ae6
Parents: 69e0934
Author: Akira Ajisaka <aa...@apache.org>
Authored: Wed Apr 5 12:47:30 2017 +0900
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/robots.txt   | 2 ++
 .../hadoop-hdfs/src/main/webapps/journal/robots.txt                | 2 ++
 .../hadoop-hdfs/src/main/webapps/secondary/robots.txt              | 2 ++
 3 files changed, 6 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c69f5a7/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/robots.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/robots.txt b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/robots.txt
new file mode 100644
index 0000000..1f53798
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/hdfs/robots.txt
@@ -0,0 +1,2 @@
+User-agent: *
+Disallow: /

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c69f5a7/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/journal/robots.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/journal/robots.txt b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/journal/robots.txt
new file mode 100644
index 0000000..1f53798
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/journal/robots.txt
@@ -0,0 +1,2 @@
+User-agent: *
+Disallow: /

http://git-wip-us.apache.org/repos/asf/hadoop/blob/8c69f5a7/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/secondary/robots.txt
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/secondary/robots.txt b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/secondary/robots.txt
new file mode 100644
index 0000000..1f53798
--- /dev/null
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/main/webapps/secondary/robots.txt
@@ -0,0 +1,2 @@
+User-agent: *
+Disallow: /


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[03/50] [abbrv] hadoop git commit: Revert "HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen."

Posted by in...@apache.org.
Revert "HADOOP-11794. Enable distcp to copy blocks in parallel. Contributed by Yongjun Zhang, Wei-Chiu Chuang, Xiao Chen."

This reverts commit 064c8b25eca9bc825dc07a54d9147d65c9290a03.


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

Branch: refs/heads/HDFS-10467
Commit: 0ca98cbb6c881b174aa430ec6207cbc9221e949b
Parents: 92421f2
Author: Yongjun Zhang <yz...@cloudera.com>
Authored: Thu Mar 30 17:38:18 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:19 2017 -0700

----------------------------------------------------------------------
 .../org/apache/hadoop/hdfs/DFSTestUtil.java     |  22 +-
 .../org/apache/hadoop/tools/CopyListing.java    |  37 +-
 .../hadoop/tools/CopyListingFileStatus.java     |  87 +----
 .../java/org/apache/hadoop/tools/DistCp.java    |  52 ---
 .../apache/hadoop/tools/DistCpOptionSwitch.java |  10 -
 .../org/apache/hadoop/tools/DistCpOptions.java  |  22 +-
 .../org/apache/hadoop/tools/OptionsParser.java  |  36 +-
 .../apache/hadoop/tools/SimpleCopyListing.java  |  83 ++---
 .../hadoop/tools/mapred/CopyCommitter.java      | 174 +--------
 .../apache/hadoop/tools/mapred/CopyMapper.java  |  40 +-
 .../tools/mapred/RetriableFileCopyCommand.java  |  26 +-
 .../tools/mapred/UniformSizeInputFormat.java    |   5 +-
 .../apache/hadoop/tools/util/DistCpUtils.java   | 111 +-----
 .../src/site/markdown/DistCp.md.vm              |   1 -
 .../apache/hadoop/tools/TestDistCpSystem.java   | 368 ++-----------------
 .../apache/hadoop/tools/TestOptionsParser.java  |   2 +-
 .../hadoop/tools/mapred/TestCopyCommitter.java  |   5 +-
 17 files changed, 110 insertions(+), 971 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
index 9b782f3..1329195 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
+++ b/hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/DFSTestUtil.java
@@ -862,27 +862,7 @@ public class DFSTestUtil {
       out.write(toAppend);
     }
   }
-
-  /**
-   * Append specified length of bytes to a given file, starting with new block.
-   * @param fs The file system
-   * @param p Path of the file to append
-   * @param length Length of bytes to append to the file
-   * @throws IOException
-   */
-  public static void appendFileNewBlock(DistributedFileSystem fs,
-      Path p, int length) throws IOException {
-    assert fs.exists(p);
-    assert length >= 0;
-    byte[] toAppend = new byte[length];
-    Random random = new Random();
-    random.nextBytes(toAppend);
-    try (FSDataOutputStream out = fs.append(p,
-        EnumSet.of(CreateFlag.APPEND, CreateFlag.NEW_BLOCK), 4096, null)) {
-      out.write(toAppend);
-    }
-  }
-
+  
   /**
    * @return url content as string (UTF-8 encoding assumed)
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
index 9ebf9d2..481aa61 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListing.java
@@ -145,22 +145,12 @@ public abstract class CopyListing extends Configured {
     Configuration config = getConf();
     FileSystem fs = pathToListFile.getFileSystem(config);
 
-    final boolean splitLargeFile = options.splitLargeFile();
-
-    // When splitLargeFile is enabled, we don't randomize the copylist
-    // earlier, so we don't do the sorting here. For a file that has
-    // multiple entries due to split, we check here that their
-    // <chunkOffset, chunkLength> is continuous.
-    //
-    Path checkPath = splitLargeFile?
-        pathToListFile : DistCpUtils.sortListing(fs, config, pathToListFile);
+    Path sortedList = DistCpUtils.sortListing(fs, config, pathToListFile);
 
     SequenceFile.Reader reader = new SequenceFile.Reader(
-                          config, SequenceFile.Reader.file(checkPath));
+                          config, SequenceFile.Reader.file(sortedList));
     try {
       Text lastKey = new Text("*"); //source relative path can never hold *
-      long lastChunkOffset = -1;
-      long lastChunkLength = -1;
       CopyListingFileStatus lastFileStatus = new CopyListingFileStatus();
 
       Text currentKey = new Text();
@@ -171,21 +161,8 @@ public abstract class CopyListing extends Configured {
         if (currentKey.equals(lastKey)) {
           CopyListingFileStatus currentFileStatus = new CopyListingFileStatus();
           reader.getCurrentValue(currentFileStatus);
-          if (!splitLargeFile) {
-            throw new DuplicateFileException("File " + lastFileStatus.getPath()
-                + " and " + currentFileStatus.getPath()
-                + " would cause duplicates. Aborting");
-          } else {
-            if (lastChunkOffset + lastChunkLength !=
-                currentFileStatus.getChunkOffset()) {
-              throw new InvalidInputException("File " + lastFileStatus.getPath()
-                  + " " + lastChunkOffset + "," + lastChunkLength
-                  + " and " + currentFileStatus.getPath()
-                  + " " + currentFileStatus.getChunkOffset() + ","
-                  + currentFileStatus.getChunkLength()
-                  + " are not continuous. Aborting");
-            }
-          }
+          throw new DuplicateFileException("File " + lastFileStatus.getPath() + " and " +
+              currentFileStatus.getPath() + " would cause duplicates. Aborting");
         }
         reader.getCurrentValue(lastFileStatus);
         if (options.shouldPreserve(DistCpOptions.FileAttribute.ACL)) {
@@ -204,12 +181,8 @@ public abstract class CopyListing extends Configured {
             xAttrSupportCheckFsSet.add(lastFsUri);
           }
         }
-
         lastKey.set(currentKey);
-        if (splitLargeFile) {
-          lastChunkOffset = lastFileStatus.getChunkOffset();
-          lastChunkLength = lastFileStatus.getChunkLength();
-        }
+
         if (options.shouldUseDiff() && LOG.isDebugEnabled()) {
           LOG.debug("Copy list entry " + idx + ": " +
                   lastFileStatus.getPath().toUri().getPath());

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
index 29c59ac..00d4b32 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/CopyListingFileStatus.java
@@ -74,14 +74,6 @@ public final class CopyListingFileStatus implements Writable {
   private List<AclEntry> aclEntries;
   private Map<String, byte[]> xAttrs;
 
-  // <chunkOffset, chunkLength> represents the offset and length of a file
-  // chunk in number of bytes.
-  // used when splitting a large file to chunks to copy in parallel.
-  // If a file is not large enough to split, chunkOffset would be 0 and
-  // chunkLength would be the length of the file.
-  private long chunkOffset = 0;
-  private long chunkLength = Long.MAX_VALUE;
-
   /**
    * Default constructor.
    */
@@ -104,32 +96,11 @@ public final class CopyListingFileStatus implements Writable {
         fileStatus.getPath());
   }
 
-  public CopyListingFileStatus(FileStatus fileStatus,
-      long chunkOffset, long chunkLength) {
-    this(fileStatus.getLen(), fileStatus.isDirectory(),
-        fileStatus.getReplication(), fileStatus.getBlockSize(),
-        fileStatus.getModificationTime(), fileStatus.getAccessTime(),
-        fileStatus.getPermission(), fileStatus.getOwner(),
-        fileStatus.getGroup(),
-        fileStatus.getPath());
-    this.chunkOffset = chunkOffset;
-    this.chunkLength = chunkLength;
-  }
-
   @SuppressWarnings("checkstyle:parameternumber")
   public CopyListingFileStatus(long length, boolean isdir,
       int blockReplication, long blocksize, long modificationTime,
       long accessTime, FsPermission permission, String owner, String group,
       Path path) {
-    this(length, isdir, blockReplication, blocksize, modificationTime,
-        accessTime, permission, owner, group, path, 0, Long.MAX_VALUE);
-  }
-
-  @SuppressWarnings("checkstyle:parameternumber")
-  public CopyListingFileStatus(long length, boolean isdir,
-      int blockReplication, long blocksize, long modificationTime,
-      long accessTime, FsPermission permission, String owner, String group,
-      Path path, long chunkOffset, long chunkLength) {
     this.length = length;
     this.isdir = isdir;
     this.blockReplication = (short)blockReplication;
@@ -146,23 +117,6 @@ public final class CopyListingFileStatus implements Writable {
     this.owner = (owner == null) ? "" : owner;
     this.group = (group == null) ? "" : group;
     this.path = path;
-    this.chunkOffset = chunkOffset;
-    this.chunkLength = chunkLength;
-  }
-
-  public CopyListingFileStatus(CopyListingFileStatus other) {
-    this.length = other.length;
-    this.isdir = other.isdir;
-    this.blockReplication = other.blockReplication;
-    this.blocksize = other.blocksize;
-    this.modificationTime = other.modificationTime;
-    this.accessTime = other.accessTime;
-    this.permission = other.permission;
-    this.owner = other.owner;
-    this.group = other.group;
-    this.path = new Path(other.path.toUri());
-    this.chunkOffset = other.chunkOffset;
-    this.chunkLength = other.chunkLength;
   }
 
   public Path getPath() {
@@ -246,31 +200,6 @@ public final class CopyListingFileStatus implements Writable {
     this.xAttrs = xAttrs;
   }
 
-  public long getChunkOffset() {
-    return chunkOffset;
-  }
-
-  public void setChunkOffset(long offset) {
-    this.chunkOffset = offset;
-  }
-
-  public long getChunkLength() {
-    return chunkLength;
-  }
-
-  public void setChunkLength(long chunkLength) {
-    this.chunkLength = chunkLength;
-  }
-
-  public boolean isSplit() {
-    return getChunkLength() != Long.MAX_VALUE &&
-        getChunkLength() != getLen();
-  }
-
-  public long getSizeToCopy() {
-    return isSplit()? getChunkLength() : getLen();
-  }
-
   @Override
   public void write(DataOutput out) throws IOException {
     Text.writeString(out, getPath().toString(), Text.DEFAULT_MAX_LEN);
@@ -315,9 +244,6 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       out.writeInt(NO_XATTRS);
     }
-
-    out.writeLong(chunkOffset);
-    out.writeLong(chunkLength);
   }
 
   @Override
@@ -366,9 +292,6 @@ public final class CopyListingFileStatus implements Writable {
     } else {
       xAttrs = null;
     }
-
-    chunkOffset = in.readLong();
-    chunkLength = in.readLong();
   }
 
   @Override
@@ -394,14 +317,8 @@ public final class CopyListingFileStatus implements Writable {
   public String toString() {
     StringBuilder sb = new StringBuilder(super.toString());
     sb.append('{');
-    sb.append(this.getPath().toString());
-    sb.append(" length = ").append(this.getLen());
-    sb.append(" aclEntries = ").append(aclEntries);
-    sb.append(", xAttrs = ").append(xAttrs);
-    if (isSplit()) {
-      sb.append(", chunkOffset = ").append(this.getChunkOffset());
-      sb.append(", chunkLength = ").append(this.getChunkLength());
-    }
+    sb.append("aclEntries = " + aclEntries);
+    sb.append(", xAttrs = " + xAttrs);
     sb.append('}');
     return sb.toString();
   }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
index 8c2fa24..ab58e9c 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCp.java
@@ -35,7 +35,6 @@ import org.apache.hadoop.mapreduce.Cluster;
 import org.apache.hadoop.mapreduce.Job;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobSubmissionFiles;
-import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.CopyListing.*;
 import org.apache.hadoop.tools.mapred.CopyMapper;
 import org.apache.hadoop.tools.mapred.CopyOutputFormat;
@@ -135,7 +134,6 @@ public class DistCp extends Configured implements Tool {
     
     try {
       inputOptions = (OptionsParser.parse(argv));
-      setOptionsForSplitLargeFile();
       setTargetPathExists();
       LOG.info("Input Options: " + inputOptions);
     } catch (Throwable e) {
@@ -237,56 +235,6 @@ public class DistCp extends Configured implements Tool {
     getConf().setBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, 
         targetExists);
   }
-
-  /**
-   * Check if concat is supported by fs.
-   * Throws UnsupportedOperationException if not.
-   */
-  private void checkConcatSupport(FileSystem fs) {
-    try {
-      Path[] src = null;
-      Path tgt = null;
-      fs.concat(tgt, src);
-    } catch (UnsupportedOperationException use) {
-      throw new UnsupportedOperationException(
-          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() +
-          " is not supported since the target file system doesn't" +
-          " support concat.", use);
-    } catch (Exception e) {
-      // Ignore other exception
-    }
-  }
-
-  /**
-   * Set up needed options for splitting large files.
-   */
-  private void setOptionsForSplitLargeFile() throws IOException {
-    if (!inputOptions.splitLargeFile()) {
-      return;
-    }
-    Path target = inputOptions.getTargetPath();
-    FileSystem targetFS = target.getFileSystem(getConf());
-    checkConcatSupport(targetFS);
-
-    LOG.info("Enabling preserving blocksize since "
-        + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " is passed.");
-    inputOptions.preserve(FileAttribute.BLOCKSIZE);
-
-    LOG.info("Set " +
-        DistCpOptionSwitch.APPEND.getSwitch()
-        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
-        + " is passed.");
-    inputOptions.setAppend(false);
-
-    LOG.info("Set " +
-        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES
-        + " to false since " + DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch()
-        + " is passed.");
-    getConf().setBoolean(
-        DistCpConstants.CONF_LABEL_SIMPLE_LISTING_RANDOMIZE_FILES, false);
-  }
-
-
   /**
    * Create Job object for submitting it, with all the configuration
    *

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
index ced9b54..fb47d76 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/DistCpOptionSwitch.java
@@ -169,16 +169,6 @@ public enum DistCpOptionSwitch {
       new Option("sizelimit", true, "(Deprecated!) Limit number of files " +
               "copied to <= n bytes")),
 
-  BLOCKS_PER_CHUNK("",
-      new Option("blocksperchunk", true, "If set to a positive value, files"
-          + "with more blocks than this value will be split into chunks of "
-          + "<blocksperchunk> blocks to be transferred in parallel, and "
-          + "reassembled on the destination. By default, <blocksperchunk> is "
-          + "0 and the files will be transmitted in their entirety without "
-          + "splitting. This switch is only applicable when the source file "
-          + "system implements getBlockLocations method and the target file "
-          + "system implements concat method")),
-
   /**
    * Specify bandwidth per map in MB, accepts bandwidth as a fraction
    */

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/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 9822d83..8c37ff3 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
@@ -97,11 +97,7 @@ public class DistCpOptions {
   // targetPathExist is a derived field, it's initialized in the
   // beginning of distcp.
   private boolean targetPathExists = true;
-
-  // Size of chunk in number of blocks when splitting large file into chunks
-  // to copy in parallel. Default is 0 and file are not splitted.
-  private int blocksPerChunk = 0;
-
+  
   public static enum FileAttribute{
     REPLICATION, BLOCKSIZE, USER, GROUP, PERMISSION, CHECKSUMTYPE, ACL, XATTR, TIMES;
 
@@ -170,7 +166,6 @@ public class DistCpOptions {
       this.targetPath = that.getTargetPath();
       this.targetPathExists = that.getTargetPathExists();
       this.filtersFile = that.getFiltersFile();
-      this.blocksPerChunk = that.blocksPerChunk;
     }
   }
 
@@ -583,18 +578,6 @@ public class DistCpOptions {
     this.filtersFile = filtersFilename;
   }
 
-  public final void setBlocksPerChunk(int csize) {
-    this.blocksPerChunk = csize;
-  }
-
-  public final int getBlocksPerChunk() {
-    return blocksPerChunk;
-  }
-
-  public final boolean splitLargeFile() {
-    return blocksPerChunk > 0;
-  }
-
   void validate() {
     if ((useDiff || useRdiff) && deleteMissing) {
       // -delete and -diff/-rdiff are mutually exclusive. For backward
@@ -686,8 +669,6 @@ public class DistCpOptions {
       DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.FILTERS,
           filtersFile);
     }
-    DistCpOptionSwitch.addToConf(conf, DistCpOptionSwitch.BLOCKS_PER_CHUNK,
-        String.valueOf(blocksPerChunk));
   }
 
   /**
@@ -723,7 +704,6 @@ public class DistCpOptions {
         ", targetPath=" + targetPath +
         ", targetPathExists=" + targetPathExists +
         ", filtersFile='" + filtersFile + '\'' +
-        ", blocksPerChunk=" + blocksPerChunk +
         '}';
   }
 

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
index 8881264..d0f82ca 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/OptionsParser.java
@@ -172,44 +172,11 @@ public class OptionsParser {
           DistCpOptionSwitch.FILTERS.getSwitch()));
     }
 
-    parseBlocksPerChunk(command, option);
-
     option.validate();
 
     return option;
   }
 
-
-  /**
-   * A helper method to parse chunk size in number of blocks.
-   * Used when breaking large file into chunks to copy in parallel.
-   *
-   * @param command command line arguments
-   */
-  private static void parseBlocksPerChunk(CommandLine command,
-      DistCpOptions option) {
-    boolean hasOption =
-        command.hasOption(DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch());
-    LOG.info("parseChunkSize: " +
-        DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch() + " " + hasOption);
-    if (hasOption) {
-      String chunkSizeString = getVal(command,
-          DistCpOptionSwitch.BLOCKS_PER_CHUNK.getSwitch().trim());
-      try {
-        int csize = Integer.parseInt(chunkSizeString);
-        if (csize < 0) {
-          csize = 0;
-        }
-        LOG.info("Set distcp blocksPerChunk to " + csize);
-        option.setBlocksPerChunk(csize);
-      }
-      catch (NumberFormatException e) {
-        throw new IllegalArgumentException("blocksPerChunk is invalid: "
-            + chunkSizeString, e);
-      }
-    }
-  }
-
   /**
    * parseSizeLimit is a helper method for parsing the deprecated
    * argument SIZE_LIMIT.
@@ -244,7 +211,8 @@ public class OptionsParser {
                               DistCpOptionSwitch.FILE_LIMIT.getSwitch().trim());
       try {
         Integer.parseInt(fileLimitString);
-      } catch (NumberFormatException e) {
+      }
+      catch (NumberFormatException e) {
         throw new IllegalArgumentException("File-limit is invalid: "
                                             + fileLimitString, e);
       }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
index af91347..105e4f2 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/SimpleCopyListing.java
@@ -19,7 +19,6 @@
 package org.apache.hadoop.tools;
 
 import com.google.common.collect.Lists;
-
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.fs.Path;
@@ -48,7 +47,6 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Random;
-import java.util.LinkedList;
 
 import static org.apache.hadoop.tools.DistCpConstants
         .HDFS_RESERVED_RAW_DIRECTORY_NAME;
@@ -242,10 +240,10 @@ public class SimpleCopyListing extends CopyListing {
     final boolean preserveAcls = options.shouldPreserve(FileAttribute.ACL);
     final boolean preserveXAttrs = options.shouldPreserve(FileAttribute.XATTR);
     final boolean preserveRawXAttrs = options.shouldPreserveRawXattrs();
-    LinkedList<CopyListingFileStatus> fileCopyListingStatus =
+    CopyListingFileStatus fileCopyListingStatus =
         DistCpUtils.toCopyListingFileStatus(sourceFS, fileStatus,
-            preserveAcls, preserveXAttrs, preserveRawXAttrs,
-            options.getBlocksPerChunk());
+            preserveAcls, preserveXAttrs, preserveRawXAttrs);
+
     writeToFileListingRoot(fileListWriter, fileCopyListingStatus,
         sourceRoot, options);
   }
@@ -350,10 +348,9 @@ public class SimpleCopyListing extends CopyListing {
         FileStatus[] sourceFiles = sourceFS.listStatus(path);
         boolean explore = (sourceFiles != null && sourceFiles.length > 0);
         if (!explore || rootStatus.isDirectory()) {
-          LinkedList<CopyListingFileStatus> rootCopyListingStatus =
-              DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
-                  preserveAcls, preserveXAttrs, preserveRawXAttrs,
-                  options.getBlocksPerChunk());
+          CopyListingFileStatus rootCopyListingStatus =
+            DistCpUtils.toCopyListingFileStatus(sourceFS, rootStatus,
+                preserveAcls, preserveXAttrs, preserveRawXAttrs);
           writeToFileListingRoot(fileListWriter, rootCopyListingStatus,
               sourcePathRoot, options);
         }
@@ -363,20 +360,20 @@ public class SimpleCopyListing extends CopyListing {
             if (LOG.isDebugEnabled()) {
               LOG.debug("Recording source-path: " + sourceStatus.getPath() + " for copy.");
             }
-            LinkedList<CopyListingFileStatus> sourceCopyListingStatus =
-                DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
-                    preserveAcls && sourceStatus.isDirectory(),
-                    preserveXAttrs && sourceStatus.isDirectory(),
-                    preserveRawXAttrs && sourceStatus.isDirectory(),
-                    options.getBlocksPerChunk());
-            for (CopyListingFileStatus fs : sourceCopyListingStatus) {
-              if (randomizeFileListing) {
-                addToFileListing(statusList,
-                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
-              } else {
-                writeToFileListing(fileListWriter, fs, sourcePathRoot);
-              }
+            CopyListingFileStatus sourceCopyListingStatus =
+              DistCpUtils.toCopyListingFileStatus(sourceFS, sourceStatus,
+                  preserveAcls && sourceStatus.isDirectory(),
+                  preserveXAttrs && sourceStatus.isDirectory(),
+                  preserveRawXAttrs && sourceStatus.isDirectory());
+            if (randomizeFileListing) {
+              addToFileListing(statusList,
+                  new FileStatusInfo(sourceCopyListingStatus, sourcePathRoot),
+                  fileListWriter);
+            } else {
+              writeToFileListing(fileListWriter, sourceCopyListingStatus,
+                  sourcePathRoot);
             }
+
             if (sourceStatus.isDirectory()) {
               if (LOG.isDebugEnabled()) {
                 LOG.debug("Adding source dir for traverse: " + sourceStatus.getPath());
@@ -644,20 +641,18 @@ public class SimpleCopyListing extends CopyListing {
             LOG.debug("Recording source-path: " + child.getPath() + " for copy.");
           }
           if (workResult.getSuccess()) {
-            LinkedList<CopyListingFileStatus> childCopyListingStatus =
+            CopyListingFileStatus childCopyListingStatus =
               DistCpUtils.toCopyListingFileStatus(sourceFS, child,
                 preserveAcls && child.isDirectory(),
                 preserveXAttrs && child.isDirectory(),
-                preserveRawXattrs && child.isDirectory(),
-                options.getBlocksPerChunk());
-
-            for (CopyListingFileStatus fs : childCopyListingStatus) {
-              if (randomizeFileListing) {
-                addToFileListing(fileStatuses,
-                    new FileStatusInfo(fs, sourcePathRoot), fileListWriter);
-              } else {
-                writeToFileListing(fileListWriter, fs, sourcePathRoot);
-              }
+                preserveRawXattrs && child.isDirectory());
+            if (randomizeFileListing) {
+              addToFileListing(fileStatuses,
+                  new FileStatusInfo(childCopyListingStatus, sourcePathRoot),
+                  fileListWriter);
+            } else {
+              writeToFileListing(fileListWriter, childCopyListingStatus,
+                  sourcePathRoot);
             }
           }
           if (retry < maxRetries) {
@@ -680,21 +675,19 @@ public class SimpleCopyListing extends CopyListing {
   }
 
   private void writeToFileListingRoot(SequenceFile.Writer fileListWriter,
-      LinkedList<CopyListingFileStatus> fileStatus, Path sourcePathRoot,
+      CopyListingFileStatus fileStatus, Path sourcePathRoot,
       DistCpOptions options) throws IOException {
     boolean syncOrOverwrite = options.shouldSyncFolder() ||
         options.shouldOverwrite();
-    for (CopyListingFileStatus fs : fileStatus) {
-      if (fs.getPath().equals(sourcePathRoot) &&
-          fs.isDirectory() && syncOrOverwrite) {
-        // Skip the root-paths when syncOrOverwrite
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("Skip " + fs.getPath());
-        }
-        return;
-      }
-      writeToFileListing(fileListWriter, fs, sourcePathRoot);
+    if (fileStatus.getPath().equals(sourcePathRoot) && 
+        fileStatus.isDirectory() && syncOrOverwrite) {
+      // Skip the root-paths when syncOrOverwrite
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("Skip " + fileStatus.getPath());
+      }      
+      return;
     }
+    writeToFileListing(fileListWriter, fileStatus, sourcePathRoot);
   }
 
   private void writeToFileListing(SequenceFile.Writer fileListWriter,
@@ -714,7 +707,7 @@ public class SimpleCopyListing extends CopyListing {
     fileListWriter.sync();
 
     if (!fileStatus.isDirectory()) {
-      totalBytesToCopy += fileStatus.getSizeToCopy();
+      totalBytesToCopy += fileStatus.getLen();
     } else {
       totalDirs++;
     }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
index 6ddaab9..75cefb4 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyCommitter.java
@@ -27,7 +27,6 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.io.IOUtils;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
-import org.apache.hadoop.ipc.RemoteException;
 import org.apache.hadoop.mapreduce.JobContext;
 import org.apache.hadoop.mapreduce.JobStatus;
 import org.apache.hadoop.mapreduce.TaskAttemptContext;
@@ -35,17 +34,14 @@ import org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter;
 import org.apache.hadoop.tools.CopyListing;
 import org.apache.hadoop.tools.CopyListingFileStatus;
 import org.apache.hadoop.tools.DistCpConstants;
-import org.apache.hadoop.tools.DistCpOptionSwitch;
 import org.apache.hadoop.tools.DistCpOptions;
 import org.apache.hadoop.tools.DistCpOptions.FileAttribute;
 import org.apache.hadoop.tools.GlobbedCopyListing;
 import org.apache.hadoop.tools.util.DistCpUtils;
 
-import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.EnumSet;
-import java.util.LinkedList;
 import java.util.List;
 
 /**
@@ -67,8 +63,7 @@ public class CopyCommitter extends FileOutputCommitter {
   private boolean syncFolder = false;
   private boolean overwrite = false;
   private boolean targetPathExists = true;
-  private boolean ignoreFailures = false;
-
+  
   /**
    * Create a output committer
    *
@@ -87,13 +82,8 @@ public class CopyCommitter extends FileOutputCommitter {
     Configuration conf = jobContext.getConfiguration();
     syncFolder = conf.getBoolean(DistCpConstants.CONF_LABEL_SYNC_FOLDERS, false);
     overwrite = conf.getBoolean(DistCpConstants.CONF_LABEL_OVERWRITE, false);
-    targetPathExists = conf.getBoolean(
-        DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
-    ignoreFailures = conf.getBoolean(
-        DistCpOptionSwitch.IGNORE_FAILURES.getConfigLabel(), false);
-
-    concatFileChunks(conf);
-
+    targetPathExists = conf.getBoolean(DistCpConstants.CONF_LABEL_TARGET_PATH_EXISTS, true);
+    
     super.commitJob(jobContext);
 
     cleanupTempFiles(jobContext);
@@ -179,112 +169,9 @@ public class CopyCommitter extends FileOutputCommitter {
     }
   }
 
-  private boolean isFileNotFoundException(IOException e) {
-    if (e instanceof FileNotFoundException) {
-      return true;
-    }
-
-    if (e instanceof RemoteException) {
-      return ((RemoteException)e).unwrapRemoteException()
-          instanceof FileNotFoundException;
-    }
-
-    return false;
-  }
-
-  /**
-   * Concat chunk files for the same file into one.
-   * Iterate through copy listing, identify chunk files for the same file,
-   * concat them into one.
-   */
-  private void concatFileChunks(Configuration conf) throws IOException {
-
-    LOG.info("concat file chunks ...");
-
-    String spath = conf.get(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH);
-    if (spath == null || spath.isEmpty()) {
-      return;
-    }
-    Path sourceListing = new Path(spath);
-    SequenceFile.Reader sourceReader = new SequenceFile.Reader(conf,
-                                      SequenceFile.Reader.file(sourceListing));
-    Path targetRoot =
-        new Path(conf.get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
-
-    try {
-      CopyListingFileStatus srcFileStatus = new CopyListingFileStatus();
-      Text srcRelPath = new Text();
-      CopyListingFileStatus lastFileStatus = null;
-      LinkedList<Path> allChunkPaths = new LinkedList<Path>();
-
-      // Iterate over every source path that was copied.
-      while (sourceReader.next(srcRelPath, srcFileStatus)) {
-        if (srcFileStatus.isDirectory()) {
-          continue;
-        }
-        Path targetFile = new Path(targetRoot.toString() + "/" + srcRelPath);
-        Path targetFileChunkPath =
-            DistCpUtils.getSplitChunkPath(targetFile, srcFileStatus);
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("  add " + targetFileChunkPath + " to concat.");
-        }
-        allChunkPaths.add(targetFileChunkPath);
-        if (srcFileStatus.getChunkOffset() + srcFileStatus.getChunkLength()
-            == srcFileStatus.getLen()) {
-          // This is the last chunk of the splits, consolidate allChunkPaths
-          try {
-            concatFileChunks(conf, targetFile, allChunkPaths);
-          } catch (IOException e) {
-            // If the concat failed because a chunk file doesn't exist,
-            // then we assume that the CopyMapper has skipped copying this
-            // file, and we ignore the exception here.
-            // If a chunk file should have been created but it was not, then
-            // the CopyMapper would have failed.
-            if (!isFileNotFoundException(e)) {
-              String emsg = "Failed to concat chunk files for " + targetFile;
-              if (!ignoreFailures) {
-                throw new IOException(emsg, e);
-              } else {
-                LOG.warn(emsg, e);
-              }
-            }
-          }
-          allChunkPaths.clear();
-          lastFileStatus = null;
-        } else {
-          if (lastFileStatus == null) {
-            lastFileStatus = new CopyListingFileStatus(srcFileStatus);
-          } else {
-            // Two neighboring chunks have to be consecutive ones for the same
-            // file, for them to be merged
-            if (!srcFileStatus.getPath().equals(lastFileStatus.getPath()) ||
-                srcFileStatus.getChunkOffset() !=
-                (lastFileStatus.getChunkOffset() +
-                lastFileStatus.getChunkLength())) {
-              String emsg = "Inconsistent sequence file: current " +
-                  "chunk file " + srcFileStatus + " doesnt match prior " +
-                  "entry " + lastFileStatus;
-              if (!ignoreFailures) {
-                throw new IOException(emsg);
-              } else {
-                LOG.warn(emsg + ", skipping concat this set.");
-              }
-            } else {
-              lastFileStatus.setChunkOffset(srcFileStatus.getChunkOffset());
-              lastFileStatus.setChunkLength(srcFileStatus.getChunkLength());
-            }
-          }
-        }
-      }
-    } finally {
-      IOUtils.closeStream(sourceReader);
-    }
-  }
-
   // This method changes the target-directories' file-attributes (owner,
   // user/group permissions, etc.) based on the corresponding source directories.
-  private void preserveFileAttributesForDirectories(Configuration conf)
-      throws IOException {
+  private void preserveFileAttributesForDirectories(Configuration conf) throws IOException {
     String attrSymbols = conf.get(DistCpConstants.CONF_LABEL_PRESERVE_STATUS);
     final boolean syncOrOverwrite = syncFolder || overwrite;
 
@@ -438,57 +325,4 @@ public class CopyCommitter extends FileOutputCommitter {
         ", Unable to move to " + finalDir);
     }
   }
-
-  /**
-   * Concat the passed chunk files into one and rename it the targetFile.
-   */
-  private void concatFileChunks(Configuration conf, Path targetFile,
-      LinkedList<Path> allChunkPaths) throws IOException {
-    if (allChunkPaths.size() == 1) {
-      return;
-    }
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("concat " + targetFile + " allChunkSize+ "
-          + allChunkPaths.size());
-    }
-    FileSystem dstfs = targetFile.getFileSystem(conf);
-
-    Path firstChunkFile = allChunkPaths.removeFirst();
-    Path[] restChunkFiles = new Path[allChunkPaths.size()];
-    allChunkPaths.toArray(restChunkFiles);
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("concat: firstchunk: " + dstfs.getFileStatus(firstChunkFile));
-      int i = 0;
-      for (Path f : restChunkFiles) {
-        LOG.debug("concat: other chunk: " + i + ": " + dstfs.getFileStatus(f));
-        ++i;
-      }
-    }
-    dstfs.concat(firstChunkFile, restChunkFiles);
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("concat: result: " + dstfs.getFileStatus(firstChunkFile));
-    }
-    rename(dstfs, firstChunkFile, targetFile);
-  }
-
-  /**
-   * Rename tmp to dst on destFileSys.
-   * @param destFileSys the file ssystem
-   * @param tmp the source path
-   * @param dst the destination path
-   * @throws IOException if renaming failed
-   */
-  private static void rename(FileSystem destFileSys, Path tmp, Path dst)
-      throws IOException {
-    try {
-      if (destFileSys.exists(dst)) {
-        destFileSys.delete(dst, true);
-      }
-      destFileSys.rename(tmp, dst);
-    } catch (IOException ioe) {
-      throw new IOException("Fail to rename tmp file (=" + tmp
-          + ") to destination file (=" + dst + ")", ioe);
-    }
-  }
-
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
index d6b3ba8..e1873f1 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/CopyMapper.java
@@ -156,12 +156,10 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         sourceFS = sourcePath.getFileSystem(conf);
         final boolean preserveXAttrs =
             fileAttributes.contains(FileAttribute.XATTR);
-        sourceCurrStatus = DistCpUtils.toCopyListingFileStatusHelper(sourceFS,
-            sourceFS.getFileStatus(sourcePath),
-            fileAttributes.contains(FileAttribute.ACL),
-            preserveXAttrs, preserveRawXattrs,
-            sourceFileStatus.getChunkOffset(),
-            sourceFileStatus.getChunkLength());
+        sourceCurrStatus = DistCpUtils.toCopyListingFileStatus(sourceFS,
+          sourceFS.getFileStatus(sourcePath),
+          fileAttributes.contains(FileAttribute.ACL), 
+          preserveXAttrs, preserveRawXattrs);
       } catch (FileNotFoundException e) {
         throw new IOException(new RetriableFileCopyCommand.CopyReadException(e));
       }
@@ -175,8 +173,7 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
           LOG.debug("Path could not be found: " + target, ignore);
       }
 
-      if (targetStatus != null &&
-          (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
+      if (targetStatus != null && (targetStatus.isDirectory() != sourceCurrStatus.isDirectory())) {
         throw new IOException("Can't replace " + target + ". Target is " +
             getFileType(targetStatus) + ", Source is " + getFileType(sourceCurrStatus));
       }
@@ -186,28 +183,19 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
         return;
       }
 
-      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target,
-          targetStatus);
-
-      Path tmpTarget = target;
+      FileAction action = checkUpdate(sourceFS, sourceCurrStatus, target, targetStatus);
       if (action == FileAction.SKIP) {
         LOG.info("Skipping copy of " + sourceCurrStatus.getPath()
                  + " to " + target);
         updateSkipCounters(context, sourceCurrStatus);
         context.write(null, new Text("SKIP: " + sourceCurrStatus.getPath()));
-
       } else {
-        if (sourceCurrStatus.isSplit()) {
-          tmpTarget = DistCpUtils.getSplitChunkPath(target, sourceCurrStatus);
-        }
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("copying " + sourceCurrStatus + " " + tmpTarget);
-        }
-        copyFileWithRetry(description, sourceCurrStatus, tmpTarget, context,
+        copyFileWithRetry(description, sourceCurrStatus, target, context,
             action, fileAttributes);
       }
-      DistCpUtils.preserve(target.getFileSystem(conf), tmpTarget,
-          sourceCurrStatus, fileAttributes, preserveRawXattrs);
+
+      DistCpUtils.preserve(target.getFileSystem(conf), target, sourceCurrStatus,
+          fileAttributes, preserveRawXattrs);
     } catch (IOException exception) {
       handleFailures(exception, sourceFileStatus, target, context);
     }
@@ -273,12 +261,8 @@ public class CopyMapper extends Mapper<Text, CopyListingFileStatus, Text, Text>
   private void handleFailures(IOException exception,
       CopyListingFileStatus sourceFileStatus, Path target, Context context)
       throws IOException, InterruptedException {
-    LOG.error("Failure in copying " + sourceFileStatus.getPath() +
-        (sourceFileStatus.isSplit()? ","
-            + " offset=" + sourceFileStatus.getChunkOffset()
-            + " chunkLength=" + sourceFileStatus.getChunkLength()
-            : "") +
-        " to " + target, exception);
+    LOG.error("Failure in copying " + sourceFileStatus.getPath() + " to " +
+                target, exception);
 
     if (ignoreFailures &&
         ExceptionUtils.indexOfType(exception, CopyReadException.class) != -1) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
index 2c17fef..06acd78 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
@@ -118,21 +118,17 @@ public class RetriableFileCopyCommand extends RetriableCommand {
           .contains(FileAttribute.CHECKSUMTYPE) ? sourceFS
           .getFileChecksum(sourcePath) : null;
 
-      long offset = (action == FileAction.APPEND) ?
-          targetFS.getFileStatus(target).getLen() : source.getChunkOffset();
+      final long offset = action == FileAction.APPEND ? targetFS.getFileStatus(
+          target).getLen() : 0;
       long bytesRead = copyToFile(targetPath, targetFS, source,
           offset, context, fileAttributes, sourceChecksum);
 
-      if (!source.isSplit()) {
-        compareFileLengths(source, targetPath, configuration, bytesRead
-            + offset);
-      }
+      compareFileLengths(source, targetPath, configuration, bytesRead
+          + offset);
       //At this point, src&dest lengths are same. if length==0, we skip checksum
       if ((bytesRead != 0) && (!skipCrc)) {
-        if (!source.isSplit()) {
-          compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
-              targetFS, targetPath);
-        }
+        compareCheckSums(sourceFS, source.getPath(), sourceChecksum,
+            targetFS, targetPath);
       }
       // it's not append case, thus we first write to a temporary file, rename
       // it to the target path.
@@ -253,26 +249,16 @@ public class RetriableFileCopyCommand extends RetriableCommand {
     ThrottledInputStream inStream = null;
     long totalBytesRead = 0;
 
-    long chunkLength = source2.getChunkLength();
-    boolean finished = false;
     try {
       inStream = getInputStream(source, context.getConfiguration());
       int bytesRead = readBytes(inStream, buf, sourceOffset);
       while (bytesRead >= 0) {
-        if (chunkLength > 0 &&
-            (totalBytesRead + bytesRead) >= chunkLength) {
-          bytesRead = (int)(chunkLength - totalBytesRead);
-          finished = true;
-        }
         totalBytesRead += bytesRead;
         if (action == FileAction.APPEND) {
           sourceOffset += bytesRead;
         }
         outStream.write(buf, 0, bytesRead);
         updateContextStatus(totalBytesRead, context, source2);
-        if (finished) {
-          break;
-        }
         bytesRead = readBytes(inStream, buf, sourceOffset);
       }
       outStream.close();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
index d1c18ea..3e86d09 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/UniformSizeInputFormat.java
@@ -99,8 +99,7 @@ public class UniformSizeInputFormat
       while (reader.next(srcRelPath, srcFileStatus)) {
         // If adding the current file would cause the bytes per map to exceed
         // limit. Add the current file to new split
-        if (currentSplitSize + srcFileStatus.getChunkLength() > nBytesPerSplit
-            && lastPosition != 0) {
+        if (currentSplitSize + srcFileStatus.getLen() > nBytesPerSplit && lastPosition != 0) {
           FileSplit split = new FileSplit(listingFilePath, lastSplitStart,
               lastPosition - lastSplitStart, null);
           if (LOG.isDebugEnabled()) {
@@ -110,7 +109,7 @@ public class UniformSizeInputFormat
           lastSplitStart = lastPosition;
           currentSplitSize = 0;
         }
-        currentSplitSize += srcFileStatus.getChunkLength();
+        currentSplitSize += srcFileStatus.getLen();
         lastPosition = reader.getPosition();
       }
       if (lastPosition > lastSplitStart) {

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
index e315b84..76bc4c5 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/util/DistCpUtils.java
@@ -19,11 +19,9 @@
 package org.apache.hadoop.tools.util;
 
 import com.google.common.collect.Maps;
-
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.BlockLocation;
 import org.apache.hadoop.fs.FileChecksum;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
@@ -32,7 +30,6 @@ import org.apache.hadoop.fs.XAttr;
 import org.apache.hadoop.fs.permission.AclEntry;
 import org.apache.hadoop.fs.permission.AclUtil;
 import org.apache.hadoop.fs.permission.FsPermission;
-import org.apache.hadoop.hdfs.DistributedFileSystem;
 import org.apache.hadoop.io.SequenceFile;
 import org.apache.hadoop.io.Text;
 import org.apache.hadoop.mapreduce.InputFormat;
@@ -47,7 +44,6 @@ import org.apache.hadoop.util.StringUtils;
 import java.io.IOException;
 import java.text.DecimalFormat;
 import java.util.EnumSet;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -120,7 +116,7 @@ public class DistCpUtils {
    * @return Class implementing the strategy specified in options.
    */
   public static Class<? extends InputFormat> getStrategy(Configuration conf,
-      DistCpOptions options) {
+                                                                 DistCpOptions options) {
     String confLabel = "distcp."
         + StringUtils.toLowerCase(options.getCopyStrategy())
         + ".strategy" + ".impl";
@@ -302,86 +298,6 @@ public class DistCpUtils {
   }
 
   /**
-   * Converts FileStatus to a list of CopyListingFileStatus.
-   * The resulted list contains either one CopyListingFileStatus per chunk of
-   * file-blocks (if file-size exceeds blockSize * blocksPerChunk, and there
-   * are more blocks in the file than blocksperChunk), or a single
-   * CopyListingFileStatus for the entire file (if file-size is too small to
-   * split).
-   * If preserving ACLs, populates the CopyListingFileStatus with the ACLs.
-   * If preserving XAttrs, populates the CopyListingFileStatus with the XAttrs.
-   *
-   * @param fileSystem FileSystem containing the file
-   * @param fileStatus FileStatus of file
-   * @param preserveAcls boolean true if preserving ACLs
-   * @param preserveXAttrs boolean true if preserving XAttrs
-   * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
-   * @param blocksPerChunk size of chunks when copying chunks in parallel
-   * @return list of CopyListingFileStatus
-   * @throws IOException if there is an I/O error
-   */
-  public static LinkedList<CopyListingFileStatus> toCopyListingFileStatus(
-      FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls,
-      boolean preserveXAttrs, boolean preserveRawXAttrs, int blocksPerChunk)
-          throws IOException {
-    LinkedList<CopyListingFileStatus> copyListingFileStatus =
-        new LinkedList<CopyListingFileStatus>();
-
-    final CopyListingFileStatus clfs = toCopyListingFileStatusHelper(
-        fileSystem, fileStatus, preserveAcls,
-        preserveXAttrs, preserveRawXAttrs,
-        0, fileStatus.getLen());
-    final long blockSize = fileStatus.getBlockSize();
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("toCopyListing: " + fileStatus + " chunkSize: "
-          + blocksPerChunk + " isDFS: " +
-          (fileSystem instanceof DistributedFileSystem));
-    }
-    if ((blocksPerChunk > 0) &&
-        !fileStatus.isDirectory() &&
-        (fileStatus.getLen() > blockSize * blocksPerChunk)) {
-      // split only when the file size is larger than the intended chunk size
-      final BlockLocation[] blockLocations;
-      blockLocations = fileSystem.getFileBlockLocations(fileStatus, 0,
-            fileStatus.getLen());
-
-      int numBlocks = blockLocations.length;
-      long curPos = 0;
-      if (numBlocks <= blocksPerChunk) {
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("  add file " + clfs);
-        }
-        copyListingFileStatus.add(clfs);
-      } else {
-        int i = 0;
-        while (i < numBlocks) {
-          long curLength = 0;
-          for (int j = 0; j < blocksPerChunk && i < numBlocks; ++j, ++i) {
-            curLength += blockLocations[i].getLength();
-          }
-          if (curLength > 0) {
-            CopyListingFileStatus clfs1 = new CopyListingFileStatus(clfs);
-            clfs1.setChunkOffset(curPos);
-            clfs1.setChunkLength(curLength);
-            if (LOG.isDebugEnabled()) {
-              LOG.debug("  add file chunk " + clfs1);
-            }
-            copyListingFileStatus.add(clfs1);
-            curPos += curLength;
-          }
-        }
-      }
-    } else {
-      if (LOG.isDebugEnabled()) {
-        LOG.debug("  add file/dir " + clfs);
-      }
-      copyListingFileStatus.add(clfs);
-    }
-
-    return copyListingFileStatus;
-  }
-
-  /**
    * Converts a FileStatus to a CopyListingFileStatus.  If preserving ACLs,
    * populates the CopyListingFileStatus with the ACLs. If preserving XAttrs,
    * populates the CopyListingFileStatus with the XAttrs.
@@ -391,17 +307,13 @@ public class DistCpUtils {
    * @param preserveAcls boolean true if preserving ACLs
    * @param preserveXAttrs boolean true if preserving XAttrs
    * @param preserveRawXAttrs boolean true if preserving raw.* XAttrs
-   * @param chunkOffset chunk offset in bytes
-   * @param chunkLength chunk length in bytes
-   * @return CopyListingFileStatus
    * @throws IOException if there is an I/O error
    */
-  public static CopyListingFileStatus toCopyListingFileStatusHelper(
+  public static CopyListingFileStatus toCopyListingFileStatus(
       FileSystem fileSystem, FileStatus fileStatus, boolean preserveAcls, 
-      boolean preserveXAttrs, boolean preserveRawXAttrs,
-      long chunkOffset, long chunkLength) throws IOException {
+      boolean preserveXAttrs, boolean preserveRawXAttrs) throws IOException {
     CopyListingFileStatus copyListingFileStatus =
-        new CopyListingFileStatus(fileStatus, chunkOffset, chunkLength);
+      new CopyListingFileStatus(fileStatus);
     if (preserveAcls) {
       FsPermission perm = fileStatus.getPermission();
       if (perm.getAclBit()) {
@@ -558,19 +470,4 @@ public class DistCpUtils {
     return (sourceChecksum == null || targetChecksum == null ||
             sourceChecksum.equals(targetChecksum));
   }
-
-  /*
-   * Return the Path for a given chunk.
-   * Used when splitting large file into chunks to copy in parallel.
-   * @param targetFile path to target file
-   * @param srcFileStatus source file status in copy listing
-   * @return path to the chunk specified by the parameters to store
-   * in target cluster temporarily
-   */
-  public static Path getSplitChunkPath(Path targetFile,
-      CopyListingFileStatus srcFileStatus) {
-    return new Path(targetFile.toString()
-        + ".____distcpSplit____" + srcFileStatus.getChunkOffset()
-        + "." + srcFileStatus.getChunkLength());
-  }
 }

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
index a77deb2..41a6e94 100644
--- a/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
+++ b/hadoop-tools/hadoop-distcp/src/site/markdown/DistCp.md.vm
@@ -237,7 +237,6 @@ Flag              | Description                          | Notes
 `-rdiff <newSnapshot> <oldSnapshot>` | Use snapshot diff report between given two snapshots to identify what has been changed on the target since the snapshot `<oldSnapshot>` was created on the target, and apply the diff reversely to the target, and copy modified files from the source's `<oldSnapshot>`, to make the target the same as `<oldSnapshot>`. | This option is valid only with `-update` option and the following conditions should be satisfied. <ol><li>Both the source and the target FileSystem must be DistributedFileSystem. The source and the target can be two different clusters/paths, or they can be exactly the same cluster/path. In the latter case, modified files are copied from target's `<oldSnapshot>` to target's current state).</li>  <li> Two snapshots `<newSnapshot>` and `<oldSnapshot>` have been created on the target FS, and `<oldSnapshot>` is older than `<newSnapshot>`. No change has been made on target since `<newSnapshot>` was created on the target. </li> <li> The sour
 ce has the same snapshot `<oldSnapshot>`, which has the same content as the `<oldSnapshot>` on the target. All the files/directories in the target's `<oldSnapshot>` are the same with source's `<oldSnapshot>`.</li> </ol> |
 `-numListstatusThreads` | Number of threads to use for building file listing | At most 40 threads.
 `-skipcrccheck` | Whether to skip CRC checks between source and target paths. |
-`-blocksperchunk <blocksperchunk>` | Number of blocks per chunk. When specified, split files into chunks to copy in parallel | If set to a positive value, files with more blocks than this value will be split into chunks of `<blocksperchunk>` blocks to be transferred in parallel, and reassembled on the destination. By default, `<blocksperchunk>` is 0 and the files will be transmitted in their entirety without splitting. This switch is only applicable when the source file system implements getBlockLocations method and the target file system implements concat method. |
 
 Architecture of DistCp
 ----------------------

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
index b2266b3..e3018a0 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/TestDistCpSystem.java
@@ -23,27 +23,17 @@ import static org.hamcrest.core.Is.is;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
-import java.io.ByteArrayOutputStream;
 import java.io.IOException;
-import java.io.PrintStream;
+import java.io.OutputStream;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Random;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
 import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataInputStream;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.FsShell;
 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.MiniDFSCluster;
-import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys;
 import org.apache.hadoop.util.ToolRunner;
 import org.junit.AfterClass;
 import org.junit.Assert;
@@ -57,15 +47,11 @@ import org.junit.rules.Timeout;
  */
 
 public class TestDistCpSystem {
-  private static final Log LOG =
-      LogFactory.getLog(TestDistCpSystem.class);
-
   @Rule
   public Timeout globalTimeout = new Timeout(30000);
 
   private static final String SRCDAT = "srcdat";
   private static final String DSTDAT = "dstdat";
-  private static final long BLOCK_SIZE = 1024;
 
   private static MiniDFSCluster cluster;
   private static Configuration conf;
@@ -77,76 +63,27 @@ public class TestDistCpSystem {
       this.path = path;
       this.isDir = isDir;
     }
-
-    String getPath() {
-      return path;
-    }
-
-    boolean isDirectory() {
-      return isDir;
-    }
-  }
-
-  @BeforeClass
-  public static void beforeClass() throws IOException {
-    conf = new Configuration();
-    conf.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, BLOCK_SIZE);
-    conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
-    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
-    cluster.waitActive();
-  }
-
-  @AfterClass
-  public static void afterClass() throws IOException {
-    if (cluster != null) {
-      cluster.shutdown();
-    }
-  }
-
-  static String execCmd(FsShell shell, String... args) throws Exception {
-    ByteArrayOutputStream baout = new ByteArrayOutputStream();
-    PrintStream out = new PrintStream(baout, true);
-    PrintStream old = System.out;
-    System.setOut(out);
-    shell.run(args);
-    out.close();
-    System.setOut(old);
-    return baout.toString();
+    String getPath() { return path; }
+    boolean isDirectory() { return isDir; }
   }
   
-  private void createFiles(DistributedFileSystem fs, String topdir,
-      FileEntry[] entries, long chunkSize) throws IOException {
-    long seed = System.currentTimeMillis();
-    Random rand = new Random(seed);
-    short replicationFactor = 2;
+  private void createFiles(FileSystem fs, String topdir,
+      FileEntry[] entries) throws IOException {
     for (FileEntry entry : entries) {
-      Path newPath = new Path(topdir + "/" + entry.getPath());
+      Path newpath = new Path(topdir + "/" + entry.getPath());
       if (entry.isDirectory()) {
-        fs.mkdirs(newPath);
+        fs.mkdirs(newpath);
       } else {
-        long fileSize = BLOCK_SIZE *100;
-        int bufSize = 128;
-        if (chunkSize == -1) {
-          DFSTestUtil.createFile(fs, newPath, bufSize,
-              fileSize, BLOCK_SIZE, replicationFactor, seed);
-        } else {
-          // Create a variable length block file, by creating
-          // one block of half block size at the chunk boundary
-          long seg1 = chunkSize * BLOCK_SIZE - BLOCK_SIZE / 2;
-          long seg2 = fileSize - seg1;
-          DFSTestUtil.createFile(fs, newPath, bufSize,
-              seg1, BLOCK_SIZE, replicationFactor, seed);
-          DFSTestUtil.appendFileNewBlock(fs, newPath, (int)seg2);
+        OutputStream out = fs.create(newpath);
+        try {
+          out.write((topdir + "/" + entry).getBytes());
+          out.write("\n".getBytes());
+        } finally {
+          out.close();
         }
       }
-      seed = System.currentTimeMillis() + rand.nextLong();
     }
   }
-
-  private void createFiles(DistributedFileSystem fs, String topdir,
-      FileEntry[] entries) throws IOException {
-    createFiles(fs, topdir, entries, -1);
-  }
    
   private static FileStatus[] getFileStatus(FileSystem fs,
       String topdir, FileEntry[] files) throws IOException {
@@ -167,19 +104,18 @@ public class TestDistCpSystem {
   }
 
   private void testPreserveUserHelper(String testRoot,
-      FileEntry[] srcEntries,
-      FileEntry[] dstEntries,
-      boolean createSrcDir,
-      boolean createTgtDir,
-      boolean update) throws Exception {
+                                      FileEntry[] srcEntries,
+                                      FileEntry[] dstEntries,
+                                      boolean createSrcDir,
+                                      boolean createTgtDir,
+                                      boolean update) throws Exception {
     final String testSrcRel = SRCDAT;
     final String testSrc = testRoot + "/" + testSrcRel;
     final String testDstRel = DSTDAT;
     final String testDst = testRoot + "/" + testDstRel;
 
     String nnUri = FileSystem.getDefaultUri(conf).toString();
-    DistributedFileSystem fs = (DistributedFileSystem)
-        FileSystem.get(URI.create(nnUri), conf);
+    FileSystem fs = FileSystem.get(URI.create(nnUri), conf);
     fs.mkdirs(new Path(testRoot));
     if (createSrcDir) {
       fs.mkdirs(new Path(testSrc));
@@ -193,8 +129,8 @@ public class TestDistCpSystem {
     for(int i = 0; i < srcEntries.length; i++) {
       fs.setOwner(srcstats[i].getPath(), "u" + i, null);
     }
-    String[] args = update? new String[]{"-pub", "-update", nnUri+testSrc,
-        nnUri+testDst} : new String[]{"-pub", nnUri+testSrc, nnUri+testDst};
+    String[] args = update? new String[]{"-pu", "-update", nnUri+testSrc,
+        nnUri+testDst} : new String[]{"-pu", nnUri+testSrc, nnUri+testDst};
 
     ToolRunner.run(conf, new DistCp(), args);
 
@@ -209,261 +145,18 @@ public class TestDistCpSystem {
     deldir(fs, testRoot);
   }
 
-  private void compareFiles(FileSystem fs, FileStatus srcStat,
-      FileStatus dstStat) throws Exception {
-    LOG.info("Comparing " + srcStat + " and " + dstStat);
-    assertEquals(srcStat.isDirectory(), dstStat.isDirectory());
-    assertEquals(srcStat.getReplication(), dstStat.getReplication());
-    assertEquals("File POSIX permission should match",
-        srcStat.getPermission(), dstStat.getPermission());
-    assertEquals("File user ownership should match",
-        srcStat.getOwner(), dstStat.getOwner());
-    assertEquals("File group ownership should match",
-        srcStat.getGroup(), dstStat.getGroup());
-    // TODO; check ACL attributes
-
-    if (srcStat.isDirectory()) {
-      return;
-    }
-
-    assertEquals("File length should match (" + srcStat.getPath() + ")",
-        srcStat.getLen(), dstStat.getLen());
-
-    FSDataInputStream srcIn = fs.open(srcStat.getPath());
-    FSDataInputStream dstIn = fs.open(dstStat.getPath());
-    try {
-      byte[] readSrc = new byte[(int)
-                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
-      byte[] readDst = new byte[(int)
-                                HdfsClientConfigKeys.DFS_BLOCK_SIZE_DEFAULT];
-
-      int srcBytesRead = 0, tgtBytesRead = 0;
-      int srcIdx = 0, tgtIdx = 0;
-      long totalComparedBytes = 0;
-      while (true) {
-        if (srcBytesRead == 0) {
-          srcBytesRead = srcIn.read(readSrc);
-          srcIdx = 0;
-        }
-        if (tgtBytesRead == 0) {
-          tgtBytesRead = dstIn.read(readDst);
-          tgtIdx = 0;
-        }
-        if (srcBytesRead == 0 || tgtBytesRead == 0) {
-          LOG.info("______ compared src and dst files for "
-              + totalComparedBytes + " bytes, content match.");
-          if (srcBytesRead != tgtBytesRead) {
-            Assert.fail("Read mismatching size, compared "
-                + totalComparedBytes + " bytes between src and dst file "
-                + srcStat + " and " + dstStat);
-          }
-          if (totalComparedBytes != srcStat.getLen()) {
-            Assert.fail("Only read/compared " + totalComparedBytes +
-                " bytes between src and dst file " + srcStat +
-                " and " + dstStat);
-          } else {
-            // success
-            break;
-          }
-        }
-        for (; srcIdx < srcBytesRead && tgtIdx < tgtBytesRead;
-            ++srcIdx, ++tgtIdx) {
-          if (readSrc[srcIdx] != readDst[tgtIdx]) {
-            Assert.fail("src and dst file does not match at "
-                + totalComparedBytes + " between "
-                + srcStat + " and " + dstStat);
-          }
-          ++totalComparedBytes;
-        }
-        LOG.info("______ compared src and dst files for "
-            + totalComparedBytes + " bytes, content match. FileLength: "
-            + srcStat.getLen());
-        if (totalComparedBytes == srcStat.getLen()) {
-          LOG.info("______ Final:" + srcIdx + " "
-              + srcBytesRead + " " + tgtIdx + " " + tgtBytesRead);
-          break;
-        }
-        if (srcIdx == srcBytesRead) {
-          srcBytesRead = 0;
-        }
-        if (tgtIdx == tgtBytesRead) {
-          tgtBytesRead = 0;
-        }
-      }
-    } finally {
-      if (srcIn != null) {
-        srcIn.close();
-      }
-      if (dstIn != null) {
-        dstIn.close();
-      }
-    }
-  }
-
-  // WC: needed because the current distcp does not create target dirs
-  private void createDestDir(FileSystem fs, String testDst,
-      FileStatus[] srcStats, FileEntry[] srcFiles) throws IOException {
-    fs.mkdirs(new Path(testDst));
-
-    for (int i=0; i<srcStats.length; i++) {
-      FileStatus srcStat = srcStats[i];
-      if (srcStat.isDirectory()) {
-        Path dstPath = new Path(testDst, srcFiles[i].getPath());
-        fs.mkdirs(dstPath);
-        fs.setOwner(dstPath, srcStat.getOwner(), srcStat.getGroup());
-      }
-    }
-  }
-
-  private void copyAndVerify(final DistributedFileSystem fs,
-      final FileEntry[] srcFiles, final FileStatus[] srcStats,
-      final String testDst,
-      final String[] args) throws Exception {
-    final String testRoot = "/testdir";
-    FsShell shell = new FsShell(fs.getConf());
-
-    LOG.info("ls before distcp");
-    LOG.info(execCmd(shell, "-lsr", testRoot));
-
-    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
-    ToolRunner.run(conf, new DistCp(), args);
-
-    LOG.info("ls after distcp");
-    LOG.info(execCmd(shell, "-lsr", testRoot));
-
-    FileStatus[] dstStat = getFileStatus(fs, testDst, srcFiles);
-    for (int i=0; i< dstStat.length; i++) {
-      compareFiles(fs, srcStats[i], dstStat[i]);
-    }
-  }
-
-  private void chunkCopy(FileEntry[] srcFiles) throws Exception {
-    final String testRoot = "/testdir";
-    final String testSrcRel = SRCDAT;
-    final String testSrc = testRoot + "/" + testSrcRel;
-    final String testDstRel = DSTDAT;
-    final String testDst = testRoot + "/" + testDstRel;
-    long chunkSize = 8;
-
-    String nnUri = FileSystem.getDefaultUri(conf).toString();
-    DistributedFileSystem fs = (DistributedFileSystem)
-        FileSystem.get(URI.create(nnUri), conf);
-
-    createFiles(fs, testRoot, srcFiles, chunkSize);
-
-    FileStatus[] srcStats = getFileStatus(fs, testRoot, srcFiles);
-    for (int i = 0; i < srcFiles.length; i++) {
-      fs.setOwner(srcStats[i].getPath(), "u" + i,  "g" + i);
-    }
-    // get file status after updating owners
-    srcStats = getFileStatus(fs, testRoot, srcFiles);
-
-    createDestDir(fs, testDst, srcStats, srcFiles);
-
-    String[] args = new String[] {"-pugp", "-blocksperchunk",
-        String.valueOf(chunkSize),
-        nnUri + testSrc, nnUri + testDst};
-
-    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
-    // Do it again
-    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
-
-    // modify last file and rerun distcp with -update option
-    LOG.info("Modify a file and copy again");
-    for(int i=srcFiles.length-1; i >=0; --i) {
-      if (!srcFiles[i].isDirectory()) {
-        LOG.info("Modifying " + srcStats[i].getPath());
-        DFSTestUtil.appendFileNewBlock(fs, srcStats[i].getPath(),
-            (int)BLOCK_SIZE * 3);
-        break;
-      }
-    }
-    // get file status after modifying file
-    srcStats = getFileStatus(fs, testRoot, srcFiles);
-
-    args = new String[] {"-pugp", "-update", "-blocksperchunk",
-        String.valueOf(chunkSize),
-        nnUri + testSrc, nnUri + testDst + "/" + testSrcRel};
-
-    copyAndVerify(fs, srcFiles, srcStats, testDst, args);
-
-    deldir(fs, testRoot);
-  }
-
-  @Test
-  public void testRecursiveChunkCopy() throws Exception {
-    FileEntry[] srcFiles = {
-        new FileEntry(SRCDAT, true),
-        new FileEntry(SRCDAT + "/file0", false),
-        new FileEntry(SRCDAT + "/dir1", true),
-        new FileEntry(SRCDAT + "/dir2", true),
-        new FileEntry(SRCDAT + "/dir1/file1", false)
-    };
-    chunkCopy(srcFiles);
-  }
-
-  @Test
-  public void testChunkCopyOneFile() throws Exception {
-    FileEntry[] srcFiles = {
-        new FileEntry(SRCDAT, true),
-        new FileEntry(SRCDAT + "/file0", false)
-    };
-    chunkCopy(srcFiles);
+  @BeforeClass
+  public static void beforeClass() throws IOException {
+    conf = new Configuration();
+    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
+    cluster.waitActive();
   }
 
-  @Test
-  public void testDistcpLargeFile() throws Exception {
-    FileEntry[] srcfiles = {
-        new FileEntry(SRCDAT, true),
-        new FileEntry(SRCDAT + "/file", false)
-    };
-
-    final String testRoot = "/testdir";
-    final String testSrcRel = SRCDAT;
-    final String testSrc = testRoot + "/" + testSrcRel;
-    final String testDstRel = DSTDAT;
-    final String testDst = testRoot + "/" + testDstRel;
-
-    String nnUri = FileSystem.getDefaultUri(conf).toString();
-    DistributedFileSystem fs =
-        (DistributedFileSystem) FileSystem.get(URI.create(nnUri), conf);
-    fs.mkdirs(new Path(testRoot));
-    fs.mkdirs(new Path(testSrc));
-    fs.mkdirs(new Path(testDst));
-    long chunkSize = 6;
-    createFiles(fs, testRoot, srcfiles, chunkSize);
-
-    String srcFileName = testRoot + Path.SEPARATOR + srcfiles[1].getPath();
-    Path srcfile = new Path(srcFileName);
-
-    if(!cluster.getFileSystem().exists(srcfile)){
-      throw new Exception("src not exist");
-    }
-
-    final long srcLen = fs.getFileStatus(srcfile).getLen();
-
-    FileStatus[] srcstats = getFileStatus(fs, testRoot, srcfiles);
-    for (int i = 0; i < srcfiles.length; i++) {
-      fs.setOwner(srcstats[i].getPath(), "u" + i, null);
+  @AfterClass
+  public static void afterClass() throws IOException {
+    if (cluster != null) {
+      cluster.shutdown();
     }
-    String[] args = new String[] {
-        "-blocksperchunk",
-        String.valueOf(chunkSize),
-        nnUri + testSrc,
-        nnUri + testDst
-    };
-
-    LOG.info("_____ running distcp: " + args[0] + " " + args[1]);
-    ToolRunner.run(conf, new DistCp(), args);
-
-    String realTgtPath = testDst;
-    FileStatus[] dststat = getFileStatus(fs, realTgtPath, srcfiles);
-    assertEquals("File length should match", srcLen,
-        dststat[dststat.length - 1].getLen());
-
-    this.compareFiles(fs,  srcstats[srcstats.length-1],
-        dststat[dststat.length-1]);
-    deldir(fs, testRoot);
   }
 
   @Test
@@ -487,6 +180,7 @@ public class TestDistCpSystem {
     testPreserveUserHelper(testRoot, srcfiles, dstfiles, false, false, false);
   }
 
+
   @Test
   public void testPreserveUserEmptyDir() throws Exception {
     String testRoot = "/testdir." + getMethodName();

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/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 f94ba97..efe4627 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
@@ -394,7 +394,7 @@ public class TestOptionsParser {
         + "copyStrategy='uniformsize', preserveStatus=[], "
         + "preserveRawXattrs=false, atomicWorkPath=null, logPath=null, "
         + "sourceFileListing=abc, sourcePaths=null, targetPath=xyz, "
-        + "targetPathExists=true, filtersFile='null', blocksPerChunk=0}";
+        + "targetPathExists=true, filtersFile='null'}";
     String optionString = option.toString();
     Assert.assertEquals(val, optionString);
     Assert.assertNotSame(DistCpOptionSwitch.ATOMIC_COMMIT.toString(),

http://git-wip-us.apache.org/repos/asf/hadoop/blob/0ca98cbb/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
index 2452d6f..2e9a350 100644
--- a/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
+++ b/hadoop-tools/hadoop-distcp/src/test/java/org/apache/hadoop/tools/mapred/TestCopyCommitter.java
@@ -81,10 +81,6 @@ public class TestCopyCommitter {
   @Before
   public void createMetaFolder() {
     config.set(DistCpConstants.CONF_LABEL_META_FOLDER, "/meta");
-    // Unset listing file path since the config is shared by
-    // multiple tests, and some test doesn't set it, such as
-    // testNoCommitAction, but the distcp code will check it.
-    config.set(DistCpConstants.CONF_LABEL_LISTING_FILE_PATH, "");
     Path meta = new Path("/meta");
     try {
       cluster.getFileSystem().mkdirs(meta);
@@ -330,6 +326,7 @@ public class TestCopyCommitter {
       committer.commitJob(jobContext);
       Assert.assertFalse(fs.exists(new Path(workPath)));
       Assert.assertTrue(fs.exists(new Path(finalPath)));
+
     } catch (IOException e) {
       LOG.error("Exception encountered while testing for preserve status", e);
       Assert.fail("Atomic commit failure");


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[26/50] [abbrv] hadoop git commit: HADOOP-14280. Fix compilation of TestKafkaMetrics.

Posted by in...@apache.org.
HADOOP-14280. Fix compilation of TestKafkaMetrics.


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

Branch: refs/heads/HDFS-10467
Commit: 26f5552f0b6e8a01fd77942c641a9a1cc3be60ae
Parents: 04ef448
Author: Andrew Wang <wa...@apache.org>
Authored: Wed Apr 5 15:12:03 2017 -0700
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 hadoop-tools/hadoop-kafka/pom.xml               | 26 --------------------
 .../hadoop/metrics2/impl/TestKafkaMetrics.java  |  4 +--
 2 files changed, 2 insertions(+), 28 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/26f5552f/hadoop-tools/hadoop-kafka/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-kafka/pom.xml b/hadoop-tools/hadoop-kafka/pom.xml
index 06c38f7..13e0ac0 100644
--- a/hadoop-tools/hadoop-kafka/pom.xml
+++ b/hadoop-tools/hadoop-kafka/pom.xml
@@ -36,32 +36,6 @@
     <downloadSources>true</downloadSources>
   </properties>
 
-  <profiles>
-    <profile>
-      <id>tests-off</id>
-      <activation>
-        <file>
-          <missing>src/test/resources/auth-keys.xml</missing>
-        </file>
-      </activation>
-      <properties>
-        <maven.test.skip>true</maven.test.skip>
-      </properties>
-    </profile>
-    <profile>
-      <id>tests-on</id>
-      <activation>
-        <file>
-          <exists>src/test/resources/auth-keys.xml</exists>
-        </file>
-      </activation>
-      <properties>
-        <maven.test.skip>false</maven.test.skip>
-      </properties>
-    </profile>
-
-  </profiles>
-
   <build>
     <plugins>
       <plugin>

http://git-wip-us.apache.org/repos/asf/hadoop/blob/26f5552f/hadoop-tools/hadoop-kafka/src/test/java/org/apache/hadoop/metrics2/impl/TestKafkaMetrics.java
----------------------------------------------------------------------
diff --git a/hadoop-tools/hadoop-kafka/src/test/java/org/apache/hadoop/metrics2/impl/TestKafkaMetrics.java b/hadoop-tools/hadoop-kafka/src/test/java/org/apache/hadoop/metrics2/impl/TestKafkaMetrics.java
index eff1afa..8479298 100644
--- a/hadoop-tools/hadoop-kafka/src/test/java/org/apache/hadoop/metrics2/impl/TestKafkaMetrics.java
+++ b/hadoop-tools/hadoop-kafka/src/test/java/org/apache/hadoop/metrics2/impl/TestKafkaMetrics.java
@@ -18,7 +18,7 @@
 
 package org.apache.hadoop.metrics2.impl;
 
-import com.google.common.base.Objects;
+import com.google.common.base.MoreObjects;
 import com.google.common.collect.Lists;
 import org.apache.commons.configuration2.SubsetConfiguration;
 import org.apache.hadoop.metrics2.AbstractMetric;
@@ -74,7 +74,7 @@ public class TestKafkaMetrics {
 
     @Override
     public String toString() {
-      return Objects.toStringHelper(this).add("name", name())
+      return MoreObjects.toStringHelper(this).add("name", name())
           .add("description", desc).toString();
     }
   }


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org


[27/50] [abbrv] hadoop git commit: HDFS-9651. All web UIs should include a robots.txt file. Contributed by Lars Francke.

Posted by in...@apache.org.
HDFS-9651. All web UIs should include a robots.txt file. Contributed by Lars Francke.


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

Branch: refs/heads/HDFS-10467
Commit: 69e0934fc7310de92279490ba5b3b7687187ddad
Parents: bf4ed74
Author: Akira Ajisaka <aa...@apache.org>
Authored: Wed Apr 5 12:45:28 2017 +0900
Committer: Inigo <in...@apache.org>
Committed: Thu Apr 6 18:58:22 2017 -0700

----------------------------------------------------------------------
 hadoop-hdfs-project/hadoop-hdfs/pom.xml | 3 +++
 1 file changed, 3 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hadoop/blob/69e0934f/hadoop-hdfs-project/hadoop-hdfs/pom.xml
----------------------------------------------------------------------
diff --git a/hadoop-hdfs-project/hadoop-hdfs/pom.xml b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
index 9e59a31..65c3943 100644
--- a/hadoop-hdfs-project/hadoop-hdfs/pom.xml
+++ b/hadoop-hdfs-project/hadoop-hdfs/pom.xml
@@ -386,6 +386,9 @@ http://maven.apache.org/xsd/maven-4.0.0.xsd">
             <exclude>src/test/resources/editsStored*</exclude>
             <exclude>src/test/resources/empty-file</exclude>
             <exclude>src/main/webapps/datanode/robots.txt</exclude>
+            <exclude>src/main/webapps/hdfs/robots.txt</exclude>
+            <exclude>src/main/webapps/journal/robots.txt</exclude>
+            <exclude>src/main/webapps/secondary/robots.txt</exclude>
             <exclude>src/contrib/**</exclude>
             <exclude>src/site/resources/images/*</exclude>
             <exclude>src/main/webapps/static/bootstrap-3.0.2/**</exclude>


---------------------------------------------------------------------
To unsubscribe, e-mail: common-commits-unsubscribe@hadoop.apache.org
For additional commands, e-mail: common-commits-help@hadoop.apache.org