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 static org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ShortCircuitFdResponse.USE_RECEIPT_VERIFICATION;
021
022import java.io.BufferedOutputStream;
023import java.io.DataInputStream;
024import java.io.DataOutputStream;
025import java.io.FileInputStream;
026import java.io.IOException;
027import java.net.InetSocketAddress;
028
029import org.apache.commons.lang.mutable.MutableBoolean;
030import org.apache.commons.logging.Log;
031import org.apache.commons.logging.LogFactory;
032import org.apache.hadoop.classification.InterfaceAudience;
033import org.apache.hadoop.conf.Configuration;
034import org.apache.hadoop.hdfs.net.DomainPeer;
035import org.apache.hadoop.hdfs.net.Peer;
036import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
037import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
038import org.apache.hadoop.hdfs.protocol.datatransfer.InvalidEncryptionKeyException;
039import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
040import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
041import org.apache.hadoop.hdfs.protocolPB.PBHelper;
042import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
043import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException;
044import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
045import org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory;
046import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache;
047import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitCache.ShortCircuitReplicaCreator;
048import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitReplica;
049import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitReplicaInfo;
050import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.Slot;
051import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.SlotId;
052import org.apache.hadoop.io.IOUtils;
053import org.apache.hadoop.ipc.RemoteException;
054import org.apache.hadoop.net.unix.DomainSocket;
055import org.apache.hadoop.security.AccessControlException;
056import org.apache.hadoop.security.UserGroupInformation;
057import org.apache.hadoop.security.token.SecretManager.InvalidToken;
058import org.apache.hadoop.security.token.Token;
059import org.apache.hadoop.util.PerformanceAdvisory;
060import org.apache.hadoop.util.Time;
061
062import com.google.common.annotations.VisibleForTesting;
063import com.google.common.base.Preconditions;
064
065
066/** 
067 * Utility class to create BlockReader implementations.
068 */
069@InterfaceAudience.Private
070public class BlockReaderFactory implements ShortCircuitReplicaCreator {
071  static final Log LOG = LogFactory.getLog(BlockReaderFactory.class);
072
073  public static class FailureInjector {
074    public void injectRequestFileDescriptorsFailure() throws IOException {
075      // do nothing
076    }
077    public boolean getSupportsReceiptVerification() {
078      return true;
079    }
080  }
081
082  @VisibleForTesting
083  static ShortCircuitReplicaCreator
084      createShortCircuitReplicaInfoCallback = null;
085
086  private final DFSClient.Conf conf;
087
088  /**
089   * Injects failures into specific operations during unit tests.
090   */
091  private final FailureInjector failureInjector;
092
093  /**
094   * The file name, for logging and debugging purposes.
095   */
096  private String fileName;
097
098  /**
099   * The block ID and block pool ID to use.
100   */
101  private ExtendedBlock block;
102
103  /**
104   * The block token to use for security purposes.
105   */
106  private Token<BlockTokenIdentifier> token;
107
108  /**
109   * The offset within the block to start reading at.
110   */
111  private long startOffset;
112
113  /**
114   * If false, we won't try to verify the block checksum.
115   */
116  private boolean verifyChecksum;
117
118  /**
119   * The name of this client.
120   */
121  private String clientName; 
122
123  /**
124   * The DataNode we're talking to.
125   */
126  private DatanodeInfo datanode;
127
128  /**
129   * StorageType of replica on DataNode.
130   */
131  private StorageType storageType;
132
133  /**
134   * If false, we won't try short-circuit local reads.
135   */
136  private boolean allowShortCircuitLocalReads;
137
138  /**
139   * The ClientContext to use for things like the PeerCache.
140   */
141  private ClientContext clientContext;
142
143  /**
144   * Number of bytes to read.  -1 indicates no limit.
145   */
146  private long length = -1;
147
148  /**
149   * Caching strategy to use when reading the block.
150   */
151  private CachingStrategy cachingStrategy;
152
153  /**
154   * Socket address to use to connect to peer.
155   */
156  private InetSocketAddress inetSocketAddress;
157
158  /**
159   * Remote peer factory to use to create a peer, if needed.
160   */
161  private RemotePeerFactory remotePeerFactory;
162
163  /**
164   * UserGroupInformation  to use for legacy block reader local objects, if needed.
165   */
166  private UserGroupInformation userGroupInformation;
167
168  /**
169   * Configuration to use for legacy block reader local objects, if needed.
170   */
171  private Configuration configuration;
172
173  /**
174   * Information about the domain socket path we should use to connect to the
175   * local peer-- or null if we haven't examined the local domain socket.
176   */
177  private DomainSocketFactory.PathInfo pathInfo;
178
179  /**
180   * The remaining number of times that we'll try to pull a socket out of the
181   * cache.
182   */
183  private int remainingCacheTries;
184
185  public BlockReaderFactory(DFSClient.Conf conf) {
186    this.conf = conf;
187    this.failureInjector = conf.brfFailureInjector;
188    this.remainingCacheTries = conf.nCachedConnRetry;
189  }
190
191  public BlockReaderFactory setFileName(String fileName) {
192    this.fileName = fileName;
193    return this;
194  }
195
196  public BlockReaderFactory setBlock(ExtendedBlock block) {
197    this.block = block;
198    return this;
199  }
200
201  public BlockReaderFactory setBlockToken(Token<BlockTokenIdentifier> token) {
202    this.token = token;
203    return this;
204  }
205
206  public BlockReaderFactory setStartOffset(long startOffset) {
207    this.startOffset = startOffset;
208    return this;
209  }
210
211  public BlockReaderFactory setVerifyChecksum(boolean verifyChecksum) {
212    this.verifyChecksum = verifyChecksum;
213    return this;
214  }
215
216  public BlockReaderFactory setClientName(String clientName) {
217    this.clientName = clientName;
218    return this;
219  }
220
221  public BlockReaderFactory setDatanodeInfo(DatanodeInfo datanode) {
222    this.datanode = datanode;
223    return this;
224  }
225
226  public BlockReaderFactory setStorageType(StorageType storageType) {
227    this.storageType = storageType;
228    return this;
229  }
230
231  public BlockReaderFactory setAllowShortCircuitLocalReads(
232      boolean allowShortCircuitLocalReads) {
233    this.allowShortCircuitLocalReads = allowShortCircuitLocalReads;
234    return this;
235  }
236
237  public BlockReaderFactory setClientCacheContext(
238      ClientContext clientContext) {
239    this.clientContext = clientContext;
240    return this;
241  }
242
243  public BlockReaderFactory setLength(long length) {
244    this.length = length;
245    return this;
246  }
247
248  public BlockReaderFactory setCachingStrategy(
249      CachingStrategy cachingStrategy) {
250    this.cachingStrategy = cachingStrategy;
251    return this;
252  }
253
254  public BlockReaderFactory setInetSocketAddress (
255      InetSocketAddress inetSocketAddress) {
256    this.inetSocketAddress = inetSocketAddress;
257    return this;
258  }
259
260  public BlockReaderFactory setUserGroupInformation(
261      UserGroupInformation userGroupInformation) {
262    this.userGroupInformation = userGroupInformation;
263    return this;
264  }
265
266  public BlockReaderFactory setRemotePeerFactory(
267      RemotePeerFactory remotePeerFactory) {
268    this.remotePeerFactory = remotePeerFactory;
269    return this;
270  }
271
272  public BlockReaderFactory setConfiguration(
273      Configuration configuration) {
274    this.configuration = configuration;
275    return this;
276  }
277
278  /**
279   * Build a BlockReader with the given options.
280   *
281   * This function will do the best it can to create a block reader that meets
282   * all of our requirements.  We prefer short-circuit block readers
283   * (BlockReaderLocal and BlockReaderLocalLegacy) over remote ones, since the
284   * former avoid the overhead of socket communication.  If short-circuit is
285   * unavailable, our next fallback is data transfer over UNIX domain sockets,
286   * if dfs.client.domain.socket.data.traffic has been enabled.  If that doesn't
287   * work, we will try to create a remote block reader that operates over TCP
288   * sockets.
289   *
290   * There are a few caches that are important here.
291   *
292   * The ShortCircuitCache stores file descriptor objects which have been passed
293   * from the DataNode. 
294   *
295   * The DomainSocketFactory stores information about UNIX domain socket paths
296   * that we not been able to use in the past, so that we don't waste time
297   * retrying them over and over.  (Like all the caches, it does have a timeout,
298   * though.)
299   *
300   * The PeerCache stores peers that we have used in the past.  If we can reuse
301   * one of these peers, we avoid the overhead of re-opening a socket.  However,
302   * if the socket has been timed out on the remote end, our attempt to reuse
303   * the socket may end with an IOException.  For that reason, we limit our
304   * attempts at socket reuse to dfs.client.cached.conn.retry times.  After
305   * that, we create new sockets.  This avoids the problem where a thread tries
306   * to talk to a peer that it hasn't talked to in a while, and has to clean out
307   * every entry in a socket cache full of stale entries.
308   *
309   * @return The new BlockReader.  We will not return null.
310   *
311   * @throws InvalidToken
312   *             If the block token was invalid.
313   *         InvalidEncryptionKeyException
314   *             If the encryption key was invalid.
315   *         Other IOException
316   *             If there was another problem.
317   */
318  public BlockReader build() throws IOException {
319    BlockReader reader = null;
320
321    Preconditions.checkNotNull(configuration);
322    if (conf.shortCircuitLocalReads && allowShortCircuitLocalReads) {
323      if (clientContext.getUseLegacyBlockReaderLocal()) {
324        reader = getLegacyBlockReaderLocal();
325        if (reader != null) {
326          if (LOG.isTraceEnabled()) {
327            LOG.trace(this + ": returning new legacy block reader local.");
328          }
329          return reader;
330        }
331      } else {
332        reader = getBlockReaderLocal();
333        if (reader != null) {
334          if (LOG.isTraceEnabled()) {
335            LOG.trace(this + ": returning new block reader local.");
336          }
337          return reader;
338        }
339      }
340    }
341    if (conf.domainSocketDataTraffic) {
342      reader = getRemoteBlockReaderFromDomain();
343      if (reader != null) {
344        if (LOG.isTraceEnabled()) {
345          LOG.trace(this + ": returning new remote block reader using " +
346              "UNIX domain socket on " + pathInfo.getPath());
347        }
348        return reader;
349      }
350    }
351    Preconditions.checkState(!DFSInputStream.tcpReadsDisabledForTesting,
352        "TCP reads were disabled for testing, but we failed to " +
353        "do a non-TCP read.");
354    return getRemoteBlockReaderFromTcp();
355  }
356
357  /**
358   * Get {@link BlockReaderLocalLegacy} for short circuited local reads.
359   * This block reader implements the path-based style of local reads
360   * first introduced in HDFS-2246.
361   */
362  private BlockReader getLegacyBlockReaderLocal() throws IOException {
363    if (LOG.isTraceEnabled()) {
364      LOG.trace(this + ": trying to construct BlockReaderLocalLegacy");
365    }
366    if (!DFSClient.isLocalAddress(inetSocketAddress)) {
367      if (LOG.isTraceEnabled()) {
368        LOG.trace(this + ": can't construct BlockReaderLocalLegacy because " +
369            "the address " + inetSocketAddress + " is not local");
370      }
371      return null;
372    }
373    if (clientContext.getDisableLegacyBlockReaderLocal()) {
374        PerformanceAdvisory.LOG.debug("{}: can't construct " +
375            "BlockReaderLocalLegacy because " +
376            "disableLegacyBlockReaderLocal is set.", this);
377      return null;
378    }
379    IOException ioe = null;
380    try {
381      return BlockReaderLocalLegacy.newBlockReader(conf,
382          userGroupInformation, configuration, fileName, block, token,
383          datanode, startOffset, length, storageType);
384    } catch (RemoteException remoteException) {
385      ioe = remoteException.unwrapRemoteException(
386                InvalidToken.class, AccessControlException.class);
387    } catch (IOException e) {
388      ioe = e;
389    }
390    if ((!(ioe instanceof AccessControlException)) &&
391        isSecurityException(ioe)) {
392      // Handle security exceptions.
393      // We do not handle AccessControlException here, since
394      // BlockReaderLocalLegacy#newBlockReader uses that exception to indicate
395      // that the user is not in dfs.block.local-path-access.user, a condition
396      // which requires us to disable legacy SCR.
397      throw ioe;
398    }
399    LOG.warn(this + ": error creating legacy BlockReaderLocal.  " +
400        "Disabling legacy local reads.", ioe);
401    clientContext.setDisableLegacyBlockReaderLocal();
402    return null;
403  }
404
405  private BlockReader getBlockReaderLocal() throws InvalidToken {
406    if (LOG.isTraceEnabled()) {
407      LOG.trace(this + ": trying to construct a BlockReaderLocal " +
408          "for short-circuit reads.");
409    }
410    if (pathInfo == null) {
411      pathInfo = clientContext.getDomainSocketFactory().
412                      getPathInfo(inetSocketAddress, conf);
413    }
414    if (!pathInfo.getPathState().getUsableForShortCircuit()) {
415      PerformanceAdvisory.LOG.debug("{}: {} is not usable for short circuit; " +
416              "giving up on BlockReaderLocal.", this, pathInfo);
417      return null;
418    }
419    ShortCircuitCache cache = clientContext.getShortCircuitCache();
420    ExtendedBlockId key = new ExtendedBlockId(block.getBlockId(), block.getBlockPoolId());
421    ShortCircuitReplicaInfo info = cache.fetchOrCreate(key, this);
422    InvalidToken exc = info.getInvalidTokenException();
423    if (exc != null) {
424      if (LOG.isTraceEnabled()) {
425        LOG.trace(this + ": got InvalidToken exception while trying to " +
426            "construct BlockReaderLocal via " + pathInfo.getPath());
427      }
428      throw exc;
429    }
430    if (info.getReplica() == null) {
431      PerformanceAdvisory.LOG.debug("{}: failed to get " +
432          "ShortCircuitReplica. Cannot construct " +
433          "BlockReaderLocal via {}", this, pathInfo.getPath());
434      return null;
435    }
436    return new BlockReaderLocal.Builder(conf).
437        setFilename(fileName).
438        setBlock(block).
439        setStartOffset(startOffset).
440        setShortCircuitReplica(info.getReplica()).
441        setVerifyChecksum(verifyChecksum).
442        setCachingStrategy(cachingStrategy).
443        setStorageType(storageType).
444        build();
445  }
446
447  /**
448   * Fetch a pair of short-circuit block descriptors from a local DataNode.
449   *
450   * @return    Null if we could not communicate with the datanode,
451   *            a new ShortCircuitReplicaInfo object otherwise.
452   *            ShortCircuitReplicaInfo objects may contain either an InvalidToken
453   *            exception, or a ShortCircuitReplica object ready to use.
454   */
455  @Override
456  public ShortCircuitReplicaInfo createShortCircuitReplicaInfo() {
457    if (createShortCircuitReplicaInfoCallback != null) {
458      ShortCircuitReplicaInfo info =
459        createShortCircuitReplicaInfoCallback.createShortCircuitReplicaInfo();
460      if (info != null) return info;
461    }
462    if (LOG.isTraceEnabled()) {
463      LOG.trace(this + ": trying to create ShortCircuitReplicaInfo.");
464    }
465    BlockReaderPeer curPeer;
466    while (true) {
467      curPeer = nextDomainPeer();
468      if (curPeer == null) break;
469      if (curPeer.fromCache) remainingCacheTries--;
470      DomainPeer peer = (DomainPeer)curPeer.peer;
471      Slot slot = null;
472      ShortCircuitCache cache = clientContext.getShortCircuitCache();
473      try {
474        MutableBoolean usedPeer = new MutableBoolean(false);
475        slot = cache.allocShmSlot(datanode, peer, usedPeer,
476            new ExtendedBlockId(block.getBlockId(), block.getBlockPoolId()),
477            clientName);
478        if (usedPeer.booleanValue()) {
479          if (LOG.isTraceEnabled()) {
480            LOG.trace(this + ": allocShmSlot used up our previous socket " +
481              peer.getDomainSocket() + ".  Allocating a new one...");
482          }
483          curPeer = nextDomainPeer();
484          if (curPeer == null) break;
485          peer = (DomainPeer)curPeer.peer;
486        }
487        ShortCircuitReplicaInfo info = requestFileDescriptors(peer, slot);
488        clientContext.getPeerCache().put(datanode, peer);
489        return info;
490      } catch (IOException e) {
491        if (slot != null) {
492          cache.freeSlot(slot);
493        }
494        if (curPeer.fromCache) {
495          // Handle an I/O error we got when using a cached socket.
496          // These are considered less serious, because the socket may be stale.
497          if (LOG.isDebugEnabled()) {
498            LOG.debug(this + ": closing stale domain peer " + peer, e);
499          }
500          IOUtils.cleanup(LOG, peer);
501        } else {
502          // Handle an I/O error we got when using a newly created socket.
503          // We temporarily disable the domain socket path for a few minutes in
504          // this case, to prevent wasting more time on it.
505          LOG.warn(this + ": I/O error requesting file descriptors.  " + 
506              "Disabling domain socket " + peer.getDomainSocket(), e);
507          IOUtils.cleanup(LOG, peer);
508          clientContext.getDomainSocketFactory()
509              .disableDomainSocketPath(pathInfo.getPath());
510          return null;
511        }
512      }
513    }
514    return null;
515  }
516
517  /**
518   * Request file descriptors from a DomainPeer.
519   *
520   * @param peer   The peer to use for communication.
521   * @param slot   If non-null, the shared memory slot to associate with the 
522   *               new ShortCircuitReplica.
523   * 
524   * @return  A ShortCircuitReplica object if we could communicate with the
525   *          datanode; null, otherwise. 
526   * @throws  IOException If we encountered an I/O exception while communicating
527   *          with the datanode.
528   */
529  private ShortCircuitReplicaInfo requestFileDescriptors(DomainPeer peer,
530          Slot slot) throws IOException {
531    ShortCircuitCache cache = clientContext.getShortCircuitCache();
532    final DataOutputStream out =
533        new DataOutputStream(new BufferedOutputStream(peer.getOutputStream()));
534    SlotId slotId = slot == null ? null : slot.getSlotId();
535    new Sender(out).requestShortCircuitFds(block, token, slotId, 1,
536        failureInjector.getSupportsReceiptVerification());
537    DataInputStream in = new DataInputStream(peer.getInputStream());
538    BlockOpResponseProto resp = BlockOpResponseProto.parseFrom(
539        PBHelper.vintPrefixed(in));
540    DomainSocket sock = peer.getDomainSocket();
541    failureInjector.injectRequestFileDescriptorsFailure();
542    switch (resp.getStatus()) {
543    case SUCCESS:
544      byte buf[] = new byte[1];
545      FileInputStream fis[] = new FileInputStream[2];
546      sock.recvFileInputStreams(fis, buf, 0, buf.length);
547      ShortCircuitReplica replica = null;
548      try {
549        ExtendedBlockId key =
550            new ExtendedBlockId(block.getBlockId(), block.getBlockPoolId());
551        if (buf[0] == USE_RECEIPT_VERIFICATION.getNumber()) {
552          LOG.trace("Sending receipt verification byte for slot " + slot);
553          sock.getOutputStream().write(0);
554        }
555        replica = new ShortCircuitReplica(key, fis[0], fis[1], cache,
556            Time.monotonicNow(), slot);
557        return new ShortCircuitReplicaInfo(replica);
558      } catch (IOException e) {
559        // This indicates an error reading from disk, or a format error.  Since
560        // it's not a socket communication problem, we return null rather than
561        // throwing an exception.
562        LOG.warn(this + ": error creating ShortCircuitReplica.", e);
563        return null;
564      } finally {
565        if (replica == null) {
566          IOUtils.cleanup(DFSClient.LOG, fis[0], fis[1]);
567        }
568      }
569    case ERROR_UNSUPPORTED:
570      if (!resp.hasShortCircuitAccessVersion()) {
571        LOG.warn("short-circuit read access is disabled for " +
572            "DataNode " + datanode + ".  reason: " + resp.getMessage());
573        clientContext.getDomainSocketFactory()
574            .disableShortCircuitForPath(pathInfo.getPath());
575      } else {
576        LOG.warn("short-circuit read access for the file " +
577            fileName + " is disabled for DataNode " + datanode +
578            ".  reason: " + resp.getMessage());
579      }
580      return null;
581    case ERROR_ACCESS_TOKEN:
582      String msg = "access control error while " +
583          "attempting to set up short-circuit access to " +
584          fileName + resp.getMessage();
585      if (LOG.isDebugEnabled()) {
586        LOG.debug(this + ":" + msg);
587      }
588      return new ShortCircuitReplicaInfo(new InvalidToken(msg));
589    default:
590      LOG.warn(this + ": unknown response code " + resp.getStatus() +
591          " while attempting to set up short-circuit access. " +
592          resp.getMessage());
593      clientContext.getDomainSocketFactory()
594          .disableShortCircuitForPath(pathInfo.getPath());
595      return null;
596    }
597  }
598
599  /**
600   * Get a RemoteBlockReader that communicates over a UNIX domain socket.
601   *
602   * @return The new BlockReader, or null if we failed to create the block
603   * reader.
604   *
605   * @throws InvalidToken    If the block token was invalid.
606   * Potentially other security-related execptions.
607   */
608  private BlockReader getRemoteBlockReaderFromDomain() throws IOException {
609    if (pathInfo == null) {
610      pathInfo = clientContext.getDomainSocketFactory().
611                      getPathInfo(inetSocketAddress, conf);
612    }
613    if (!pathInfo.getPathState().getUsableForDataTransfer()) {
614      PerformanceAdvisory.LOG.debug("{}: not trying to create a " +
615          "remote block reader because the UNIX domain socket at {}" +
616           " is not usable.", this, pathInfo);
617      return null;
618    }
619    if (LOG.isTraceEnabled()) {
620      LOG.trace(this + ": trying to create a remote block reader from the " +
621          "UNIX domain socket at " + pathInfo.getPath());
622    }
623
624    while (true) {
625      BlockReaderPeer curPeer = nextDomainPeer();
626      if (curPeer == null) break;
627      if (curPeer.fromCache) remainingCacheTries--;
628      DomainPeer peer = (DomainPeer)curPeer.peer;
629      BlockReader blockReader = null;
630      try {
631        blockReader = getRemoteBlockReader(peer);
632        return blockReader;
633      } catch (IOException ioe) {
634        IOUtils.cleanup(LOG, peer);
635        if (isSecurityException(ioe)) {
636          if (LOG.isTraceEnabled()) {
637            LOG.trace(this + ": got security exception while constructing " +
638                "a remote block reader from the unix domain socket at " +
639                pathInfo.getPath(), ioe);
640          }
641          throw ioe;
642        }
643        if (curPeer.fromCache) {
644          // Handle an I/O error we got when using a cached peer.  These are
645          // considered less serious, because the underlying socket may be stale.
646          if (LOG.isDebugEnabled()) {
647            LOG.debug("Closed potentially stale domain peer " + peer, ioe);
648          }
649        } else {
650          // Handle an I/O error we got when using a newly created domain peer.
651          // We temporarily disable the domain socket path for a few minutes in
652          // this case, to prevent wasting more time on it.
653          LOG.warn("I/O error constructing remote block reader.  Disabling " +
654              "domain socket " + peer.getDomainSocket(), ioe);
655          clientContext.getDomainSocketFactory()
656              .disableDomainSocketPath(pathInfo.getPath());
657          return null;
658        }
659      } finally {
660        if (blockReader == null) {
661          IOUtils.cleanup(LOG, peer);
662        }
663      }
664    }
665    return null;
666  }
667
668  /**
669   * Get a RemoteBlockReader that communicates over a TCP socket.
670   *
671   * @return The new BlockReader.  We will not return null, but instead throw
672   *         an exception if this fails.
673   *
674   * @throws InvalidToken
675   *             If the block token was invalid.
676   *         InvalidEncryptionKeyException
677   *             If the encryption key was invalid.
678   *         Other IOException
679   *             If there was another problem.
680   */
681  private BlockReader getRemoteBlockReaderFromTcp() throws IOException {
682    if (LOG.isTraceEnabled()) {
683      LOG.trace(this + ": trying to create a remote block reader from a " +
684          "TCP socket");
685    }
686    BlockReader blockReader = null;
687    while (true) {
688      BlockReaderPeer curPeer = null;
689      Peer peer = null;
690      try {
691        curPeer = nextTcpPeer();
692        if (curPeer == null) break;
693        if (curPeer.fromCache) remainingCacheTries--;
694        peer = curPeer.peer;
695        blockReader = getRemoteBlockReader(peer);
696        return blockReader;
697      } catch (IOException ioe) {
698        if (isSecurityException(ioe)) {
699          if (LOG.isTraceEnabled()) {
700            LOG.trace(this + ": got security exception while constructing " +
701                "a remote block reader from " + peer, ioe);
702          }
703          throw ioe;
704        }
705        if ((curPeer != null) && curPeer.fromCache) {
706          // Handle an I/O error we got when using a cached peer.  These are
707          // considered less serious, because the underlying socket may be
708          // stale.
709          if (LOG.isDebugEnabled()) {
710            LOG.debug("Closed potentially stale remote peer " + peer, ioe);
711          }
712        } else {
713          // Handle an I/O error we got when using a newly created peer.
714          LOG.warn("I/O error constructing remote block reader.", ioe);
715          throw ioe;
716        }
717      } finally {
718        if (blockReader == null) {
719          IOUtils.cleanup(LOG, peer);
720        }
721      }
722    }
723    return null;
724  }
725
726  public static class BlockReaderPeer {
727    final Peer peer;
728    final boolean fromCache;
729    
730    BlockReaderPeer(Peer peer, boolean fromCache) {
731      this.peer = peer;
732      this.fromCache = fromCache;
733    }
734  }
735
736  /**
737   * Get the next DomainPeer-- either from the cache or by creating it.
738   *
739   * @return the next DomainPeer, or null if we could not construct one.
740   */
741  private BlockReaderPeer nextDomainPeer() {
742    if (remainingCacheTries > 0) {
743      Peer peer = clientContext.getPeerCache().get(datanode, true);
744      if (peer != null) {
745        if (LOG.isTraceEnabled()) {
746          LOG.trace("nextDomainPeer: reusing existing peer " + peer);
747        }
748        return new BlockReaderPeer(peer, true);
749      }
750    }
751    DomainSocket sock = clientContext.getDomainSocketFactory().
752        createSocket(pathInfo, conf.socketTimeout);
753    if (sock == null) return null;
754    return new BlockReaderPeer(new DomainPeer(sock), false);
755  }
756
757  /**
758   * Get the next TCP-based peer-- either from the cache or by creating it.
759   *
760   * @return the next Peer, or null if we could not construct one.
761   *
762   * @throws IOException  If there was an error while constructing the peer
763   *                      (such as an InvalidEncryptionKeyException)
764   */
765  private BlockReaderPeer nextTcpPeer() throws IOException {
766    if (remainingCacheTries > 0) {
767      Peer peer = clientContext.getPeerCache().get(datanode, false);
768      if (peer != null) {
769        if (LOG.isTraceEnabled()) {
770          LOG.trace("nextTcpPeer: reusing existing peer " + peer);
771        }
772        return new BlockReaderPeer(peer, true);
773      }
774    }
775    try {
776      Peer peer = remotePeerFactory.newConnectedPeer(inetSocketAddress, token,
777        datanode);
778      if (LOG.isTraceEnabled()) {
779        LOG.trace("nextTcpPeer: created newConnectedPeer " + peer);
780      }
781      return new BlockReaderPeer(peer, false);
782    } catch (IOException e) {
783      if (LOG.isTraceEnabled()) {
784        LOG.trace("nextTcpPeer: failed to create newConnectedPeer " +
785                  "connected to " + datanode);
786      }
787      throw e;
788    }
789  }
790
791  /**
792   * Determine if an exception is security-related.
793   *
794   * We need to handle these exceptions differently than other IOExceptions.
795   * They don't indicate a communication problem.  Instead, they mean that there
796   * is some action the client needs to take, such as refetching block tokens,
797   * renewing encryption keys, etc.
798   *
799   * @param ioe    The exception
800   * @return       True only if the exception is security-related.
801   */
802  private static boolean isSecurityException(IOException ioe) {
803    return (ioe instanceof InvalidToken) ||
804            (ioe instanceof InvalidEncryptionKeyException) ||
805            (ioe instanceof InvalidBlockTokenException) ||
806            (ioe instanceof AccessControlException);
807  }
808
809  @SuppressWarnings("deprecation")
810  private BlockReader getRemoteBlockReader(Peer peer) throws IOException {
811    if (conf.useLegacyBlockReader) {
812      return RemoteBlockReader.newBlockReader(fileName,
813          block, token, startOffset, length, conf.ioBufferSize,
814          verifyChecksum, clientName, peer, datanode,
815          clientContext.getPeerCache(), cachingStrategy);
816    } else {
817      return RemoteBlockReader2.newBlockReader(
818          fileName, block, token, startOffset, length,
819          verifyChecksum, clientName, peer, datanode,
820          clientContext.getPeerCache(), cachingStrategy);
821    }
822  }
823
824  @Override
825  public String toString() {
826    return "BlockReaderFactory(fileName=" + fileName + ", block=" + block + ")";
827  }
828
829  /**
830   * File name to print when accessing a block directly (from servlets)
831   * @param s Address of the block location
832   * @param poolId Block pool ID of the block
833   * @param blockId Block ID of the block
834   * @return string that has a file name for debug purposes
835   */
836  public static String getFileName(final InetSocketAddress s,
837      final String poolId, final long blockId) {
838    return s.toString() + ":" + poolId + ":" + blockId;
839  }
840}