001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hdfs.server.balancer;
019
020import static org.apache.hadoop.hdfs.protocolPB.PBHelper.vintPrefixed;
021
022import java.io.BufferedInputStream;
023import java.io.BufferedOutputStream;
024import java.io.DataInputStream;
025import java.io.DataOutputStream;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.OutputStream;
029import java.net.Socket;
030import java.util.ArrayList;
031import java.util.Arrays;
032import java.util.Collection;
033import java.util.EnumMap;
034import java.util.HashMap;
035import java.util.HashSet;
036import java.util.Iterator;
037import java.util.List;
038import java.util.Map;
039import java.util.Set;
040import java.util.concurrent.ExecutionException;
041import java.util.concurrent.ExecutorService;
042import java.util.concurrent.Executors;
043import java.util.concurrent.Future;
044
045import org.apache.commons.logging.Log;
046import org.apache.commons.logging.LogFactory;
047import org.apache.hadoop.classification.InterfaceAudience;
048import org.apache.hadoop.conf.Configuration;
049import org.apache.hadoop.fs.CommonConfigurationKeys;
050import org.apache.hadoop.hdfs.DFSConfigKeys;
051import org.apache.hadoop.hdfs.DFSUtil;
052import org.apache.hadoop.hdfs.DistributedFileSystem;
053import org.apache.hadoop.hdfs.StorageType;
054import org.apache.hadoop.hdfs.protocol.Block;
055import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
056import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
057import org.apache.hadoop.hdfs.protocol.HdfsConstants;
058import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair;
059import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
060import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver;
061import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil;
062import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient;
063import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
064import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
065import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
066import org.apache.hadoop.hdfs.server.balancer.Dispatcher.DDatanode.StorageGroup;
067import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
068import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations;
069import org.apache.hadoop.hdfs.server.protocol.BlocksWithLocations.BlockWithLocations;
070import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport;
071import org.apache.hadoop.io.IOUtils;
072import org.apache.hadoop.net.NetUtils;
073import org.apache.hadoop.net.NetworkTopology;
074import org.apache.hadoop.security.token.Token;
075import org.apache.hadoop.util.HostsFileReader;
076import org.apache.hadoop.util.StringUtils;
077import org.apache.hadoop.util.Time;
078
079import com.google.common.annotations.VisibleForTesting;
080import com.google.common.base.Preconditions;
081
082/** Dispatching block replica moves between datanodes. */
083@InterfaceAudience.Private
084public class Dispatcher {
085  static final Log LOG = LogFactory.getLog(Dispatcher.class);
086
087  private static final long GB = 1L << 30; // 1GB
088  private static final long MAX_BLOCKS_SIZE_TO_FETCH = 2 * GB;
089
090  private static final int MAX_NO_PENDING_MOVE_ITERATIONS = 5;
091  /**
092   * the period of time to delay the usage of a DataNode after hitting
093   * errors when using it for migrating data
094   */
095  private static long delayAfterErrors = 10 * 1000;
096
097  private final NameNodeConnector nnc;
098  private final SaslDataTransferClient saslClient;
099
100  /** Set of datanodes to be excluded. */
101  private final Set<String> excludedNodes;
102  /** Restrict to the following nodes. */
103  private final Set<String> includedNodes;
104
105  private final Collection<Source> sources = new HashSet<Source>();
106  private final Collection<StorageGroup> targets = new HashSet<StorageGroup>();
107
108  private final GlobalBlockMap globalBlocks = new GlobalBlockMap();
109  private final MovedBlocks<StorageGroup> movedBlocks;
110
111  /** Map (datanodeUuid,storageType -> StorageGroup) */
112  private final StorageGroupMap<StorageGroup> storageGroupMap
113      = new StorageGroupMap<StorageGroup>();
114
115  private NetworkTopology cluster;
116
117  private final ExecutorService moveExecutor;
118  private final ExecutorService dispatchExecutor;
119
120  /** The maximum number of concurrent blocks moves at a datanode */
121  private final int maxConcurrentMovesPerNode;
122
123  private static class GlobalBlockMap {
124    private final Map<Block, DBlock> map = new HashMap<Block, DBlock>();
125
126    /**
127     * Get the block from the map;
128     * if the block is not found, create a new block and put it in the map.
129     */
130    private DBlock get(Block b) {
131      DBlock block = map.get(b);
132      if (block == null) {
133        block = new DBlock(b);
134        map.put(b, block);
135      }
136      return block;
137    }
138    
139    /** Remove all blocks except for the moved blocks. */
140    private void removeAllButRetain(MovedBlocks<StorageGroup> movedBlocks) {
141      for (Iterator<Block> i = map.keySet().iterator(); i.hasNext();) {
142        if (!movedBlocks.contains(i.next())) {
143          i.remove();
144        }
145      }
146    }
147  }
148
149  public static class StorageGroupMap<G extends StorageGroup> {
150    private static String toKey(String datanodeUuid, StorageType storageType) {
151      return datanodeUuid + ":" + storageType;
152    }
153
154    private final Map<String, G> map = new HashMap<String, G>();
155
156    public G get(String datanodeUuid, StorageType storageType) {
157      return map.get(toKey(datanodeUuid, storageType));
158    }
159
160    public void put(G g) {
161      final String key = toKey(g.getDatanodeInfo().getDatanodeUuid(), g.storageType);
162      final StorageGroup existing = map.put(key, g);
163      Preconditions.checkState(existing == null);
164    }
165
166    int size() {
167      return map.size();
168    }
169
170    void clear() {
171      map.clear();
172    }
173
174    public Collection<G> values() {
175      return map.values();
176    }
177  }
178
179  /** This class keeps track of a scheduled block move */
180  public class PendingMove {
181    private DBlock block;
182    private Source source;
183    private DDatanode proxySource;
184    private StorageGroup target;
185
186    private PendingMove(Source source, StorageGroup target) {
187      this.source = source;
188      this.target = target;
189    }
190
191    @Override
192    public String toString() {
193      final Block b = block != null ? block.getBlock() : null;
194      String bStr = b != null ? (b + " with size=" + b.getNumBytes() + " ")
195          : " ";
196      return bStr + "from " + source.getDisplayName() + " to " + target
197          .getDisplayName() + " through " + (proxySource != null ? proxySource
198          .datanode : "");
199    }
200
201    /**
202     * Choose a block & a proxy source for this pendingMove whose source &
203     * target have already been chosen.
204     * 
205     * @return true if a block and its proxy are chosen; false otherwise
206     */
207    private boolean chooseBlockAndProxy() {
208      // source and target must have the same storage type
209      final StorageType t = source.getStorageType();
210      // iterate all source's blocks until find a good one
211      for (Iterator<DBlock> i = source.getBlockIterator(); i.hasNext();) {
212        if (markMovedIfGoodBlock(i.next(), t)) {
213          i.remove();
214          return true;
215        }
216      }
217      return false;
218    }
219
220    /**
221     * @return true if the given block is good for the tentative move.
222     */
223    private boolean markMovedIfGoodBlock(DBlock block, StorageType targetStorageType) {
224      synchronized (block) {
225        synchronized (movedBlocks) {
226          if (isGoodBlockCandidate(source, target, targetStorageType, block)) {
227            this.block = block;
228            if (chooseProxySource()) {
229              movedBlocks.put(block);
230              if (LOG.isDebugEnabled()) {
231                LOG.debug("Decided to move " + this);
232              }
233              return true;
234            }
235          }
236        }
237      }
238      return false;
239    }
240
241    /**
242     * Choose a proxy source.
243     * 
244     * @return true if a proxy is found; otherwise false
245     */
246    private boolean chooseProxySource() {
247      final DatanodeInfo targetDN = target.getDatanodeInfo();
248      // if source and target are same nodes then no need of proxy
249      if (source.getDatanodeInfo().equals(targetDN) && addTo(source)) {
250        return true;
251      }
252      // if node group is supported, first try add nodes in the same node group
253      if (cluster.isNodeGroupAware()) {
254        for (StorageGroup loc : block.getLocations()) {
255          if (cluster.isOnSameNodeGroup(loc.getDatanodeInfo(), targetDN)
256              && addTo(loc)) {
257            return true;
258          }
259        }
260      }
261      // check if there is replica which is on the same rack with the target
262      for (StorageGroup loc : block.getLocations()) {
263        if (cluster.isOnSameRack(loc.getDatanodeInfo(), targetDN) && addTo(loc)) {
264          return true;
265        }
266      }
267      // find out a non-busy replica
268      for (StorageGroup loc : block.getLocations()) {
269        if (addTo(loc)) {
270          return true;
271        }
272      }
273      return false;
274    }
275
276    /** add to a proxy source for specific block movement */
277    private boolean addTo(StorageGroup g) {
278      final DDatanode dn = g.getDDatanode();
279      if (dn.addPendingBlock(this)) {
280        proxySource = dn;
281        return true;
282      }
283      return false;
284    }
285
286    /** Dispatch the move to the proxy source & wait for the response. */
287    private void dispatch() {
288      if (LOG.isDebugEnabled()) {
289        LOG.debug("Start moving " + this);
290      }
291
292      Socket sock = new Socket();
293      DataOutputStream out = null;
294      DataInputStream in = null;
295      try {
296        sock.connect(
297            NetUtils.createSocketAddr(target.getDatanodeInfo().getXferAddr()),
298            HdfsServerConstants.READ_TIMEOUT);
299
300        sock.setKeepAlive(true);
301
302        OutputStream unbufOut = sock.getOutputStream();
303        InputStream unbufIn = sock.getInputStream();
304        ExtendedBlock eb = new ExtendedBlock(nnc.getBlockpoolID(),
305            block.getBlock());
306        final KeyManager km = nnc.getKeyManager(); 
307        Token<BlockTokenIdentifier> accessToken = km.getAccessToken(eb);
308        IOStreamPair saslStreams = saslClient.socketSend(sock, unbufOut,
309            unbufIn, km, accessToken, target.getDatanodeInfo());
310        unbufOut = saslStreams.out;
311        unbufIn = saslStreams.in;
312        out = new DataOutputStream(new BufferedOutputStream(unbufOut,
313            HdfsConstants.IO_FILE_BUFFER_SIZE));
314        in = new DataInputStream(new BufferedInputStream(unbufIn,
315            HdfsConstants.IO_FILE_BUFFER_SIZE));
316
317        sendRequest(out, eb, accessToken);
318        receiveResponse(in);
319        nnc.getBytesMoved().addAndGet(block.getNumBytes());
320        LOG.info("Successfully moved " + this);
321      } catch (IOException e) {
322        LOG.warn("Failed to move " + this + ": " + e.getMessage());
323        target.getDDatanode().setHasFailure();
324        // Proxy or target may have some issues, delay before using these nodes
325        // further in order to avoid a potential storm of "threads quota
326        // exceeded" warnings when the dispatcher gets out of sync with work
327        // going on in datanodes.
328        proxySource.activateDelay(delayAfterErrors);
329        target.getDDatanode().activateDelay(delayAfterErrors);
330      } finally {
331        IOUtils.closeStream(out);
332        IOUtils.closeStream(in);
333        IOUtils.closeSocket(sock);
334
335        proxySource.removePendingBlock(this);
336        target.getDDatanode().removePendingBlock(this);
337
338        synchronized (this) {
339          reset();
340        }
341        synchronized (Dispatcher.this) {
342          Dispatcher.this.notifyAll();
343        }
344      }
345    }
346
347    /** Send a block replace request to the output stream */
348    private void sendRequest(DataOutputStream out, ExtendedBlock eb,
349        Token<BlockTokenIdentifier> accessToken) throws IOException {
350      new Sender(out).replaceBlock(eb, target.storageType, accessToken,
351          source.getDatanodeInfo().getDatanodeUuid(), proxySource.datanode);
352    }
353
354    /** Receive a block copy response from the input stream */
355    private void receiveResponse(DataInputStream in) throws IOException {
356      BlockOpResponseProto response =
357          BlockOpResponseProto.parseFrom(vintPrefixed(in));
358      while (response.getStatus() == Status.IN_PROGRESS) {
359        // read intermediate responses
360        response = BlockOpResponseProto.parseFrom(vintPrefixed(in));
361      }
362      if (response.getStatus() != Status.SUCCESS) {
363        if (response.getStatus() == Status.ERROR_ACCESS_TOKEN) {
364          throw new IOException("block move failed due to access token error");
365        }
366        throw new IOException("block move is failed: " + response.getMessage());
367      }
368    }
369
370    /** reset the object */
371    private void reset() {
372      block = null;
373      source = null;
374      proxySource = null;
375      target = null;
376    }
377  }
378
379  /** A class for keeping track of block locations in the dispatcher. */
380  public static class DBlock extends MovedBlocks.Locations<StorageGroup> {
381    public DBlock(Block block) {
382      super(block);
383    }
384  }
385
386  /** The class represents a desired move. */
387  static class Task {
388    private final StorageGroup target;
389    private long size; // bytes scheduled to move
390
391    Task(StorageGroup target, long size) {
392      this.target = target;
393      this.size = size;
394    }
395
396    long getSize() {
397      return size;
398    }
399  }
400
401  /** A class that keeps track of a datanode. */
402  public static class DDatanode {
403
404    /** A group of storages in a datanode with the same storage type. */
405    public class StorageGroup {
406      final StorageType storageType;
407      final long maxSize2Move;
408      private long scheduledSize = 0L;
409
410      private StorageGroup(StorageType storageType, long maxSize2Move) {
411        this.storageType = storageType;
412        this.maxSize2Move = maxSize2Move;
413      }
414      
415      public StorageType getStorageType() {
416        return storageType;
417      }
418
419      private DDatanode getDDatanode() {
420        return DDatanode.this;
421      }
422
423      public DatanodeInfo getDatanodeInfo() {
424        return DDatanode.this.datanode;
425      }
426
427      /** Decide if still need to move more bytes */
428      boolean hasSpaceForScheduling() {
429        return hasSpaceForScheduling(0L);
430      }
431
432      synchronized boolean hasSpaceForScheduling(long size) {
433        return availableSizeToMove() > size;
434      }
435
436      /** @return the total number of bytes that need to be moved */
437      synchronized long availableSizeToMove() {
438        return maxSize2Move - scheduledSize;
439      }
440
441      /** increment scheduled size */
442      public synchronized void incScheduledSize(long size) {
443        scheduledSize += size;
444      }
445
446      /** @return scheduled size */
447      synchronized long getScheduledSize() {
448        return scheduledSize;
449      }
450
451      /** Reset scheduled size to zero. */
452      synchronized void resetScheduledSize() {
453        scheduledSize = 0L;
454      }
455
456      private PendingMove addPendingMove(DBlock block, final PendingMove pm) {
457        if (getDDatanode().addPendingBlock(pm)) {
458          if (pm.markMovedIfGoodBlock(block, getStorageType())) {
459            incScheduledSize(pm.block.getNumBytes());
460            return pm;
461          } else {
462            getDDatanode().removePendingBlock(pm);
463          }
464        }
465        return null;
466      }
467
468      /** @return the name for display */
469      String getDisplayName() {
470        return datanode + ":" + storageType;
471      }
472
473      @Override
474      public String toString() {
475        return getDisplayName();
476      }
477    }
478
479    final DatanodeInfo datanode;
480    private final EnumMap<StorageType, Source> sourceMap
481        = new EnumMap<StorageType, Source>(StorageType.class);
482    private final EnumMap<StorageType, StorageGroup> targetMap
483        = new EnumMap<StorageType, StorageGroup>(StorageType.class);
484    protected long delayUntil = 0L;
485    /** blocks being moved but not confirmed yet */
486    private final List<PendingMove> pendings;
487    private volatile boolean hasFailure = false;
488    private final int maxConcurrentMoves;
489
490    @Override
491    public String toString() {
492      return getClass().getSimpleName() + ":" + datanode;
493    }
494
495    private DDatanode(DatanodeInfo datanode, int maxConcurrentMoves) {
496      this.datanode = datanode;
497      this.maxConcurrentMoves = maxConcurrentMoves;
498      this.pendings = new ArrayList<PendingMove>(maxConcurrentMoves);
499    }
500
501    public DatanodeInfo getDatanodeInfo() {
502      return datanode;
503    }
504
505    private static <G extends StorageGroup> void put(StorageType storageType,
506        G g, EnumMap<StorageType, G> map) {
507      final StorageGroup existing = map.put(storageType, g);
508      Preconditions.checkState(existing == null);
509    }
510
511    public StorageGroup addTarget(StorageType storageType, long maxSize2Move) {
512      final StorageGroup g = new StorageGroup(storageType, maxSize2Move);
513      put(storageType, g, targetMap);
514      return g;
515    }
516
517    public Source addSource(StorageType storageType, long maxSize2Move, Dispatcher d) {
518      final Source s = d.new Source(storageType, maxSize2Move, this);
519      put(storageType, s, sourceMap);
520      return s;
521    }
522
523    synchronized private void activateDelay(long delta) {
524      delayUntil = Time.monotonicNow() + delta;
525    }
526
527    synchronized private boolean isDelayActive() {
528      if (delayUntil == 0 || Time.monotonicNow() > delayUntil) {
529        delayUntil = 0;
530        return false;
531      }
532      return true;
533    }
534
535    /** Check if the node can schedule more blocks to move */
536    synchronized boolean isPendingQNotFull() {
537      return pendings.size() < maxConcurrentMoves;
538    }
539
540    /** Check if all the dispatched moves are done */
541    synchronized boolean isPendingQEmpty() {
542      return pendings.isEmpty();
543    }
544
545    /** Add a scheduled block move to the node */
546    synchronized boolean addPendingBlock(PendingMove pendingBlock) {
547      if (!isDelayActive() && isPendingQNotFull()) {
548        return pendings.add(pendingBlock);
549      }
550      return false;
551    }
552
553    /** Remove a scheduled block move from the node */
554    synchronized boolean removePendingBlock(PendingMove pendingBlock) {
555      return pendings.remove(pendingBlock);
556    }
557
558    void setHasFailure() {
559      this.hasFailure = true;
560    }
561  }
562
563  /** A node that can be the sources of a block move */
564  public class Source extends DDatanode.StorageGroup {
565
566    private final List<Task> tasks = new ArrayList<Task>(2);
567    private long blocksToReceive = 0L;
568    /**
569     * Source blocks point to the objects in {@link Dispatcher#globalBlocks}
570     * because we want to keep one copy of a block and be aware that the
571     * locations are changing over time.
572     */
573    private final List<DBlock> srcBlocks = new ArrayList<DBlock>();
574
575    private Source(StorageType storageType, long maxSize2Move, DDatanode dn) {
576      dn.super(storageType, maxSize2Move);
577    }
578
579    /** Add a task */
580    void addTask(Task task) {
581      Preconditions.checkState(task.target != this,
582          "Source and target are the same storage group " + getDisplayName());
583      incScheduledSize(task.size);
584      tasks.add(task);
585    }
586
587    /** @return an iterator to this source's blocks */
588    Iterator<DBlock> getBlockIterator() {
589      return srcBlocks.iterator();
590    }
591
592    /**
593     * Fetch new blocks of this source from namenode and update this source's
594     * block list & {@link Dispatcher#globalBlocks}.
595     * 
596     * @return the total size of the received blocks in the number of bytes.
597     */
598    private long getBlockList() throws IOException {
599      final long size = Math.min(MAX_BLOCKS_SIZE_TO_FETCH, blocksToReceive);
600      final BlocksWithLocations newBlocks = nnc.getBlocks(getDatanodeInfo(), size);
601
602      long bytesReceived = 0;
603      for (BlockWithLocations blk : newBlocks.getBlocks()) {
604        bytesReceived += blk.getBlock().getNumBytes();
605        synchronized (globalBlocks) {
606          final DBlock block = globalBlocks.get(blk.getBlock());
607          synchronized (block) {
608            block.clearLocations();
609
610            // update locations
611            final String[] datanodeUuids = blk.getDatanodeUuids();
612            final StorageType[] storageTypes = blk.getStorageTypes();
613            for (int i = 0; i < datanodeUuids.length; i++) {
614              final StorageGroup g = storageGroupMap.get(
615                  datanodeUuids[i], storageTypes[i]);
616              if (g != null) { // not unknown
617                block.addLocation(g);
618              }
619            }
620          }
621          if (!srcBlocks.contains(block) && isGoodBlockCandidate(block)) {
622            // filter bad candidates
623            srcBlocks.add(block);
624          }
625        }
626      }
627      return bytesReceived;
628    }
629
630    /** Decide if the given block is a good candidate to move or not */
631    private boolean isGoodBlockCandidate(DBlock block) {
632      // source and target must have the same storage type
633      final StorageType sourceStorageType = getStorageType();
634      for (Task t : tasks) {
635        if (Dispatcher.this.isGoodBlockCandidate(this, t.target,
636            sourceStorageType, block)) {
637          return true;
638        }
639      }
640      return false;
641    }
642
643    /**
644     * Choose a move for the source. The block's source, target, and proxy
645     * are determined too. When choosing proxy and target, source &
646     * target throttling has been considered. They are chosen only when they
647     * have the capacity to support this block move. The block should be
648     * dispatched immediately after this method is returned.
649     * 
650     * @return a move that's good for the source to dispatch immediately.
651     */
652    private PendingMove chooseNextMove() {
653      for (Iterator<Task> i = tasks.iterator(); i.hasNext();) {
654        final Task task = i.next();
655        final DDatanode target = task.target.getDDatanode();
656        final PendingMove pendingBlock = new PendingMove(this, task.target);
657        if (target.addPendingBlock(pendingBlock)) {
658          // target is not busy, so do a tentative block allocation
659          if (pendingBlock.chooseBlockAndProxy()) {
660            long blockSize = pendingBlock.block.getNumBytes();
661            incScheduledSize(-blockSize);
662            task.size -= blockSize;
663            if (task.size == 0) {
664              i.remove();
665            }
666            return pendingBlock;
667          } else {
668            // cancel the tentative move
669            target.removePendingBlock(pendingBlock);
670          }
671        }
672      }
673      return null;
674    }
675    
676    /** Add a pending move */
677    public PendingMove addPendingMove(DBlock block, StorageGroup target) {
678      return target.addPendingMove(block, new PendingMove(this, target));
679    }
680
681    /** Iterate all source's blocks to remove moved ones */
682    private void removeMovedBlocks() {
683      for (Iterator<DBlock> i = getBlockIterator(); i.hasNext();) {
684        if (movedBlocks.contains(i.next().getBlock())) {
685          i.remove();
686        }
687      }
688    }
689
690    private static final int SOURCE_BLOCKS_MIN_SIZE = 5;
691
692    /** @return if should fetch more blocks from namenode */
693    private boolean shouldFetchMoreBlocks() {
694      return srcBlocks.size() < SOURCE_BLOCKS_MIN_SIZE && blocksToReceive > 0;
695    }
696
697    private static final long MAX_ITERATION_TIME = 20 * 60 * 1000L; // 20 mins
698
699    /**
700     * This method iteratively does the following: it first selects a block to
701     * move, then sends a request to the proxy source to start the block move
702     * when the source's block list falls below a threshold, it asks the
703     * namenode for more blocks. It terminates when it has dispatch enough block
704     * move tasks or it has received enough blocks from the namenode, or the
705     * elapsed time of the iteration has exceeded the max time limit.
706     */
707    private void dispatchBlocks() {
708      final long startTime = Time.monotonicNow();
709      this.blocksToReceive = 2 * getScheduledSize();
710      boolean isTimeUp = false;
711      int noPendingMoveIteration = 0;
712      while (!isTimeUp && getScheduledSize() > 0
713          && (!srcBlocks.isEmpty() || blocksToReceive > 0)) {
714        final PendingMove p = chooseNextMove();
715        if (p != null) {
716          // Reset no pending move counter
717          noPendingMoveIteration=0;
718          executePendingMove(p);
719          continue;
720        }
721
722        // Since we cannot schedule any block to move,
723        // remove any moved blocks from the source block list and
724        removeMovedBlocks(); // filter already moved blocks
725        // check if we should fetch more blocks from the namenode
726        if (shouldFetchMoreBlocks()) {
727          // fetch new blocks
728          try {
729            blocksToReceive -= getBlockList();
730            continue;
731          } catch (IOException e) {
732            LOG.warn("Exception while getting block list", e);
733            return;
734          }
735        } else {
736          // source node cannot find a pending block to move, iteration +1
737          noPendingMoveIteration++;
738          // in case no blocks can be moved for source node's task,
739          // jump out of while-loop after 5 iterations.
740          if (noPendingMoveIteration >= MAX_NO_PENDING_MOVE_ITERATIONS) {
741            resetScheduledSize();
742          }
743        }
744
745        // check if time is up or not
746        if (Time.monotonicNow() - startTime > MAX_ITERATION_TIME) {
747          isTimeUp = true;
748          continue;
749        }
750
751        // Now we can not schedule any block to move and there are
752        // no new blocks added to the source block list, so we wait.
753        try {
754          synchronized (Dispatcher.this) {
755            Dispatcher.this.wait(1000); // wait for targets/sources to be idle
756          }
757        } catch (InterruptedException ignored) {
758        }
759      }
760    }
761  }
762
763  public Dispatcher(NameNodeConnector nnc, Set<String> includedNodes,
764      Set<String> excludedNodes, long movedWinWidth, int moverThreads,
765      int dispatcherThreads, int maxConcurrentMovesPerNode, Configuration conf) {
766    this.nnc = nnc;
767    this.excludedNodes = excludedNodes;
768    this.includedNodes = includedNodes;
769    this.movedBlocks = new MovedBlocks<StorageGroup>(movedWinWidth);
770
771    this.cluster = NetworkTopology.getInstance(conf);
772
773    this.moveExecutor = Executors.newFixedThreadPool(moverThreads);
774    this.dispatchExecutor = dispatcherThreads == 0? null
775        : Executors.newFixedThreadPool(dispatcherThreads);
776    this.maxConcurrentMovesPerNode = maxConcurrentMovesPerNode;
777
778    this.saslClient = new SaslDataTransferClient(conf,
779        DataTransferSaslUtil.getSaslPropertiesResolver(conf),
780        TrustedChannelResolver.getInstance(conf), nnc.fallbackToSimpleAuth);
781  }
782
783  public DistributedFileSystem getDistributedFileSystem() {
784    return nnc.getDistributedFileSystem();
785  }
786
787  public StorageGroupMap<StorageGroup> getStorageGroupMap() {
788    return storageGroupMap;
789  }
790
791  public NetworkTopology getCluster() {
792    return cluster;
793  }
794  
795  long getBytesMoved() {
796    return nnc.getBytesMoved().get();
797  }
798
799  long bytesToMove() {
800    Preconditions.checkState(
801        storageGroupMap.size() >= sources.size() + targets.size(),
802        "Mismatched number of storage groups (" + storageGroupMap.size()
803            + " < " + sources.size() + " sources + " + targets.size()
804            + " targets)");
805
806    long b = 0L;
807    for (Source src : sources) {
808      b += src.getScheduledSize();
809    }
810    return b;
811  }
812
813  void add(Source source, StorageGroup target) {
814    sources.add(source);
815    targets.add(target);
816  }
817
818  private boolean shouldIgnore(DatanodeInfo dn) {
819    // ignore decommissioned nodes
820    final boolean decommissioned = dn.isDecommissioned();
821    // ignore decommissioning nodes
822    final boolean decommissioning = dn.isDecommissionInProgress();
823    // ignore nodes in exclude list
824    final boolean excluded = Util.isExcluded(excludedNodes, dn);
825    // ignore nodes not in the include list (if include list is not empty)
826    final boolean notIncluded = !Util.isIncluded(includedNodes, dn);
827
828    if (decommissioned || decommissioning || excluded || notIncluded) {
829      if (LOG.isTraceEnabled()) {
830        LOG.trace("Excluding datanode " + dn + ": " + decommissioned + ", "
831            + decommissioning + ", " + excluded + ", " + notIncluded);
832      }
833      return true;
834    }
835    return false;
836  }
837
838  /** Get live datanode storage reports and then build the network topology. */
839  public List<DatanodeStorageReport> init() throws IOException {
840    final DatanodeStorageReport[] reports = nnc.getLiveDatanodeStorageReport();
841    final List<DatanodeStorageReport> trimmed = new ArrayList<DatanodeStorageReport>(); 
842    // create network topology and classify utilization collections:
843    // over-utilized, above-average, below-average and under-utilized.
844    for (DatanodeStorageReport r : DFSUtil.shuffle(reports)) {
845      final DatanodeInfo datanode = r.getDatanodeInfo();
846      if (shouldIgnore(datanode)) {
847        continue;
848      }
849      trimmed.add(r);
850      cluster.add(datanode);
851    }
852    return trimmed;
853  }
854
855  public DDatanode newDatanode(DatanodeInfo datanode) {
856    return new DDatanode(datanode, maxConcurrentMovesPerNode);
857  }
858
859  public void executePendingMove(final PendingMove p) {
860    // move the block
861    moveExecutor.execute(new Runnable() {
862      @Override
863      public void run() {
864        p.dispatch();
865      }
866    });
867  }
868
869  public boolean dispatchAndCheckContinue() throws InterruptedException {
870    return nnc.shouldContinue(dispatchBlockMoves());
871  }
872
873  /**
874   * Dispatch block moves for each source. The thread selects blocks to move &
875   * sends request to proxy source to initiate block move. The process is flow
876   * controlled. Block selection is blocked if there are too many un-confirmed
877   * block moves.
878   * 
879   * @return the total number of bytes successfully moved in this iteration.
880   */
881  private long dispatchBlockMoves() throws InterruptedException {
882    final long bytesLastMoved = getBytesMoved();
883    final Future<?>[] futures = new Future<?>[sources.size()];
884
885    final Iterator<Source> i = sources.iterator();
886    for (int j = 0; j < futures.length; j++) {
887      final Source s = i.next();
888      futures[j] = dispatchExecutor.submit(new Runnable() {
889        @Override
890        public void run() {
891          s.dispatchBlocks();
892        }
893      });
894    }
895
896    // wait for all dispatcher threads to finish
897    for (Future<?> future : futures) {
898      try {
899        future.get();
900      } catch (ExecutionException e) {
901        LOG.warn("Dispatcher thread failed", e.getCause());
902      }
903    }
904
905    // wait for all block moving to be done
906    waitForMoveCompletion(targets);
907
908    return getBytesMoved() - bytesLastMoved;
909  }
910
911  /** The sleeping period before checking if block move is completed again */
912  static private long blockMoveWaitTime = 30000L;
913
914  /**
915   * Wait for all block move confirmations.
916   * @return true if there is failed move execution
917   */
918  public static boolean waitForMoveCompletion(
919      Iterable<? extends StorageGroup> targets) {
920    boolean hasFailure = false;
921    for(;;) {
922      boolean empty = true;
923      for (StorageGroup t : targets) {
924        if (!t.getDDatanode().isPendingQEmpty()) {
925          empty = false;
926          break;
927        } else {
928          hasFailure |= t.getDDatanode().hasFailure;
929        }
930      }
931      if (empty) {
932        return hasFailure; // all pending queues are empty
933      }
934      try {
935        Thread.sleep(blockMoveWaitTime);
936      } catch (InterruptedException ignored) {
937      }
938    }
939  }
940
941  /**
942   * Decide if the block is a good candidate to be moved from source to target.
943   * A block is a good candidate if
944   * 1. the block is not in the process of being moved/has not been moved;
945   * 2. the block does not have a replica on the target;
946   * 3. doing the move does not reduce the number of racks that the block has
947   */
948  private boolean isGoodBlockCandidate(StorageGroup source, StorageGroup target,
949      StorageType targetStorageType, DBlock block) {
950    if (target.storageType != targetStorageType) {
951      return false;
952    }
953    // check if the block is moved or not
954    if (movedBlocks.contains(block.getBlock())) {
955      return false;
956    }
957    if (block.isLocatedOn(target)) {
958      return false;
959    }
960    if (cluster.isNodeGroupAware()
961        && isOnSameNodeGroupWithReplicas(source, target, block)) {
962      return false;
963    }
964    if (reduceNumOfRacks(source, target, block)) {
965      return false;
966    }
967    return true;
968  }
969
970  /**
971   * Determine whether moving the given block replica from source to target
972   * would reduce the number of racks of the block replicas.
973   */
974  private boolean reduceNumOfRacks(StorageGroup source, StorageGroup target,
975      DBlock block) {
976    final DatanodeInfo sourceDn = source.getDatanodeInfo();
977    if (cluster.isOnSameRack(sourceDn, target.getDatanodeInfo())) {
978      // source and target are on the same rack
979      return false;
980    }
981    boolean notOnSameRack = true;
982    synchronized (block) {
983      for (StorageGroup loc : block.getLocations()) {
984        if (cluster.isOnSameRack(loc.getDatanodeInfo(), target.getDatanodeInfo())) {
985          notOnSameRack = false;
986          break;
987        }
988      }
989    }
990    if (notOnSameRack) {
991      // target is not on the same rack as any replica
992      return false;
993    }
994    for (StorageGroup g : block.getLocations()) {
995      if (g != source && cluster.isOnSameRack(g.getDatanodeInfo(), sourceDn)) {
996        // source is on the same rack of another replica
997        return false;
998      }
999    }
1000    return true;
1001  }
1002
1003  /**
1004   * Check if there are any replica (other than source) on the same node group
1005   * with target. If true, then target is not a good candidate for placing
1006   * specific replica as we don't want 2 replicas under the same nodegroup.
1007   *
1008   * @return true if there are any replica (other than source) on the same node
1009   *         group with target
1010   */
1011  private boolean isOnSameNodeGroupWithReplicas(StorageGroup source,
1012      StorageGroup target, DBlock block) {
1013    final DatanodeInfo targetDn = target.getDatanodeInfo();
1014    for (StorageGroup g : block.getLocations()) {
1015      if (g != source && cluster.isOnSameNodeGroup(g.getDatanodeInfo(), targetDn)) {
1016        return true;
1017      }
1018    }
1019    return false;
1020  }
1021
1022  /** Reset all fields in order to prepare for the next iteration */
1023  void reset(Configuration conf) {
1024    cluster = NetworkTopology.getInstance(conf);
1025    storageGroupMap.clear();
1026    sources.clear();
1027    targets.clear();
1028    globalBlocks.removeAllButRetain(movedBlocks);
1029    movedBlocks.cleanup();
1030  }
1031
1032  /** set the sleeping period for block move completion check */
1033  @VisibleForTesting
1034  public static void setBlockMoveWaitTime(long time) {
1035    blockMoveWaitTime = time;
1036  }
1037
1038  @VisibleForTesting
1039  public static void setDelayAfterErrors(long time) {
1040    delayAfterErrors = time;
1041  }
1042
1043  /** shutdown thread pools */
1044  public void shutdownNow() {
1045    if (dispatchExecutor != null) {
1046      dispatchExecutor.shutdownNow();
1047    }
1048    moveExecutor.shutdownNow();
1049  }
1050
1051  static class Util {
1052    /** @return true if data node is part of the excludedNodes. */
1053    static boolean isExcluded(Set<String> excludedNodes, DatanodeInfo dn) {
1054      return isIn(excludedNodes, dn);
1055    }
1056
1057    /**
1058     * @return true if includedNodes is empty or data node is part of the
1059     *         includedNodes.
1060     */
1061    static boolean isIncluded(Set<String> includedNodes, DatanodeInfo dn) {
1062      return (includedNodes.isEmpty() || isIn(includedNodes, dn));
1063    }
1064
1065    /**
1066     * Match is checked using host name , ip address with and without port
1067     * number.
1068     * 
1069     * @return true if the datanode's transfer address matches the set of nodes.
1070     */
1071    private static boolean isIn(Set<String> datanodes, DatanodeInfo dn) {
1072      return isIn(datanodes, dn.getPeerHostName(), dn.getXferPort())
1073          || isIn(datanodes, dn.getIpAddr(), dn.getXferPort())
1074          || isIn(datanodes, dn.getHostName(), dn.getXferPort());
1075    }
1076
1077    /** @return true if nodes contains host or host:port */
1078    private static boolean isIn(Set<String> nodes, String host, int port) {
1079      if (host == null) {
1080        return false;
1081      }
1082      return (nodes.contains(host) || nodes.contains(host + ":" + port));
1083    }
1084
1085    /**
1086     * Parse a comma separated string to obtain set of host names
1087     * 
1088     * @return set of host names
1089     */
1090    static Set<String> parseHostList(String string) {
1091      String[] addrs = StringUtils.getTrimmedStrings(string);
1092      return new HashSet<String>(Arrays.asList(addrs));
1093    }
1094
1095    /**
1096     * Read set of host names from a file
1097     * 
1098     * @return set of host names
1099     */
1100    static Set<String> getHostListFromFile(String fileName, String type) {
1101      Set<String> nodes = new HashSet<String>();
1102      try {
1103        HostsFileReader.readFileToSet(type, fileName, nodes);
1104        return StringUtils.getTrimmedStrings(nodes);
1105      } catch (IOException e) {
1106        throw new IllegalArgumentException(
1107            "Failed to read host list from file: " + fileName);
1108      }
1109    }
1110  }
1111}