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;
019
020import java.io.EOFException;
021import java.io.IOException;
022import java.net.InetSocketAddress;
023import java.nio.ByteBuffer;
024import java.util.AbstractMap;
025import java.util.ArrayList;
026import java.util.Arrays;
027import java.util.Collection;
028import java.util.EnumSet;
029import java.util.HashMap;
030import java.util.HashSet;
031import java.util.Iterator;
032import java.util.List;
033import java.util.Map;
034import java.util.Map.Entry;
035import java.util.Set;
036import java.util.concurrent.Callable;
037import java.util.concurrent.CancellationException;
038import java.util.concurrent.CompletionService;
039import java.util.concurrent.ConcurrentHashMap;
040import java.util.concurrent.ExecutionException;
041import java.util.concurrent.ExecutorCompletionService;
042import java.util.concurrent.Future;
043import java.util.concurrent.TimeUnit;
044import java.util.concurrent.atomic.AtomicBoolean;
045
046import org.apache.commons.io.IOUtils;
047import org.apache.hadoop.classification.InterfaceAudience;
048import org.apache.hadoop.fs.ByteBufferReadable;
049import org.apache.hadoop.fs.ByteBufferUtil;
050import org.apache.hadoop.fs.CanSetDropBehind;
051import org.apache.hadoop.fs.CanSetReadahead;
052import org.apache.hadoop.fs.CanUnbuffer;
053import org.apache.hadoop.fs.ChecksumException;
054import org.apache.hadoop.fs.FSInputStream;
055import org.apache.hadoop.fs.HasEnhancedByteBufferAccess;
056import org.apache.hadoop.fs.ReadOption;
057import org.apache.hadoop.fs.UnresolvedLinkException;
058import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
059import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
060import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
061import org.apache.hadoop.fs.FileEncryptionInfo;
062import org.apache.hadoop.hdfs.protocol.LocatedBlock;
063import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
064import org.apache.hadoop.hdfs.protocol.datatransfer.InvalidEncryptionKeyException;
065import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
066import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException;
067import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
068import org.apache.hadoop.hdfs.server.datanode.ReplicaNotFoundException;
069import org.apache.hadoop.hdfs.shortcircuit.ClientMmap;
070import org.apache.hadoop.io.ByteBufferPool;
071import org.apache.hadoop.ipc.RPC;
072import org.apache.hadoop.ipc.RemoteException;
073import org.apache.hadoop.net.NetUtils;
074import org.apache.hadoop.security.token.SecretManager.InvalidToken;
075import org.apache.hadoop.security.token.Token;
076import org.apache.hadoop.util.IdentityHashStore;
077
078import com.google.common.annotations.VisibleForTesting;
079
080/****************************************************************
081 * DFSInputStream provides bytes from a named file.  It handles 
082 * negotiation of the namenode and various datanodes as necessary.
083 ****************************************************************/
084@InterfaceAudience.Private
085public class DFSInputStream extends FSInputStream
086implements ByteBufferReadable, CanSetDropBehind, CanSetReadahead,
087    HasEnhancedByteBufferAccess, CanUnbuffer {
088  @VisibleForTesting
089  public static boolean tcpReadsDisabledForTesting = false;
090  private long hedgedReadOpsLoopNumForTesting = 0;
091  private final DFSClient dfsClient;
092  private AtomicBoolean closed = new AtomicBoolean(false);
093  private final String src;
094  private final boolean verifyChecksum;
095
096  // state by stateful read only:
097  // (protected by lock on this)
098  /////
099  private DatanodeInfo currentNode = null;
100  private LocatedBlock currentLocatedBlock = null;
101  private long pos = 0;
102  private long blockEnd = -1;
103  private BlockReader blockReader = null;
104  ////
105
106  // state shared by stateful and positional read:
107  // (protected by lock on infoLock)
108  ////
109  private LocatedBlocks locatedBlocks = null;
110  private long lastBlockBeingWrittenLength = 0;
111  private FileEncryptionInfo fileEncryptionInfo = null;
112  private CachingStrategy cachingStrategy;
113  ////
114
115  private final ReadStatistics readStatistics = new ReadStatistics();
116  // lock for state shared between read and pread
117  // Note: Never acquire a lock on <this> with this lock held to avoid deadlocks
118  //       (it's OK to acquire this lock when the lock on <this> is held)
119  private final Object infoLock = new Object();
120
121  /**
122   * Track the ByteBuffers that we have handed out to readers.
123   * 
124   * The value type can be either ByteBufferPool or ClientMmap, depending on
125   * whether we this is a memory-mapped buffer or not.
126   */
127  private IdentityHashStore<ByteBuffer, Object> extendedReadBuffers;
128
129  private synchronized IdentityHashStore<ByteBuffer, Object>
130        getExtendedReadBuffers() {
131    if (extendedReadBuffers == null) {
132      extendedReadBuffers = new IdentityHashStore<ByteBuffer, Object>(0);
133    }
134    return extendedReadBuffers;
135  }
136
137  public static class ReadStatistics {
138    public ReadStatistics() {
139      clear();
140    }
141
142    public ReadStatistics(ReadStatistics rhs) {
143      this.totalBytesRead = rhs.getTotalBytesRead();
144      this.totalLocalBytesRead = rhs.getTotalLocalBytesRead();
145      this.totalShortCircuitBytesRead = rhs.getTotalShortCircuitBytesRead();
146      this.totalZeroCopyBytesRead = rhs.getTotalZeroCopyBytesRead();
147    }
148
149    /**
150     * @return The total bytes read.  This will always be at least as
151     * high as the other numbers, since it includes all of them.
152     */
153    public long getTotalBytesRead() {
154      return totalBytesRead;
155    }
156
157    /**
158     * @return The total local bytes read.  This will always be at least
159     * as high as totalShortCircuitBytesRead, since all short-circuit
160     * reads are also local.
161     */
162    public long getTotalLocalBytesRead() {
163      return totalLocalBytesRead;
164    }
165
166    /**
167     * @return The total short-circuit local bytes read.
168     */
169    public long getTotalShortCircuitBytesRead() {
170      return totalShortCircuitBytesRead;
171    }
172    
173    /**
174     * @return The total number of zero-copy bytes read.
175     */
176    public long getTotalZeroCopyBytesRead() {
177      return totalZeroCopyBytesRead;
178    }
179
180    /**
181     * @return The total number of bytes read which were not local.
182     */
183    public long getRemoteBytesRead() {
184      return totalBytesRead - totalLocalBytesRead;
185    }
186    
187    void addRemoteBytes(long amt) {
188      this.totalBytesRead += amt;
189    }
190
191    void addLocalBytes(long amt) {
192      this.totalBytesRead += amt;
193      this.totalLocalBytesRead += amt;
194    }
195
196    void addShortCircuitBytes(long amt) {
197      this.totalBytesRead += amt;
198      this.totalLocalBytesRead += amt;
199      this.totalShortCircuitBytesRead += amt;
200    }
201
202    void addZeroCopyBytes(long amt) {
203      this.totalBytesRead += amt;
204      this.totalLocalBytesRead += amt;
205      this.totalShortCircuitBytesRead += amt;
206      this.totalZeroCopyBytesRead += amt;
207    }
208
209    void clear() {
210      this.totalBytesRead = 0;
211      this.totalLocalBytesRead = 0;
212      this.totalShortCircuitBytesRead = 0;
213      this.totalZeroCopyBytesRead = 0;
214    }
215    
216    private long totalBytesRead;
217
218    private long totalLocalBytesRead;
219
220    private long totalShortCircuitBytesRead;
221
222    private long totalZeroCopyBytesRead;
223  }
224  
225  /**
226   * This variable tracks the number of failures since the start of the
227   * most recent user-facing operation. That is to say, it should be reset
228   * whenever the user makes a call on this stream, and if at any point
229   * during the retry logic, the failure count exceeds a threshold,
230   * the errors will be thrown back to the operation.
231   *
232   * Specifically this counts the number of times the client has gone
233   * back to the namenode to get a new list of block locations, and is
234   * capped at maxBlockAcquireFailures
235   */
236  private int failures = 0;
237
238  /* XXX Use of CocurrentHashMap is temp fix. Need to fix 
239   * parallel accesses to DFSInputStream (through ptreads) properly */
240  private final ConcurrentHashMap<DatanodeInfo, DatanodeInfo> deadNodes =
241             new ConcurrentHashMap<DatanodeInfo, DatanodeInfo>();
242
243  private byte[] oneByteBuf; // used for 'int read()'
244
245  void addToDeadNodes(DatanodeInfo dnInfo) {
246    deadNodes.put(dnInfo, dnInfo);
247  }
248  
249  DFSInputStream(DFSClient dfsClient, String src, boolean verifyChecksum
250                 ) throws IOException, UnresolvedLinkException {
251    this.dfsClient = dfsClient;
252    this.verifyChecksum = verifyChecksum;
253    this.src = src;
254    synchronized (infoLock) {
255      this.cachingStrategy = dfsClient.getDefaultReadCachingStrategy();
256    }
257    openInfo();
258  }
259
260  /**
261   * Grab the open-file info from namenode
262   */
263  void openInfo() throws IOException, UnresolvedLinkException {
264    synchronized(infoLock) {
265      lastBlockBeingWrittenLength = fetchLocatedBlocksAndGetLastBlockLength();
266      int retriesForLastBlockLength = dfsClient.getConf().retryTimesForGetLastBlockLength;
267      while (retriesForLastBlockLength > 0) {
268        // Getting last block length as -1 is a special case. When cluster
269        // restarts, DNs may not report immediately. At this time partial block
270        // locations will not be available with NN for getting the length. Lets
271        // retry for 3 times to get the length.
272        if (lastBlockBeingWrittenLength == -1) {
273          DFSClient.LOG.warn("Last block locations not available. "
274              + "Datanodes might not have reported blocks completely."
275              + " Will retry for " + retriesForLastBlockLength + " times");
276          waitFor(dfsClient.getConf().retryIntervalForGetLastBlockLength);
277          lastBlockBeingWrittenLength = fetchLocatedBlocksAndGetLastBlockLength();
278        } else {
279          break;
280        }
281        retriesForLastBlockLength--;
282      }
283      if (retriesForLastBlockLength == 0) {
284        throw new IOException("Could not obtain the last block locations.");
285      }
286    }
287  }
288
289  private void waitFor(int waitTime) throws IOException {
290    try {
291      Thread.sleep(waitTime);
292    } catch (InterruptedException e) {
293      throw new IOException(
294          "Interrupted while getting the last block length.");
295    }
296  }
297
298  private long fetchLocatedBlocksAndGetLastBlockLength() throws IOException {
299    final LocatedBlocks newInfo = dfsClient.getLocatedBlocks(src, 0);
300    if (DFSClient.LOG.isDebugEnabled()) {
301      DFSClient.LOG.debug("newInfo = " + newInfo);
302    }
303    if (newInfo == null) {
304      throw new IOException("Cannot open filename " + src);
305    }
306
307    if (locatedBlocks != null) {
308      Iterator<LocatedBlock> oldIter = locatedBlocks.getLocatedBlocks().iterator();
309      Iterator<LocatedBlock> newIter = newInfo.getLocatedBlocks().iterator();
310      while (oldIter.hasNext() && newIter.hasNext()) {
311        if (! oldIter.next().getBlock().equals(newIter.next().getBlock())) {
312          throw new IOException("Blocklist for " + src + " has changed!");
313        }
314      }
315    }
316    locatedBlocks = newInfo;
317    long lastBlockBeingWrittenLength = 0;
318    if (!locatedBlocks.isLastBlockComplete()) {
319      final LocatedBlock last = locatedBlocks.getLastLocatedBlock();
320      if (last != null) {
321        if (last.getLocations().length == 0) {
322          if (last.getBlockSize() == 0) {
323            // if the length is zero, then no data has been written to
324            // datanode. So no need to wait for the locations.
325            return 0;
326          }
327          return -1;
328        }
329        final long len = readBlockLength(last);
330        last.getBlock().setNumBytes(len);
331        lastBlockBeingWrittenLength = len; 
332      }
333    }
334
335    fileEncryptionInfo = locatedBlocks.getFileEncryptionInfo();
336
337    return lastBlockBeingWrittenLength;
338  }
339
340  /** Read the block length from one of the datanodes. */
341  private long readBlockLength(LocatedBlock locatedblock) throws IOException {
342    assert locatedblock != null : "LocatedBlock cannot be null";
343    int replicaNotFoundCount = locatedblock.getLocations().length;
344    
345    for(DatanodeInfo datanode : locatedblock.getLocations()) {
346      ClientDatanodeProtocol cdp = null;
347      
348      try {
349        cdp = DFSUtil.createClientDatanodeProtocolProxy(datanode,
350            dfsClient.getConfiguration(), dfsClient.getConf().socketTimeout,
351            dfsClient.getConf().connectToDnViaHostname, locatedblock);
352        
353        final long n = cdp.getReplicaVisibleLength(locatedblock.getBlock());
354        
355        if (n >= 0) {
356          return n;
357        }
358      }
359      catch(IOException ioe) {
360        if (ioe instanceof RemoteException &&
361          (((RemoteException) ioe).unwrapRemoteException() instanceof
362            ReplicaNotFoundException)) {
363          // special case : replica might not be on the DN, treat as 0 length
364          replicaNotFoundCount--;
365        }
366        
367        if (DFSClient.LOG.isDebugEnabled()) {
368          DFSClient.LOG.debug("Failed to getReplicaVisibleLength from datanode "
369              + datanode + " for block " + locatedblock.getBlock(), ioe);
370        }
371      } finally {
372        if (cdp != null) {
373          RPC.stopProxy(cdp);
374        }
375      }
376    }
377
378    // Namenode told us about these locations, but none know about the replica
379    // means that we hit the race between pipeline creation start and end.
380    // we require all 3 because some other exception could have happened
381    // on a DN that has it.  we want to report that error
382    if (replicaNotFoundCount == 0) {
383      return 0;
384    }
385
386    throw new IOException("Cannot obtain block length for " + locatedblock);
387  }
388  
389  public long getFileLength() {
390    synchronized(infoLock) {
391      return locatedBlocks == null? 0:
392          locatedBlocks.getFileLength() + lastBlockBeingWrittenLength;
393    }
394  }
395
396  // Short circuit local reads are forbidden for files that are
397  // under construction.  See HDFS-2757.
398  boolean shortCircuitForbidden() {
399    synchronized(infoLock) {
400      return locatedBlocks.isUnderConstruction();
401    }
402  }
403
404  /**
405   * Returns the datanode from which the stream is currently reading.
406   */
407  public synchronized DatanodeInfo getCurrentDatanode() {
408    return currentNode;
409  }
410
411  /**
412   * Returns the block containing the target position. 
413   */
414  synchronized public ExtendedBlock getCurrentBlock() {
415    if (currentLocatedBlock == null){
416      return null;
417    }
418    return currentLocatedBlock.getBlock();
419  }
420
421  /**
422   * Return collection of blocks that has already been located.
423   */
424  public List<LocatedBlock> getAllBlocks() throws IOException {
425    return getBlockRange(0, getFileLength());
426  }
427
428  /**
429   * Get block at the specified position.
430   * Fetch it from the namenode if not cached.
431   * 
432   * @param offset block corresponding to this offset in file is returned
433   * @param updatePosition whether to update current position
434   * @return located block
435   * @throws IOException
436   */
437  private LocatedBlock getBlockAt(long offset,
438      boolean updatePosition) throws IOException {
439    synchronized(infoLock) {
440      assert (locatedBlocks != null) : "locatedBlocks is null";
441
442      final LocatedBlock blk;
443
444      //check offset
445      if (offset < 0 || offset >= getFileLength()) {
446        throw new IOException("offset < 0 || offset >= getFileLength(), offset="
447            + offset
448            + ", updatePosition=" + updatePosition
449            + ", locatedBlocks=" + locatedBlocks);
450      }
451      else if (offset >= locatedBlocks.getFileLength()) {
452        // offset to the portion of the last block,
453        // which is not known to the name-node yet;
454        // getting the last block
455        blk = locatedBlocks.getLastLocatedBlock();
456      }
457      else {
458        // search cached blocks first
459        int targetBlockIdx = locatedBlocks.findBlock(offset);
460        if (targetBlockIdx < 0) { // block is not cached
461          targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx);
462          // fetch more blocks
463          final LocatedBlocks newBlocks = dfsClient.getLocatedBlocks(src, offset);
464          assert (newBlocks != null) : "Could not find target position " + offset;
465          locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks());
466        }
467        blk = locatedBlocks.get(targetBlockIdx);
468      }
469
470      // update current position
471      if (updatePosition) {
472        // synchronized not strictly needed, since we only get here
473        // from synchronized caller methods
474        synchronized(this) {
475          pos = offset;
476          blockEnd = blk.getStartOffset() + blk.getBlockSize() - 1;
477          currentLocatedBlock = blk;
478        }
479      }
480      return blk;
481    }
482  }
483
484  /** Fetch a block from namenode and cache it */
485  private void fetchBlockAt(long offset) throws IOException {
486    synchronized(infoLock) {
487      int targetBlockIdx = locatedBlocks.findBlock(offset);
488      if (targetBlockIdx < 0) { // block is not cached
489        targetBlockIdx = LocatedBlocks.getInsertIndex(targetBlockIdx);
490      }
491      // fetch blocks
492      final LocatedBlocks newBlocks = dfsClient.getLocatedBlocks(src, offset);
493      if (newBlocks == null) {
494        throw new IOException("Could not find target position " + offset);
495      }
496      locatedBlocks.insertRange(targetBlockIdx, newBlocks.getLocatedBlocks());
497    }
498  }
499
500  /**
501   * Get blocks in the specified range.
502   * Fetch them from the namenode if not cached. This function
503   * will not get a read request beyond the EOF.
504   * @param offset starting offset in file
505   * @param length length of data
506   * @return consequent segment of located blocks
507   * @throws IOException
508   */
509  private List<LocatedBlock> getBlockRange(long offset,
510      long length)  throws IOException {
511    // getFileLength(): returns total file length
512    // locatedBlocks.getFileLength(): returns length of completed blocks
513    if (offset >= getFileLength()) {
514      throw new IOException("Offset: " + offset +
515        " exceeds file length: " + getFileLength());
516    }
517    synchronized(infoLock) {
518      final List<LocatedBlock> blocks;
519      final long lengthOfCompleteBlk = locatedBlocks.getFileLength();
520      final boolean readOffsetWithinCompleteBlk = offset < lengthOfCompleteBlk;
521      final boolean readLengthPastCompleteBlk = offset + length > lengthOfCompleteBlk;
522
523      if (readOffsetWithinCompleteBlk) {
524        //get the blocks of finalized (completed) block range
525        blocks = getFinalizedBlockRange(offset,
526          Math.min(length, lengthOfCompleteBlk - offset));
527      } else {
528        blocks = new ArrayList<LocatedBlock>(1);
529      }
530
531      // get the blocks from incomplete block range
532      if (readLengthPastCompleteBlk) {
533         blocks.add(locatedBlocks.getLastLocatedBlock());
534      }
535
536      return blocks;
537    }
538  }
539
540  /**
541   * Get blocks in the specified range.
542   * Includes only the complete blocks.
543   * Fetch them from the namenode if not cached.
544   */
545  private List<LocatedBlock> getFinalizedBlockRange(
546      long offset, long length) throws IOException {
547    synchronized(infoLock) {
548      assert (locatedBlocks != null) : "locatedBlocks is null";
549      List<LocatedBlock> blockRange = new ArrayList<LocatedBlock>();
550      // search cached blocks first
551      int blockIdx = locatedBlocks.findBlock(offset);
552      if (blockIdx < 0) { // block is not cached
553        blockIdx = LocatedBlocks.getInsertIndex(blockIdx);
554      }
555      long remaining = length;
556      long curOff = offset;
557      while(remaining > 0) {
558        LocatedBlock blk = null;
559        if(blockIdx < locatedBlocks.locatedBlockCount())
560          blk = locatedBlocks.get(blockIdx);
561        if (blk == null || curOff < blk.getStartOffset()) {
562          LocatedBlocks newBlocks;
563          newBlocks = dfsClient.getLocatedBlocks(src, curOff, remaining);
564          locatedBlocks.insertRange(blockIdx, newBlocks.getLocatedBlocks());
565          continue;
566        }
567        assert curOff >= blk.getStartOffset() : "Block not found";
568        blockRange.add(blk);
569        long bytesRead = blk.getStartOffset() + blk.getBlockSize() - curOff;
570        remaining -= bytesRead;
571        curOff += bytesRead;
572        blockIdx++;
573      }
574      return blockRange;
575    }
576  }
577
578  /**
579   * Open a DataInputStream to a DataNode so that it can be read from.
580   * We get block ID and the IDs of the destinations at startup, from the namenode.
581   */
582  private synchronized DatanodeInfo blockSeekTo(long target) throws IOException {
583    if (target >= getFileLength()) {
584      throw new IOException("Attempted to read past end of file");
585    }
586
587    // Will be getting a new BlockReader.
588    closeCurrentBlockReader();
589
590    //
591    // Connect to best DataNode for desired Block, with potential offset
592    //
593    DatanodeInfo chosenNode = null;
594    int refetchToken = 1; // only need to get a new access token once
595    int refetchEncryptionKey = 1; // only need to get a new encryption key once
596    
597    boolean connectFailedOnce = false;
598
599    while (true) {
600      //
601      // Compute desired block
602      //
603      LocatedBlock targetBlock = getBlockAt(target, true);
604      assert (target==pos) : "Wrong postion " + pos + " expect " + target;
605      long offsetIntoBlock = target - targetBlock.getStartOffset();
606
607      DNAddrPair retval = chooseDataNode(targetBlock, null);
608      chosenNode = retval.info;
609      InetSocketAddress targetAddr = retval.addr;
610      StorageType storageType = retval.storageType;
611
612      try {
613        ExtendedBlock blk = targetBlock.getBlock();
614        Token<BlockTokenIdentifier> accessToken = targetBlock.getBlockToken();
615        CachingStrategy curCachingStrategy;
616        boolean shortCircuitForbidden;
617        synchronized(infoLock) {
618          curCachingStrategy = cachingStrategy;
619          shortCircuitForbidden = shortCircuitForbidden();
620        }
621        blockReader = new BlockReaderFactory(dfsClient.getConf()).
622            setInetSocketAddress(targetAddr).
623            setRemotePeerFactory(dfsClient).
624            setDatanodeInfo(chosenNode).
625            setStorageType(storageType).
626            setFileName(src).
627            setBlock(blk).
628            setBlockToken(accessToken).
629            setStartOffset(offsetIntoBlock).
630            setVerifyChecksum(verifyChecksum).
631            setClientName(dfsClient.clientName).
632            setLength(blk.getNumBytes() - offsetIntoBlock).
633            setCachingStrategy(curCachingStrategy).
634            setAllowShortCircuitLocalReads(!shortCircuitForbidden).
635            setClientCacheContext(dfsClient.getClientContext()).
636            setUserGroupInformation(dfsClient.ugi).
637            setConfiguration(dfsClient.getConfiguration()).
638            build();
639        if(connectFailedOnce) {
640          DFSClient.LOG.info("Successfully connected to " + targetAddr +
641                             " for " + blk);
642        }
643        return chosenNode;
644      } catch (IOException ex) {
645        if (ex instanceof InvalidEncryptionKeyException && refetchEncryptionKey > 0) {
646          DFSClient.LOG.info("Will fetch a new encryption key and retry, " 
647              + "encryption key was invalid when connecting to " + targetAddr
648              + " : " + ex);
649          // The encryption key used is invalid.
650          refetchEncryptionKey--;
651          dfsClient.clearDataEncryptionKey();
652        } else if (refetchToken > 0 && tokenRefetchNeeded(ex, targetAddr)) {
653          refetchToken--;
654          fetchBlockAt(target);
655        } else {
656          connectFailedOnce = true;
657          DFSClient.LOG.warn("Failed to connect to " + targetAddr + " for block"
658            + ", add to deadNodes and continue. " + ex, ex);
659          // Put chosen node into dead list, continue
660          addToDeadNodes(chosenNode);
661        }
662      }
663    }
664  }
665
666  /**
667   * Close it down!
668   */
669  @Override
670  public synchronized void close() throws IOException {
671    if (!closed.compareAndSet(false, true)) {
672      DFSClient.LOG.debug("DFSInputStream has been closed already");
673      return;
674    }
675    dfsClient.checkOpen();
676
677    if ((extendedReadBuffers != null) && (!extendedReadBuffers.isEmpty())) {
678      final StringBuilder builder = new StringBuilder();
679      extendedReadBuffers.visitAll(new IdentityHashStore.Visitor<ByteBuffer, Object>() {
680        private String prefix = "";
681        @Override
682        public void accept(ByteBuffer k, Object v) {
683          builder.append(prefix).append(k);
684          prefix = ", ";
685        }
686      });
687      DFSClient.LOG.warn("closing file " + src + ", but there are still " +
688          "unreleased ByteBuffers allocated by read().  " +
689          "Please release " + builder.toString() + ".");
690    }
691    closeCurrentBlockReader();
692    super.close();
693  }
694
695  @Override
696  public synchronized int read() throws IOException {
697    if (oneByteBuf == null) {
698      oneByteBuf = new byte[1];
699    }
700    int ret = read( oneByteBuf, 0, 1 );
701    return ( ret <= 0 ) ? -1 : (oneByteBuf[0] & 0xff);
702  }
703
704  /**
705   * Wraps different possible read implementations so that readBuffer can be
706   * strategy-agnostic.
707   */
708  private interface ReaderStrategy {
709    public int doRead(BlockReader blockReader, int off, int len)
710        throws ChecksumException, IOException;
711  }
712
713  private void updateReadStatistics(ReadStatistics readStatistics, 
714        int nRead, BlockReader blockReader) {
715    if (nRead <= 0) return;
716    synchronized(infoLock) {
717      if (blockReader.isShortCircuit()) {
718        readStatistics.addShortCircuitBytes(nRead);
719      } else if (blockReader.isLocal()) {
720        readStatistics.addLocalBytes(nRead);
721      } else {
722        readStatistics.addRemoteBytes(nRead);
723      }
724    }
725  }
726  
727  /**
728   * Used to read bytes into a byte[]
729   */
730  private class ByteArrayStrategy implements ReaderStrategy {
731    final byte[] buf;
732
733    public ByteArrayStrategy(byte[] buf) {
734      this.buf = buf;
735    }
736
737    @Override
738    public int doRead(BlockReader blockReader, int off, int len)
739          throws ChecksumException, IOException {
740      int nRead = blockReader.read(buf, off, len);
741      updateReadStatistics(readStatistics, nRead, blockReader);
742      return nRead;
743    }
744  }
745
746  /**
747   * Used to read bytes into a user-supplied ByteBuffer
748   */
749  private class ByteBufferStrategy implements ReaderStrategy {
750    final ByteBuffer buf;
751    ByteBufferStrategy(ByteBuffer buf) {
752      this.buf = buf;
753    }
754
755    @Override
756    public int doRead(BlockReader blockReader, int off, int len)
757        throws ChecksumException, IOException {
758      int oldpos = buf.position();
759      int oldlimit = buf.limit();
760      boolean success = false;
761      try {
762        int ret = blockReader.read(buf);
763        success = true;
764        updateReadStatistics(readStatistics, ret, blockReader);
765        return ret;
766      } finally {
767        if (!success) {
768          // Reset to original state so that retries work correctly.
769          buf.position(oldpos);
770          buf.limit(oldlimit);
771        }
772      } 
773    }
774  }
775
776  /* This is a used by regular read() and handles ChecksumExceptions.
777   * name readBuffer() is chosen to imply similarity to readBuffer() in
778   * ChecksumFileSystem
779   */ 
780  private synchronized int readBuffer(ReaderStrategy reader, int off, int len,
781      Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap)
782      throws IOException {
783    IOException ioe;
784    
785    /* we retry current node only once. So this is set to true only here.
786     * Intention is to handle one common case of an error that is not a
787     * failure on datanode or client : when DataNode closes the connection
788     * since client is idle. If there are other cases of "non-errors" then
789     * then a datanode might be retried by setting this to true again.
790     */
791    boolean retryCurrentNode = true;
792
793    while (true) {
794      // retry as many times as seekToNewSource allows.
795      try {
796        return reader.doRead(blockReader, off, len);
797      } catch ( ChecksumException ce ) {
798        DFSClient.LOG.warn("Found Checksum error for "
799            + getCurrentBlock() + " from " + currentNode
800            + " at " + ce.getPos());        
801        ioe = ce;
802        retryCurrentNode = false;
803        // we want to remember which block replicas we have tried
804        addIntoCorruptedBlockMap(getCurrentBlock(), currentNode,
805            corruptedBlockMap);
806      } catch ( IOException e ) {
807        if (!retryCurrentNode) {
808          DFSClient.LOG.warn("Exception while reading from "
809              + getCurrentBlock() + " of " + src + " from "
810              + currentNode, e);
811        }
812        ioe = e;
813      }
814      boolean sourceFound = false;
815      if (retryCurrentNode) {
816        /* possibly retry the same node so that transient errors don't
817         * result in application level failures (e.g. Datanode could have
818         * closed the connection because the client is idle for too long).
819         */ 
820        sourceFound = seekToBlockSource(pos);
821      } else {
822        addToDeadNodes(currentNode);
823        sourceFound = seekToNewSource(pos);
824      }
825      if (!sourceFound) {
826        throw ioe;
827      }
828      retryCurrentNode = false;
829    }
830  }
831
832  private synchronized int readWithStrategy(ReaderStrategy strategy, int off, int len) throws IOException {
833    dfsClient.checkOpen();
834    if (closed.get()) {
835      throw new IOException("Stream closed");
836    }
837    Map<ExtendedBlock,Set<DatanodeInfo>> corruptedBlockMap 
838      = new HashMap<ExtendedBlock, Set<DatanodeInfo>>();
839    failures = 0;
840    if (pos < getFileLength()) {
841      int retries = 2;
842      while (retries > 0) {
843        try {
844          // currentNode can be left as null if previous read had a checksum
845          // error on the same block. See HDFS-3067
846          if (pos > blockEnd || currentNode == null) {
847            currentNode = blockSeekTo(pos);
848          }
849          int realLen = (int) Math.min(len, (blockEnd - pos + 1L));
850          synchronized(infoLock) {
851            if (locatedBlocks.isLastBlockComplete()) {
852              realLen = (int) Math.min(realLen,
853                  locatedBlocks.getFileLength() - pos);
854            }
855          }
856          int result = readBuffer(strategy, off, realLen, corruptedBlockMap);
857          
858          if (result >= 0) {
859            pos += result;
860          } else {
861            // got a EOS from reader though we expect more data on it.
862            throw new IOException("Unexpected EOS from the reader");
863          }
864          if (dfsClient.stats != null) {
865            dfsClient.stats.incrementBytesRead(result);
866          }
867          return result;
868        } catch (ChecksumException ce) {
869          throw ce;            
870        } catch (IOException e) {
871          if (retries == 1) {
872            DFSClient.LOG.warn("DFS Read", e);
873          }
874          blockEnd = -1;
875          if (currentNode != null) { addToDeadNodes(currentNode); }
876          if (--retries == 0) {
877            throw e;
878          }
879        } finally {
880          // Check if need to report block replicas corruption either read
881          // was successful or ChecksumException occured.
882          reportCheckSumFailure(corruptedBlockMap, 
883              currentLocatedBlock.getLocations().length);
884        }
885      }
886    }
887    return -1;
888  }
889
890  /**
891   * Read the entire buffer.
892   */
893  @Override
894  public synchronized int read(final byte buf[], int off, int len) throws IOException {
895    ReaderStrategy byteArrayReader = new ByteArrayStrategy(buf);
896
897    return readWithStrategy(byteArrayReader, off, len);
898  }
899
900  @Override
901  public synchronized int read(final ByteBuffer buf) throws IOException {
902    ReaderStrategy byteBufferReader = new ByteBufferStrategy(buf);
903
904    return readWithStrategy(byteBufferReader, 0, buf.remaining());
905  }
906
907
908  /**
909   * Add corrupted block replica into map.
910   */
911  private void addIntoCorruptedBlockMap(ExtendedBlock blk, DatanodeInfo node, 
912      Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap) {
913    Set<DatanodeInfo> dnSet = null;
914    if((corruptedBlockMap.containsKey(blk))) {
915      dnSet = corruptedBlockMap.get(blk);
916    }else {
917      dnSet = new HashSet<DatanodeInfo>();
918    }
919    if (!dnSet.contains(node)) {
920      dnSet.add(node);
921      corruptedBlockMap.put(blk, dnSet);
922    }
923  }
924
925  private DNAddrPair chooseDataNode(LocatedBlock block,
926      Collection<DatanodeInfo> ignoredNodes) throws IOException {
927    while (true) {
928      try {
929        return getBestNodeDNAddrPair(block, ignoredNodes);
930      } catch (IOException ie) {
931        String errMsg = getBestNodeDNAddrPairErrorString(block.getLocations(),
932          deadNodes, ignoredNodes);
933        String blockInfo = block.getBlock() + " file=" + src;
934        if (failures >= dfsClient.getMaxBlockAcquireFailures()) {
935          String description = "Could not obtain block: " + blockInfo;
936          DFSClient.LOG.warn(description + errMsg
937              + ". Throwing a BlockMissingException");
938          throw new BlockMissingException(src, description,
939              block.getStartOffset());
940        }
941
942        DatanodeInfo[] nodes = block.getLocations();
943        if (nodes == null || nodes.length == 0) {
944          DFSClient.LOG.info("No node available for " + blockInfo);
945        }
946        DFSClient.LOG.info("Could not obtain " + block.getBlock()
947            + " from any node: " + ie + errMsg
948            + ". Will get new block locations from namenode and retry...");
949        try {
950          // Introducing a random factor to the wait time before another retry.
951          // The wait time is dependent on # of failures and a random factor.
952          // At the first time of getting a BlockMissingException, the wait time
953          // is a random number between 0..3000 ms. If the first retry
954          // still fails, we will wait 3000 ms grace period before the 2nd retry.
955          // Also at the second retry, the waiting window is expanded to 6000 ms
956          // alleviating the request rate from the server. Similarly the 3rd retry
957          // will wait 6000ms grace period before retry and the waiting window is
958          // expanded to 9000ms. 
959          final int timeWindow = dfsClient.getConf().timeWindow;
960          double waitTime = timeWindow * failures +       // grace period for the last round of attempt
961            timeWindow * (failures + 1) * DFSUtil.getRandom().nextDouble(); // expanding time window for each failure
962          DFSClient.LOG.warn("DFS chooseDataNode: got # " + (failures + 1) + " IOException, will wait for " + waitTime + " msec.");
963          Thread.sleep((long)waitTime);
964        } catch (InterruptedException iex) {
965        }
966        deadNodes.clear(); //2nd option is to remove only nodes[blockId]
967        openInfo();
968        block = getBlockAt(block.getStartOffset(), false);
969        failures++;
970        continue;
971      }
972    }
973  }
974
975  /**
976   * Get the best node from which to stream the data.
977   * @param block LocatedBlock, containing nodes in priority order.
978   * @param ignoredNodes Do not choose nodes in this array (may be null)
979   * @return The DNAddrPair of the best node.
980   * @throws IOException
981   */
982  private DNAddrPair getBestNodeDNAddrPair(LocatedBlock block,
983      Collection<DatanodeInfo> ignoredNodes) throws IOException {
984    DatanodeInfo[] nodes = block.getLocations();
985    StorageType[] storageTypes = block.getStorageTypes();
986    DatanodeInfo chosenNode = null;
987    StorageType storageType = null;
988    if (nodes != null) {
989      for (int i = 0; i < nodes.length; i++) {
990        if (!deadNodes.containsKey(nodes[i])
991            && (ignoredNodes == null || !ignoredNodes.contains(nodes[i]))) {
992          chosenNode = nodes[i];
993          // Storage types are ordered to correspond with nodes, so use the same
994          // index to get storage type.
995          if (storageTypes != null && i < storageTypes.length) {
996            storageType = storageTypes[i];
997          }
998          break;
999        }
1000      }
1001    }
1002    if (chosenNode == null) {
1003      throw new IOException("No live nodes contain block " + block.getBlock() +
1004          " after checking nodes = " + Arrays.toString(nodes) +
1005          ", ignoredNodes = " + ignoredNodes);
1006    }
1007    final String dnAddr =
1008        chosenNode.getXferAddr(dfsClient.getConf().connectToDnViaHostname);
1009    if (DFSClient.LOG.isDebugEnabled()) {
1010      DFSClient.LOG.debug("Connecting to datanode " + dnAddr);
1011    }
1012    InetSocketAddress targetAddr = NetUtils.createSocketAddr(dnAddr);
1013    return new DNAddrPair(chosenNode, targetAddr, storageType);
1014  }
1015
1016  private static String getBestNodeDNAddrPairErrorString(
1017      DatanodeInfo nodes[], AbstractMap<DatanodeInfo,
1018      DatanodeInfo> deadNodes, Collection<DatanodeInfo> ignoredNodes) {
1019    StringBuilder errMsgr = new StringBuilder(
1020        " No live nodes contain current block ");
1021    errMsgr.append("Block locations:");
1022    for (DatanodeInfo datanode : nodes) {
1023      errMsgr.append(" ");
1024      errMsgr.append(datanode.toString());
1025    }
1026    errMsgr.append(" Dead nodes: ");
1027    for (DatanodeInfo datanode : deadNodes.keySet()) {
1028      errMsgr.append(" ");
1029      errMsgr.append(datanode.toString());
1030    }
1031    if (ignoredNodes != null) {
1032      errMsgr.append(" Ignored nodes: ");
1033      for (DatanodeInfo datanode : ignoredNodes) {
1034        errMsgr.append(" ");
1035        errMsgr.append(datanode.toString());
1036      }
1037    }
1038    return errMsgr.toString();
1039  }
1040
1041  private void fetchBlockByteRange(LocatedBlock block, long start, long end,
1042      byte[] buf, int offset,
1043      Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap)
1044      throws IOException {
1045    block = getBlockAt(block.getStartOffset(), false);
1046    while (true) {
1047      DNAddrPair addressPair = chooseDataNode(block, null);
1048      try {
1049        actualGetFromOneDataNode(addressPair, block, start, end, buf, offset,
1050            corruptedBlockMap);
1051        return;
1052      } catch (IOException e) {
1053        // Ignore. Already processed inside the function.
1054        // Loop through to try the next node.
1055      }
1056    }
1057  }
1058
1059  private Callable<ByteBuffer> getFromOneDataNode(final DNAddrPair datanode,
1060      final LocatedBlock block, final long start, final long end,
1061      final ByteBuffer bb,
1062      final Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap) {
1063    return new Callable<ByteBuffer>() {
1064      @Override
1065      public ByteBuffer call() throws Exception {
1066        byte[] buf = bb.array();
1067        int offset = bb.position();
1068        actualGetFromOneDataNode(datanode, block, start, end, buf, offset,
1069            corruptedBlockMap);
1070        return bb;
1071      }
1072    };
1073  }
1074
1075  private void actualGetFromOneDataNode(final DNAddrPair datanode,
1076      LocatedBlock block, final long start, final long end, byte[] buf,
1077      int offset, Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap)
1078      throws IOException {
1079    DFSClientFaultInjector.get().startFetchFromDatanode();
1080    int refetchToken = 1; // only need to get a new access token once
1081    int refetchEncryptionKey = 1; // only need to get a new encryption key once
1082
1083    while (true) {
1084      // cached block locations may have been updated by chooseDataNode()
1085      // or fetchBlockAt(). Always get the latest list of locations at the
1086      // start of the loop.
1087      CachingStrategy curCachingStrategy;
1088      boolean allowShortCircuitLocalReads;
1089      block = getBlockAt(block.getStartOffset(), false);
1090      synchronized(infoLock) {
1091        curCachingStrategy = cachingStrategy;
1092        allowShortCircuitLocalReads = !shortCircuitForbidden();
1093      }
1094      DatanodeInfo chosenNode = datanode.info;
1095      InetSocketAddress targetAddr = datanode.addr;
1096      StorageType storageType = datanode.storageType;
1097      BlockReader reader = null;
1098
1099      try {
1100        DFSClientFaultInjector.get().fetchFromDatanodeException();
1101        Token<BlockTokenIdentifier> blockToken = block.getBlockToken();
1102        int len = (int) (end - start + 1);
1103        reader = new BlockReaderFactory(dfsClient.getConf()).
1104            setInetSocketAddress(targetAddr).
1105            setRemotePeerFactory(dfsClient).
1106            setDatanodeInfo(chosenNode).
1107            setStorageType(storageType).
1108            setFileName(src).
1109            setBlock(block.getBlock()).
1110            setBlockToken(blockToken).
1111            setStartOffset(start).
1112            setVerifyChecksum(verifyChecksum).
1113            setClientName(dfsClient.clientName).
1114            setLength(len).
1115            setCachingStrategy(curCachingStrategy).
1116            setAllowShortCircuitLocalReads(allowShortCircuitLocalReads).
1117            setClientCacheContext(dfsClient.getClientContext()).
1118            setUserGroupInformation(dfsClient.ugi).
1119            setConfiguration(dfsClient.getConfiguration()).
1120            build();
1121        int nread = reader.readAll(buf, offset, len);
1122        updateReadStatistics(readStatistics, nread, reader);
1123
1124        if (nread != len) {
1125          throw new IOException("truncated return from reader.read(): " +
1126                                "excpected " + len + ", got " + nread);
1127        }
1128        DFSClientFaultInjector.get().readFromDatanodeDelay();
1129        return;
1130      } catch (ChecksumException e) {
1131        String msg = "fetchBlockByteRange(). Got a checksum exception for "
1132            + src + " at " + block.getBlock() + ":" + e.getPos() + " from "
1133            + chosenNode;
1134        DFSClient.LOG.warn(msg);
1135        // we want to remember what we have tried
1136        addIntoCorruptedBlockMap(block.getBlock(), chosenNode, corruptedBlockMap);
1137        addToDeadNodes(chosenNode);
1138        throw new IOException(msg);
1139      } catch (IOException e) {
1140        if (e instanceof InvalidEncryptionKeyException && refetchEncryptionKey > 0) {
1141          DFSClient.LOG.info("Will fetch a new encryption key and retry, " 
1142              + "encryption key was invalid when connecting to " + targetAddr
1143              + " : " + e);
1144          // The encryption key used is invalid.
1145          refetchEncryptionKey--;
1146          dfsClient.clearDataEncryptionKey();
1147          continue;
1148        } else if (refetchToken > 0 && tokenRefetchNeeded(e, targetAddr)) {
1149          refetchToken--;
1150          try {
1151            fetchBlockAt(block.getStartOffset());
1152          } catch (IOException fbae) {
1153            // ignore IOE, since we can retry it later in a loop
1154          }
1155          continue;
1156        } else {
1157          String msg = "Failed to connect to " + targetAddr + " for file "
1158              + src + " for block " + block.getBlock() + ":" + e;
1159          DFSClient.LOG.warn("Connection failure: " + msg, e);
1160          addToDeadNodes(chosenNode);
1161          throw new IOException(msg);
1162        }
1163      } finally {
1164        if (reader != null) {
1165          reader.close();
1166        }
1167      }
1168    }
1169  }
1170
1171  /**
1172   * Like {@link #fetchBlockByteRange(LocatedBlock, long, long, byte[],
1173   * int, Map)} except we start up a second, parallel, 'hedged' read
1174   * if the first read is taking longer than configured amount of
1175   * time.  We then wait on which ever read returns first.
1176   */
1177  private void hedgedFetchBlockByteRange(LocatedBlock block, long start,
1178      long end, byte[] buf, int offset,
1179      Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap)
1180      throws IOException {
1181    ArrayList<Future<ByteBuffer>> futures = new ArrayList<Future<ByteBuffer>>();
1182    CompletionService<ByteBuffer> hedgedService =
1183        new ExecutorCompletionService<ByteBuffer>(
1184        dfsClient.getHedgedReadsThreadPool());
1185    ArrayList<DatanodeInfo> ignored = new ArrayList<DatanodeInfo>();
1186    ByteBuffer bb = null;
1187    int len = (int) (end - start + 1);
1188    block = getBlockAt(block.getStartOffset(), false);
1189    while (true) {
1190      // see HDFS-6591, this metric is used to verify/catch unnecessary loops
1191      hedgedReadOpsLoopNumForTesting++;
1192      DNAddrPair chosenNode = null;
1193      // there is no request already executing.
1194      if (futures.isEmpty()) {
1195        // chooseDataNode is a commitment. If no node, we go to
1196        // the NN to reget block locations. Only go here on first read.
1197        chosenNode = chooseDataNode(block, ignored);
1198        bb = ByteBuffer.wrap(buf, offset, len);
1199        Callable<ByteBuffer> getFromDataNodeCallable = getFromOneDataNode(
1200            chosenNode, block, start, end, bb, corruptedBlockMap);
1201        Future<ByteBuffer> firstRequest = hedgedService
1202            .submit(getFromDataNodeCallable);
1203        futures.add(firstRequest);
1204        try {
1205          Future<ByteBuffer> future = hedgedService.poll(
1206              dfsClient.getHedgedReadTimeout(), TimeUnit.MILLISECONDS);
1207          if (future != null) {
1208            future.get();
1209            return;
1210          }
1211          if (DFSClient.LOG.isDebugEnabled()) {
1212            DFSClient.LOG.debug("Waited " + dfsClient.getHedgedReadTimeout()
1213                + "ms to read from " + chosenNode.info
1214                + "; spawning hedged read");
1215          }
1216          // Ignore this node on next go around.
1217          ignored.add(chosenNode.info);
1218          dfsClient.getHedgedReadMetrics().incHedgedReadOps();
1219          continue; // no need to refresh block locations
1220        } catch (InterruptedException e) {
1221          // Ignore
1222        } catch (ExecutionException e) {
1223          // Ignore already logged in the call.
1224        }
1225      } else {
1226        // We are starting up a 'hedged' read. We have a read already
1227        // ongoing. Call getBestNodeDNAddrPair instead of chooseDataNode.
1228        // If no nodes to do hedged reads against, pass.
1229        try {
1230          try {
1231            chosenNode = getBestNodeDNAddrPair(block, ignored);
1232          } catch (IOException ioe) {
1233            chosenNode = chooseDataNode(block, ignored);
1234          }
1235          bb = ByteBuffer.allocate(len);
1236          Callable<ByteBuffer> getFromDataNodeCallable = getFromOneDataNode(
1237              chosenNode, block, start, end, bb, corruptedBlockMap);
1238          Future<ByteBuffer> oneMoreRequest = hedgedService
1239              .submit(getFromDataNodeCallable);
1240          futures.add(oneMoreRequest);
1241        } catch (IOException ioe) {
1242          if (DFSClient.LOG.isDebugEnabled()) {
1243            DFSClient.LOG.debug("Failed getting node for hedged read: "
1244                + ioe.getMessage());
1245          }
1246        }
1247        // if not succeeded. Submit callables for each datanode in a loop, wait
1248        // for a fixed interval and get the result from the fastest one.
1249        try {
1250          ByteBuffer result = getFirstToComplete(hedgedService, futures);
1251          // cancel the rest.
1252          cancelAll(futures);
1253          if (result.array() != buf) { // compare the array pointers
1254            dfsClient.getHedgedReadMetrics().incHedgedReadWins();
1255            System.arraycopy(result.array(), result.position(), buf, offset,
1256                len);
1257          } else {
1258            dfsClient.getHedgedReadMetrics().incHedgedReadOps();
1259          }
1260          return;
1261        } catch (InterruptedException ie) {
1262          // Ignore and retry
1263        }
1264        // We got here if exception. Ignore this node on next go around IFF
1265        // we found a chosenNode to hedge read against.
1266        if (chosenNode != null && chosenNode.info != null) {
1267          ignored.add(chosenNode.info);
1268        }
1269      }
1270    }
1271  }
1272
1273  @VisibleForTesting
1274  public long getHedgedReadOpsLoopNumForTesting() {
1275    return hedgedReadOpsLoopNumForTesting;
1276  }
1277
1278  private ByteBuffer getFirstToComplete(
1279      CompletionService<ByteBuffer> hedgedService,
1280      ArrayList<Future<ByteBuffer>> futures) throws InterruptedException {
1281    if (futures.isEmpty()) {
1282      throw new InterruptedException("let's retry");
1283    }
1284    Future<ByteBuffer> future = null;
1285    try {
1286      future = hedgedService.take();
1287      ByteBuffer bb = future.get();
1288      futures.remove(future);
1289      return bb;
1290    } catch (ExecutionException e) {
1291      // already logged in the Callable
1292      futures.remove(future);
1293    } catch (CancellationException ce) {
1294      // already logged in the Callable
1295      futures.remove(future);
1296    }
1297
1298    throw new InterruptedException("let's retry");
1299  }
1300
1301  private void cancelAll(List<Future<ByteBuffer>> futures) {
1302    for (Future<ByteBuffer> future : futures) {
1303      // Unfortunately, hdfs reads do not take kindly to interruption.
1304      // Threads return a variety of interrupted-type exceptions but
1305      // also complaints about invalid pbs -- likely because read
1306      // is interrupted before gets whole pb.  Also verbose WARN
1307      // logging.  So, for now, do not interrupt running read.
1308      future.cancel(false);
1309    }
1310  }
1311
1312  /**
1313   * Should the block access token be refetched on an exception
1314   * 
1315   * @param ex Exception received
1316   * @param targetAddr Target datanode address from where exception was received
1317   * @return true if block access token has expired or invalid and it should be
1318   *         refetched
1319   */
1320  private static boolean tokenRefetchNeeded(IOException ex,
1321      InetSocketAddress targetAddr) {
1322    /*
1323     * Get a new access token and retry. Retry is needed in 2 cases. 1)
1324     * When both NN and DN re-started while DFSClient holding a cached
1325     * access token. 2) In the case that NN fails to update its
1326     * access key at pre-set interval (by a wide margin) and
1327     * subsequently restarts. In this case, DN re-registers itself with
1328     * NN and receives a new access key, but DN will delete the old
1329     * access key from its memory since it's considered expired based on
1330     * the estimated expiration date.
1331     */
1332    if (ex instanceof InvalidBlockTokenException || ex instanceof InvalidToken) {
1333      DFSClient.LOG.info("Access token was invalid when connecting to "
1334          + targetAddr + " : " + ex);
1335      return true;
1336    }
1337    return false;
1338  }
1339
1340  /**
1341   * Read bytes starting from the specified position.
1342   * 
1343   * @param position start read from this position
1344   * @param buffer read buffer
1345   * @param offset offset into buffer
1346   * @param length number of bytes to read
1347   * 
1348   * @return actual number of bytes read
1349   */
1350  @Override
1351  public int read(long position, byte[] buffer, int offset, int length)
1352    throws IOException {
1353    // sanity checks
1354    dfsClient.checkOpen();
1355    if (closed.get()) {
1356      throw new IOException("Stream closed");
1357    }
1358    failures = 0;
1359    long filelen = getFileLength();
1360    if ((position < 0) || (position >= filelen)) {
1361      return -1;
1362    }
1363    int realLen = length;
1364    if ((position + length) > filelen) {
1365      realLen = (int)(filelen - position);
1366    }
1367    
1368    // determine the block and byte range within the block
1369    // corresponding to position and realLen
1370    List<LocatedBlock> blockRange = getBlockRange(position, realLen);
1371    int remaining = realLen;
1372    Map<ExtendedBlock,Set<DatanodeInfo>> corruptedBlockMap 
1373      = new HashMap<ExtendedBlock, Set<DatanodeInfo>>();
1374    for (LocatedBlock blk : blockRange) {
1375      long targetStart = position - blk.getStartOffset();
1376      long bytesToRead = Math.min(remaining, blk.getBlockSize() - targetStart);
1377      try {
1378        if (dfsClient.isHedgedReadsEnabled()) {
1379          hedgedFetchBlockByteRange(blk, targetStart, targetStart + bytesToRead
1380              - 1, buffer, offset, corruptedBlockMap);
1381        } else {
1382          fetchBlockByteRange(blk, targetStart, targetStart + bytesToRead - 1,
1383              buffer, offset, corruptedBlockMap);
1384        }
1385      } finally {
1386        // Check and report if any block replicas are corrupted.
1387        // BlockMissingException may be caught if all block replicas are
1388        // corrupted.
1389        reportCheckSumFailure(corruptedBlockMap, blk.getLocations().length);
1390      }
1391
1392      remaining -= bytesToRead;
1393      position += bytesToRead;
1394      offset += bytesToRead;
1395    }
1396    assert remaining == 0 : "Wrong number of bytes read.";
1397    if (dfsClient.stats != null) {
1398      dfsClient.stats.incrementBytesRead(realLen);
1399    }
1400    return realLen;
1401  }
1402  
1403  /**
1404   * DFSInputStream reports checksum failure.
1405   * Case I : client has tried multiple data nodes and at least one of the
1406   * attempts has succeeded. We report the other failures as corrupted block to
1407   * namenode. 
1408   * Case II: client has tried out all data nodes, but all failed. We
1409   * only report if the total number of replica is 1. We do not
1410   * report otherwise since this maybe due to the client is a handicapped client
1411   * (who can not read).
1412   * @param corruptedBlockMap map of corrupted blocks
1413   * @param dataNodeCount number of data nodes who contains the block replicas
1414   */
1415  private void reportCheckSumFailure(
1416      Map<ExtendedBlock, Set<DatanodeInfo>> corruptedBlockMap, 
1417      int dataNodeCount) {
1418    if (corruptedBlockMap.isEmpty()) {
1419      return;
1420    }
1421    Iterator<Entry<ExtendedBlock, Set<DatanodeInfo>>> it = corruptedBlockMap
1422        .entrySet().iterator();
1423    Entry<ExtendedBlock, Set<DatanodeInfo>> entry = it.next();
1424    ExtendedBlock blk = entry.getKey();
1425    Set<DatanodeInfo> dnSet = entry.getValue();
1426    if (((dnSet.size() < dataNodeCount) && (dnSet.size() > 0))
1427        || ((dataNodeCount == 1) && (dnSet.size() == dataNodeCount))) {
1428      DatanodeInfo[] locs = new DatanodeInfo[dnSet.size()];
1429      int i = 0;
1430      for (DatanodeInfo dn:dnSet) {
1431        locs[i++] = dn;
1432      }
1433      LocatedBlock [] lblocks = { new LocatedBlock(blk, locs) };
1434      dfsClient.reportChecksumFailure(src, lblocks);
1435    }
1436    corruptedBlockMap.clear();
1437  }
1438
1439  @Override
1440  public long skip(long n) throws IOException {
1441    if ( n > 0 ) {
1442      long curPos = getPos();
1443      long fileLen = getFileLength();
1444      if( n+curPos > fileLen ) {
1445        n = fileLen - curPos;
1446      }
1447      seek(curPos+n);
1448      return n;
1449    }
1450    return n < 0 ? -1 : 0;
1451  }
1452
1453  /**
1454   * Seek to a new arbitrary location
1455   */
1456  @Override
1457  public synchronized void seek(long targetPos) throws IOException {
1458    if (targetPos > getFileLength()) {
1459      throw new EOFException("Cannot seek after EOF");
1460    }
1461    if (targetPos < 0) {
1462      throw new EOFException("Cannot seek to negative offset");
1463    }
1464    if (closed.get()) {
1465      throw new IOException("Stream is closed!");
1466    }
1467    boolean done = false;
1468    if (pos <= targetPos && targetPos <= blockEnd) {
1469      //
1470      // If this seek is to a positive position in the current
1471      // block, and this piece of data might already be lying in
1472      // the TCP buffer, then just eat up the intervening data.
1473      //
1474      int diff = (int)(targetPos - pos);
1475      if (diff <= blockReader.available()) {
1476        try {
1477          pos += blockReader.skip(diff);
1478          if (pos == targetPos) {
1479            done = true;
1480          } else {
1481            // The range was already checked. If the block reader returns
1482            // something unexpected instead of throwing an exception, it is
1483            // most likely a bug. 
1484            String errMsg = "BlockReader failed to seek to " + 
1485                targetPos + ". Instead, it seeked to " + pos + ".";
1486            DFSClient.LOG.warn(errMsg);
1487            throw new IOException(errMsg);
1488          }
1489        } catch (IOException e) {//make following read to retry
1490          if(DFSClient.LOG.isDebugEnabled()) {
1491            DFSClient.LOG.debug("Exception while seek to " + targetPos
1492                + " from " + getCurrentBlock() + " of " + src + " from "
1493                + currentNode, e);
1494          }
1495        }
1496      }
1497    }
1498    if (!done) {
1499      pos = targetPos;
1500      blockEnd = -1;
1501    }
1502  }
1503
1504  /**
1505   * Same as {@link #seekToNewSource(long)} except that it does not exclude
1506   * the current datanode and might connect to the same node.
1507   */
1508  private boolean seekToBlockSource(long targetPos)
1509                                                 throws IOException {
1510    currentNode = blockSeekTo(targetPos);
1511    return true;
1512  }
1513  
1514  /**
1515   * Seek to given position on a node other than the current node.  If
1516   * a node other than the current node is found, then returns true. 
1517   * If another node could not be found, then returns false.
1518   */
1519  @Override
1520  public synchronized boolean seekToNewSource(long targetPos) throws IOException {
1521    boolean markedDead = deadNodes.containsKey(currentNode);
1522    addToDeadNodes(currentNode);
1523    DatanodeInfo oldNode = currentNode;
1524    DatanodeInfo newNode = blockSeekTo(targetPos);
1525    if (!markedDead) {
1526      /* remove it from deadNodes. blockSeekTo could have cleared 
1527       * deadNodes and added currentNode again. Thats ok. */
1528      deadNodes.remove(oldNode);
1529    }
1530    if (!oldNode.getDatanodeUuid().equals(newNode.getDatanodeUuid())) {
1531      currentNode = newNode;
1532      return true;
1533    } else {
1534      return false;
1535    }
1536  }
1537      
1538  /**
1539   */
1540  @Override
1541  public synchronized long getPos() throws IOException {
1542    return pos;
1543  }
1544
1545  /** Return the size of the remaining available bytes
1546   * if the size is less than or equal to {@link Integer#MAX_VALUE},
1547   * otherwise, return {@link Integer#MAX_VALUE}.
1548   */
1549  @Override
1550  public synchronized int available() throws IOException {
1551    if (closed.get()) {
1552      throw new IOException("Stream closed");
1553    }
1554
1555    final long remaining = getFileLength() - pos;
1556    return remaining <= Integer.MAX_VALUE? (int)remaining: Integer.MAX_VALUE;
1557  }
1558
1559  /**
1560   * We definitely don't support marks
1561   */
1562  @Override
1563  public boolean markSupported() {
1564    return false;
1565  }
1566  @Override
1567  public void mark(int readLimit) {
1568  }
1569  @Override
1570  public void reset() throws IOException {
1571    throw new IOException("Mark/reset not supported");
1572  }
1573
1574  /** Utility class to encapsulate data node info and its address. */
1575  private static final class DNAddrPair {
1576    final DatanodeInfo info;
1577    final InetSocketAddress addr;
1578    final StorageType storageType;
1579
1580    DNAddrPair(DatanodeInfo info, InetSocketAddress addr,
1581        StorageType storageType) {
1582      this.info = info;
1583      this.addr = addr;
1584      this.storageType = storageType;
1585    }
1586  }
1587
1588  /**
1589   * Get statistics about the reads which this DFSInputStream has done.
1590   */
1591  public ReadStatistics getReadStatistics() {
1592    synchronized(infoLock) {
1593      return new ReadStatistics(readStatistics);
1594    }
1595  }
1596
1597  /**
1598   * Clear statistics about the reads which this DFSInputStream has done.
1599   */
1600  public void clearReadStatistics() {
1601    synchronized(infoLock) {
1602      readStatistics.clear();
1603    }
1604  }
1605
1606  public FileEncryptionInfo getFileEncryptionInfo() {
1607    synchronized(infoLock) {
1608      return fileEncryptionInfo;
1609    }
1610  }
1611
1612  private void closeCurrentBlockReader() {
1613    if (blockReader == null) return;
1614    // Close the current block reader so that the new caching settings can 
1615    // take effect immediately.
1616    try {
1617      blockReader.close();
1618    } catch (IOException e) {
1619      DFSClient.LOG.error("error closing blockReader", e);
1620    }
1621    blockReader = null;
1622    blockEnd = -1;
1623  }
1624
1625  @Override
1626  public synchronized void setReadahead(Long readahead)
1627      throws IOException {
1628    synchronized (infoLock) {
1629      this.cachingStrategy =
1630          new CachingStrategy.Builder(this.cachingStrategy).setReadahead(readahead).build();
1631    }
1632    closeCurrentBlockReader();
1633  }
1634
1635  @Override
1636  public synchronized void setDropBehind(Boolean dropBehind)
1637      throws IOException {
1638    synchronized (infoLock) {
1639      this.cachingStrategy =
1640          new CachingStrategy.Builder(this.cachingStrategy).setDropBehind(dropBehind).build();
1641    }
1642    closeCurrentBlockReader();
1643  }
1644
1645  /**
1646   * The immutable empty buffer we return when we reach EOF when doing a
1647   * zero-copy read.
1648   */
1649  private static final ByteBuffer EMPTY_BUFFER =
1650    ByteBuffer.allocateDirect(0).asReadOnlyBuffer();
1651
1652  @Override
1653  public synchronized ByteBuffer read(ByteBufferPool bufferPool,
1654      int maxLength, EnumSet<ReadOption> opts) 
1655          throws IOException, UnsupportedOperationException {
1656    if (maxLength == 0) {
1657      return EMPTY_BUFFER;
1658    } else if (maxLength < 0) {
1659      throw new IllegalArgumentException("can't read a negative " +
1660          "number of bytes.");
1661    }
1662    if ((blockReader == null) || (blockEnd == -1)) {
1663      if (pos >= getFileLength()) {
1664        return null;
1665      }
1666      /*
1667       * If we don't have a blockReader, or the one we have has no more bytes
1668       * left to read, we call seekToBlockSource to get a new blockReader and
1669       * recalculate blockEnd.  Note that we assume we're not at EOF here
1670       * (we check this above).
1671       */
1672      if ((!seekToBlockSource(pos)) || (blockReader == null)) {
1673        throw new IOException("failed to allocate new BlockReader " +
1674            "at position " + pos);
1675      }
1676    }
1677    ByteBuffer buffer = null;
1678    if (dfsClient.getConf().shortCircuitMmapEnabled) {
1679      buffer = tryReadZeroCopy(maxLength, opts);
1680    }
1681    if (buffer != null) {
1682      return buffer;
1683    }
1684    buffer = ByteBufferUtil.fallbackRead(this, bufferPool, maxLength);
1685    if (buffer != null) {
1686      getExtendedReadBuffers().put(buffer, bufferPool);
1687    }
1688    return buffer;
1689  }
1690
1691  private synchronized ByteBuffer tryReadZeroCopy(int maxLength,
1692      EnumSet<ReadOption> opts) throws IOException {
1693    // Copy 'pos' and 'blockEnd' to local variables to make it easier for the
1694    // JVM to optimize this function.
1695    final long curPos = pos;
1696    final long curEnd = blockEnd;
1697    final long blockStartInFile = currentLocatedBlock.getStartOffset();
1698    final long blockPos = curPos - blockStartInFile;
1699
1700    // Shorten this read if the end of the block is nearby.
1701    long length63;
1702    if ((curPos + maxLength) <= (curEnd + 1)) {
1703      length63 = maxLength;
1704    } else {
1705      length63 = 1 + curEnd - curPos;
1706      if (length63 <= 0) {
1707        if (DFSClient.LOG.isDebugEnabled()) {
1708          DFSClient.LOG.debug("Unable to perform a zero-copy read from offset " +
1709            curPos + " of " + src + "; " + length63 + " bytes left in block.  " +
1710            "blockPos=" + blockPos + "; curPos=" + curPos +
1711            "; curEnd=" + curEnd);
1712        }
1713        return null;
1714      }
1715      if (DFSClient.LOG.isDebugEnabled()) {
1716        DFSClient.LOG.debug("Reducing read length from " + maxLength +
1717            " to " + length63 + " to avoid going more than one byte " +
1718            "past the end of the block.  blockPos=" + blockPos +
1719            "; curPos=" + curPos + "; curEnd=" + curEnd);
1720      }
1721    }
1722    // Make sure that don't go beyond 31-bit offsets in the MappedByteBuffer.
1723    int length;
1724    if (blockPos + length63 <= Integer.MAX_VALUE) {
1725      length = (int)length63;
1726    } else {
1727      long length31 = Integer.MAX_VALUE - blockPos;
1728      if (length31 <= 0) {
1729        // Java ByteBuffers can't be longer than 2 GB, because they use
1730        // 4-byte signed integers to represent capacity, etc.
1731        // So we can't mmap the parts of the block higher than the 2 GB offset.
1732        // FIXME: we could work around this with multiple memory maps.
1733        // See HDFS-5101.
1734        if (DFSClient.LOG.isDebugEnabled()) {
1735          DFSClient.LOG.debug("Unable to perform a zero-copy read from offset " +
1736            curPos + " of " + src + "; 31-bit MappedByteBuffer limit " +
1737            "exceeded.  blockPos=" + blockPos + ", curEnd=" + curEnd);
1738        }
1739        return null;
1740      }
1741      length = (int)length31;
1742      if (DFSClient.LOG.isDebugEnabled()) {
1743        DFSClient.LOG.debug("Reducing read length from " + maxLength +
1744            " to " + length + " to avoid 31-bit limit.  " +
1745            "blockPos=" + blockPos + "; curPos=" + curPos +
1746            "; curEnd=" + curEnd);
1747      }
1748    }
1749    final ClientMmap clientMmap = blockReader.getClientMmap(opts);
1750    if (clientMmap == null) {
1751      if (DFSClient.LOG.isDebugEnabled()) {
1752        DFSClient.LOG.debug("unable to perform a zero-copy read from offset " +
1753          curPos + " of " + src + "; BlockReader#getClientMmap returned " +
1754          "null.");
1755      }
1756      return null;
1757    }
1758    boolean success = false;
1759    ByteBuffer buffer;
1760    try {
1761      seek(curPos + length);
1762      buffer = clientMmap.getMappedByteBuffer().asReadOnlyBuffer();
1763      buffer.position((int)blockPos);
1764      buffer.limit((int)(blockPos + length));
1765      getExtendedReadBuffers().put(buffer, clientMmap);
1766      synchronized (infoLock) {
1767        readStatistics.addZeroCopyBytes(length);
1768      }
1769      if (DFSClient.LOG.isDebugEnabled()) {
1770        DFSClient.LOG.debug("readZeroCopy read " + length + 
1771            " bytes from offset " + curPos + " via the zero-copy read " +
1772            "path.  blockEnd = " + blockEnd);
1773      }
1774      success = true;
1775    } finally {
1776      if (!success) {
1777        IOUtils.closeQuietly(clientMmap);
1778      }
1779    }
1780    return buffer;
1781  }
1782
1783  @Override
1784  public synchronized void releaseBuffer(ByteBuffer buffer) {
1785    if (buffer == EMPTY_BUFFER) return;
1786    Object val = getExtendedReadBuffers().remove(buffer);
1787    if (val == null) {
1788      throw new IllegalArgumentException("tried to release a buffer " +
1789          "that was not created by this stream, " + buffer);
1790    }
1791    if (val instanceof ClientMmap) {
1792      IOUtils.closeQuietly((ClientMmap)val);
1793    } else if (val instanceof ByteBufferPool) {
1794      ((ByteBufferPool)val).putBuffer(buffer);
1795    }
1796  }
1797
1798  @Override
1799  public synchronized void unbuffer() {
1800    closeCurrentBlockReader();
1801  }
1802}