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.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX;
021import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT;
022import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCK_SIZE_KEY;
023import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_DEFAULT;
024import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY;
025import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT;
026import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY;
027import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT;
028import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY;
029import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT;
030import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHED_CONN_RETRY_KEY;
031import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_DROP_BEHIND_READS;
032import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_DROP_BEHIND_WRITES;
033import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CACHE_READAHEAD;
034import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CONTEXT;
035import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_CONTEXT_DEFAULT;
036import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_DATANODE_RESTART_TIMEOUT_DEFAULT;
037import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_DATANODE_RESTART_TIMEOUT_KEY;
038import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT;
039import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY;
040import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT;
041import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY;
042import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT;
043import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY;
044import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT;
045import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY;
046import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_READ_PREFETCH_SIZE_KEY;
047import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_RETRY_MAX_ATTEMPTS_DEFAULT;
048import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_RETRY_MAX_ATTEMPTS_KEY;
049import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_RETRY_WINDOW_BASE;
050import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT;
051import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY;
052import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT;
053import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY;
054import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_SOCKET_TIMEOUT_KEY;
055import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME;
056import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT;
057import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL;
058import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL_DEFAULT;
059import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT;
060import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_CLIENT_WRITE_PACKET_SIZE_KEY;
061import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY;
062import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_DEFAULT;
063import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_KEY;
064
065import java.io.BufferedOutputStream;
066import java.io.DataInputStream;
067import java.io.DataOutputStream;
068import java.io.FileNotFoundException;
069import java.io.IOException;
070import java.io.InputStream;
071import java.io.OutputStream;
072import java.net.InetAddress;
073import java.net.InetSocketAddress;
074import java.net.Socket;
075import java.net.SocketAddress;
076import java.net.URI;
077import java.net.UnknownHostException;
078import java.security.GeneralSecurityException;
079import java.util.ArrayList;
080import java.util.Collections;
081import java.util.EnumSet;
082import java.util.HashMap;
083import java.util.LinkedHashMap;
084import java.util.List;
085import java.util.Map;
086import java.util.Random;
087import java.util.concurrent.SynchronousQueue;
088import java.util.concurrent.ThreadPoolExecutor;
089import java.util.concurrent.TimeUnit;
090import java.util.concurrent.atomic.AtomicBoolean;
091import java.util.concurrent.atomic.AtomicInteger;
092
093import javax.net.SocketFactory;
094
095import org.apache.commons.logging.Log;
096import org.apache.commons.logging.LogFactory;
097import org.apache.hadoop.HadoopIllegalArgumentException;
098import org.apache.hadoop.classification.InterfaceAudience;
099import org.apache.hadoop.conf.Configuration;
100import org.apache.hadoop.crypto.CipherSuite;
101import org.apache.hadoop.crypto.CryptoCodec;
102import org.apache.hadoop.crypto.CryptoInputStream;
103import org.apache.hadoop.crypto.CryptoOutputStream;
104import org.apache.hadoop.crypto.CryptoProtocolVersion;
105import org.apache.hadoop.crypto.key.KeyProvider;
106import org.apache.hadoop.crypto.key.KeyProvider.KeyVersion;
107import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
108import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension.EncryptedKeyVersion;
109import org.apache.hadoop.fs.BlockLocation;
110import org.apache.hadoop.fs.BlockStorageLocation;
111import org.apache.hadoop.fs.CacheFlag;
112import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
113import org.apache.hadoop.fs.ContentSummary;
114import org.apache.hadoop.fs.CreateFlag;
115import org.apache.hadoop.fs.FileAlreadyExistsException;
116import org.apache.hadoop.fs.FileEncryptionInfo;
117import org.apache.hadoop.fs.FileSystem;
118import org.apache.hadoop.fs.FsServerDefaults;
119import org.apache.hadoop.fs.FsStatus;
120import org.apache.hadoop.fs.HdfsBlockLocation;
121import org.apache.hadoop.fs.InvalidPathException;
122import org.apache.hadoop.fs.MD5MD5CRC32CastagnoliFileChecksum;
123import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
124import org.apache.hadoop.fs.MD5MD5CRC32GzipFileChecksum;
125import org.apache.hadoop.fs.Options;
126import org.apache.hadoop.fs.Options.ChecksumOpt;
127import org.apache.hadoop.fs.ParentNotDirectoryException;
128import org.apache.hadoop.fs.Path;
129import org.apache.hadoop.fs.RemoteIterator;
130import org.apache.hadoop.fs.UnresolvedLinkException;
131import org.apache.hadoop.fs.VolumeId;
132import org.apache.hadoop.fs.XAttr;
133import org.apache.hadoop.fs.XAttrSetFlag;
134import org.apache.hadoop.fs.permission.AclEntry;
135import org.apache.hadoop.fs.permission.AclStatus;
136import org.apache.hadoop.fs.permission.FsAction;
137import org.apache.hadoop.fs.permission.FsPermission;
138import org.apache.hadoop.hdfs.client.HdfsDataInputStream;
139import org.apache.hadoop.hdfs.client.HdfsDataOutputStream;
140import org.apache.hadoop.hdfs.net.Peer;
141import org.apache.hadoop.hdfs.net.TcpPeerServer;
142import org.apache.hadoop.hdfs.protocol.AclException;
143import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
144import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
145import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
146import org.apache.hadoop.hdfs.protocol.CacheDirectiveIterator;
147import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
148import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
149import org.apache.hadoop.hdfs.protocol.CachePoolIterator;
150import org.apache.hadoop.hdfs.protocol.ClientProtocol;
151import org.apache.hadoop.hdfs.protocol.CorruptFileBlocks;
152import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
153import org.apache.hadoop.hdfs.protocol.DatanodeID;
154import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
155import org.apache.hadoop.hdfs.protocol.DirectoryListing;
156import org.apache.hadoop.hdfs.protocol.EncryptionZone;
157import org.apache.hadoop.hdfs.protocol.EncryptionZoneIterator;
158import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
159import org.apache.hadoop.hdfs.protocol.HdfsBlocksMetadata;
160import org.apache.hadoop.hdfs.protocol.HdfsConstants;
161import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
162import org.apache.hadoop.hdfs.protocol.HdfsConstants.RollingUpgradeAction;
163import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
164import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
165import org.apache.hadoop.hdfs.protocol.LocatedBlock;
166import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
167import org.apache.hadoop.hdfs.protocol.NSQuotaExceededException;
168import org.apache.hadoop.hdfs.protocol.RollingUpgradeInfo;
169import org.apache.hadoop.hdfs.protocol.SnapshotAccessControlException;
170import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport;
171import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus;
172import org.apache.hadoop.hdfs.protocol.UnresolvedPathException;
173import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair;
174import org.apache.hadoop.hdfs.protocol.datatransfer.Op;
175import org.apache.hadoop.hdfs.protocol.datatransfer.ReplaceDatanodeOnFailure;
176import org.apache.hadoop.hdfs.protocol.datatransfer.Sender;
177import org.apache.hadoop.hdfs.protocol.datatransfer.TrustedChannelResolver;
178import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataEncryptionKeyFactory;
179import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.DataTransferSaslUtil;
180import org.apache.hadoop.hdfs.protocol.datatransfer.sasl.SaslDataTransferClient;
181import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto;
182import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto;
183import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.Status;
184import org.apache.hadoop.hdfs.protocolPB.PBHelper;
185import org.apache.hadoop.hdfs.security.token.block.BlockTokenIdentifier;
186import org.apache.hadoop.hdfs.security.token.block.DataEncryptionKey;
187import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException;
188import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
189import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
190import org.apache.hadoop.hdfs.server.datanode.CachingStrategy;
191import org.apache.hadoop.hdfs.server.namenode.NameNode;
192import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
193import org.apache.hadoop.hdfs.server.protocol.DatanodeStorageReport;
194import org.apache.hadoop.hdfs.util.ByteArrayManager;
195import org.apache.hadoop.io.DataOutputBuffer;
196import org.apache.hadoop.io.EnumSetWritable;
197import org.apache.hadoop.io.IOUtils;
198import org.apache.hadoop.io.MD5Hash;
199import org.apache.hadoop.io.Text;
200import org.apache.hadoop.io.retry.LossyRetryInvocationHandler;
201import org.apache.hadoop.ipc.Client;
202import org.apache.hadoop.ipc.RPC;
203import org.apache.hadoop.ipc.RemoteException;
204import org.apache.hadoop.net.DNS;
205import org.apache.hadoop.net.NetUtils;
206import org.apache.hadoop.security.AccessControlException;
207import org.apache.hadoop.security.UserGroupInformation;
208import org.apache.hadoop.security.token.SecretManager.InvalidToken;
209import org.apache.hadoop.security.token.Token;
210import org.apache.hadoop.security.token.TokenRenewer;
211import org.apache.hadoop.util.Daemon;
212import org.apache.hadoop.util.DataChecksum;
213import org.apache.hadoop.util.DataChecksum.Type;
214import org.apache.hadoop.util.Progressable;
215import org.apache.hadoop.util.Time;
216import org.htrace.Sampler;
217import org.htrace.Span;
218import org.htrace.Trace;
219import org.htrace.TraceScope;
220
221import com.google.common.annotations.VisibleForTesting;
222import com.google.common.base.Joiner;
223import com.google.common.base.Preconditions;
224import com.google.common.collect.Lists;
225import com.google.common.net.InetAddresses;
226
227/********************************************************
228 * DFSClient can connect to a Hadoop Filesystem and 
229 * perform basic file tasks.  It uses the ClientProtocol
230 * to communicate with a NameNode daemon, and connects 
231 * directly to DataNodes to read/write block data.
232 *
233 * Hadoop DFS users should obtain an instance of 
234 * DistributedFileSystem, which uses DFSClient to handle
235 * filesystem tasks.
236 *
237 ********************************************************/
238@InterfaceAudience.Private
239public class DFSClient implements java.io.Closeable, RemotePeerFactory,
240    DataEncryptionKeyFactory {
241  public static final Log LOG = LogFactory.getLog(DFSClient.class);
242  public static final long SERVER_DEFAULTS_VALIDITY_PERIOD = 60 * 60 * 1000L; // 1 hour
243  static final int TCP_WINDOW_SIZE = 128 * 1024; // 128 KB
244
245  private final Configuration conf;
246  private final Conf dfsClientConf;
247  final ClientProtocol namenode;
248  /* The service used for delegation tokens */
249  private Text dtService;
250
251  final UserGroupInformation ugi;
252  volatile boolean clientRunning = true;
253  volatile long lastLeaseRenewal;
254  private volatile FsServerDefaults serverDefaults;
255  private volatile long serverDefaultsLastUpdate;
256  final String clientName;
257  final SocketFactory socketFactory;
258  final ReplaceDatanodeOnFailure dtpReplaceDatanodeOnFailure;
259  final FileSystem.Statistics stats;
260  private final String authority;
261  private final Random r = new Random();
262  private SocketAddress[] localInterfaceAddrs;
263  private DataEncryptionKey encryptionKey;
264  final SaslDataTransferClient saslClient;
265  private final CachingStrategy defaultReadCachingStrategy;
266  private final CachingStrategy defaultWriteCachingStrategy;
267  private final ClientContext clientContext;
268  private volatile long hedgedReadThresholdMillis;
269  private static final DFSHedgedReadMetrics HEDGED_READ_METRIC =
270      new DFSHedgedReadMetrics();
271  private static ThreadPoolExecutor HEDGED_READ_THREAD_POOL;
272
273  /**
274   * DFSClient configuration 
275   */
276  public static class Conf {
277    final int hdfsTimeout;    // timeout value for a DFS operation.
278
279    final int maxFailoverAttempts;
280    final int maxRetryAttempts;
281    final int failoverSleepBaseMillis;
282    final int failoverSleepMaxMillis;
283    final int maxBlockAcquireFailures;
284    final int confTime;
285    final int ioBufferSize;
286    final ChecksumOpt defaultChecksumOpt;
287    final int writePacketSize;
288    final int writeMaxPackets;
289    final ByteArrayManager.Conf writeByteArrayManagerConf;
290    final int socketTimeout;
291    final int socketCacheCapacity;
292    final long socketCacheExpiry;
293    final long excludedNodesCacheExpiry;
294    /** Wait time window (in msec) if BlockMissingException is caught */
295    final int timeWindow;
296    final int nCachedConnRetry;
297    final int nBlockWriteRetry;
298    final int nBlockWriteLocateFollowingRetry;
299    final long defaultBlockSize;
300    final long prefetchSize;
301    final short defaultReplication;
302    final String taskId;
303    final FsPermission uMask;
304    final boolean connectToDnViaHostname;
305    final boolean getHdfsBlocksMetadataEnabled;
306    final int getFileBlockStorageLocationsNumThreads;
307    final int getFileBlockStorageLocationsTimeoutMs;
308    final int retryTimesForGetLastBlockLength;
309    final int retryIntervalForGetLastBlockLength;
310    final long datanodeRestartTimeout;
311    final long dfsclientSlowIoWarningThresholdMs;
312
313    final boolean useLegacyBlockReader;
314    final boolean useLegacyBlockReaderLocal;
315    final String domainSocketPath;
316    final boolean skipShortCircuitChecksums;
317    final int shortCircuitBufferSize;
318    final boolean shortCircuitLocalReads;
319    final boolean domainSocketDataTraffic;
320    final int shortCircuitStreamsCacheSize;
321    final long shortCircuitStreamsCacheExpiryMs; 
322    final int shortCircuitSharedMemoryWatcherInterruptCheckMs;
323    
324    final boolean shortCircuitMmapEnabled;
325    final int shortCircuitMmapCacheSize;
326    final long shortCircuitMmapCacheExpiryMs;
327    final long shortCircuitMmapCacheRetryTimeout;
328    final long shortCircuitCacheStaleThresholdMs;
329
330    final long keyProviderCacheExpiryMs;
331    public BlockReaderFactory.FailureInjector brfFailureInjector =
332      new BlockReaderFactory.FailureInjector();
333
334    public Conf(Configuration conf) {
335      // The hdfsTimeout is currently the same as the ipc timeout 
336      hdfsTimeout = Client.getTimeout(conf);
337      maxFailoverAttempts = conf.getInt(
338          DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY,
339          DFS_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT);
340      maxRetryAttempts = conf.getInt(
341          DFS_CLIENT_RETRY_MAX_ATTEMPTS_KEY,
342          DFS_CLIENT_RETRY_MAX_ATTEMPTS_DEFAULT);
343      failoverSleepBaseMillis = conf.getInt(
344          DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY,
345          DFS_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT);
346      failoverSleepMaxMillis = conf.getInt(
347          DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
348          DFS_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT);
349
350      maxBlockAcquireFailures = conf.getInt(
351          DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_KEY,
352          DFS_CLIENT_MAX_BLOCK_ACQUIRE_FAILURES_DEFAULT);
353      confTime = conf.getInt(DFS_DATANODE_SOCKET_WRITE_TIMEOUT_KEY,
354          HdfsServerConstants.WRITE_TIMEOUT);
355      ioBufferSize = conf.getInt(
356          CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_KEY,
357          CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT);
358      defaultChecksumOpt = getChecksumOptFromConf(conf);
359      socketTimeout = conf.getInt(DFS_CLIENT_SOCKET_TIMEOUT_KEY,
360          HdfsServerConstants.READ_TIMEOUT);
361      /** dfs.write.packet.size is an internal config variable */
362      writePacketSize = conf.getInt(DFS_CLIENT_WRITE_PACKET_SIZE_KEY,
363          DFS_CLIENT_WRITE_PACKET_SIZE_DEFAULT);
364      writeMaxPackets = conf.getInt(
365          DFSConfigKeys.DFS_CLIENT_WRITE_MAX_PACKETS_IN_FLIGHT_KEY,
366          DFSConfigKeys.DFS_CLIENT_WRITE_MAX_PACKETS_IN_FLIGHT_DEFAULT);
367      
368      final boolean byteArrayManagerEnabled = conf.getBoolean(
369          DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_ENABLED_KEY,
370          DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_ENABLED_DEFAULT);
371      if (!byteArrayManagerEnabled) {
372        writeByteArrayManagerConf = null;
373      } else {
374        final int countThreshold = conf.getInt(
375            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_THRESHOLD_KEY,
376            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_THRESHOLD_DEFAULT);
377        final int countLimit = conf.getInt(
378            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_LIMIT_KEY,
379            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_LIMIT_DEFAULT);
380        final long countResetTimePeriodMs = conf.getLong(
381            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_RESET_TIME_PERIOD_MS_KEY,
382            DFSConfigKeys.DFS_CLIENT_WRITE_BYTE_ARRAY_MANAGER_COUNT_RESET_TIME_PERIOD_MS_DEFAULT);
383        writeByteArrayManagerConf = new ByteArrayManager.Conf(
384            countThreshold, countLimit, countResetTimePeriodMs); 
385      }
386      
387      
388      defaultBlockSize = conf.getLongBytes(DFS_BLOCK_SIZE_KEY,
389          DFS_BLOCK_SIZE_DEFAULT);
390      defaultReplication = (short) conf.getInt(
391          DFS_REPLICATION_KEY, DFS_REPLICATION_DEFAULT);
392      taskId = conf.get("mapreduce.task.attempt.id", "NONMAPREDUCE");
393      socketCacheCapacity = conf.getInt(DFS_CLIENT_SOCKET_CACHE_CAPACITY_KEY,
394          DFS_CLIENT_SOCKET_CACHE_CAPACITY_DEFAULT);
395      socketCacheExpiry = conf.getLong(DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_KEY,
396          DFS_CLIENT_SOCKET_CACHE_EXPIRY_MSEC_DEFAULT);
397      excludedNodesCacheExpiry = conf.getLong(
398          DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL,
399          DFS_CLIENT_WRITE_EXCLUDE_NODES_CACHE_EXPIRY_INTERVAL_DEFAULT);
400      prefetchSize = conf.getLong(DFS_CLIENT_READ_PREFETCH_SIZE_KEY,
401          10 * defaultBlockSize);
402      timeWindow = conf.getInt(DFS_CLIENT_RETRY_WINDOW_BASE, 3000);
403      nCachedConnRetry = conf.getInt(DFS_CLIENT_CACHED_CONN_RETRY_KEY,
404          DFS_CLIENT_CACHED_CONN_RETRY_DEFAULT);
405      nBlockWriteRetry = conf.getInt(DFS_CLIENT_BLOCK_WRITE_RETRIES_KEY,
406          DFS_CLIENT_BLOCK_WRITE_RETRIES_DEFAULT);
407      nBlockWriteLocateFollowingRetry = conf.getInt(
408          DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_KEY,
409          DFS_CLIENT_BLOCK_WRITE_LOCATEFOLLOWINGBLOCK_RETRIES_DEFAULT);
410      uMask = FsPermission.getUMask(conf);
411      connectToDnViaHostname = conf.getBoolean(DFS_CLIENT_USE_DN_HOSTNAME,
412          DFS_CLIENT_USE_DN_HOSTNAME_DEFAULT);
413      getHdfsBlocksMetadataEnabled = conf.getBoolean(
414          DFSConfigKeys.DFS_HDFS_BLOCKS_METADATA_ENABLED, 
415          DFSConfigKeys.DFS_HDFS_BLOCKS_METADATA_ENABLED_DEFAULT);
416      getFileBlockStorageLocationsNumThreads = conf.getInt(
417          DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS,
418          DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_NUM_THREADS_DEFAULT);
419      getFileBlockStorageLocationsTimeoutMs = conf.getInt(
420          DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_MS,
421          DFSConfigKeys.DFS_CLIENT_FILE_BLOCK_STORAGE_LOCATIONS_TIMEOUT_MS_DEFAULT);
422      retryTimesForGetLastBlockLength = conf.getInt(
423          DFSConfigKeys.DFS_CLIENT_RETRY_TIMES_GET_LAST_BLOCK_LENGTH,
424          DFSConfigKeys.DFS_CLIENT_RETRY_TIMES_GET_LAST_BLOCK_LENGTH_DEFAULT);
425      retryIntervalForGetLastBlockLength = conf.getInt(
426        DFSConfigKeys.DFS_CLIENT_RETRY_INTERVAL_GET_LAST_BLOCK_LENGTH,
427        DFSConfigKeys.DFS_CLIENT_RETRY_INTERVAL_GET_LAST_BLOCK_LENGTH_DEFAULT);
428
429      useLegacyBlockReader = conf.getBoolean(
430          DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADER,
431          DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADER_DEFAULT);
432      useLegacyBlockReaderLocal = conf.getBoolean(
433          DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL,
434          DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL_DEFAULT);
435      shortCircuitLocalReads = conf.getBoolean(
436          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY,
437          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_DEFAULT);
438      domainSocketDataTraffic = conf.getBoolean(
439          DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC,
440          DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC_DEFAULT);
441      domainSocketPath = conf.getTrimmed(
442          DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
443          DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_DEFAULT);
444
445      if (BlockReaderLocal.LOG.isDebugEnabled()) {
446        BlockReaderLocal.LOG.debug(
447            DFSConfigKeys.DFS_CLIENT_USE_LEGACY_BLOCKREADERLOCAL
448            + " = " + useLegacyBlockReaderLocal);
449        BlockReaderLocal.LOG.debug(
450            DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY
451            + " = " + shortCircuitLocalReads);
452        BlockReaderLocal.LOG.debug(
453            DFSConfigKeys.DFS_CLIENT_DOMAIN_SOCKET_DATA_TRAFFIC
454            + " = " + domainSocketDataTraffic);
455        BlockReaderLocal.LOG.debug(
456            DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY
457            + " = " + domainSocketPath);
458      }
459
460      skipShortCircuitChecksums = conf.getBoolean(
461          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY,
462          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_DEFAULT);
463      shortCircuitBufferSize = conf.getInt(
464          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_KEY,
465          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_BUFFER_SIZE_DEFAULT);
466      shortCircuitStreamsCacheSize = conf.getInt(
467          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_KEY,
468          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_SIZE_DEFAULT);
469      shortCircuitStreamsCacheExpiryMs = conf.getLong(
470          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_KEY,
471          DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_STREAMS_CACHE_EXPIRY_MS_DEFAULT);
472      shortCircuitMmapEnabled = conf.getBoolean(
473          DFSConfigKeys.DFS_CLIENT_MMAP_ENABLED,
474          DFSConfigKeys.DFS_CLIENT_MMAP_ENABLED_DEFAULT);
475      shortCircuitMmapCacheSize = conf.getInt(
476          DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE,
477          DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE_DEFAULT);
478      shortCircuitMmapCacheExpiryMs = conf.getLong(
479          DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS,
480          DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS_DEFAULT);
481      shortCircuitMmapCacheRetryTimeout = conf.getLong(
482          DFSConfigKeys.DFS_CLIENT_MMAP_RETRY_TIMEOUT_MS,
483          DFSConfigKeys.DFS_CLIENT_MMAP_RETRY_TIMEOUT_MS_DEFAULT);
484      shortCircuitCacheStaleThresholdMs = conf.getLong(
485          DFSConfigKeys.DFS_CLIENT_SHORT_CIRCUIT_REPLICA_STALE_THRESHOLD_MS,
486          DFSConfigKeys.DFS_CLIENT_SHORT_CIRCUIT_REPLICA_STALE_THRESHOLD_MS_DEFAULT);
487      shortCircuitSharedMemoryWatcherInterruptCheckMs = conf.getInt(
488          DFSConfigKeys.DFS_SHORT_CIRCUIT_SHARED_MEMORY_WATCHER_INTERRUPT_CHECK_MS,
489          DFSConfigKeys.DFS_SHORT_CIRCUIT_SHARED_MEMORY_WATCHER_INTERRUPT_CHECK_MS_DEFAULT);
490
491      datanodeRestartTimeout = conf.getLong(
492          DFS_CLIENT_DATANODE_RESTART_TIMEOUT_KEY,
493          DFS_CLIENT_DATANODE_RESTART_TIMEOUT_DEFAULT) * 1000;
494      dfsclientSlowIoWarningThresholdMs = conf.getLong(
495          DFSConfigKeys.DFS_CLIENT_SLOW_IO_WARNING_THRESHOLD_KEY,
496          DFSConfigKeys.DFS_CLIENT_SLOW_IO_WARNING_THRESHOLD_DEFAULT);
497
498      keyProviderCacheExpiryMs = conf.getLong(
499          DFSConfigKeys.DFS_CLIENT_KEY_PROVIDER_CACHE_EXPIRY_MS,
500          DFSConfigKeys.DFS_CLIENT_KEY_PROVIDER_CACHE_EXPIRY_DEFAULT);
501    }
502
503    public boolean isUseLegacyBlockReaderLocal() {
504      return useLegacyBlockReaderLocal;
505    }
506
507    public String getDomainSocketPath() {
508      return domainSocketPath;
509    }
510
511    public boolean isShortCircuitLocalReads() {
512      return shortCircuitLocalReads;
513    }
514
515    public boolean isDomainSocketDataTraffic() {
516      return domainSocketDataTraffic;
517    }
518
519    private DataChecksum.Type getChecksumType(Configuration conf) {
520      final String checksum = conf.get(
521          DFSConfigKeys.DFS_CHECKSUM_TYPE_KEY,
522          DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
523      try {
524        return DataChecksum.Type.valueOf(checksum);
525      } catch(IllegalArgumentException iae) {
526        LOG.warn("Bad checksum type: " + checksum + ". Using default "
527            + DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT);
528        return DataChecksum.Type.valueOf(
529            DFSConfigKeys.DFS_CHECKSUM_TYPE_DEFAULT); 
530      }
531    }
532
533    // Construct a checksum option from conf
534    private ChecksumOpt getChecksumOptFromConf(Configuration conf) {
535      DataChecksum.Type type = getChecksumType(conf);
536      int bytesPerChecksum = conf.getInt(DFS_BYTES_PER_CHECKSUM_KEY,
537          DFS_BYTES_PER_CHECKSUM_DEFAULT);
538      return new ChecksumOpt(type, bytesPerChecksum);
539    }
540
541    // create a DataChecksum with the default option.
542    private DataChecksum createChecksum() throws IOException {
543      return createChecksum(null);
544    }
545
546    private DataChecksum createChecksum(ChecksumOpt userOpt) {
547      // Fill in any missing field with the default.
548      ChecksumOpt myOpt = ChecksumOpt.processChecksumOpt(
549          defaultChecksumOpt, userOpt);
550      DataChecksum dataChecksum = DataChecksum.newDataChecksum(
551          myOpt.getChecksumType(),
552          myOpt.getBytesPerChecksum());
553      if (dataChecksum == null) {
554        throw new HadoopIllegalArgumentException("Invalid checksum type: userOpt="
555            + userOpt + ", default=" + defaultChecksumOpt
556            + ", effective=null");
557      }
558      return dataChecksum;
559    }
560  }
561 
562  public Conf getConf() {
563    return dfsClientConf;
564  }
565
566  Configuration getConfiguration() {
567    return conf;
568  }
569
570  /**
571   * A map from file names to {@link DFSOutputStream} objects
572   * that are currently being written by this client.
573   * Note that a file can only be written by a single client.
574   */
575  private final Map<Long, DFSOutputStream> filesBeingWritten
576      = new HashMap<Long, DFSOutputStream>();
577
578  /**
579   * Same as this(NameNode.getAddress(conf), conf);
580   * @see #DFSClient(InetSocketAddress, Configuration)
581   * @deprecated Deprecated at 0.21
582   */
583  @Deprecated
584  public DFSClient(Configuration conf) throws IOException {
585    this(NameNode.getAddress(conf), conf);
586  }
587  
588  public DFSClient(InetSocketAddress address, Configuration conf) throws IOException {
589    this(NameNode.getUri(address), conf);
590  }
591
592  /**
593   * Same as this(nameNodeUri, conf, null);
594   * @see #DFSClient(URI, Configuration, FileSystem.Statistics)
595   */
596  public DFSClient(URI nameNodeUri, Configuration conf
597      ) throws IOException {
598    this(nameNodeUri, conf, null);
599  }
600
601  /**
602   * Same as this(nameNodeUri, null, conf, stats);
603   * @see #DFSClient(URI, ClientProtocol, Configuration, FileSystem.Statistics) 
604   */
605  public DFSClient(URI nameNodeUri, Configuration conf,
606                   FileSystem.Statistics stats)
607    throws IOException {
608    this(nameNodeUri, null, conf, stats);
609  }
610  
611  /** 
612   * Create a new DFSClient connected to the given nameNodeUri or rpcNamenode.
613   * If HA is enabled and a positive value is set for 
614   * {@link DFSConfigKeys#DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY} in the
615   * configuration, the DFSClient will use {@link LossyRetryInvocationHandler}
616   * as its RetryInvocationHandler. Otherwise one of nameNodeUri or rpcNamenode 
617   * must be null.
618   */
619  @VisibleForTesting
620  public DFSClient(URI nameNodeUri, ClientProtocol rpcNamenode,
621      Configuration conf, FileSystem.Statistics stats)
622    throws IOException {
623    // Copy only the required DFSClient configuration
624    this.dfsClientConf = new Conf(conf);
625    if (this.dfsClientConf.useLegacyBlockReaderLocal) {
626      LOG.debug("Using legacy short-circuit local reads.");
627    }
628    this.conf = conf;
629    this.stats = stats;
630    this.socketFactory = NetUtils.getSocketFactory(conf, ClientProtocol.class);
631    this.dtpReplaceDatanodeOnFailure = ReplaceDatanodeOnFailure.get(conf);
632
633    this.ugi = UserGroupInformation.getCurrentUser();
634    
635    this.authority = nameNodeUri == null? "null": nameNodeUri.getAuthority();
636    this.clientName = "DFSClient_" + dfsClientConf.taskId + "_" + 
637        DFSUtil.getRandom().nextInt()  + "_" + Thread.currentThread().getId();
638    int numResponseToDrop = conf.getInt(
639        DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY,
640        DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_DEFAULT);
641    NameNodeProxies.ProxyAndInfo<ClientProtocol> proxyInfo = null;
642    AtomicBoolean nnFallbackToSimpleAuth = new AtomicBoolean(false);
643    if (numResponseToDrop > 0) {
644      // This case is used for testing.
645      LOG.warn(DFSConfigKeys.DFS_CLIENT_TEST_DROP_NAMENODE_RESPONSE_NUM_KEY
646          + " is set to " + numResponseToDrop
647          + ", this hacked client will proactively drop responses");
648      proxyInfo = NameNodeProxies.createProxyWithLossyRetryHandler(conf,
649          nameNodeUri, ClientProtocol.class, numResponseToDrop,
650          nnFallbackToSimpleAuth);
651    }
652    
653    if (proxyInfo != null) {
654      this.dtService = proxyInfo.getDelegationTokenService();
655      this.namenode = proxyInfo.getProxy();
656    } else if (rpcNamenode != null) {
657      // This case is used for testing.
658      Preconditions.checkArgument(nameNodeUri == null);
659      this.namenode = rpcNamenode;
660      dtService = null;
661    } else {
662      Preconditions.checkArgument(nameNodeUri != null,
663          "null URI");
664      proxyInfo = NameNodeProxies.createProxy(conf, nameNodeUri,
665          ClientProtocol.class, nnFallbackToSimpleAuth);
666      this.dtService = proxyInfo.getDelegationTokenService();
667      this.namenode = proxyInfo.getProxy();
668    }
669
670    String localInterfaces[] =
671      conf.getTrimmedStrings(DFSConfigKeys.DFS_CLIENT_LOCAL_INTERFACES);
672    localInterfaceAddrs = getLocalInterfaceAddrs(localInterfaces);
673    if (LOG.isDebugEnabled() && 0 != localInterfaces.length) {
674      LOG.debug("Using local interfaces [" +
675      Joiner.on(',').join(localInterfaces)+ "] with addresses [" +
676      Joiner.on(',').join(localInterfaceAddrs) + "]");
677    }
678    
679    Boolean readDropBehind = (conf.get(DFS_CLIENT_CACHE_DROP_BEHIND_READS) == null) ?
680        null : conf.getBoolean(DFS_CLIENT_CACHE_DROP_BEHIND_READS, false);
681    Long readahead = (conf.get(DFS_CLIENT_CACHE_READAHEAD) == null) ?
682        null : conf.getLong(DFS_CLIENT_CACHE_READAHEAD, 0);
683    Boolean writeDropBehind = (conf.get(DFS_CLIENT_CACHE_DROP_BEHIND_WRITES) == null) ?
684        null : conf.getBoolean(DFS_CLIENT_CACHE_DROP_BEHIND_WRITES, false);
685    this.defaultReadCachingStrategy =
686        new CachingStrategy(readDropBehind, readahead);
687    this.defaultWriteCachingStrategy =
688        new CachingStrategy(writeDropBehind, readahead);
689    this.clientContext = ClientContext.get(
690        conf.get(DFS_CLIENT_CONTEXT, DFS_CLIENT_CONTEXT_DEFAULT),
691        dfsClientConf);
692    this.hedgedReadThresholdMillis = conf.getLong(
693        DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THRESHOLD_MILLIS,
694        DFSConfigKeys.DEFAULT_DFSCLIENT_HEDGED_READ_THRESHOLD_MILLIS);
695    int numThreads = conf.getInt(
696        DFSConfigKeys.DFS_DFSCLIENT_HEDGED_READ_THREADPOOL_SIZE,
697        DFSConfigKeys.DEFAULT_DFSCLIENT_HEDGED_READ_THREADPOOL_SIZE);
698    if (numThreads > 0) {
699      this.initThreadsNumForHedgedReads(numThreads);
700    }
701    this.saslClient = new SaslDataTransferClient(
702      conf, DataTransferSaslUtil.getSaslPropertiesResolver(conf),
703      TrustedChannelResolver.getInstance(conf), nnFallbackToSimpleAuth);
704  }
705  
706  /**
707   * Return the socket addresses to use with each configured
708   * local interface. Local interfaces may be specified by IP
709   * address, IP address range using CIDR notation, interface
710   * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
711   * The socket addresses consist of the IPs for the interfaces
712   * and the ephemeral port (port 0). If an IP, IP range, or
713   * interface name matches an interface with sub-interfaces
714   * only the IP of the interface is used. Sub-interfaces can
715   * be used by specifying them explicitly (by IP or name).
716   * 
717   * @return SocketAddresses for the configured local interfaces,
718   *    or an empty array if none are configured
719   * @throws UnknownHostException if a given interface name is invalid
720   */
721  private static SocketAddress[] getLocalInterfaceAddrs(
722      String interfaceNames[]) throws UnknownHostException {
723    List<SocketAddress> localAddrs = new ArrayList<SocketAddress>();
724    for (String interfaceName : interfaceNames) {
725      if (InetAddresses.isInetAddress(interfaceName)) {
726        localAddrs.add(new InetSocketAddress(interfaceName, 0));
727      } else if (NetUtils.isValidSubnet(interfaceName)) {
728        for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
729          localAddrs.add(new InetSocketAddress(addr, 0));
730        }
731      } else {
732        for (String ip : DNS.getIPs(interfaceName, false)) {
733          localAddrs.add(new InetSocketAddress(ip, 0));
734        }
735      }
736    }
737    return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
738  }
739
740  /**
741   * Select one of the configured local interfaces at random. We use a random
742   * interface because other policies like round-robin are less effective
743   * given that we cache connections to datanodes.
744   *
745   * @return one of the local interface addresses at random, or null if no
746   *    local interfaces are configured
747   */
748  SocketAddress getRandomLocalInterfaceAddr() {
749    if (localInterfaceAddrs.length == 0) {
750      return null;
751    }
752    final int idx = r.nextInt(localInterfaceAddrs.length);
753    final SocketAddress addr = localInterfaceAddrs[idx];
754    if (LOG.isDebugEnabled()) {
755      LOG.debug("Using local interface " + addr);
756    }
757    return addr;
758  }
759
760  /**
761   * Return the number of times the client should go back to the namenode
762   * to retrieve block locations when reading.
763   */
764  int getMaxBlockAcquireFailures() {
765    return dfsClientConf.maxBlockAcquireFailures;
766  }
767
768  /**
769   * Return the timeout that clients should use when writing to datanodes.
770   * @param numNodes the number of nodes in the pipeline.
771   */
772  int getDatanodeWriteTimeout(int numNodes) {
773    return (dfsClientConf.confTime > 0) ?
774      (dfsClientConf.confTime + HdfsServerConstants.WRITE_TIMEOUT_EXTENSION * numNodes) : 0;
775  }
776
777  int getDatanodeReadTimeout(int numNodes) {
778    return dfsClientConf.socketTimeout > 0 ?
779        (HdfsServerConstants.READ_TIMEOUT_EXTENSION * numNodes +
780            dfsClientConf.socketTimeout) : 0;
781  }
782  
783  int getHdfsTimeout() {
784    return dfsClientConf.hdfsTimeout;
785  }
786  
787  @VisibleForTesting
788  public String getClientName() {
789    return clientName;
790  }
791
792  void checkOpen() throws IOException {
793    if (!clientRunning) {
794      IOException result = new IOException("Filesystem closed");
795      throw result;
796    }
797  }
798
799  /** Return the lease renewer instance. The renewer thread won't start
800   *  until the first output stream is created. The same instance will
801   *  be returned until all output streams are closed.
802   */
803  public LeaseRenewer getLeaseRenewer() throws IOException {
804      return LeaseRenewer.getInstance(authority, ugi, this);
805  }
806
807  /** Get a lease and start automatic renewal */
808  private void beginFileLease(final long inodeId, final DFSOutputStream out)
809      throws IOException {
810    getLeaseRenewer().put(inodeId, out, this);
811  }
812
813  /** Stop renewal of lease for the file. */
814  void endFileLease(final long inodeId) throws IOException {
815    getLeaseRenewer().closeFile(inodeId, this);
816  }
817    
818
819  /** Put a file. Only called from LeaseRenewer, where proper locking is
820   *  enforced to consistently update its local dfsclients array and 
821   *  client's filesBeingWritten map.
822   */
823  void putFileBeingWritten(final long inodeId, final DFSOutputStream out) {
824    synchronized(filesBeingWritten) {
825      filesBeingWritten.put(inodeId, out);
826      // update the last lease renewal time only when there was no
827      // writes. once there is one write stream open, the lease renewer
828      // thread keeps it updated well with in anyone's expiration time.
829      if (lastLeaseRenewal == 0) {
830        updateLastLeaseRenewal();
831      }
832    }
833  }
834
835  /** Remove a file. Only called from LeaseRenewer. */
836  void removeFileBeingWritten(final long inodeId) {
837    synchronized(filesBeingWritten) {
838      filesBeingWritten.remove(inodeId);
839      if (filesBeingWritten.isEmpty()) {
840        lastLeaseRenewal = 0;
841      }
842    }
843  }
844
845  /** Is file-being-written map empty? */
846  boolean isFilesBeingWrittenEmpty() {
847    synchronized(filesBeingWritten) {
848      return filesBeingWritten.isEmpty();
849    }
850  }
851  
852  /** @return true if the client is running */
853  boolean isClientRunning() {
854    return clientRunning;
855  }
856
857  long getLastLeaseRenewal() {
858    return lastLeaseRenewal;
859  }
860
861  void updateLastLeaseRenewal() {
862    synchronized(filesBeingWritten) {
863      if (filesBeingWritten.isEmpty()) {
864        return;
865      }
866      lastLeaseRenewal = Time.now();
867    }
868  }
869
870  /**
871   * Renew leases.
872   * @return true if lease was renewed. May return false if this
873   * client has been closed or has no files open.
874   **/
875  boolean renewLease() throws IOException {
876    if (clientRunning && !isFilesBeingWrittenEmpty()) {
877      try {
878        namenode.renewLease(clientName);
879        updateLastLeaseRenewal();
880        return true;
881      } catch (IOException e) {
882        // Abort if the lease has already expired. 
883        final long elapsed = Time.now() - getLastLeaseRenewal();
884        if (elapsed > HdfsConstants.LEASE_HARDLIMIT_PERIOD) {
885          LOG.warn("Failed to renew lease for " + clientName + " for "
886              + (elapsed/1000) + " seconds (>= hard-limit ="
887              + (HdfsConstants.LEASE_HARDLIMIT_PERIOD/1000) + " seconds.) "
888              + "Closing all files being written ...", e);
889          closeAllFilesBeingWritten(true);
890        } else {
891          // Let the lease renewer handle it and retry.
892          throw e;
893        }
894      }
895    }
896    return false;
897  }
898  
899  /**
900   * Close connections the Namenode.
901   */
902  void closeConnectionToNamenode() {
903    RPC.stopProxy(namenode);
904  }
905  
906  /** Abort and release resources held.  Ignore all errors. */
907  void abort() {
908    clientRunning = false;
909    closeAllFilesBeingWritten(true);
910    try {
911      // remove reference to this client and stop the renewer,
912      // if there is no more clients under the renewer.
913      getLeaseRenewer().closeClient(this);
914    } catch (IOException ioe) {
915       LOG.info("Exception occurred while aborting the client " + ioe);
916    }
917    closeConnectionToNamenode();
918  }
919
920  /** Close/abort all files being written. */
921  private void closeAllFilesBeingWritten(final boolean abort) {
922    for(;;) {
923      final long inodeId;
924      final DFSOutputStream out;
925      synchronized(filesBeingWritten) {
926        if (filesBeingWritten.isEmpty()) {
927          return;
928        }
929        inodeId = filesBeingWritten.keySet().iterator().next();
930        out = filesBeingWritten.remove(inodeId);
931      }
932      if (out != null) {
933        try {
934          if (abort) {
935            out.abort();
936          } else {
937            out.close();
938          }
939        } catch(IOException ie) {
940          LOG.error("Failed to " + (abort? "abort": "close") +
941                  " inode " + inodeId, ie);
942        }
943      }
944    }
945  }
946
947  /**
948   * Close the file system, abandoning all of the leases and files being
949   * created and close connections to the namenode.
950   */
951  @Override
952  public synchronized void close() throws IOException {
953    if(clientRunning) {
954      closeAllFilesBeingWritten(false);
955      clientRunning = false;
956      getLeaseRenewer().closeClient(this);
957      // close connections to the namenode
958      closeConnectionToNamenode();
959    }
960  }
961
962  /**
963   * Close all open streams, abandoning all of the leases and files being
964   * created.
965   * @param abort whether streams should be gracefully closed
966   */
967  public void closeOutputStreams(boolean abort) {
968    if (clientRunning) {
969      closeAllFilesBeingWritten(abort);
970    }
971  }
972
973  /**
974   * Get the default block size for this cluster
975   * @return the default block size in bytes
976   */
977  public long getDefaultBlockSize() {
978    return dfsClientConf.defaultBlockSize;
979  }
980    
981  /**
982   * @see ClientProtocol#getPreferredBlockSize(String)
983   */
984  public long getBlockSize(String f) throws IOException {
985    try {
986      return namenode.getPreferredBlockSize(f);
987    } catch (IOException ie) {
988      LOG.warn("Problem getting block size", ie);
989      throw ie;
990    }
991  }
992
993  /**
994   * Get server default values for a number of configuration params.
995   * @see ClientProtocol#getServerDefaults()
996   */
997  public FsServerDefaults getServerDefaults() throws IOException {
998    long now = Time.now();
999    if (now - serverDefaultsLastUpdate > SERVER_DEFAULTS_VALIDITY_PERIOD) {
1000      serverDefaults = namenode.getServerDefaults();
1001      serverDefaultsLastUpdate = now;
1002    }
1003    return serverDefaults;
1004  }
1005  
1006  /**
1007   * Get a canonical token service name for this client's tokens.  Null should
1008   * be returned if the client is not using tokens.
1009   * @return the token service for the client
1010   */
1011  @InterfaceAudience.LimitedPrivate( { "HDFS" }) 
1012  public String getCanonicalServiceName() {
1013    return (dtService != null) ? dtService.toString() : null;
1014  }
1015  
1016  /**
1017   * @see ClientProtocol#getDelegationToken(Text)
1018   */
1019  public Token<DelegationTokenIdentifier> getDelegationToken(Text renewer)
1020      throws IOException {
1021    assert dtService != null;
1022    Token<DelegationTokenIdentifier> token =
1023      namenode.getDelegationToken(renewer);
1024
1025    if (token != null) {
1026      token.setService(this.dtService);
1027      LOG.info("Created " + DelegationTokenIdentifier.stringifyToken(token));
1028    } else {
1029      LOG.info("Cannot get delegation token from " + renewer);
1030    }
1031    return token;
1032
1033  }
1034
1035  /**
1036   * Renew a delegation token
1037   * @param token the token to renew
1038   * @return the new expiration time
1039   * @throws InvalidToken
1040   * @throws IOException
1041   * @deprecated Use Token.renew instead.
1042   */
1043  @Deprecated
1044  public long renewDelegationToken(Token<DelegationTokenIdentifier> token)
1045      throws InvalidToken, IOException {
1046    LOG.info("Renewing " + DelegationTokenIdentifier.stringifyToken(token));
1047    try {
1048      return token.renew(conf);
1049    } catch (InterruptedException ie) {                                       
1050      throw new RuntimeException("caught interrupted", ie);
1051    } catch (RemoteException re) {
1052      throw re.unwrapRemoteException(InvalidToken.class,
1053                                     AccessControlException.class);
1054    }
1055  }
1056  
1057  private static final Map<String, Boolean> localAddrMap = Collections
1058      .synchronizedMap(new HashMap<String, Boolean>());
1059  
1060  public static boolean isLocalAddress(InetSocketAddress targetAddr) {
1061    InetAddress addr = targetAddr.getAddress();
1062    Boolean cached = localAddrMap.get(addr.getHostAddress());
1063    if (cached != null) {
1064      if (LOG.isTraceEnabled()) {
1065        LOG.trace("Address " + targetAddr +
1066                  (cached ? " is local" : " is not local"));
1067      }
1068      return cached;
1069    }
1070    
1071    boolean local = NetUtils.isLocalAddress(addr);
1072
1073    if (LOG.isTraceEnabled()) {
1074      LOG.trace("Address " + targetAddr +
1075                (local ? " is local" : " is not local"));
1076    }
1077    localAddrMap.put(addr.getHostAddress(), local);
1078    return local;
1079  }
1080  
1081  /**
1082   * Cancel a delegation token
1083   * @param token the token to cancel
1084   * @throws InvalidToken
1085   * @throws IOException
1086   * @deprecated Use Token.cancel instead.
1087   */
1088  @Deprecated
1089  public void cancelDelegationToken(Token<DelegationTokenIdentifier> token)
1090      throws InvalidToken, IOException {
1091    LOG.info("Cancelling " + DelegationTokenIdentifier.stringifyToken(token));
1092    try {
1093      token.cancel(conf);
1094     } catch (InterruptedException ie) {                                       
1095      throw new RuntimeException("caught interrupted", ie);
1096    } catch (RemoteException re) {
1097      throw re.unwrapRemoteException(InvalidToken.class,
1098                                     AccessControlException.class);
1099    }
1100  }
1101  
1102  @InterfaceAudience.Private
1103  public static class Renewer extends TokenRenewer {
1104    
1105    static {
1106      //Ensure that HDFS Configuration files are loaded before trying to use
1107      // the renewer.
1108      HdfsConfiguration.init();
1109    }
1110    
1111    @Override
1112    public boolean handleKind(Text kind) {
1113      return DelegationTokenIdentifier.HDFS_DELEGATION_KIND.equals(kind);
1114    }
1115
1116    @SuppressWarnings("unchecked")
1117    @Override
1118    public long renew(Token<?> token, Configuration conf) throws IOException {
1119      Token<DelegationTokenIdentifier> delToken = 
1120        (Token<DelegationTokenIdentifier>) token;
1121      ClientProtocol nn = getNNProxy(delToken, conf);
1122      try {
1123        return nn.renewDelegationToken(delToken);
1124      } catch (RemoteException re) {
1125        throw re.unwrapRemoteException(InvalidToken.class, 
1126                                       AccessControlException.class);
1127      }
1128    }
1129
1130    @SuppressWarnings("unchecked")
1131    @Override
1132    public void cancel(Token<?> token, Configuration conf) throws IOException {
1133      Token<DelegationTokenIdentifier> delToken = 
1134          (Token<DelegationTokenIdentifier>) token;
1135      LOG.info("Cancelling " + 
1136               DelegationTokenIdentifier.stringifyToken(delToken));
1137      ClientProtocol nn = getNNProxy(delToken, conf);
1138      try {
1139        nn.cancelDelegationToken(delToken);
1140      } catch (RemoteException re) {
1141        throw re.unwrapRemoteException(InvalidToken.class,
1142            AccessControlException.class);
1143      }
1144    }
1145    
1146    private static ClientProtocol getNNProxy(
1147        Token<DelegationTokenIdentifier> token, Configuration conf)
1148        throws IOException {
1149      URI uri = HAUtil.getServiceUriFromToken(HdfsConstants.HDFS_URI_SCHEME,
1150              token);
1151      if (HAUtil.isTokenForLogicalUri(token) &&
1152          !HAUtil.isLogicalUri(conf, uri)) {
1153        // If the token is for a logical nameservice, but the configuration
1154        // we have disagrees about that, we can't actually renew it.
1155        // This can be the case in MR, for example, if the RM doesn't
1156        // have all of the HA clusters configured in its configuration.
1157        throw new IOException("Unable to map logical nameservice URI '" +
1158            uri + "' to a NameNode. Local configuration does not have " +
1159            "a failover proxy provider configured.");
1160      }
1161      
1162      NameNodeProxies.ProxyAndInfo<ClientProtocol> info =
1163        NameNodeProxies.createProxy(conf, uri, ClientProtocol.class);
1164      assert info.getDelegationTokenService().equals(token.getService()) :
1165        "Returned service '" + info.getDelegationTokenService().toString() +
1166        "' doesn't match expected service '" +
1167        token.getService().toString() + "'";
1168        
1169      return info.getProxy();
1170    }
1171
1172    @Override
1173    public boolean isManaged(Token<?> token) throws IOException {
1174      return true;
1175    }
1176    
1177  }
1178
1179  /**
1180   * Report corrupt blocks that were discovered by the client.
1181   * @see ClientProtocol#reportBadBlocks(LocatedBlock[])
1182   */
1183  public void reportBadBlocks(LocatedBlock[] blocks) throws IOException {
1184    namenode.reportBadBlocks(blocks);
1185  }
1186  
1187  public short getDefaultReplication() {
1188    return dfsClientConf.defaultReplication;
1189  }
1190  
1191  public LocatedBlocks getLocatedBlocks(String src, long start)
1192      throws IOException {
1193    return getLocatedBlocks(src, start, dfsClientConf.prefetchSize);
1194  }
1195
1196  /*
1197   * This is just a wrapper around callGetBlockLocations, but non-static so that
1198   * we can stub it out for tests.
1199   */
1200  @VisibleForTesting
1201  public LocatedBlocks getLocatedBlocks(String src, long start, long length)
1202      throws IOException {
1203    return callGetBlockLocations(namenode, src, start, length);
1204  }
1205
1206  /**
1207   * @see ClientProtocol#getBlockLocations(String, long, long)
1208   */
1209  static LocatedBlocks callGetBlockLocations(ClientProtocol namenode,
1210      String src, long start, long length) 
1211      throws IOException {
1212    try {
1213      return namenode.getBlockLocations(src, start, length);
1214    } catch(RemoteException re) {
1215      throw re.unwrapRemoteException(AccessControlException.class,
1216                                     FileNotFoundException.class,
1217                                     UnresolvedPathException.class);
1218    }
1219  }
1220
1221  /**
1222   * Recover a file's lease
1223   * @param src a file's path
1224   * @return true if the file is already closed
1225   * @throws IOException
1226   */
1227  boolean recoverLease(String src) throws IOException {
1228    checkOpen();
1229
1230    try {
1231      return namenode.recoverLease(src, clientName);
1232    } catch (RemoteException re) {
1233      throw re.unwrapRemoteException(FileNotFoundException.class,
1234                                     AccessControlException.class,
1235                                     UnresolvedPathException.class);
1236    }
1237  }
1238
1239  /**
1240   * Get block location info about file
1241   * 
1242   * getBlockLocations() returns a list of hostnames that store 
1243   * data for a specific file region.  It returns a set of hostnames
1244   * for every block within the indicated region.
1245   *
1246   * This function is very useful when writing code that considers
1247   * data-placement when performing operations.  For example, the
1248   * MapReduce system tries to schedule tasks on the same machines
1249   * as the data-block the task processes. 
1250   */
1251  public BlockLocation[] getBlockLocations(String src, long start, 
1252    long length) throws IOException, UnresolvedLinkException {
1253    LocatedBlocks blocks = getLocatedBlocks(src, start, length);
1254    BlockLocation[] locations =  DFSUtil.locatedBlocks2Locations(blocks);
1255    HdfsBlockLocation[] hdfsLocations = new HdfsBlockLocation[locations.length];
1256    for (int i = 0; i < locations.length; i++) {
1257      hdfsLocations[i] = new HdfsBlockLocation(locations[i], blocks.get(i));
1258    }
1259    return hdfsLocations;
1260  }
1261  
1262  /**
1263   * Get block location information about a list of {@link HdfsBlockLocation}.
1264   * Used by {@link DistributedFileSystem#getFileBlockStorageLocations(List)} to
1265   * get {@link BlockStorageLocation}s for blocks returned by
1266   * {@link DistributedFileSystem#getFileBlockLocations(org.apache.hadoop.fs.FileStatus, long, long)}
1267   * .
1268   * 
1269   * This is done by making a round of RPCs to the associated datanodes, asking
1270   * the volume of each block replica. The returned array of
1271   * {@link BlockStorageLocation} expose this information as a
1272   * {@link VolumeId}.
1273   * 
1274   * @param blockLocations
1275   *          target blocks on which to query volume location information
1276   * @return volumeBlockLocations original block array augmented with additional
1277   *         volume location information for each replica.
1278   */
1279  public BlockStorageLocation[] getBlockStorageLocations(
1280      List<BlockLocation> blockLocations) throws IOException,
1281      UnsupportedOperationException, InvalidBlockTokenException {
1282    if (!getConf().getHdfsBlocksMetadataEnabled) {
1283      throw new UnsupportedOperationException("Datanode-side support for " +
1284          "getVolumeBlockLocations() must also be enabled in the client " +
1285          "configuration.");
1286    }
1287    // Downcast blockLocations and fetch out required LocatedBlock(s)
1288    List<LocatedBlock> blocks = new ArrayList<LocatedBlock>();
1289    for (BlockLocation loc : blockLocations) {
1290      if (!(loc instanceof HdfsBlockLocation)) {
1291        throw new ClassCastException("DFSClient#getVolumeBlockLocations " +
1292            "expected to be passed HdfsBlockLocations");
1293      }
1294      HdfsBlockLocation hdfsLoc = (HdfsBlockLocation) loc;
1295      blocks.add(hdfsLoc.getLocatedBlock());
1296    }
1297    
1298    // Re-group the LocatedBlocks to be grouped by datanodes, with the values
1299    // a list of the LocatedBlocks on the datanode.
1300    Map<DatanodeInfo, List<LocatedBlock>> datanodeBlocks = 
1301        new LinkedHashMap<DatanodeInfo, List<LocatedBlock>>();
1302    for (LocatedBlock b : blocks) {
1303      for (DatanodeInfo info : b.getLocations()) {
1304        if (!datanodeBlocks.containsKey(info)) {
1305          datanodeBlocks.put(info, new ArrayList<LocatedBlock>());
1306        }
1307        List<LocatedBlock> l = datanodeBlocks.get(info);
1308        l.add(b);
1309      }
1310    }
1311        
1312    // Make RPCs to the datanodes to get volume locations for its replicas
1313    Map<DatanodeInfo, HdfsBlocksMetadata> metadatas = BlockStorageLocationUtil
1314        .queryDatanodesForHdfsBlocksMetadata(conf, datanodeBlocks,
1315            getConf().getFileBlockStorageLocationsNumThreads,
1316            getConf().getFileBlockStorageLocationsTimeoutMs,
1317            getConf().connectToDnViaHostname);
1318    
1319    if (LOG.isTraceEnabled()) {
1320      LOG.trace("metadata returned: "
1321          + Joiner.on("\n").withKeyValueSeparator("=").join(metadatas));
1322    }
1323    
1324    // Regroup the returned VolumeId metadata to again be grouped by
1325    // LocatedBlock rather than by datanode
1326    Map<LocatedBlock, List<VolumeId>> blockVolumeIds = BlockStorageLocationUtil
1327        .associateVolumeIdsWithBlocks(blocks, metadatas);
1328    
1329    // Combine original BlockLocations with new VolumeId information
1330    BlockStorageLocation[] volumeBlockLocations = BlockStorageLocationUtil
1331        .convertToVolumeBlockLocations(blocks, blockVolumeIds);
1332
1333    return volumeBlockLocations;
1334  }
1335
1336  /**
1337   * Decrypts a EDEK by consulting the KeyProvider.
1338   */
1339  private KeyVersion decryptEncryptedDataEncryptionKey(FileEncryptionInfo
1340      feInfo) throws IOException {
1341    KeyProvider provider = getKeyProvider();
1342    if (provider == null) {
1343      throw new IOException("No KeyProvider is configured, cannot access" +
1344          " an encrypted file");
1345    }
1346    EncryptedKeyVersion ekv = EncryptedKeyVersion.createForDecryption(
1347        feInfo.getKeyName(), feInfo.getEzKeyVersionName(), feInfo.getIV(),
1348        feInfo.getEncryptedDataEncryptionKey());
1349    try {
1350      KeyProviderCryptoExtension cryptoProvider = KeyProviderCryptoExtension
1351          .createKeyProviderCryptoExtension(provider);
1352      return cryptoProvider.decryptEncryptedKey(ekv);
1353    } catch (GeneralSecurityException e) {
1354      throw new IOException(e);
1355    }
1356  }
1357
1358  /**
1359   * Obtain the crypto protocol version from the provided FileEncryptionInfo,
1360   * checking to see if this version is supported by.
1361   *
1362   * @param feInfo FileEncryptionInfo
1363   * @return CryptoProtocolVersion from the feInfo
1364   * @throws IOException if the protocol version is unsupported.
1365   */
1366  private static CryptoProtocolVersion getCryptoProtocolVersion
1367      (FileEncryptionInfo feInfo) throws IOException {
1368    final CryptoProtocolVersion version = feInfo.getCryptoProtocolVersion();
1369    if (!CryptoProtocolVersion.supports(version)) {
1370      throw new IOException("Client does not support specified " +
1371          "CryptoProtocolVersion " + version.getDescription() + " version " +
1372          "number" + version.getVersion());
1373    }
1374    return version;
1375  }
1376
1377  /**
1378   * Obtain a CryptoCodec based on the CipherSuite set in a FileEncryptionInfo
1379   * and the available CryptoCodecs configured in the Configuration.
1380   *
1381   * @param conf   Configuration
1382   * @param feInfo FileEncryptionInfo
1383   * @return CryptoCodec
1384   * @throws IOException if no suitable CryptoCodec for the CipherSuite is
1385   *                     available.
1386   */
1387  private static CryptoCodec getCryptoCodec(Configuration conf,
1388      FileEncryptionInfo feInfo) throws IOException {
1389    final CipherSuite suite = feInfo.getCipherSuite();
1390    if (suite.equals(CipherSuite.UNKNOWN)) {
1391      throw new IOException("NameNode specified unknown CipherSuite with ID "
1392          + suite.getUnknownValue() + ", cannot instantiate CryptoCodec.");
1393    }
1394    final CryptoCodec codec = CryptoCodec.getInstance(conf, suite);
1395    if (codec == null) {
1396      throw new UnknownCipherSuiteException(
1397          "No configuration found for the cipher suite "
1398          + suite.getConfigSuffix() + " prefixed with "
1399          + HADOOP_SECURITY_CRYPTO_CODEC_CLASSES_KEY_PREFIX
1400          + ". Please see the example configuration "
1401          + "hadoop.security.crypto.codec.classes.EXAMPLECIPHERSUITE "
1402          + "at core-default.xml for details.");
1403    }
1404    return codec;
1405  }
1406
1407  /**
1408   * Wraps the stream in a CryptoInputStream if the underlying file is
1409   * encrypted.
1410   */
1411  public HdfsDataInputStream createWrappedInputStream(DFSInputStream dfsis)
1412      throws IOException {
1413    final FileEncryptionInfo feInfo = dfsis.getFileEncryptionInfo();
1414    if (feInfo != null) {
1415      // File is encrypted, wrap the stream in a crypto stream.
1416      // Currently only one version, so no special logic based on the version #
1417      getCryptoProtocolVersion(feInfo);
1418      final CryptoCodec codec = getCryptoCodec(conf, feInfo);
1419      final KeyVersion decrypted = decryptEncryptedDataEncryptionKey(feInfo);
1420      final CryptoInputStream cryptoIn =
1421          new CryptoInputStream(dfsis, codec, decrypted.getMaterial(),
1422              feInfo.getIV());
1423      return new HdfsDataInputStream(cryptoIn);
1424    } else {
1425      // No FileEncryptionInfo so no encryption.
1426      return new HdfsDataInputStream(dfsis);
1427    }
1428  }
1429
1430  /**
1431   * Wraps the stream in a CryptoOutputStream if the underlying file is
1432   * encrypted.
1433   */
1434  public HdfsDataOutputStream createWrappedOutputStream(DFSOutputStream dfsos,
1435      FileSystem.Statistics statistics) throws IOException {
1436    return createWrappedOutputStream(dfsos, statistics, 0);
1437  }
1438
1439  /**
1440   * Wraps the stream in a CryptoOutputStream if the underlying file is
1441   * encrypted.
1442   */
1443  public HdfsDataOutputStream createWrappedOutputStream(DFSOutputStream dfsos,
1444      FileSystem.Statistics statistics, long startPos) throws IOException {
1445    final FileEncryptionInfo feInfo = dfsos.getFileEncryptionInfo();
1446    if (feInfo != null) {
1447      // File is encrypted, wrap the stream in a crypto stream.
1448      // Currently only one version, so no special logic based on the version #
1449      getCryptoProtocolVersion(feInfo);
1450      final CryptoCodec codec = getCryptoCodec(conf, feInfo);
1451      KeyVersion decrypted = decryptEncryptedDataEncryptionKey(feInfo);
1452      final CryptoOutputStream cryptoOut =
1453          new CryptoOutputStream(dfsos, codec,
1454              decrypted.getMaterial(), feInfo.getIV(), startPos);
1455      return new HdfsDataOutputStream(cryptoOut, statistics, startPos);
1456    } else {
1457      // No FileEncryptionInfo present so no encryption.
1458      return new HdfsDataOutputStream(dfsos, statistics, startPos);
1459    }
1460  }
1461
1462  public DFSInputStream open(String src) 
1463      throws IOException, UnresolvedLinkException {
1464    return open(src, dfsClientConf.ioBufferSize, true, null);
1465  }
1466
1467  /**
1468   * Create an input stream that obtains a nodelist from the
1469   * namenode, and then reads from all the right places.  Creates
1470   * inner subclass of InputStream that does the right out-of-band
1471   * work.
1472   * @deprecated Use {@link #open(String, int, boolean)} instead.
1473   */
1474  @Deprecated
1475  public DFSInputStream open(String src, int buffersize, boolean verifyChecksum,
1476                             FileSystem.Statistics stats)
1477      throws IOException, UnresolvedLinkException {
1478    return open(src, buffersize, verifyChecksum);
1479  }
1480  
1481
1482  /**
1483   * Create an input stream that obtains a nodelist from the
1484   * namenode, and then reads from all the right places.  Creates
1485   * inner subclass of InputStream that does the right out-of-band
1486   * work.
1487   */
1488  public DFSInputStream open(String src, int buffersize, boolean verifyChecksum)
1489      throws IOException, UnresolvedLinkException {
1490    checkOpen();
1491    //    Get block info from namenode
1492    return new DFSInputStream(this, src, verifyChecksum);
1493  }
1494
1495  /**
1496   * Get the namenode associated with this DFSClient object
1497   * @return the namenode associated with this DFSClient object
1498   */
1499  public ClientProtocol getNamenode() {
1500    return namenode;
1501  }
1502  
1503  /**
1504   * Call {@link #create(String, boolean, short, long, Progressable)} with
1505   * default <code>replication</code> and <code>blockSize<code> and null <code>
1506   * progress</code>.
1507   */
1508  public OutputStream create(String src, boolean overwrite) 
1509      throws IOException {
1510    return create(src, overwrite, dfsClientConf.defaultReplication,
1511        dfsClientConf.defaultBlockSize, null);
1512  }
1513    
1514  /**
1515   * Call {@link #create(String, boolean, short, long, Progressable)} with
1516   * default <code>replication</code> and <code>blockSize<code>.
1517   */
1518  public OutputStream create(String src, 
1519                             boolean overwrite,
1520                             Progressable progress) throws IOException {
1521    return create(src, overwrite, dfsClientConf.defaultReplication,
1522        dfsClientConf.defaultBlockSize, progress);
1523  }
1524    
1525  /**
1526   * Call {@link #create(String, boolean, short, long, Progressable)} with
1527   * null <code>progress</code>.
1528   */
1529  public OutputStream create(String src, 
1530                             boolean overwrite, 
1531                             short replication,
1532                             long blockSize) throws IOException {
1533    return create(src, overwrite, replication, blockSize, null);
1534  }
1535
1536  /**
1537   * Call {@link #create(String, boolean, short, long, Progressable, int)}
1538   * with default bufferSize.
1539   */
1540  public OutputStream create(String src, boolean overwrite, short replication,
1541      long blockSize, Progressable progress) throws IOException {
1542    return create(src, overwrite, replication, blockSize, progress,
1543        dfsClientConf.ioBufferSize);
1544  }
1545
1546  /**
1547   * Call {@link #create(String, FsPermission, EnumSet, short, long, 
1548   * Progressable, int, ChecksumOpt)} with default <code>permission</code>
1549   * {@link FsPermission#getFileDefault()}.
1550   * 
1551   * @param src File name
1552   * @param overwrite overwrite an existing file if true
1553   * @param replication replication factor for the file
1554   * @param blockSize maximum block size
1555   * @param progress interface for reporting client progress
1556   * @param buffersize underlying buffersize
1557   * 
1558   * @return output stream
1559   */
1560  public OutputStream create(String src,
1561                             boolean overwrite,
1562                             short replication,
1563                             long blockSize,
1564                             Progressable progress,
1565                             int buffersize)
1566      throws IOException {
1567    return create(src, FsPermission.getFileDefault(),
1568        overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
1569            : EnumSet.of(CreateFlag.CREATE), replication, blockSize, progress,
1570        buffersize, null);
1571  }
1572
1573  /**
1574   * Call {@link #create(String, FsPermission, EnumSet, boolean, short, 
1575   * long, Progressable, int, ChecksumOpt)} with <code>createParent</code>
1576   *  set to true.
1577   */
1578  public DFSOutputStream create(String src, 
1579                             FsPermission permission,
1580                             EnumSet<CreateFlag> flag, 
1581                             short replication,
1582                             long blockSize,
1583                             Progressable progress,
1584                             int buffersize,
1585                             ChecksumOpt checksumOpt)
1586      throws IOException {
1587    return create(src, permission, flag, true,
1588        replication, blockSize, progress, buffersize, checksumOpt, null);
1589  }
1590
1591  /**
1592   * Create a new dfs file with the specified block replication 
1593   * with write-progress reporting and return an output stream for writing
1594   * into the file.  
1595   * 
1596   * @param src File name
1597   * @param permission The permission of the directory being created.
1598   *          If null, use default permission {@link FsPermission#getFileDefault()}
1599   * @param flag indicates create a new file or create/overwrite an
1600   *          existing file or append to an existing file
1601   * @param createParent create missing parent directory if true
1602   * @param replication block replication
1603   * @param blockSize maximum block size
1604   * @param progress interface for reporting client progress
1605   * @param buffersize underlying buffer size 
1606   * @param checksumOpt checksum options
1607   * 
1608   * @return output stream
1609   * 
1610   * @see ClientProtocol#create(String, FsPermission, String, EnumSetWritable,
1611   * boolean, short, long) for detailed description of exceptions thrown
1612   */
1613  public DFSOutputStream create(String src, 
1614                             FsPermission permission,
1615                             EnumSet<CreateFlag> flag, 
1616                             boolean createParent,
1617                             short replication,
1618                             long blockSize,
1619                             Progressable progress,
1620                             int buffersize,
1621                             ChecksumOpt checksumOpt) throws IOException {
1622    return create(src, permission, flag, createParent, replication, blockSize, 
1623        progress, buffersize, checksumOpt, null);
1624  }
1625
1626  /**
1627   * Same as {@link #create(String, FsPermission, EnumSet, boolean, short, long,
1628   * Progressable, int, ChecksumOpt)} with the addition of favoredNodes that is
1629   * a hint to where the namenode should place the file blocks.
1630   * The favored nodes hint is not persisted in HDFS. Hence it may be honored
1631   * at the creation time only. HDFS could move the blocks during balancing or
1632   * replication, to move the blocks from favored nodes. A value of null means
1633   * no favored nodes for this create
1634   */
1635  public DFSOutputStream create(String src, 
1636                             FsPermission permission,
1637                             EnumSet<CreateFlag> flag, 
1638                             boolean createParent,
1639                             short replication,
1640                             long blockSize,
1641                             Progressable progress,
1642                             int buffersize,
1643                             ChecksumOpt checksumOpt,
1644                             InetSocketAddress[] favoredNodes) throws IOException {
1645    checkOpen();
1646    if (permission == null) {
1647      permission = FsPermission.getFileDefault();
1648    }
1649    FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
1650    if(LOG.isDebugEnabled()) {
1651      LOG.debug(src + ": masked=" + masked);
1652    }
1653    String[] favoredNodeStrs = null;
1654    if (favoredNodes != null) {
1655      favoredNodeStrs = new String[favoredNodes.length];
1656      for (int i = 0; i < favoredNodes.length; i++) {
1657        favoredNodeStrs[i] = 
1658            favoredNodes[i].getHostName() + ":" 
1659                         + favoredNodes[i].getPort();
1660      }
1661    }
1662    final DFSOutputStream result = DFSOutputStream.newStreamForCreate(this,
1663        src, masked, flag, createParent, replication, blockSize, progress,
1664        buffersize, dfsClientConf.createChecksum(checksumOpt),
1665        favoredNodeStrs);
1666    beginFileLease(result.getFileId(), result);
1667    return result;
1668  }
1669  
1670  /**
1671   * Append to an existing file if {@link CreateFlag#APPEND} is present
1672   */
1673  private DFSOutputStream primitiveAppend(String src, EnumSet<CreateFlag> flag,
1674      int buffersize, Progressable progress) throws IOException {
1675    if (flag.contains(CreateFlag.APPEND)) {
1676      HdfsFileStatus stat = getFileInfo(src);
1677      if (stat == null) { // No file to append to
1678        // New file needs to be created if create option is present
1679        if (!flag.contains(CreateFlag.CREATE)) {
1680          throw new FileNotFoundException("failed to append to non-existent file "
1681              + src + " on client " + clientName);
1682        }
1683        return null;
1684      }
1685      return callAppend(src, buffersize, progress);
1686    }
1687    return null;
1688  }
1689  
1690  /**
1691   * Same as {{@link #create(String, FsPermission, EnumSet, short, long,
1692   *  Progressable, int, ChecksumOpt)} except that the permission
1693   *  is absolute (ie has already been masked with umask.
1694   */
1695  public DFSOutputStream primitiveCreate(String src, 
1696                             FsPermission absPermission,
1697                             EnumSet<CreateFlag> flag,
1698                             boolean createParent,
1699                             short replication,
1700                             long blockSize,
1701                             Progressable progress,
1702                             int buffersize,
1703                             ChecksumOpt checksumOpt)
1704      throws IOException, UnresolvedLinkException {
1705    checkOpen();
1706    CreateFlag.validate(flag);
1707    DFSOutputStream result = primitiveAppend(src, flag, buffersize, progress);
1708    if (result == null) {
1709      DataChecksum checksum = dfsClientConf.createChecksum(checksumOpt);
1710      result = DFSOutputStream.newStreamForCreate(this, src, absPermission,
1711          flag, createParent, replication, blockSize, progress, buffersize,
1712          checksum, null);
1713    }
1714    beginFileLease(result.getFileId(), result);
1715    return result;
1716  }
1717  
1718  /**
1719   * Creates a symbolic link.
1720   * 
1721   * @see ClientProtocol#createSymlink(String, String,FsPermission, boolean) 
1722   */
1723  public void createSymlink(String target, String link, boolean createParent)
1724      throws IOException {
1725    try {
1726      FsPermission dirPerm = 
1727          FsPermission.getDefault().applyUMask(dfsClientConf.uMask); 
1728      namenode.createSymlink(target, link, dirPerm, createParent);
1729    } catch (RemoteException re) {
1730      throw re.unwrapRemoteException(AccessControlException.class,
1731                                     FileAlreadyExistsException.class, 
1732                                     FileNotFoundException.class,
1733                                     ParentNotDirectoryException.class,
1734                                     NSQuotaExceededException.class, 
1735                                     DSQuotaExceededException.class,
1736                                     UnresolvedPathException.class,
1737                                     SnapshotAccessControlException.class);
1738    }
1739  }
1740
1741  /**
1742   * Resolve the *first* symlink, if any, in the path.
1743   * 
1744   * @see ClientProtocol#getLinkTarget(String)
1745   */
1746  public String getLinkTarget(String path) throws IOException { 
1747    checkOpen();
1748    try {
1749      return namenode.getLinkTarget(path);
1750    } catch (RemoteException re) {
1751      throw re.unwrapRemoteException(AccessControlException.class,
1752                                     FileNotFoundException.class);
1753    }
1754  }
1755
1756  /** Method to get stream returned by append call */
1757  private DFSOutputStream callAppend(String src,
1758      int buffersize, Progressable progress) throws IOException {
1759    LocatedBlock lastBlock = null;
1760    try {
1761      lastBlock = namenode.append(src, clientName);
1762    } catch(RemoteException re) {
1763      throw re.unwrapRemoteException(AccessControlException.class,
1764                                     FileNotFoundException.class,
1765                                     SafeModeException.class,
1766                                     DSQuotaExceededException.class,
1767                                     UnsupportedOperationException.class,
1768                                     UnresolvedPathException.class,
1769                                     SnapshotAccessControlException.class);
1770    }
1771    HdfsFileStatus newStat = getFileInfo(src);
1772    return DFSOutputStream.newStreamForAppend(this, src, buffersize, progress,
1773        lastBlock, newStat, dfsClientConf.createChecksum());
1774  }
1775  
1776  /**
1777   * Append to an existing HDFS file.  
1778   * 
1779   * @param src file name
1780   * @param buffersize buffer size
1781   * @param progress for reporting write-progress; null is acceptable.
1782   * @param statistics file system statistics; null is acceptable.
1783   * @return an output stream for writing into the file
1784   * 
1785   * @see ClientProtocol#append(String, String) 
1786   */
1787  public HdfsDataOutputStream append(final String src, final int buffersize,
1788      final Progressable progress, final FileSystem.Statistics statistics
1789      ) throws IOException {
1790    final DFSOutputStream out = append(src, buffersize, progress);
1791    return createWrappedOutputStream(out, statistics, out.getInitialLen());
1792  }
1793
1794  private DFSOutputStream append(String src, int buffersize, Progressable progress) 
1795      throws IOException {
1796    checkOpen();
1797    final DFSOutputStream result = callAppend(src, buffersize, progress);
1798    beginFileLease(result.getFileId(), result);
1799    return result;
1800  }
1801
1802  /**
1803   * Set replication for an existing file.
1804   * @param src file name
1805   * @param replication replication to set the file to
1806   * 
1807   * @see ClientProtocol#setReplication(String, short)
1808   */
1809  public boolean setReplication(String src, short replication)
1810      throws IOException {
1811    try {
1812      return namenode.setReplication(src, replication);
1813    } catch(RemoteException re) {
1814      throw re.unwrapRemoteException(AccessControlException.class,
1815                                     FileNotFoundException.class,
1816                                     SafeModeException.class,
1817                                     DSQuotaExceededException.class,
1818                                     UnresolvedPathException.class,
1819                                     SnapshotAccessControlException.class);
1820    }
1821  }
1822
1823  /**
1824   * Set storage policy for an existing file/directory
1825   * @param src file/directory name
1826   * @param policyName name of the storage policy
1827   */
1828  public void setStoragePolicy(String src, String policyName)
1829      throws IOException {
1830    try {
1831      namenode.setStoragePolicy(src, policyName);
1832    } catch (RemoteException e) {
1833      throw e.unwrapRemoteException(AccessControlException.class,
1834                                    FileNotFoundException.class,
1835                                    SafeModeException.class,
1836                                    NSQuotaExceededException.class,
1837                                    UnresolvedPathException.class,
1838                                    SnapshotAccessControlException.class);
1839    }
1840  }
1841
1842  /**
1843   * @return All the existing storage policies
1844   */
1845  public BlockStoragePolicy[] getStoragePolicies() throws IOException {
1846    return namenode.getStoragePolicies();
1847  }
1848
1849  /**
1850   * Rename file or directory.
1851   * @see ClientProtocol#rename(String, String)
1852   * @deprecated Use {@link #rename(String, String, Options.Rename...)} instead.
1853   */
1854  @Deprecated
1855  public boolean rename(String src, String dst) throws IOException {
1856    checkOpen();
1857    try {
1858      return namenode.rename(src, dst);
1859    } catch(RemoteException re) {
1860      throw re.unwrapRemoteException(AccessControlException.class,
1861                                     NSQuotaExceededException.class,
1862                                     DSQuotaExceededException.class,
1863                                     UnresolvedPathException.class,
1864                                     SnapshotAccessControlException.class);
1865    }
1866  }
1867
1868  /**
1869   * Move blocks from src to trg and delete src
1870   * See {@link ClientProtocol#concat(String, String [])}. 
1871   */
1872  public void concat(String trg, String [] srcs) throws IOException {
1873    checkOpen();
1874    try {
1875      namenode.concat(trg, srcs);
1876    } catch(RemoteException re) {
1877      throw re.unwrapRemoteException(AccessControlException.class,
1878                                     UnresolvedPathException.class,
1879                                     SnapshotAccessControlException.class);
1880    }
1881  }
1882  /**
1883   * Rename file or directory.
1884   * @see ClientProtocol#rename2(String, String, Options.Rename...)
1885   */
1886  public void rename(String src, String dst, Options.Rename... options)
1887      throws IOException {
1888    checkOpen();
1889    try {
1890      namenode.rename2(src, dst, options);
1891    } catch(RemoteException re) {
1892      throw re.unwrapRemoteException(AccessControlException.class,
1893                                     DSQuotaExceededException.class,
1894                                     FileAlreadyExistsException.class,
1895                                     FileNotFoundException.class,
1896                                     ParentNotDirectoryException.class,
1897                                     SafeModeException.class,
1898                                     NSQuotaExceededException.class,
1899                                     UnresolvedPathException.class,
1900                                     SnapshotAccessControlException.class);
1901    }
1902  }
1903  /**
1904   * Delete file or directory.
1905   * See {@link ClientProtocol#delete(String, boolean)}. 
1906   */
1907  @Deprecated
1908  public boolean delete(String src) throws IOException {
1909    checkOpen();
1910    return namenode.delete(src, true);
1911  }
1912
1913  /**
1914   * delete file or directory.
1915   * delete contents of the directory if non empty and recursive 
1916   * set to true
1917   *
1918   * @see ClientProtocol#delete(String, boolean)
1919   */
1920  public boolean delete(String src, boolean recursive) throws IOException {
1921    checkOpen();
1922    try {
1923      return namenode.delete(src, recursive);
1924    } catch(RemoteException re) {
1925      throw re.unwrapRemoteException(AccessControlException.class,
1926                                     FileNotFoundException.class,
1927                                     SafeModeException.class,
1928                                     UnresolvedPathException.class,
1929                                     SnapshotAccessControlException.class);
1930    }
1931  }
1932  
1933  /** Implemented using getFileInfo(src)
1934   */
1935  public boolean exists(String src) throws IOException {
1936    checkOpen();
1937    return getFileInfo(src) != null;
1938  }
1939
1940  /**
1941   * Get a partial listing of the indicated directory
1942   * No block locations need to be fetched
1943   */
1944  public DirectoryListing listPaths(String src,  byte[] startAfter)
1945    throws IOException {
1946    return listPaths(src, startAfter, false);
1947  }
1948  
1949  /**
1950   * Get a partial listing of the indicated directory
1951   *
1952   * Recommend to use HdfsFileStatus.EMPTY_NAME as startAfter
1953   * if the application wants to fetch a listing starting from
1954   * the first entry in the directory
1955   *
1956   * @see ClientProtocol#getListing(String, byte[], boolean)
1957   */
1958  public DirectoryListing listPaths(String src,  byte[] startAfter,
1959      boolean needLocation) 
1960    throws IOException {
1961    checkOpen();
1962    try {
1963      return namenode.getListing(src, startAfter, needLocation);
1964    } catch(RemoteException re) {
1965      throw re.unwrapRemoteException(AccessControlException.class,
1966                                     FileNotFoundException.class,
1967                                     UnresolvedPathException.class);
1968    }
1969  }
1970
1971  /**
1972   * Get the file info for a specific file or directory.
1973   * @param src The string representation of the path to the file
1974   * @return object containing information regarding the file
1975   *         or null if file not found
1976   *         
1977   * @see ClientProtocol#getFileInfo(String) for description of exceptions
1978   */
1979  public HdfsFileStatus getFileInfo(String src) throws IOException {
1980    checkOpen();
1981    try {
1982      return namenode.getFileInfo(src);
1983    } catch(RemoteException re) {
1984      throw re.unwrapRemoteException(AccessControlException.class,
1985                                     FileNotFoundException.class,
1986                                     UnresolvedPathException.class);
1987    }
1988  }
1989  
1990  /**
1991   * Close status of a file
1992   * @return true if file is already closed
1993   */
1994  public boolean isFileClosed(String src) throws IOException{
1995    checkOpen();
1996    try {
1997      return namenode.isFileClosed(src);
1998    } catch(RemoteException re) {
1999      throw re.unwrapRemoteException(AccessControlException.class,
2000                                     FileNotFoundException.class,
2001                                     UnresolvedPathException.class);
2002    }
2003  }
2004  
2005  /**
2006   * Get the file info for a specific file or directory. If src
2007   * refers to a symlink then the FileStatus of the link is returned.
2008   * @param src path to a file or directory.
2009   * 
2010   * For description of exceptions thrown 
2011   * @see ClientProtocol#getFileLinkInfo(String)
2012   */
2013  public HdfsFileStatus getFileLinkInfo(String src) throws IOException {
2014    checkOpen();
2015    try {
2016      return namenode.getFileLinkInfo(src);
2017    } catch(RemoteException re) {
2018      throw re.unwrapRemoteException(AccessControlException.class,
2019                                     UnresolvedPathException.class);
2020     }
2021   }
2022  
2023  @InterfaceAudience.Private
2024  public void clearDataEncryptionKey() {
2025    LOG.debug("Clearing encryption key");
2026    synchronized (this) {
2027      encryptionKey = null;
2028    }
2029  }
2030  
2031  /**
2032   * @return true if data sent between this client and DNs should be encrypted,
2033   *         false otherwise.
2034   * @throws IOException in the event of error communicating with the NN
2035   */
2036  boolean shouldEncryptData() throws IOException {
2037    FsServerDefaults d = getServerDefaults();
2038    return d == null ? false : d.getEncryptDataTransfer();
2039  }
2040  
2041  @Override
2042  public DataEncryptionKey newDataEncryptionKey() throws IOException {
2043    if (shouldEncryptData()) {
2044      synchronized (this) {
2045        if (encryptionKey == null ||
2046            encryptionKey.expiryDate < Time.now()) {
2047          LOG.debug("Getting new encryption token from NN");
2048          encryptionKey = namenode.getDataEncryptionKey();
2049        }
2050        return encryptionKey;
2051      }
2052    } else {
2053      return null;
2054    }
2055  }
2056
2057  /**
2058   * Get the checksum of the whole file of a range of the file. Note that the
2059   * range always starts from the beginning of the file.
2060   * @param src The file path
2061   * @param length the length of the range, i.e., the range is [0, length]
2062   * @return The checksum 
2063   * @see DistributedFileSystem#getFileChecksum(Path)
2064   */
2065  public MD5MD5CRC32FileChecksum getFileChecksum(String src, long length)
2066      throws IOException {
2067    checkOpen();
2068    Preconditions.checkArgument(length >= 0);
2069    //get block locations for the file range
2070    LocatedBlocks blockLocations = callGetBlockLocations(namenode, src, 0,
2071        length);
2072    if (null == blockLocations) {
2073      throw new FileNotFoundException("File does not exist: " + src);
2074    }
2075    List<LocatedBlock> locatedblocks = blockLocations.getLocatedBlocks();
2076    final DataOutputBuffer md5out = new DataOutputBuffer();
2077    int bytesPerCRC = -1;
2078    DataChecksum.Type crcType = DataChecksum.Type.DEFAULT;
2079    long crcPerBlock = 0;
2080    boolean refetchBlocks = false;
2081    int lastRetriedIndex = -1;
2082
2083    // get block checksum for each block
2084    long remaining = length;
2085    if (src.contains(HdfsConstants.SEPARATOR_DOT_SNAPSHOT_DIR_SEPARATOR)) {
2086      remaining = Math.min(length, blockLocations.getFileLength());
2087    }
2088    for(int i = 0; i < locatedblocks.size() && remaining > 0; i++) {
2089      if (refetchBlocks) {  // refetch to get fresh tokens
2090        blockLocations = callGetBlockLocations(namenode, src, 0, length);
2091        if (null == blockLocations) {
2092          throw new FileNotFoundException("File does not exist: " + src);
2093        }
2094        locatedblocks = blockLocations.getLocatedBlocks();
2095        refetchBlocks = false;
2096      }
2097      LocatedBlock lb = locatedblocks.get(i);
2098      final ExtendedBlock block = lb.getBlock();
2099      if (remaining < block.getNumBytes()) {
2100        block.setNumBytes(remaining);
2101      }
2102      remaining -= block.getNumBytes();
2103      final DatanodeInfo[] datanodes = lb.getLocations();
2104      
2105      //try each datanode location of the block
2106      final int timeout = 3000 * datanodes.length + dfsClientConf.socketTimeout;
2107      boolean done = false;
2108      for(int j = 0; !done && j < datanodes.length; j++) {
2109        DataOutputStream out = null;
2110        DataInputStream in = null;
2111        
2112        try {
2113          //connect to a datanode
2114          IOStreamPair pair = connectToDN(datanodes[j], timeout, lb);
2115          out = new DataOutputStream(new BufferedOutputStream(pair.out,
2116              HdfsConstants.SMALL_BUFFER_SIZE));
2117          in = new DataInputStream(pair.in);
2118
2119          if (LOG.isDebugEnabled()) {
2120            LOG.debug("write to " + datanodes[j] + ": "
2121                + Op.BLOCK_CHECKSUM + ", block=" + block);
2122          }
2123          // get block MD5
2124          new Sender(out).blockChecksum(block, lb.getBlockToken());
2125
2126          final BlockOpResponseProto reply =
2127            BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(in));
2128
2129          if (reply.getStatus() != Status.SUCCESS) {
2130            if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) {
2131              throw new InvalidBlockTokenException();
2132            } else {
2133              throw new IOException("Bad response " + reply + " for block "
2134                  + block + " from datanode " + datanodes[j]);
2135            }
2136          }
2137          
2138          OpBlockChecksumResponseProto checksumData =
2139            reply.getChecksumResponse();
2140
2141          //read byte-per-checksum
2142          final int bpc = checksumData.getBytesPerCrc();
2143          if (i == 0) { //first block
2144            bytesPerCRC = bpc;
2145          }
2146          else if (bpc != bytesPerCRC) {
2147            throw new IOException("Byte-per-checksum not matched: bpc=" + bpc
2148                + " but bytesPerCRC=" + bytesPerCRC);
2149          }
2150          
2151          //read crc-per-block
2152          final long cpb = checksumData.getCrcPerBlock();
2153          if (locatedblocks.size() > 1 && i == 0) {
2154            crcPerBlock = cpb;
2155          }
2156
2157          //read md5
2158          final MD5Hash md5 = new MD5Hash(
2159              checksumData.getMd5().toByteArray());
2160          md5.write(md5out);
2161          
2162          // read crc-type
2163          final DataChecksum.Type ct;
2164          if (checksumData.hasCrcType()) {
2165            ct = PBHelper.convert(checksumData
2166                .getCrcType());
2167          } else {
2168            LOG.debug("Retrieving checksum from an earlier-version DataNode: " +
2169                      "inferring checksum by reading first byte");
2170            ct = inferChecksumTypeByReading(lb, datanodes[j]);
2171          }
2172
2173          if (i == 0) { // first block
2174            crcType = ct;
2175          } else if (crcType != DataChecksum.Type.MIXED
2176              && crcType != ct) {
2177            // if crc types are mixed in a file
2178            crcType = DataChecksum.Type.MIXED;
2179          }
2180
2181          done = true;
2182
2183          if (LOG.isDebugEnabled()) {
2184            if (i == 0) {
2185              LOG.debug("set bytesPerCRC=" + bytesPerCRC
2186                  + ", crcPerBlock=" + crcPerBlock);
2187            }
2188            LOG.debug("got reply from " + datanodes[j] + ": md5=" + md5);
2189          }
2190        } catch (InvalidBlockTokenException ibte) {
2191          if (i > lastRetriedIndex) {
2192            if (LOG.isDebugEnabled()) {
2193              LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM "
2194                  + "for file " + src + " for block " + block
2195                  + " from datanode " + datanodes[j]
2196                  + ". Will retry the block once.");
2197            }
2198            lastRetriedIndex = i;
2199            done = true; // actually it's not done; but we'll retry
2200            i--; // repeat at i-th block
2201            refetchBlocks = true;
2202            break;
2203          }
2204        } catch (IOException ie) {
2205          LOG.warn("src=" + src + ", datanodes["+j+"]=" + datanodes[j], ie);
2206        } finally {
2207          IOUtils.closeStream(in);
2208          IOUtils.closeStream(out);
2209        }
2210      }
2211
2212      if (!done) {
2213        throw new IOException("Fail to get block MD5 for " + block);
2214      }
2215    }
2216
2217    //compute file MD5
2218    final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData()); 
2219    switch (crcType) {
2220      case CRC32:
2221        return new MD5MD5CRC32GzipFileChecksum(bytesPerCRC,
2222            crcPerBlock, fileMD5);
2223      case CRC32C:
2224        return new MD5MD5CRC32CastagnoliFileChecksum(bytesPerCRC,
2225            crcPerBlock, fileMD5);
2226      default:
2227        // If there is no block allocated for the file,
2228        // return one with the magic entry that matches what previous
2229        // hdfs versions return.
2230        if (locatedblocks.size() == 0) {
2231          return new MD5MD5CRC32GzipFileChecksum(0, 0, fileMD5);
2232        }
2233
2234        // we should never get here since the validity was checked
2235        // when getCrcType() was called above.
2236        return null;
2237    }
2238  }
2239
2240  /**
2241   * Connect to the given datanode's datantrasfer port, and return
2242   * the resulting IOStreamPair. This includes encryption wrapping, etc.
2243   */
2244  private IOStreamPair connectToDN(DatanodeInfo dn, int timeout,
2245      LocatedBlock lb) throws IOException {
2246    boolean success = false;
2247    Socket sock = null;
2248    try {
2249      sock = socketFactory.createSocket();
2250      String dnAddr = dn.getXferAddr(getConf().connectToDnViaHostname);
2251      if (LOG.isDebugEnabled()) {
2252        LOG.debug("Connecting to datanode " + dnAddr);
2253      }
2254      NetUtils.connect(sock, NetUtils.createSocketAddr(dnAddr), timeout);
2255      sock.setSoTimeout(timeout);
2256  
2257      OutputStream unbufOut = NetUtils.getOutputStream(sock);
2258      InputStream unbufIn = NetUtils.getInputStream(sock);
2259      IOStreamPair ret = saslClient.newSocketSend(sock, unbufOut, unbufIn, this,
2260        lb.getBlockToken(), dn);
2261      success = true;
2262      return ret;
2263    } finally {
2264      if (!success) {
2265        IOUtils.closeSocket(sock);
2266      }
2267    }
2268  }
2269  
2270  /**
2271   * Infer the checksum type for a replica by sending an OP_READ_BLOCK
2272   * for the first byte of that replica. This is used for compatibility
2273   * with older HDFS versions which did not include the checksum type in
2274   * OpBlockChecksumResponseProto.
2275   *
2276   * @param lb the located block
2277   * @param dn the connected datanode
2278   * @return the inferred checksum type
2279   * @throws IOException if an error occurs
2280   */
2281  private Type inferChecksumTypeByReading(LocatedBlock lb, DatanodeInfo dn)
2282      throws IOException {
2283    IOStreamPair pair = connectToDN(dn, dfsClientConf.socketTimeout, lb);
2284
2285    try {
2286      DataOutputStream out = new DataOutputStream(new BufferedOutputStream(pair.out,
2287          HdfsConstants.SMALL_BUFFER_SIZE));
2288      DataInputStream in = new DataInputStream(pair.in);
2289  
2290      new Sender(out).readBlock(lb.getBlock(), lb.getBlockToken(), clientName,
2291          0, 1, true, CachingStrategy.newDefaultStrategy());
2292      final BlockOpResponseProto reply =
2293          BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(in));
2294      
2295      if (reply.getStatus() != Status.SUCCESS) {
2296        if (reply.getStatus() == Status.ERROR_ACCESS_TOKEN) {
2297          throw new InvalidBlockTokenException();
2298        } else {
2299          throw new IOException("Bad response " + reply + " trying to read "
2300              + lb.getBlock() + " from datanode " + dn);
2301        }
2302      }
2303      
2304      return PBHelper.convert(reply.getReadOpChecksumInfo().getChecksum().getType());
2305    } finally {
2306      IOUtils.cleanup(null, pair.in, pair.out);
2307    }
2308  }
2309
2310  /**
2311   * Set permissions to a file or directory.
2312   * @param src path name.
2313   * @param permission permission to set to
2314   * 
2315   * @see ClientProtocol#setPermission(String, FsPermission)
2316   */
2317  public void setPermission(String src, FsPermission permission)
2318      throws IOException {
2319    checkOpen();
2320    try {
2321      namenode.setPermission(src, permission);
2322    } catch(RemoteException re) {
2323      throw re.unwrapRemoteException(AccessControlException.class,
2324                                     FileNotFoundException.class,
2325                                     SafeModeException.class,
2326                                     UnresolvedPathException.class,
2327                                     SnapshotAccessControlException.class);
2328    }
2329  }
2330
2331  /**
2332   * Set file or directory owner.
2333   * @param src path name.
2334   * @param username user id.
2335   * @param groupname user group.
2336   * 
2337   * @see ClientProtocol#setOwner(String, String, String)
2338   */
2339  public void setOwner(String src, String username, String groupname)
2340      throws IOException {
2341    checkOpen();
2342    try {
2343      namenode.setOwner(src, username, groupname);
2344    } catch(RemoteException re) {
2345      throw re.unwrapRemoteException(AccessControlException.class,
2346                                     FileNotFoundException.class,
2347                                     SafeModeException.class,
2348                                     UnresolvedPathException.class,
2349                                     SnapshotAccessControlException.class);                                   
2350    }
2351  }
2352
2353  /**
2354   * @see ClientProtocol#getStats()
2355   */
2356  public FsStatus getDiskStatus() throws IOException {
2357    long rawNums[] = namenode.getStats();
2358    return new FsStatus(rawNums[0], rawNums[1], rawNums[2]);
2359  }
2360
2361  /**
2362   * Returns count of blocks with no good replicas left. Normally should be 
2363   * zero.
2364   * @throws IOException
2365   */ 
2366  public long getMissingBlocksCount() throws IOException {
2367    return namenode.getStats()[ClientProtocol.GET_STATS_MISSING_BLOCKS_IDX];
2368  }
2369  
2370  /**
2371   * Returns count of blocks with replication factor 1 and have
2372   * lost the only replica.
2373   * @throws IOException
2374   */
2375  public long getMissingReplOneBlocksCount() throws IOException {
2376    return namenode.getStats()[ClientProtocol.
2377        GET_STATS_MISSING_REPL_ONE_BLOCKS_IDX];
2378  }
2379
2380  /**
2381   * Returns count of blocks with one of more replica missing.
2382   * @throws IOException
2383   */ 
2384  public long getUnderReplicatedBlocksCount() throws IOException {
2385    return namenode.getStats()[ClientProtocol.GET_STATS_UNDER_REPLICATED_IDX];
2386  }
2387  
2388  /**
2389   * Returns count of blocks with at least one replica marked corrupt. 
2390   * @throws IOException
2391   */ 
2392  public long getCorruptBlocksCount() throws IOException {
2393    return namenode.getStats()[ClientProtocol.GET_STATS_CORRUPT_BLOCKS_IDX];
2394  }
2395  
2396  /**
2397   * @return a list in which each entry describes a corrupt file/block
2398   * @throws IOException
2399   */
2400  public CorruptFileBlocks listCorruptFileBlocks(String path,
2401                                                 String cookie)
2402    throws IOException {
2403    return namenode.listCorruptFileBlocks(path, cookie);
2404  }
2405
2406  public DatanodeInfo[] datanodeReport(DatanodeReportType type)
2407  throws IOException {
2408    return namenode.getDatanodeReport(type);
2409  }
2410    
2411  public DatanodeStorageReport[] getDatanodeStorageReport(
2412      DatanodeReportType type) throws IOException {
2413    return namenode.getDatanodeStorageReport(type);
2414  }
2415
2416  /**
2417   * Enter, leave or get safe mode.
2418   * 
2419   * @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction,boolean)
2420   */
2421  public boolean setSafeMode(SafeModeAction action) throws IOException {
2422    return setSafeMode(action, false);
2423  }
2424  
2425  /**
2426   * Enter, leave or get safe mode.
2427   * 
2428   * @param action
2429   *          One of SafeModeAction.GET, SafeModeAction.ENTER and
2430   *          SafeModeActiob.LEAVE
2431   * @param isChecked
2432   *          If true, then check only active namenode's safemode status, else
2433   *          check first namenode's status.
2434   * @see ClientProtocol#setSafeMode(HdfsConstants.SafeModeAction, boolean)
2435   */
2436  public boolean setSafeMode(SafeModeAction action, boolean isChecked) throws IOException{
2437    return namenode.setSafeMode(action, isChecked);    
2438  }
2439 
2440  /**
2441   * Create one snapshot.
2442   * 
2443   * @param snapshotRoot The directory where the snapshot is to be taken
2444   * @param snapshotName Name of the snapshot
2445   * @return the snapshot path.
2446   * @see ClientProtocol#createSnapshot(String, String)
2447   */
2448  public String createSnapshot(String snapshotRoot, String snapshotName)
2449      throws IOException {
2450    checkOpen();
2451    try {
2452      return namenode.createSnapshot(snapshotRoot, snapshotName);
2453    } catch(RemoteException re) {
2454      throw re.unwrapRemoteException();
2455    }
2456  }
2457  
2458  /**
2459   * Delete a snapshot of a snapshottable directory.
2460   * 
2461   * @param snapshotRoot The snapshottable directory that the 
2462   *                    to-be-deleted snapshot belongs to
2463   * @param snapshotName The name of the to-be-deleted snapshot
2464   * @throws IOException
2465   * @see ClientProtocol#deleteSnapshot(String, String)
2466   */
2467  public void deleteSnapshot(String snapshotRoot, String snapshotName)
2468      throws IOException {
2469    try {
2470      namenode.deleteSnapshot(snapshotRoot, snapshotName);
2471    } catch(RemoteException re) {
2472      throw re.unwrapRemoteException();
2473    }
2474  }
2475  
2476  /**
2477   * Rename a snapshot.
2478   * @param snapshotDir The directory path where the snapshot was taken
2479   * @param snapshotOldName Old name of the snapshot
2480   * @param snapshotNewName New name of the snapshot
2481   * @throws IOException
2482   * @see ClientProtocol#renameSnapshot(String, String, String)
2483   */
2484  public void renameSnapshot(String snapshotDir, String snapshotOldName,
2485      String snapshotNewName) throws IOException {
2486    checkOpen();
2487    try {
2488      namenode.renameSnapshot(snapshotDir, snapshotOldName, snapshotNewName);
2489    } catch(RemoteException re) {
2490      throw re.unwrapRemoteException();
2491    }
2492  }
2493  
2494  /**
2495   * Get all the current snapshottable directories.
2496   * @return All the current snapshottable directories
2497   * @throws IOException
2498   * @see ClientProtocol#getSnapshottableDirListing()
2499   */
2500  public SnapshottableDirectoryStatus[] getSnapshottableDirListing()
2501      throws IOException {
2502    checkOpen();
2503    try {
2504      return namenode.getSnapshottableDirListing();
2505    } catch(RemoteException re) {
2506      throw re.unwrapRemoteException();
2507    }
2508  }
2509
2510  /**
2511   * Allow snapshot on a directory.
2512   * 
2513   * @see ClientProtocol#allowSnapshot(String snapshotRoot)
2514   */
2515  public void allowSnapshot(String snapshotRoot) throws IOException {
2516    checkOpen();
2517    try {
2518      namenode.allowSnapshot(snapshotRoot);
2519    } catch (RemoteException re) {
2520      throw re.unwrapRemoteException();
2521    }
2522  }
2523  
2524  /**
2525   * Disallow snapshot on a directory.
2526   * 
2527   * @see ClientProtocol#disallowSnapshot(String snapshotRoot)
2528   */
2529  public void disallowSnapshot(String snapshotRoot) throws IOException {
2530    checkOpen();
2531    try {
2532      namenode.disallowSnapshot(snapshotRoot);
2533    } catch (RemoteException re) {
2534      throw re.unwrapRemoteException();
2535    }
2536  }
2537  
2538  /**
2539   * Get the difference between two snapshots, or between a snapshot and the
2540   * current tree of a directory.
2541   * @see ClientProtocol#getSnapshotDiffReport(String, String, String)
2542   */
2543  public SnapshotDiffReport getSnapshotDiffReport(String snapshotDir,
2544      String fromSnapshot, String toSnapshot) throws IOException {
2545    checkOpen();
2546    try {
2547      return namenode.getSnapshotDiffReport(snapshotDir,
2548          fromSnapshot, toSnapshot);
2549    } catch(RemoteException re) {
2550      throw re.unwrapRemoteException();
2551    }
2552  }
2553
2554  public long addCacheDirective(
2555      CacheDirectiveInfo info, EnumSet<CacheFlag> flags) throws IOException {
2556    checkOpen();
2557    try {
2558      return namenode.addCacheDirective(info, flags);
2559    } catch (RemoteException re) {
2560      throw re.unwrapRemoteException();
2561    }
2562  }
2563  
2564  public void modifyCacheDirective(
2565      CacheDirectiveInfo info, EnumSet<CacheFlag> flags) throws IOException {
2566    checkOpen();
2567    try {
2568      namenode.modifyCacheDirective(info, flags);
2569    } catch (RemoteException re) {
2570      throw re.unwrapRemoteException();
2571    }
2572  }
2573
2574  public void removeCacheDirective(long id)
2575      throws IOException {
2576    checkOpen();
2577    try {
2578      namenode.removeCacheDirective(id);
2579    } catch (RemoteException re) {
2580      throw re.unwrapRemoteException();
2581    }
2582  }
2583  
2584  public RemoteIterator<CacheDirectiveEntry> listCacheDirectives(
2585      CacheDirectiveInfo filter) throws IOException {
2586    return new CacheDirectiveIterator(namenode, filter);
2587  }
2588
2589  public void addCachePool(CachePoolInfo info) throws IOException {
2590    checkOpen();
2591    try {
2592      namenode.addCachePool(info);
2593    } catch (RemoteException re) {
2594      throw re.unwrapRemoteException();
2595    }
2596  }
2597
2598  public void modifyCachePool(CachePoolInfo info) throws IOException {
2599    checkOpen();
2600    try {
2601      namenode.modifyCachePool(info);
2602    } catch (RemoteException re) {
2603      throw re.unwrapRemoteException();
2604    }
2605  }
2606
2607  public void removeCachePool(String poolName) throws IOException {
2608    checkOpen();
2609    try {
2610      namenode.removeCachePool(poolName);
2611    } catch (RemoteException re) {
2612      throw re.unwrapRemoteException();
2613    }
2614  }
2615
2616  public RemoteIterator<CachePoolEntry> listCachePools() throws IOException {
2617    return new CachePoolIterator(namenode);
2618  }
2619
2620  /**
2621   * Save namespace image.
2622   * 
2623   * @see ClientProtocol#saveNamespace()
2624   */
2625  void saveNamespace() throws AccessControlException, IOException {
2626    try {
2627      namenode.saveNamespace();
2628    } catch(RemoteException re) {
2629      throw re.unwrapRemoteException(AccessControlException.class);
2630    }
2631  }
2632
2633  /**
2634   * Rolls the edit log on the active NameNode.
2635   * @return the txid of the new log segment 
2636   *
2637   * @see ClientProtocol#rollEdits()
2638   */
2639  long rollEdits() throws AccessControlException, IOException {
2640    try {
2641      return namenode.rollEdits();
2642    } catch(RemoteException re) {
2643      throw re.unwrapRemoteException(AccessControlException.class);
2644    }
2645  }
2646
2647  @VisibleForTesting
2648  ExtendedBlock getPreviousBlock(long fileId) {
2649    return filesBeingWritten.get(fileId).getBlock();
2650  }
2651  
2652  /**
2653   * enable/disable restore failed storage.
2654   * 
2655   * @see ClientProtocol#restoreFailedStorage(String arg)
2656   */
2657  boolean restoreFailedStorage(String arg)
2658      throws AccessControlException, IOException{
2659    return namenode.restoreFailedStorage(arg);
2660  }
2661
2662  /**
2663   * Refresh the hosts and exclude files.  (Rereads them.)
2664   * See {@link ClientProtocol#refreshNodes()} 
2665   * for more details.
2666   * 
2667   * @see ClientProtocol#refreshNodes()
2668   */
2669  public void refreshNodes() throws IOException {
2670    namenode.refreshNodes();
2671  }
2672
2673  /**
2674   * Dumps DFS data structures into specified file.
2675   * 
2676   * @see ClientProtocol#metaSave(String)
2677   */
2678  public void metaSave(String pathname) throws IOException {
2679    namenode.metaSave(pathname);
2680  }
2681
2682  /**
2683   * Requests the namenode to tell all datanodes to use a new, non-persistent
2684   * bandwidth value for dfs.balance.bandwidthPerSec.
2685   * See {@link ClientProtocol#setBalancerBandwidth(long)} 
2686   * for more details.
2687   * 
2688   * @see ClientProtocol#setBalancerBandwidth(long)
2689   */
2690  public void setBalancerBandwidth(long bandwidth) throws IOException {
2691    namenode.setBalancerBandwidth(bandwidth);
2692  }
2693    
2694  /**
2695   * @see ClientProtocol#finalizeUpgrade()
2696   */
2697  public void finalizeUpgrade() throws IOException {
2698    namenode.finalizeUpgrade();
2699  }
2700
2701  RollingUpgradeInfo rollingUpgrade(RollingUpgradeAction action) throws IOException {
2702    return namenode.rollingUpgrade(action);
2703  }
2704
2705  /**
2706   */
2707  @Deprecated
2708  public boolean mkdirs(String src) throws IOException {
2709    return mkdirs(src, null, true);
2710  }
2711
2712  /**
2713   * Create a directory (or hierarchy of directories) with the given
2714   * name and permission.
2715   *
2716   * @param src The path of the directory being created
2717   * @param permission The permission of the directory being created.
2718   * If permission == null, use {@link FsPermission#getDefault()}.
2719   * @param createParent create missing parent directory if true
2720   * 
2721   * @return True if the operation success.
2722   * 
2723   * @see ClientProtocol#mkdirs(String, FsPermission, boolean)
2724   */
2725  public boolean mkdirs(String src, FsPermission permission,
2726      boolean createParent) throws IOException {
2727    if (permission == null) {
2728      permission = FsPermission.getDefault();
2729    }
2730    FsPermission masked = permission.applyUMask(dfsClientConf.uMask);
2731    return primitiveMkdir(src, masked, createParent);
2732  }
2733
2734  /**
2735   * Same {{@link #mkdirs(String, FsPermission, boolean)} except
2736   * that the permissions has already been masked against umask.
2737   */
2738  public boolean primitiveMkdir(String src, FsPermission absPermission)
2739    throws IOException {
2740    return primitiveMkdir(src, absPermission, true);
2741  }
2742
2743  /**
2744   * Same {{@link #mkdirs(String, FsPermission, boolean)} except
2745   * that the permissions has already been masked against umask.
2746   */
2747  public boolean primitiveMkdir(String src, FsPermission absPermission, 
2748    boolean createParent)
2749    throws IOException {
2750    checkOpen();
2751    if (absPermission == null) {
2752      absPermission = 
2753        FsPermission.getDefault().applyUMask(dfsClientConf.uMask);
2754    } 
2755
2756    if(LOG.isDebugEnabled()) {
2757      LOG.debug(src + ": masked=" + absPermission);
2758    }
2759    try {
2760      return namenode.mkdirs(src, absPermission, createParent);
2761    } catch(RemoteException re) {
2762      throw re.unwrapRemoteException(AccessControlException.class,
2763                                     InvalidPathException.class,
2764                                     FileAlreadyExistsException.class,
2765                                     FileNotFoundException.class,
2766                                     ParentNotDirectoryException.class,
2767                                     SafeModeException.class,
2768                                     NSQuotaExceededException.class,
2769                                     DSQuotaExceededException.class,
2770                                     UnresolvedPathException.class,
2771                                     SnapshotAccessControlException.class);
2772    }
2773  }
2774  
2775  /**
2776   * Get {@link ContentSummary} rooted at the specified directory.
2777   * @param path The string representation of the path
2778   * 
2779   * @see ClientProtocol#getContentSummary(String)
2780   */
2781  ContentSummary getContentSummary(String src) throws IOException {
2782    try {
2783      return namenode.getContentSummary(src);
2784    } catch(RemoteException re) {
2785      throw re.unwrapRemoteException(AccessControlException.class,
2786                                     FileNotFoundException.class,
2787                                     UnresolvedPathException.class);
2788    }
2789  }
2790
2791  /**
2792   * Sets or resets quotas for a directory.
2793   * @see ClientProtocol#setQuota(String, long, long)
2794   */
2795  void setQuota(String src, long namespaceQuota, long diskspaceQuota) 
2796      throws IOException {
2797    // sanity check
2798    if ((namespaceQuota <= 0 && namespaceQuota != HdfsConstants.QUOTA_DONT_SET &&
2799         namespaceQuota != HdfsConstants.QUOTA_RESET) ||
2800        (diskspaceQuota <= 0 && diskspaceQuota != HdfsConstants.QUOTA_DONT_SET &&
2801         diskspaceQuota != HdfsConstants.QUOTA_RESET)) {
2802      throw new IllegalArgumentException("Invalid values for quota : " +
2803                                         namespaceQuota + " and " + 
2804                                         diskspaceQuota);
2805                                         
2806    }
2807    try {
2808      namenode.setQuota(src, namespaceQuota, diskspaceQuota);
2809    } catch(RemoteException re) {
2810      throw re.unwrapRemoteException(AccessControlException.class,
2811                                     FileNotFoundException.class,
2812                                     NSQuotaExceededException.class,
2813                                     DSQuotaExceededException.class,
2814                                     UnresolvedPathException.class,
2815                                     SnapshotAccessControlException.class);
2816    }
2817  }
2818
2819  /**
2820   * set the modification and access time of a file
2821   * 
2822   * @see ClientProtocol#setTimes(String, long, long)
2823   */
2824  public void setTimes(String src, long mtime, long atime) throws IOException {
2825    checkOpen();
2826    try {
2827      namenode.setTimes(src, mtime, atime);
2828    } catch(RemoteException re) {
2829      throw re.unwrapRemoteException(AccessControlException.class,
2830                                     FileNotFoundException.class,
2831                                     UnresolvedPathException.class,
2832                                     SnapshotAccessControlException.class);
2833    }
2834  }
2835
2836  /**
2837   * @deprecated use {@link HdfsDataInputStream} instead.
2838   */
2839  @Deprecated
2840  public static class DFSDataInputStream extends HdfsDataInputStream {
2841
2842    public DFSDataInputStream(DFSInputStream in) throws IOException {
2843      super(in);
2844    }
2845  }
2846
2847  void reportChecksumFailure(String file, ExtendedBlock blk, DatanodeInfo dn) {
2848    DatanodeInfo [] dnArr = { dn };
2849    LocatedBlock [] lblocks = { new LocatedBlock(blk, dnArr) };
2850    reportChecksumFailure(file, lblocks);
2851  }
2852    
2853  // just reports checksum failure and ignores any exception during the report.
2854  void reportChecksumFailure(String file, LocatedBlock lblocks[]) {
2855    try {
2856      reportBadBlocks(lblocks);
2857    } catch (IOException ie) {
2858      LOG.info("Found corruption while reading " + file
2859          + ". Error repairing corrupt blocks. Bad blocks remain.", ie);
2860    }
2861  }
2862
2863  @Override
2864  public String toString() {
2865    return getClass().getSimpleName() + "[clientName=" + clientName
2866        + ", ugi=" + ugi + "]"; 
2867  }
2868
2869  public CachingStrategy getDefaultReadCachingStrategy() {
2870    return defaultReadCachingStrategy;
2871  }
2872
2873  public CachingStrategy getDefaultWriteCachingStrategy() {
2874    return defaultWriteCachingStrategy;
2875  }
2876
2877  public ClientContext getClientContext() {
2878    return clientContext;
2879  }
2880
2881  public void modifyAclEntries(String src, List<AclEntry> aclSpec)
2882      throws IOException {
2883    checkOpen();
2884    try {
2885      namenode.modifyAclEntries(src, aclSpec);
2886    } catch(RemoteException re) {
2887      throw re.unwrapRemoteException(AccessControlException.class,
2888                                     AclException.class,
2889                                     FileNotFoundException.class,
2890                                     NSQuotaExceededException.class,
2891                                     SafeModeException.class,
2892                                     SnapshotAccessControlException.class,
2893                                     UnresolvedPathException.class);
2894    }
2895  }
2896
2897  public void removeAclEntries(String src, List<AclEntry> aclSpec)
2898      throws IOException {
2899    checkOpen();
2900    try {
2901      namenode.removeAclEntries(src, aclSpec);
2902    } catch(RemoteException re) {
2903      throw re.unwrapRemoteException(AccessControlException.class,
2904                                     AclException.class,
2905                                     FileNotFoundException.class,
2906                                     NSQuotaExceededException.class,
2907                                     SafeModeException.class,
2908                                     SnapshotAccessControlException.class,
2909                                     UnresolvedPathException.class);
2910    }
2911  }
2912
2913  public void removeDefaultAcl(String src) throws IOException {
2914    checkOpen();
2915    try {
2916      namenode.removeDefaultAcl(src);
2917    } catch(RemoteException re) {
2918      throw re.unwrapRemoteException(AccessControlException.class,
2919                                     AclException.class,
2920                                     FileNotFoundException.class,
2921                                     NSQuotaExceededException.class,
2922                                     SafeModeException.class,
2923                                     SnapshotAccessControlException.class,
2924                                     UnresolvedPathException.class);
2925    }
2926  }
2927
2928  public void removeAcl(String src) throws IOException {
2929    checkOpen();
2930    try {
2931      namenode.removeAcl(src);
2932    } catch(RemoteException re) {
2933      throw re.unwrapRemoteException(AccessControlException.class,
2934                                     AclException.class,
2935                                     FileNotFoundException.class,
2936                                     NSQuotaExceededException.class,
2937                                     SafeModeException.class,
2938                                     SnapshotAccessControlException.class,
2939                                     UnresolvedPathException.class);
2940    }
2941  }
2942
2943  public void setAcl(String src, List<AclEntry> aclSpec) throws IOException {
2944    checkOpen();
2945    try {
2946      namenode.setAcl(src, aclSpec);
2947    } catch(RemoteException re) {
2948      throw re.unwrapRemoteException(AccessControlException.class,
2949                                     AclException.class,
2950                                     FileNotFoundException.class,
2951                                     NSQuotaExceededException.class,
2952                                     SafeModeException.class,
2953                                     SnapshotAccessControlException.class,
2954                                     UnresolvedPathException.class);
2955    }
2956  }
2957
2958  public AclStatus getAclStatus(String src) throws IOException {
2959    checkOpen();
2960    try {
2961      return namenode.getAclStatus(src);
2962    } catch(RemoteException re) {
2963      throw re.unwrapRemoteException(AccessControlException.class,
2964                                     AclException.class,
2965                                     FileNotFoundException.class,
2966                                     UnresolvedPathException.class);
2967    }
2968  }
2969  
2970  public void createEncryptionZone(String src, String keyName)
2971    throws IOException {
2972    checkOpen();
2973    try {
2974      namenode.createEncryptionZone(src, keyName);
2975    } catch (RemoteException re) {
2976      throw re.unwrapRemoteException(AccessControlException.class,
2977                                     SafeModeException.class,
2978                                     UnresolvedPathException.class);
2979    }
2980  }
2981
2982  public EncryptionZone getEZForPath(String src)
2983          throws IOException {
2984    checkOpen();
2985    try {
2986      return namenode.getEZForPath(src);
2987    } catch (RemoteException re) {
2988      throw re.unwrapRemoteException(AccessControlException.class,
2989                                     UnresolvedPathException.class);
2990    }
2991  }
2992
2993  public RemoteIterator<EncryptionZone> listEncryptionZones()
2994      throws IOException {
2995    checkOpen();
2996    return new EncryptionZoneIterator(namenode);
2997  }
2998
2999  public void setXAttr(String src, String name, byte[] value, 
3000      EnumSet<XAttrSetFlag> flag) throws IOException {
3001    checkOpen();
3002    try {
3003      namenode.setXAttr(src, XAttrHelper.buildXAttr(name, value), flag);
3004    } catch (RemoteException re) {
3005      throw re.unwrapRemoteException(AccessControlException.class,
3006                                     FileNotFoundException.class,
3007                                     NSQuotaExceededException.class,
3008                                     SafeModeException.class,
3009                                     SnapshotAccessControlException.class,
3010                                     UnresolvedPathException.class);
3011    }
3012  }
3013  
3014  public byte[] getXAttr(String src, String name) throws IOException {
3015    checkOpen();
3016    try {
3017      final List<XAttr> xAttrs = XAttrHelper.buildXAttrAsList(name);
3018      final List<XAttr> result = namenode.getXAttrs(src, xAttrs);
3019      return XAttrHelper.getFirstXAttrValue(result);
3020    } catch(RemoteException re) {
3021      throw re.unwrapRemoteException(AccessControlException.class,
3022                                     FileNotFoundException.class,
3023                                     UnresolvedPathException.class);
3024    }
3025  }
3026  
3027  public Map<String, byte[]> getXAttrs(String src) throws IOException {
3028    checkOpen();
3029    try {
3030      return XAttrHelper.buildXAttrMap(namenode.getXAttrs(src, null));
3031    } catch(RemoteException re) {
3032      throw re.unwrapRemoteException(AccessControlException.class,
3033                                     FileNotFoundException.class,
3034                                     UnresolvedPathException.class);
3035    }
3036  }
3037  
3038  public Map<String, byte[]> getXAttrs(String src, List<String> names) 
3039      throws IOException {
3040    checkOpen();
3041    try {
3042      return XAttrHelper.buildXAttrMap(namenode.getXAttrs(
3043          src, XAttrHelper.buildXAttrs(names)));
3044    } catch(RemoteException re) {
3045      throw re.unwrapRemoteException(AccessControlException.class,
3046                                     FileNotFoundException.class,
3047                                     UnresolvedPathException.class);
3048    }
3049  }
3050  
3051  public List<String> listXAttrs(String src)
3052          throws IOException {
3053    checkOpen();
3054    try {
3055      final Map<String, byte[]> xattrs =
3056        XAttrHelper.buildXAttrMap(namenode.listXAttrs(src));
3057      return Lists.newArrayList(xattrs.keySet());
3058    } catch(RemoteException re) {
3059      throw re.unwrapRemoteException(AccessControlException.class,
3060                                     FileNotFoundException.class,
3061                                     UnresolvedPathException.class);
3062    }
3063  }
3064
3065  public void removeXAttr(String src, String name) throws IOException {
3066    checkOpen();
3067    try {
3068      namenode.removeXAttr(src, XAttrHelper.buildXAttr(name));
3069    } catch(RemoteException re) {
3070      throw re.unwrapRemoteException(AccessControlException.class,
3071                                     FileNotFoundException.class,
3072                                     NSQuotaExceededException.class,
3073                                     SafeModeException.class,
3074                                     SnapshotAccessControlException.class,
3075                                     UnresolvedPathException.class);
3076    }
3077  }
3078
3079  public void checkAccess(String src, FsAction mode) throws IOException {
3080    checkOpen();
3081    try {
3082      namenode.checkAccess(src, mode);
3083    } catch (RemoteException re) {
3084      throw re.unwrapRemoteException(AccessControlException.class,
3085          FileNotFoundException.class,
3086          UnresolvedPathException.class);
3087    }
3088  }
3089
3090  public DFSInotifyEventInputStream getInotifyEventStream() throws IOException {
3091    return new DFSInotifyEventInputStream(namenode);
3092  }
3093
3094  public DFSInotifyEventInputStream getInotifyEventStream(long lastReadTxid)
3095      throws IOException {
3096    return new DFSInotifyEventInputStream(namenode, lastReadTxid);
3097  }
3098
3099  @Override // RemotePeerFactory
3100  public Peer newConnectedPeer(InetSocketAddress addr,
3101      Token<BlockTokenIdentifier> blockToken, DatanodeID datanodeId)
3102      throws IOException {
3103    Peer peer = null;
3104    boolean success = false;
3105    Socket sock = null;
3106    try {
3107      sock = socketFactory.createSocket();
3108      NetUtils.connect(sock, addr,
3109        getRandomLocalInterfaceAddr(),
3110        dfsClientConf.socketTimeout);
3111      peer = TcpPeerServer.peerFromSocketAndKey(saslClient, sock, this,
3112          blockToken, datanodeId);
3113      peer.setReadTimeout(dfsClientConf.socketTimeout);
3114      success = true;
3115      return peer;
3116    } finally {
3117      if (!success) {
3118        IOUtils.cleanup(LOG, peer);
3119        IOUtils.closeSocket(sock);
3120      }
3121    }
3122  }
3123
3124  /**
3125   * Create hedged reads thread pool, HEDGED_READ_THREAD_POOL, if
3126   * it does not already exist.
3127   * @param num Number of threads for hedged reads thread pool.
3128   * If zero, skip hedged reads thread pool creation.
3129   */
3130  private synchronized void initThreadsNumForHedgedReads(int num) {
3131    if (num <= 0 || HEDGED_READ_THREAD_POOL != null) return;
3132    HEDGED_READ_THREAD_POOL = new ThreadPoolExecutor(1, num, 60,
3133        TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
3134        new Daemon.DaemonFactory() {
3135          private final AtomicInteger threadIndex =
3136            new AtomicInteger(0); 
3137          @Override
3138          public Thread newThread(Runnable r) {
3139            Thread t = super.newThread(r);
3140            t.setName("hedgedRead-" +
3141              threadIndex.getAndIncrement());
3142            return t;
3143          }
3144        },
3145        new ThreadPoolExecutor.CallerRunsPolicy() {
3146
3147      @Override
3148      public void rejectedExecution(Runnable runnable,
3149          ThreadPoolExecutor e) {
3150        LOG.info("Execution rejected, Executing in current thread");
3151        HEDGED_READ_METRIC.incHedgedReadOpsInCurThread();
3152        // will run in the current thread
3153        super.rejectedExecution(runnable, e);
3154      }
3155    });
3156    HEDGED_READ_THREAD_POOL.allowCoreThreadTimeOut(true);
3157    if (LOG.isDebugEnabled()) {
3158      LOG.debug("Using hedged reads; pool threads=" + num);
3159    }
3160  }
3161
3162  long getHedgedReadTimeout() {
3163    return this.hedgedReadThresholdMillis;
3164  }
3165
3166  @VisibleForTesting
3167  void setHedgedReadTimeout(long timeoutMillis) {
3168    this.hedgedReadThresholdMillis = timeoutMillis;
3169  }
3170
3171  ThreadPoolExecutor getHedgedReadsThreadPool() {
3172    return HEDGED_READ_THREAD_POOL;
3173  }
3174
3175  boolean isHedgedReadsEnabled() {
3176    return (HEDGED_READ_THREAD_POOL != null) &&
3177      HEDGED_READ_THREAD_POOL.getMaximumPoolSize() > 0;
3178  }
3179
3180  DFSHedgedReadMetrics getHedgedReadMetrics() {
3181    return HEDGED_READ_METRIC;
3182  }
3183
3184  public KeyProvider getKeyProvider() {
3185    return clientContext.getKeyProviderCache().get(conf);
3186  }
3187
3188  @VisibleForTesting
3189  public void setKeyProvider(KeyProvider provider) {
3190    try {
3191      clientContext.getKeyProviderCache().setKeyProvider(conf, provider);
3192    } catch (IOException e) {
3193     LOG.error("Could not set KeyProvider !!", e);
3194    }
3195  }
3196
3197  public boolean isHDFSEncryptionEnabled() {
3198    return conf.get(
3199        DFSConfigKeys.DFS_ENCRYPTION_KEY_PROVIDER_URI, null) != null;
3200  }
3201  /**
3202   * Returns the SaslDataTransferClient configured for this DFSClient.
3203   *
3204   * @return SaslDataTransferClient configured for this DFSClient
3205   */
3206  public SaslDataTransferClient getSaslDataTransferClient() {
3207    return saslClient;
3208  }
3209}