001/**
002res * 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 */
018
019package org.apache.hadoop.hdfs.web;
020
021import java.io.BufferedOutputStream;
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.InputStreamReader;
026import java.net.HttpURLConnection;
027import java.net.InetSocketAddress;
028import java.net.MalformedURLException;
029import java.net.URI;
030import java.net.URL;
031import java.security.PrivilegedExceptionAction;
032import java.util.ArrayList;
033import java.util.EnumSet;
034import java.util.List;
035import java.util.Map;
036import java.util.StringTokenizer;
037
038import javax.ws.rs.core.MediaType;
039
040import org.apache.commons.logging.Log;
041import org.apache.commons.logging.LogFactory;
042import org.apache.hadoop.conf.Configuration;
043import org.apache.hadoop.fs.BlockLocation;
044import org.apache.hadoop.fs.CommonConfigurationKeys;
045import org.apache.hadoop.fs.ContentSummary;
046import org.apache.hadoop.fs.DelegationTokenRenewer;
047import org.apache.hadoop.fs.FSDataInputStream;
048import org.apache.hadoop.fs.FSDataOutputStream;
049import org.apache.hadoop.fs.FileStatus;
050import org.apache.hadoop.fs.FileSystem;
051import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum;
052import org.apache.hadoop.fs.Options;
053import org.apache.hadoop.fs.Path;
054import org.apache.hadoop.fs.XAttrCodec;
055import org.apache.hadoop.fs.XAttrSetFlag;
056import org.apache.hadoop.fs.permission.AclEntry;
057import org.apache.hadoop.fs.permission.AclStatus;
058import org.apache.hadoop.fs.permission.FsAction;
059import org.apache.hadoop.fs.permission.FsPermission;
060import org.apache.hadoop.hdfs.DFSConfigKeys;
061import org.apache.hadoop.hdfs.DFSUtil;
062import org.apache.hadoop.hdfs.HAUtil;
063import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
064import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
065import org.apache.hadoop.hdfs.server.namenode.SafeModeException;
066import org.apache.hadoop.hdfs.web.resources.*;
067import org.apache.hadoop.hdfs.web.resources.HttpOpParam.Op;
068import org.apache.hadoop.io.Text;
069import org.apache.hadoop.io.retry.RetryPolicies;
070import org.apache.hadoop.io.retry.RetryPolicy;
071import org.apache.hadoop.io.retry.RetryUtils;
072import org.apache.hadoop.ipc.RemoteException;
073import org.apache.hadoop.net.NetUtils;
074import org.apache.hadoop.security.AccessControlException;
075import org.apache.hadoop.security.SecurityUtil;
076import org.apache.hadoop.security.UserGroupInformation;
077import org.apache.hadoop.security.token.SecretManager.InvalidToken;
078import org.apache.hadoop.security.token.Token;
079import org.apache.hadoop.security.token.TokenIdentifier;
080import org.apache.hadoop.security.token.TokenSelector;
081import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSelector;
082import org.apache.hadoop.util.Progressable;
083import org.mortbay.util.ajax.JSON;
084
085import com.google.common.annotations.VisibleForTesting;
086import com.google.common.base.Charsets;
087import com.google.common.base.Preconditions;
088import com.google.common.collect.Lists;
089
090/** A FileSystem for HDFS over the web. */
091public class WebHdfsFileSystem extends FileSystem
092    implements DelegationTokenRenewer.Renewable, TokenAspect.TokenManagementDelegator {
093  public static final Log LOG = LogFactory.getLog(WebHdfsFileSystem.class);
094  /** File System URI: {SCHEME}://namenode:port/path/to/file */
095  public static final String SCHEME = "webhdfs";
096  /** WebHdfs version. */
097  public static final int VERSION = 1;
098  /** Http URI: http://namenode:port/{PATH_PREFIX}/path/to/file */
099  public static final String PATH_PREFIX = "/" + SCHEME + "/v" + VERSION;
100
101  /** Default connection factory may be overridden in tests to use smaller timeout values */
102  protected URLConnectionFactory connectionFactory;
103
104  /** Delegation token kind */
105  public static final Text TOKEN_KIND = new Text("WEBHDFS delegation");
106
107  @VisibleForTesting
108  public static final String CANT_FALLBACK_TO_INSECURE_MSG =
109      "The client is configured to only allow connecting to secure cluster";
110
111  private boolean canRefreshDelegationToken;
112
113  private UserGroupInformation ugi;
114  private URI uri;
115  private Token<?> delegationToken;
116  protected Text tokenServiceName;
117  private RetryPolicy retryPolicy = null;
118  private Path workingDir;
119  private InetSocketAddress nnAddrs[];
120  private int currentNNAddrIndex;
121  private boolean disallowFallbackToInsecureCluster;
122
123  /**
124   * Return the protocol scheme for the FileSystem.
125   * <p/>
126   *
127   * @return <code>webhdfs</code>
128   */
129  @Override
130  public String getScheme() {
131    return SCHEME;
132  }
133
134  /**
135   * return the underlying transport protocol (http / https).
136   */
137  protected String getTransportScheme() {
138    return "http";
139  }
140
141  protected Text getTokenKind() {
142    return TOKEN_KIND;
143  }
144
145  @Override
146  public synchronized void initialize(URI uri, Configuration conf
147      ) throws IOException {
148    super.initialize(uri, conf);
149    setConf(conf);
150    /** set user pattern based on configuration file */
151    UserParam.setUserPattern(conf.get(
152        DFSConfigKeys.DFS_WEBHDFS_USER_PATTERN_KEY,
153        DFSConfigKeys.DFS_WEBHDFS_USER_PATTERN_DEFAULT));
154
155    connectionFactory = URLConnectionFactory
156        .newDefaultURLConnectionFactory(conf);
157
158    ugi = UserGroupInformation.getCurrentUser();
159    this.uri = URI.create(uri.getScheme() + "://" + uri.getAuthority());
160    this.nnAddrs = resolveNNAddr();
161
162    boolean isHA = HAUtil.isClientFailoverConfigured(conf, this.uri);
163    boolean isLogicalUri = isHA && HAUtil.isLogicalUri(conf, this.uri);
164    // In non-HA or non-logical URI case, the code needs to call
165    // getCanonicalUri() in order to handle the case where no port is
166    // specified in the URI
167    this.tokenServiceName = isLogicalUri ?
168        HAUtil.buildTokenServiceForLogicalUri(uri, getScheme())
169        : SecurityUtil.buildTokenService(getCanonicalUri());
170
171    if (!isHA) {
172      this.retryPolicy =
173          RetryUtils.getDefaultRetryPolicy(
174              conf,
175              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_ENABLED_KEY,
176              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_ENABLED_DEFAULT,
177              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_SPEC_KEY,
178              DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_POLICY_SPEC_DEFAULT,
179              SafeModeException.class);
180    } else {
181
182      int maxFailoverAttempts = conf.getInt(
183          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_MAX_ATTEMPTS_KEY,
184          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_MAX_ATTEMPTS_DEFAULT);
185      int maxRetryAttempts = conf.getInt(
186          DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_MAX_ATTEMPTS_KEY,
187          DFSConfigKeys.DFS_HTTP_CLIENT_RETRY_MAX_ATTEMPTS_DEFAULT);
188      int failoverSleepBaseMillis = conf.getInt(
189          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_BASE_KEY,
190          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_BASE_DEFAULT);
191      int failoverSleepMaxMillis = conf.getInt(
192          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_MAX_KEY,
193          DFSConfigKeys.DFS_HTTP_CLIENT_FAILOVER_SLEEPTIME_MAX_DEFAULT);
194
195      this.retryPolicy = RetryPolicies
196          .failoverOnNetworkException(RetryPolicies.TRY_ONCE_THEN_FAIL,
197              maxFailoverAttempts, maxRetryAttempts, failoverSleepBaseMillis,
198              failoverSleepMaxMillis);
199    }
200
201    this.workingDir = getHomeDirectory();
202    this.canRefreshDelegationToken = UserGroupInformation.isSecurityEnabled();
203    this.disallowFallbackToInsecureCluster = !conf.getBoolean(
204        CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_KEY,
205        CommonConfigurationKeys.IPC_CLIENT_FALLBACK_TO_SIMPLE_AUTH_ALLOWED_DEFAULT);
206    this.delegationToken = null;
207  }
208
209  @Override
210  public URI getCanonicalUri() {
211    return super.getCanonicalUri();
212  }
213
214  /** Is WebHDFS enabled in conf? */
215  public static boolean isEnabled(final Configuration conf, final Log log) {
216    final boolean b = conf.getBoolean(DFSConfigKeys.DFS_WEBHDFS_ENABLED_KEY,
217        DFSConfigKeys.DFS_WEBHDFS_ENABLED_DEFAULT);
218    return b;
219  }
220
221  TokenSelector<DelegationTokenIdentifier> tokenSelector =
222      new AbstractDelegationTokenSelector<DelegationTokenIdentifier>(getTokenKind()){};
223
224  // the first getAuthParams() for a non-token op will either get the
225  // internal token from the ugi or lazy fetch one
226  protected synchronized Token<?> getDelegationToken() throws IOException {
227    if (canRefreshDelegationToken && delegationToken == null) {
228      Token<?> token = tokenSelector.selectToken(
229          new Text(getCanonicalServiceName()), ugi.getTokens());
230      // ugi tokens are usually indicative of a task which can't
231      // refetch tokens.  even if ugi has credentials, don't attempt
232      // to get another token to match hdfs/rpc behavior
233      if (token != null) {
234        if(LOG.isDebugEnabled()) {
235          LOG.debug("Using UGI token: " + token);
236        }
237        canRefreshDelegationToken = false; 
238      } else {
239        token = getDelegationToken(null);
240        if (token != null) {
241          if(LOG.isDebugEnabled()) {
242            LOG.debug("Fetched new token: " + token);
243          }
244        } else { // security is disabled
245          canRefreshDelegationToken = false;
246        }
247      }
248      setDelegationToken(token);
249    }
250    return delegationToken;
251  }
252
253  @VisibleForTesting
254  synchronized boolean replaceExpiredDelegationToken() throws IOException {
255    boolean replaced = false;
256    if (canRefreshDelegationToken) {
257      Token<?> token = getDelegationToken(null);
258      if(LOG.isDebugEnabled()) {
259        LOG.debug("Replaced expired token: " + token);
260      }
261      setDelegationToken(token);
262      replaced = (token != null);
263    }
264    return replaced;
265  }
266
267  @Override
268  @VisibleForTesting
269  public int getDefaultPort() {
270    return getConf().getInt(DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_KEY,
271        DFSConfigKeys.DFS_NAMENODE_HTTP_PORT_DEFAULT);
272  }
273
274  @Override
275  public URI getUri() {
276    return this.uri;
277  }
278  
279  @Override
280  protected URI canonicalizeUri(URI uri) {
281    return NetUtils.getCanonicalUri(uri, getDefaultPort());
282  }
283
284  /** @return the home directory. */
285  public static String getHomeDirectoryString(final UserGroupInformation ugi) {
286    return "/user/" + ugi.getShortUserName();
287  }
288
289  @Override
290  public Path getHomeDirectory() {
291    return makeQualified(new Path(getHomeDirectoryString(ugi)));
292  }
293
294  @Override
295  public synchronized Path getWorkingDirectory() {
296    return workingDir;
297  }
298
299  @Override
300  public synchronized void setWorkingDirectory(final Path dir) {
301    String result = makeAbsolute(dir).toUri().getPath();
302    if (!DFSUtil.isValidName(result)) {
303      throw new IllegalArgumentException("Invalid DFS directory name " + 
304                                         result);
305    }
306    workingDir = makeAbsolute(dir);
307  }
308
309  private Path makeAbsolute(Path f) {
310    return f.isAbsolute()? f: new Path(workingDir, f);
311  }
312
313  static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
314      ) throws IOException {
315    if (c.getContentLength() == 0) {
316      return null;
317    }
318    final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
319    if (in == null) {
320      throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
321    }
322    final String contentType = c.getContentType();
323    if (contentType != null) {
324      final MediaType parsed = MediaType.valueOf(contentType);
325      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
326        throw new IOException("Content-Type \"" + contentType
327            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
328            + "\" (parsed=\"" + parsed + "\")");
329      }
330    }
331    return (Map<?, ?>)JSON.parse(new InputStreamReader(in, Charsets.UTF_8));
332  }
333
334  private static Map<?, ?> validateResponse(final HttpOpParam.Op op,
335      final HttpURLConnection conn, boolean unwrapException) throws IOException {
336    final int code = conn.getResponseCode();
337    // server is demanding an authentication we don't support
338    if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
339      // match hdfs/rpc exception
340      throw new AccessControlException(conn.getResponseMessage());
341    }
342    if (code != op.getExpectedHttpResponseCode()) {
343      final Map<?, ?> m;
344      try {
345        m = jsonParse(conn, true);
346      } catch(Exception e) {
347        throw new IOException("Unexpected HTTP response: code=" + code + " != "
348            + op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
349            + ", message=" + conn.getResponseMessage(), e);
350      }
351
352      if (m == null) {
353        throw new IOException("Unexpected HTTP response: code=" + code + " != "
354            + op.getExpectedHttpResponseCode() + ", " + op.toQueryString()
355            + ", message=" + conn.getResponseMessage());
356      } else if (m.get(RemoteException.class.getSimpleName()) == null) {
357        return m;
358      }
359
360      IOException re = JsonUtil.toRemoteException(m);
361      // extract UGI-related exceptions and unwrap InvalidToken
362      // the NN mangles these exceptions but the DN does not and may need
363      // to re-fetch a token if either report the token is expired
364      if (re.getMessage() != null && re.getMessage().startsWith("Failed to obtain user group information:")) {
365        String[] parts = re.getMessage().split(":\\s+", 3);
366        re = new RemoteException(parts[1], parts[2]);
367        re = ((RemoteException)re).unwrapRemoteException(InvalidToken.class);
368      }
369      throw unwrapException? toIOException(re): re;
370    }
371    return null;
372  }
373
374  /**
375   * Covert an exception to an IOException.
376   * 
377   * For a non-IOException, wrap it with IOException.
378   * For a RemoteException, unwrap it.
379   * For an IOException which is not a RemoteException, return it. 
380   */
381  private static IOException toIOException(Exception e) {
382    if (!(e instanceof IOException)) {
383      return new IOException(e);
384    }
385
386    final IOException ioe = (IOException)e;
387    if (!(ioe instanceof RemoteException)) {
388      return ioe;
389    }
390
391    return ((RemoteException)ioe).unwrapRemoteException();
392  }
393
394  private synchronized InetSocketAddress getCurrentNNAddr() {
395    return nnAddrs[currentNNAddrIndex];
396  }
397
398  /**
399   * Reset the appropriate state to gracefully fail over to another name node
400   */
401  private synchronized void resetStateToFailOver() {
402    currentNNAddrIndex = (currentNNAddrIndex + 1) % nnAddrs.length;
403  }
404
405  /**
406   * Return a URL pointing to given path on the namenode.
407   *
408   * @param path to obtain the URL for
409   * @param query string to append to the path
410   * @return namenode URL referring to the given path
411   * @throws IOException on error constructing the URL
412   */
413  private URL getNamenodeURL(String path, String query) throws IOException {
414    InetSocketAddress nnAddr = getCurrentNNAddr();
415    final URL url = new URL(getTransportScheme(), nnAddr.getHostName(),
416          nnAddr.getPort(), path + '?' + query);
417    if (LOG.isTraceEnabled()) {
418      LOG.trace("url=" + url);
419    }
420    return url;
421  }
422  
423  Param<?,?>[] getAuthParameters(final HttpOpParam.Op op) throws IOException {
424    List<Param<?,?>> authParams = Lists.newArrayList();    
425    // Skip adding delegation token for token operations because these
426    // operations require authentication.
427    Token<?> token = null;
428    if (!op.getRequireAuth()) {
429      token = getDelegationToken();
430    }
431    if (token != null) {
432      authParams.add(new DelegationParam(token.encodeToUrlString()));
433    } else {
434      UserGroupInformation userUgi = ugi;
435      UserGroupInformation realUgi = userUgi.getRealUser();
436      if (realUgi != null) { // proxy user
437        authParams.add(new DoAsParam(userUgi.getShortUserName()));
438        userUgi = realUgi;
439      }
440      authParams.add(new UserParam(userUgi.getShortUserName()));
441    }
442    return authParams.toArray(new Param<?,?>[0]);
443  }
444
445  URL toUrl(final HttpOpParam.Op op, final Path fspath,
446      final Param<?,?>... parameters) throws IOException {
447    //initialize URI path and query
448    final String path = PATH_PREFIX
449        + (fspath == null? "/": makeQualified(fspath).toUri().getRawPath());
450    final String query = op.toQueryString()
451        + Param.toSortedString("&", getAuthParameters(op))
452        + Param.toSortedString("&", parameters);
453    final URL url = getNamenodeURL(path, query);
454    if (LOG.isTraceEnabled()) {
455      LOG.trace("url=" + url);
456    }
457    return url;
458  }
459
460  /**
461   * This class is for initialing a HTTP connection, connecting to server,
462   * obtaining a response, and also handling retry on failures.
463   */
464  abstract class AbstractRunner<T> {
465    abstract protected URL getUrl() throws IOException;
466
467    protected final HttpOpParam.Op op;
468    private final boolean redirected;
469    protected ExcludeDatanodesParam excludeDatanodes = new ExcludeDatanodesParam("");
470
471    private boolean checkRetry;
472
473    protected AbstractRunner(final HttpOpParam.Op op, boolean redirected) {
474      this.op = op;
475      this.redirected = redirected;
476    }
477
478    T run() throws IOException {
479      UserGroupInformation connectUgi = ugi.getRealUser();
480      if (connectUgi == null) {
481        connectUgi = ugi;
482      }
483      if (op.getRequireAuth()) {
484        connectUgi.checkTGTAndReloginFromKeytab();
485      }
486      try {
487        // the entire lifecycle of the connection must be run inside the
488        // doAs to ensure authentication is performed correctly
489        return connectUgi.doAs(
490            new PrivilegedExceptionAction<T>() {
491              @Override
492              public T run() throws IOException {
493                return runWithRetry();
494              }
495            });
496      } catch (InterruptedException e) {
497        throw new IOException(e);
498      }
499    }
500
501    /**
502     * Two-step requests redirected to a DN
503     * 
504     * Create/Append:
505     * Step 1) Submit a Http request with neither auto-redirect nor data. 
506     * Step 2) Submit another Http request with the URL from the Location header with data.
507     * 
508     * The reason of having two-step create/append is for preventing clients to
509     * send out the data before the redirect. This issue is addressed by the
510     * "Expect: 100-continue" header in HTTP/1.1; see RFC 2616, Section 8.2.3.
511     * Unfortunately, there are software library bugs (e.g. Jetty 6 http server
512     * and Java 6 http client), which do not correctly implement "Expect:
513     * 100-continue". The two-step create/append is a temporary workaround for
514     * the software library bugs.
515     * 
516     * Open/Checksum
517     * Also implements two-step connects for other operations redirected to
518     * a DN such as open and checksum
519     */
520    private HttpURLConnection connect(URL url) throws IOException {
521      //redirect hostname and port
522      String redirectHost = null;
523
524      
525      // resolve redirects for a DN operation unless already resolved
526      if (op.getRedirect() && !redirected) {
527        final HttpOpParam.Op redirectOp =
528            HttpOpParam.TemporaryRedirectOp.valueOf(op);
529        final HttpURLConnection conn = connect(redirectOp, url);
530        // application level proxy like httpfs might not issue a redirect
531        if (conn.getResponseCode() == op.getExpectedHttpResponseCode()) {
532          return conn;
533        }
534        try {
535          validateResponse(redirectOp, conn, false);
536          url = new URL(conn.getHeaderField("Location"));
537          redirectHost = url.getHost() + ":" + url.getPort();
538        } finally {
539          conn.disconnect();
540        }
541      }
542      try {
543        return connect(op, url);
544      } catch (IOException ioe) {
545        if (redirectHost != null) {
546          if (excludeDatanodes.getValue() != null) {
547            excludeDatanodes = new ExcludeDatanodesParam(redirectHost + ","
548                + excludeDatanodes.getValue());
549          } else {
550            excludeDatanodes = new ExcludeDatanodesParam(redirectHost);
551          }
552        }
553        throw ioe;
554      }      
555    }
556
557    private HttpURLConnection connect(final HttpOpParam.Op op, final URL url)
558        throws IOException {
559      final HttpURLConnection conn =
560          (HttpURLConnection)connectionFactory.openConnection(url);
561      final boolean doOutput = op.getDoOutput();
562      conn.setRequestMethod(op.getType().toString());
563      conn.setInstanceFollowRedirects(false);
564      switch (op.getType()) {
565        // if not sending a message body for a POST or PUT operation, need
566        // to ensure the server/proxy knows this 
567        case POST:
568        case PUT: {
569          conn.setDoOutput(true);
570          if (!doOutput) {
571            // explicitly setting content-length to 0 won't do spnego!!
572            // opening and closing the stream will send "Content-Length: 0"
573            conn.getOutputStream().close();
574          } else {
575            conn.setRequestProperty("Content-Type",
576                MediaType.APPLICATION_OCTET_STREAM);
577            conn.setChunkedStreamingMode(32 << 10); //32kB-chunk
578          }
579          break;
580        }
581        default: {
582          conn.setDoOutput(doOutput);
583          break;
584        }
585      }
586      conn.connect();
587      return conn;
588    }
589
590    private T runWithRetry() throws IOException {
591      /**
592       * Do the real work.
593       *
594       * There are three cases that the code inside the loop can throw an
595       * IOException:
596       *
597       * <ul>
598       * <li>The connection has failed (e.g., ConnectException,
599       * @see FailoverOnNetworkExceptionRetry for more details)</li>
600       * <li>The namenode enters the standby state (i.e., StandbyException).</li>
601       * <li>The server returns errors for the command (i.e., RemoteException)</li>
602       * </ul>
603       *
604       * The call to shouldRetry() will conduct the retry policy. The policy
605       * examines the exception and swallows it if it decides to rerun the work.
606       */
607      for(int retry = 0; ; retry++) {
608        checkRetry = !redirected;
609        final URL url = getUrl();
610        try {
611          final HttpURLConnection conn = connect(url);
612          // output streams will validate on close
613          if (!op.getDoOutput()) {
614            validateResponse(op, conn, false);
615          }
616          return getResponse(conn);
617        } catch (AccessControlException ace) {
618          // no retries for auth failures
619          throw ace;
620        } catch (InvalidToken it) {
621          // try to replace the expired token with a new one.  the attempt
622          // to acquire a new token must be outside this operation's retry
623          // so if it fails after its own retries, this operation fails too.
624          if (op.getRequireAuth() || !replaceExpiredDelegationToken()) {
625            throw it;
626          }
627        } catch (IOException ioe) {
628          shouldRetry(ioe, retry);
629        }
630      }
631    }
632
633    private void shouldRetry(final IOException ioe, final int retry
634        ) throws IOException {
635      InetSocketAddress nnAddr = getCurrentNNAddr();
636      if (checkRetry) {
637        try {
638          final RetryPolicy.RetryAction a = retryPolicy.shouldRetry(
639              ioe, retry, 0, true);
640
641          boolean isRetry = a.action == RetryPolicy.RetryAction.RetryDecision.RETRY;
642          boolean isFailoverAndRetry =
643              a.action == RetryPolicy.RetryAction.RetryDecision.FAILOVER_AND_RETRY;
644
645          if (isRetry || isFailoverAndRetry) {
646            LOG.info("Retrying connect to namenode: " + nnAddr
647                + ". Already tried " + retry + " time(s); retry policy is "
648                + retryPolicy + ", delay " + a.delayMillis + "ms.");
649
650            if (isFailoverAndRetry) {
651              resetStateToFailOver();
652            }
653
654            Thread.sleep(a.delayMillis);
655            return;
656          }
657        } catch(Exception e) {
658          LOG.warn("Original exception is ", ioe);
659          throw toIOException(e);
660        }
661      }
662      throw toIOException(ioe);
663    }
664
665    abstract T getResponse(HttpURLConnection conn) throws IOException;
666  }
667
668  /**
669   * Abstract base class to handle path-based operations with params
670   */
671  abstract class AbstractFsPathRunner<T> extends AbstractRunner<T> {
672    private final Path fspath;
673    private final Param<?,?>[] parameters;
674    
675    AbstractFsPathRunner(final HttpOpParam.Op op, final Path fspath,
676        Param<?,?>... parameters) {
677      super(op, false);
678      this.fspath = fspath;
679      this.parameters = parameters;
680    }
681    
682    AbstractFsPathRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
683        final Path fspath) {
684      super(op, false);
685      this.fspath = fspath;
686      this.parameters = parameters;
687    }
688    
689    @Override
690    protected URL getUrl() throws IOException {
691      if (excludeDatanodes.getValue() != null) {
692        Param<?, ?>[] tmpParam = new Param<?, ?>[parameters.length + 1];
693        System.arraycopy(parameters, 0, tmpParam, 0, parameters.length);
694        tmpParam[parameters.length] = excludeDatanodes;
695        return toUrl(op, fspath, tmpParam);
696      } else {
697        return toUrl(op, fspath, parameters);
698      }
699    }
700  }
701
702  /**
703   * Default path-based implementation expects no json response
704   */
705  class FsPathRunner extends AbstractFsPathRunner<Void> {
706    FsPathRunner(Op op, Path fspath, Param<?,?>... parameters) {
707      super(op, fspath, parameters);
708    }
709    
710    @Override
711    Void getResponse(HttpURLConnection conn) throws IOException {
712      return null;
713    }
714  }
715
716  /**
717   * Handle path-based operations with a json response
718   */
719  abstract class FsPathResponseRunner<T> extends AbstractFsPathRunner<T> {
720    FsPathResponseRunner(final HttpOpParam.Op op, final Path fspath,
721        Param<?,?>... parameters) {
722      super(op, fspath, parameters);
723    }
724    
725    FsPathResponseRunner(final HttpOpParam.Op op, Param<?,?>[] parameters,
726        final Path fspath) {
727      super(op, parameters, fspath);
728    }
729    
730    @Override
731    final T getResponse(HttpURLConnection conn) throws IOException {
732      try {
733        final Map<?,?> json = jsonParse(conn, false);
734        if (json == null) {
735          // match exception class thrown by parser
736          throw new IllegalStateException("Missing response");
737        }
738        return decodeResponse(json);
739      } catch (IOException ioe) {
740        throw ioe;
741      } catch (Exception e) { // catch json parser errors
742        final IOException ioe =
743            new IOException("Response decoding failure: "+e.toString(), e);
744        if (LOG.isDebugEnabled()) {
745          LOG.debug(ioe);
746        }
747        throw ioe;
748      } finally {
749        conn.disconnect();
750      }
751    }
752    
753    abstract T decodeResponse(Map<?,?> json) throws IOException;
754  }
755
756  /**
757   * Handle path-based operations with json boolean response
758   */
759  class FsPathBooleanRunner extends FsPathResponseRunner<Boolean> {
760    FsPathBooleanRunner(Op op, Path fspath, Param<?,?>... parameters) {
761      super(op, fspath, parameters);
762    }
763    
764    @Override
765    Boolean decodeResponse(Map<?,?> json) throws IOException {
766      return (Boolean)json.get("boolean");
767    }
768  }
769
770  /**
771   * Handle create/append output streams
772   */
773  class FsPathOutputStreamRunner extends AbstractFsPathRunner<FSDataOutputStream> {
774    private final int bufferSize;
775    
776    FsPathOutputStreamRunner(Op op, Path fspath, int bufferSize,
777        Param<?,?>... parameters) {
778      super(op, fspath, parameters);
779      this.bufferSize = bufferSize;
780    }
781    
782    @Override
783    FSDataOutputStream getResponse(final HttpURLConnection conn)
784        throws IOException {
785      return new FSDataOutputStream(new BufferedOutputStream(
786          conn.getOutputStream(), bufferSize), statistics) {
787        @Override
788        public void close() throws IOException {
789          try {
790            super.close();
791          } finally {
792            try {
793              validateResponse(op, conn, true);
794            } finally {
795              conn.disconnect();
796            }
797          }
798        }
799      };
800    }
801  }
802
803  class FsPathConnectionRunner extends AbstractFsPathRunner<HttpURLConnection> {
804    FsPathConnectionRunner(Op op, Path fspath, Param<?,?>... parameters) {
805      super(op, fspath, parameters);
806    }
807    @Override
808    HttpURLConnection getResponse(final HttpURLConnection conn)
809        throws IOException {
810      return conn;
811    }
812  }
813  
814  /**
815   * Used by open() which tracks the resolved url itself
816   */
817  final class URLRunner extends AbstractRunner<HttpURLConnection> {
818    private final URL url;
819    @Override
820    protected URL getUrl() {
821      return url;
822    }
823
824    protected URLRunner(final HttpOpParam.Op op, final URL url, boolean redirected) {
825      super(op, redirected);
826      this.url = url;
827    }
828
829    @Override
830    HttpURLConnection getResponse(HttpURLConnection conn) throws IOException {
831      return conn;
832    }
833  }
834
835  private FsPermission applyUMask(FsPermission permission) {
836    if (permission == null) {
837      permission = FsPermission.getDefault();
838    }
839    return permission.applyUMask(FsPermission.getUMask(getConf()));
840  }
841
842  private HdfsFileStatus getHdfsFileStatus(Path f) throws IOException {
843    final HttpOpParam.Op op = GetOpParam.Op.GETFILESTATUS;
844    HdfsFileStatus status = new FsPathResponseRunner<HdfsFileStatus>(op, f) {
845      @Override
846      HdfsFileStatus decodeResponse(Map<?,?> json) {
847        return JsonUtil.toFileStatus(json, true);
848      }
849    }.run();
850    if (status == null) {
851      throw new FileNotFoundException("File does not exist: " + f);
852    }
853    return status;
854  }
855
856  @Override
857  public FileStatus getFileStatus(Path f) throws IOException {
858    statistics.incrementReadOps(1);
859    return makeQualified(getHdfsFileStatus(f), f);
860  }
861
862  private FileStatus makeQualified(HdfsFileStatus f, Path parent) {
863    return new FileStatus(f.getLen(), f.isDir(), f.getReplication(),
864        f.getBlockSize(), f.getModificationTime(), f.getAccessTime(),
865        f.getPermission(), f.getOwner(), f.getGroup(),
866        f.isSymlink() ? new Path(f.getSymlink()) : null,
867        f.getFullPath(parent).makeQualified(getUri(), getWorkingDirectory()));
868  }
869
870  @Override
871  public AclStatus getAclStatus(Path f) throws IOException {
872    final HttpOpParam.Op op = GetOpParam.Op.GETACLSTATUS;
873    AclStatus status = new FsPathResponseRunner<AclStatus>(op, f) {
874      @Override
875      AclStatus decodeResponse(Map<?,?> json) {
876        return JsonUtil.toAclStatus(json);
877      }
878    }.run();
879    if (status == null) {
880      throw new FileNotFoundException("File does not exist: " + f);
881    }
882    return status;
883  }
884
885  @Override
886  public boolean mkdirs(Path f, FsPermission permission) throws IOException {
887    statistics.incrementWriteOps(1);
888    final HttpOpParam.Op op = PutOpParam.Op.MKDIRS;
889    return new FsPathBooleanRunner(op, f,
890        new PermissionParam(applyUMask(permission))
891    ).run();
892  }
893
894  /**
895   * Create a symlink pointing to the destination path.
896   * @see org.apache.hadoop.fs.Hdfs#createSymlink(Path, Path, boolean) 
897   */
898  public void createSymlink(Path destination, Path f, boolean createParent
899      ) throws IOException {
900    statistics.incrementWriteOps(1);
901    final HttpOpParam.Op op = PutOpParam.Op.CREATESYMLINK;
902    new FsPathRunner(op, f,
903        new DestinationParam(makeQualified(destination).toUri().getPath()),
904        new CreateParentParam(createParent)
905    ).run();
906  }
907
908  @Override
909  public boolean rename(final Path src, final Path dst) throws IOException {
910    statistics.incrementWriteOps(1);
911    final HttpOpParam.Op op = PutOpParam.Op.RENAME;
912    return new FsPathBooleanRunner(op, src,
913        new DestinationParam(makeQualified(dst).toUri().getPath())
914    ).run();
915  }
916
917  @SuppressWarnings("deprecation")
918  @Override
919  public void rename(final Path src, final Path dst,
920      final Options.Rename... options) throws IOException {
921    statistics.incrementWriteOps(1);
922    final HttpOpParam.Op op = PutOpParam.Op.RENAME;
923    new FsPathRunner(op, src,
924        new DestinationParam(makeQualified(dst).toUri().getPath()),
925        new RenameOptionSetParam(options)
926    ).run();
927  }
928  
929  @Override
930  public void setXAttr(Path p, String name, byte[] value, 
931      EnumSet<XAttrSetFlag> flag) throws IOException {
932    statistics.incrementWriteOps(1);
933    final HttpOpParam.Op op = PutOpParam.Op.SETXATTR;
934    if (value != null) {
935      new FsPathRunner(op, p, new XAttrNameParam(name), new XAttrValueParam(
936          XAttrCodec.encodeValue(value, XAttrCodec.HEX)), 
937          new XAttrSetFlagParam(flag)).run();
938    } else {
939      new FsPathRunner(op, p, new XAttrNameParam(name), 
940          new XAttrSetFlagParam(flag)).run();
941    }
942  }
943  
944  @Override
945  public byte[] getXAttr(Path p, final String name) throws IOException {
946    final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
947    return new FsPathResponseRunner<byte[]>(op, p, new XAttrNameParam(name), 
948        new XAttrEncodingParam(XAttrCodec.HEX)) {
949      @Override
950      byte[] decodeResponse(Map<?, ?> json) throws IOException {
951        return JsonUtil.getXAttr(json, name);
952      }
953    }.run();
954  }
955  
956  @Override
957  public Map<String, byte[]> getXAttrs(Path p) throws IOException {
958    final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
959    return new FsPathResponseRunner<Map<String, byte[]>>(op, p, 
960        new XAttrEncodingParam(XAttrCodec.HEX)) {
961      @Override
962      Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
963        return JsonUtil.toXAttrs(json);
964      }
965    }.run();
966  }
967  
968  @Override
969  public Map<String, byte[]> getXAttrs(Path p, final List<String> names) 
970      throws IOException {
971    Preconditions.checkArgument(names != null && !names.isEmpty(), 
972        "XAttr names cannot be null or empty.");
973    Param<?,?>[] parameters = new Param<?,?>[names.size() + 1];
974    for (int i = 0; i < parameters.length - 1; i++) {
975      parameters[i] = new XAttrNameParam(names.get(i));
976    }
977    parameters[parameters.length - 1] = new XAttrEncodingParam(XAttrCodec.HEX);
978    
979    final HttpOpParam.Op op = GetOpParam.Op.GETXATTRS;
980    return new FsPathResponseRunner<Map<String, byte[]>>(op, parameters, p) {
981      @Override
982      Map<String, byte[]> decodeResponse(Map<?, ?> json) throws IOException {
983        return JsonUtil.toXAttrs(json);
984      }
985    }.run();
986  }
987  
988  @Override
989  public List<String> listXAttrs(Path p) throws IOException {
990    final HttpOpParam.Op op = GetOpParam.Op.LISTXATTRS;
991    return new FsPathResponseRunner<List<String>>(op, p) {
992      @Override
993      List<String> decodeResponse(Map<?, ?> json) throws IOException {
994        return JsonUtil.toXAttrNames(json);
995      }
996    }.run();
997  }
998
999  @Override
1000  public void removeXAttr(Path p, String name) throws IOException {
1001    statistics.incrementWriteOps(1);
1002    final HttpOpParam.Op op = PutOpParam.Op.REMOVEXATTR;
1003    new FsPathRunner(op, p, new XAttrNameParam(name)).run();
1004  }
1005
1006  @Override
1007  public void setOwner(final Path p, final String owner, final String group
1008      ) throws IOException {
1009    if (owner == null && group == null) {
1010      throw new IOException("owner == null && group == null");
1011    }
1012
1013    statistics.incrementWriteOps(1);
1014    final HttpOpParam.Op op = PutOpParam.Op.SETOWNER;
1015    new FsPathRunner(op, p,
1016        new OwnerParam(owner), new GroupParam(group)
1017    ).run();
1018  }
1019
1020  @Override
1021  public void setPermission(final Path p, final FsPermission permission
1022      ) throws IOException {
1023    statistics.incrementWriteOps(1);
1024    final HttpOpParam.Op op = PutOpParam.Op.SETPERMISSION;
1025    new FsPathRunner(op, p,new PermissionParam(permission)).run();
1026  }
1027
1028  @Override
1029  public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
1030      throws IOException {
1031    statistics.incrementWriteOps(1);
1032    final HttpOpParam.Op op = PutOpParam.Op.MODIFYACLENTRIES;
1033    new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
1034  }
1035
1036  @Override
1037  public void removeAclEntries(Path path, List<AclEntry> aclSpec)
1038      throws IOException {
1039    statistics.incrementWriteOps(1);
1040    final HttpOpParam.Op op = PutOpParam.Op.REMOVEACLENTRIES;
1041    new FsPathRunner(op, path, new AclPermissionParam(aclSpec)).run();
1042  }
1043
1044  @Override
1045  public void removeDefaultAcl(Path path) throws IOException {
1046    statistics.incrementWriteOps(1);
1047    final HttpOpParam.Op op = PutOpParam.Op.REMOVEDEFAULTACL;
1048    new FsPathRunner(op, path).run();
1049  }
1050
1051  @Override
1052  public void removeAcl(Path path) throws IOException {
1053    statistics.incrementWriteOps(1);
1054    final HttpOpParam.Op op = PutOpParam.Op.REMOVEACL;
1055    new FsPathRunner(op, path).run();
1056  }
1057
1058  @Override
1059  public void setAcl(final Path p, final List<AclEntry> aclSpec)
1060      throws IOException {
1061    statistics.incrementWriteOps(1);
1062    final HttpOpParam.Op op = PutOpParam.Op.SETACL;
1063    new FsPathRunner(op, p, new AclPermissionParam(aclSpec)).run();
1064  }
1065
1066  @Override
1067  public Path createSnapshot(final Path path, final String snapshotName) 
1068      throws IOException {
1069    statistics.incrementWriteOps(1);
1070    final HttpOpParam.Op op = PutOpParam.Op.CREATESNAPSHOT;
1071    Path spath = new FsPathResponseRunner<Path>(op, path,
1072        new SnapshotNameParam(snapshotName)) {
1073      @Override
1074      Path decodeResponse(Map<?,?> json) {
1075        return new Path((String) json.get(Path.class.getSimpleName()));
1076      }
1077    }.run();
1078    return spath;
1079  }
1080
1081  @Override
1082  public void deleteSnapshot(final Path path, final String snapshotName)
1083      throws IOException {
1084    statistics.incrementWriteOps(1);
1085    final HttpOpParam.Op op = DeleteOpParam.Op.DELETESNAPSHOT;
1086    new FsPathRunner(op, path, new SnapshotNameParam(snapshotName)).run();
1087  }
1088
1089  @Override
1090  public void renameSnapshot(final Path path, final String snapshotOldName,
1091      final String snapshotNewName) throws IOException {
1092    statistics.incrementWriteOps(1);
1093    final HttpOpParam.Op op = PutOpParam.Op.RENAMESNAPSHOT;
1094    new FsPathRunner(op, path, new OldSnapshotNameParam(snapshotOldName),
1095        new SnapshotNameParam(snapshotNewName)).run();
1096  }
1097
1098  @Override
1099  public boolean setReplication(final Path p, final short replication
1100     ) throws IOException {
1101    statistics.incrementWriteOps(1);
1102    final HttpOpParam.Op op = PutOpParam.Op.SETREPLICATION;
1103    return new FsPathBooleanRunner(op, p,
1104        new ReplicationParam(replication)
1105    ).run();
1106  }
1107
1108  @Override
1109  public void setTimes(final Path p, final long mtime, final long atime
1110      ) throws IOException {
1111    statistics.incrementWriteOps(1);
1112    final HttpOpParam.Op op = PutOpParam.Op.SETTIMES;
1113    new FsPathRunner(op, p,
1114        new ModificationTimeParam(mtime),
1115        new AccessTimeParam(atime)
1116    ).run();
1117  }
1118
1119  @Override
1120  public long getDefaultBlockSize() {
1121    return getConf().getLongBytes(DFSConfigKeys.DFS_BLOCK_SIZE_KEY,
1122        DFSConfigKeys.DFS_BLOCK_SIZE_DEFAULT);
1123  }
1124
1125  @Override
1126  public short getDefaultReplication() {
1127    return (short)getConf().getInt(DFSConfigKeys.DFS_REPLICATION_KEY,
1128        DFSConfigKeys.DFS_REPLICATION_DEFAULT);
1129  }
1130
1131  @Override
1132  public void concat(final Path trg, final Path [] srcs) throws IOException {
1133    statistics.incrementWriteOps(1);
1134    final HttpOpParam.Op op = PostOpParam.Op.CONCAT;
1135    new FsPathRunner(op, trg, new ConcatSourcesParam(srcs)).run();
1136  }
1137
1138  @Override
1139  public FSDataOutputStream create(final Path f, final FsPermission permission,
1140      final boolean overwrite, final int bufferSize, final short replication,
1141      final long blockSize, final Progressable progress) throws IOException {
1142    statistics.incrementWriteOps(1);
1143
1144    final HttpOpParam.Op op = PutOpParam.Op.CREATE;
1145    return new FsPathOutputStreamRunner(op, f, bufferSize,
1146        new PermissionParam(applyUMask(permission)),
1147        new OverwriteParam(overwrite),
1148        new BufferSizeParam(bufferSize),
1149        new ReplicationParam(replication),
1150        new BlockSizeParam(blockSize)
1151    ).run();
1152  }
1153
1154  @Override
1155  public FSDataOutputStream append(final Path f, final int bufferSize,
1156      final Progressable progress) throws IOException {
1157    statistics.incrementWriteOps(1);
1158
1159    final HttpOpParam.Op op = PostOpParam.Op.APPEND;
1160    return new FsPathOutputStreamRunner(op, f, bufferSize,
1161        new BufferSizeParam(bufferSize)
1162    ).run();
1163  }
1164
1165  @Override
1166  public boolean delete(Path f, boolean recursive) throws IOException {
1167    final HttpOpParam.Op op = DeleteOpParam.Op.DELETE;
1168    return new FsPathBooleanRunner(op, f,
1169        new RecursiveParam(recursive)
1170    ).run();
1171  }
1172
1173  @Override
1174  public FSDataInputStream open(final Path f, final int buffersize
1175      ) throws IOException {
1176    statistics.incrementReadOps(1);
1177    final HttpOpParam.Op op = GetOpParam.Op.OPEN;
1178    // use a runner so the open can recover from an invalid token
1179    FsPathConnectionRunner runner =
1180        new FsPathConnectionRunner(op, f, new BufferSizeParam(buffersize));
1181    return new FSDataInputStream(new OffsetUrlInputStream(
1182        new UnresolvedUrlOpener(runner), new OffsetUrlOpener(null)));
1183  }
1184
1185  @Override
1186  public synchronized void close() throws IOException {
1187    try {
1188      if (canRefreshDelegationToken && delegationToken != null) {
1189        cancelDelegationToken(delegationToken);
1190      }
1191    } catch (IOException ioe) {
1192      if (LOG.isDebugEnabled()) {
1193        LOG.debug("Token cancel failed: " + ioe);
1194      }
1195    } finally {
1196      super.close();
1197    }
1198  }
1199
1200  // use FsPathConnectionRunner to ensure retries for InvalidTokens
1201  class UnresolvedUrlOpener extends ByteRangeInputStream.URLOpener {
1202    private final FsPathConnectionRunner runner;
1203    UnresolvedUrlOpener(FsPathConnectionRunner runner) {
1204      super(null);
1205      this.runner = runner;
1206    }
1207
1208    @Override
1209    protected HttpURLConnection connect(long offset, boolean resolved)
1210        throws IOException {
1211      assert offset == 0;
1212      HttpURLConnection conn = runner.run();
1213      setURL(conn.getURL());
1214      return conn;
1215    }
1216  }
1217
1218  class OffsetUrlOpener extends ByteRangeInputStream.URLOpener {
1219    OffsetUrlOpener(final URL url) {
1220      super(url);
1221    }
1222
1223    /** Setup offset url and connect. */
1224    @Override
1225    protected HttpURLConnection connect(final long offset,
1226        final boolean resolved) throws IOException {
1227      final URL offsetUrl = offset == 0L? url
1228          : new URL(url + "&" + new OffsetParam(offset));
1229      return new URLRunner(GetOpParam.Op.OPEN, offsetUrl, resolved).run();
1230    }  
1231  }
1232
1233  private static final String OFFSET_PARAM_PREFIX = OffsetParam.NAME + "=";
1234
1235  /** Remove offset parameter, if there is any, from the url */
1236  static URL removeOffsetParam(final URL url) throws MalformedURLException {
1237    String query = url.getQuery();
1238    if (query == null) {
1239      return url;
1240    }
1241    final String lower = query.toLowerCase();
1242    if (!lower.startsWith(OFFSET_PARAM_PREFIX)
1243        && !lower.contains("&" + OFFSET_PARAM_PREFIX)) {
1244      return url;
1245    }
1246
1247    //rebuild query
1248    StringBuilder b = null;
1249    for(final StringTokenizer st = new StringTokenizer(query, "&");
1250        st.hasMoreTokens();) {
1251      final String token = st.nextToken();
1252      if (!token.toLowerCase().startsWith(OFFSET_PARAM_PREFIX)) {
1253        if (b == null) {
1254          b = new StringBuilder("?").append(token);
1255        } else {
1256          b.append('&').append(token);
1257        }
1258      }
1259    }
1260    query = b == null? "": b.toString();
1261
1262    final String urlStr = url.toString();
1263    return new URL(urlStr.substring(0, urlStr.indexOf('?')) + query);
1264  }
1265
1266  static class OffsetUrlInputStream extends ByteRangeInputStream {
1267    OffsetUrlInputStream(UnresolvedUrlOpener o, OffsetUrlOpener r)
1268        throws IOException {
1269      super(o, r);
1270    }
1271
1272    /** Remove offset parameter before returning the resolved url. */
1273    @Override
1274    protected URL getResolvedUrl(final HttpURLConnection connection
1275        ) throws MalformedURLException {
1276      return removeOffsetParam(connection.getURL());
1277    }
1278  }
1279
1280  @Override
1281  public FileStatus[] listStatus(final Path f) throws IOException {
1282    statistics.incrementReadOps(1);
1283
1284    final HttpOpParam.Op op = GetOpParam.Op.LISTSTATUS;
1285    return new FsPathResponseRunner<FileStatus[]>(op, f) {
1286      @Override
1287      FileStatus[] decodeResponse(Map<?,?> json) {
1288        final Map<?, ?> rootmap = (Map<?, ?>)json.get(FileStatus.class.getSimpleName() + "es");
1289        final Object[] array = (Object[])rootmap.get(FileStatus.class.getSimpleName());
1290
1291        //convert FileStatus
1292        final FileStatus[] statuses = new FileStatus[array.length];
1293        for (int i = 0; i < array.length; i++) {
1294          final Map<?, ?> m = (Map<?, ?>)array[i];
1295          statuses[i] = makeQualified(JsonUtil.toFileStatus(m, false), f);
1296        }
1297        return statuses;
1298      }
1299    }.run();
1300  }
1301
1302  @Override
1303  public Token<DelegationTokenIdentifier> getDelegationToken(
1304      final String renewer) throws IOException {
1305    try {
1306      final HttpOpParam.Op op = GetOpParam.Op.GETDELEGATIONTOKEN;
1307      Token<DelegationTokenIdentifier> token =
1308          new FsPathResponseRunner<Token<DelegationTokenIdentifier>>(
1309              op, null, new RenewerParam(renewer)) {
1310        @Override
1311        Token<DelegationTokenIdentifier> decodeResponse(Map<?,?> json)
1312            throws IOException {
1313          return JsonUtil.toDelegationToken(json);
1314        }
1315      }.run();
1316      if (token != null) {
1317        token.setService(tokenServiceName);
1318      } else {
1319        if (disallowFallbackToInsecureCluster) {
1320          throw new AccessControlException(CANT_FALLBACK_TO_INSECURE_MSG);
1321        }
1322      }
1323      return token;
1324    } catch (IOException ioe) {
1325      if (ioe.getMessage().startsWith("Failed to get the token for")) {
1326        // cluster that is insecure and doesn't have the fix of HDFS-6776
1327        // throws IOException with msg that starts with
1328        // ""Failed to get the token for" when requested for delegation
1329        // token. Catch it here and return null delegation token if 
1330        // fallback is allowed
1331        if (disallowFallbackToInsecureCluster) {
1332          throw new AccessControlException(CANT_FALLBACK_TO_INSECURE_MSG);
1333        }
1334        return null;
1335      }
1336      throw ioe;
1337    }
1338  }
1339
1340  @Override
1341  public synchronized Token<?> getRenewToken() {
1342    return delegationToken;
1343  }
1344
1345  @Override
1346  public <T extends TokenIdentifier> void setDelegationToken(
1347      final Token<T> token) {
1348    synchronized (this) {
1349      delegationToken = token;
1350    }
1351  }
1352
1353  @Override
1354  public synchronized long renewDelegationToken(final Token<?> token
1355      ) throws IOException {
1356    final HttpOpParam.Op op = PutOpParam.Op.RENEWDELEGATIONTOKEN;
1357    return new FsPathResponseRunner<Long>(op, null,
1358        new TokenArgumentParam(token.encodeToUrlString())) {
1359      @Override
1360      Long decodeResponse(Map<?,?> json) throws IOException {
1361        return (Long) json.get("long");
1362      }
1363    }.run();
1364  }
1365
1366  @Override
1367  public synchronized void cancelDelegationToken(final Token<?> token
1368      ) throws IOException {
1369    final HttpOpParam.Op op = PutOpParam.Op.CANCELDELEGATIONTOKEN;
1370    new FsPathRunner(op, null,
1371        new TokenArgumentParam(token.encodeToUrlString())
1372    ).run();
1373  }
1374  
1375  @Override
1376  public BlockLocation[] getFileBlockLocations(final FileStatus status,
1377      final long offset, final long length) throws IOException {
1378    if (status == null) {
1379      return null;
1380    }
1381    return getFileBlockLocations(status.getPath(), offset, length);
1382  }
1383
1384  @Override
1385  public BlockLocation[] getFileBlockLocations(final Path p, 
1386      final long offset, final long length) throws IOException {
1387    statistics.incrementReadOps(1);
1388
1389    final HttpOpParam.Op op = GetOpParam.Op.GET_BLOCK_LOCATIONS;
1390    return new FsPathResponseRunner<BlockLocation[]>(op, p,
1391        new OffsetParam(offset), new LengthParam(length)) {
1392      @Override
1393      BlockLocation[] decodeResponse(Map<?,?> json) throws IOException {
1394        return DFSUtil.locatedBlocks2Locations(
1395            JsonUtil.toLocatedBlocks(json));
1396      }
1397    }.run();
1398  }
1399
1400  @Override
1401  public void access(final Path path, final FsAction mode) throws IOException {
1402    final HttpOpParam.Op op = GetOpParam.Op.CHECKACCESS;
1403    new FsPathRunner(op, path, new FsActionParam(mode)).run();
1404  }
1405
1406  @Override
1407  public ContentSummary getContentSummary(final Path p) throws IOException {
1408    statistics.incrementReadOps(1);
1409
1410    final HttpOpParam.Op op = GetOpParam.Op.GETCONTENTSUMMARY;
1411    return new FsPathResponseRunner<ContentSummary>(op, p) {
1412      @Override
1413      ContentSummary decodeResponse(Map<?,?> json) {
1414        return JsonUtil.toContentSummary(json);        
1415      }
1416    }.run();
1417  }
1418
1419  @Override
1420  public MD5MD5CRC32FileChecksum getFileChecksum(final Path p
1421      ) throws IOException {
1422    statistics.incrementReadOps(1);
1423  
1424    final HttpOpParam.Op op = GetOpParam.Op.GETFILECHECKSUM;
1425    return new FsPathResponseRunner<MD5MD5CRC32FileChecksum>(op, p) {
1426      @Override
1427      MD5MD5CRC32FileChecksum decodeResponse(Map<?,?> json) throws IOException {
1428        return JsonUtil.toMD5MD5CRC32FileChecksum(json);
1429      }
1430    }.run();
1431  }
1432
1433  /**
1434   * Resolve an HDFS URL into real INetSocketAddress. It works like a DNS
1435   * resolver when the URL points to an non-HA cluster. When the URL points to
1436   * an HA cluster with its logical name, the resolver further resolves the
1437   * logical name(i.e., the authority in the URL) into real namenode addresses.
1438   */
1439  private InetSocketAddress[] resolveNNAddr() throws IOException {
1440    Configuration conf = getConf();
1441    final String scheme = uri.getScheme();
1442
1443    ArrayList<InetSocketAddress> ret = new ArrayList<InetSocketAddress>();
1444
1445    if (!HAUtil.isLogicalUri(conf, uri)) {
1446      InetSocketAddress addr = NetUtils.createSocketAddr(uri.getAuthority(),
1447          getDefaultPort());
1448      ret.add(addr);
1449
1450    } else {
1451      Map<String, Map<String, InetSocketAddress>> addresses = DFSUtil
1452          .getHaNnWebHdfsAddresses(conf, scheme);
1453
1454      // Extract the entry corresponding to the logical name.
1455      Map<String, InetSocketAddress> addrs = addresses.get(uri.getHost());
1456      for (InetSocketAddress addr : addrs.values()) {
1457        ret.add(addr);
1458      }
1459    }
1460
1461    InetSocketAddress[] r = new InetSocketAddress[ret.size()];
1462    return ret.toArray(r);
1463  }
1464
1465  @Override
1466  public String getCanonicalServiceName() {
1467    return tokenServiceName == null ? super.getCanonicalServiceName()
1468        : tokenServiceName.toString();
1469  }
1470
1471  @VisibleForTesting
1472  InetSocketAddress[] getResolvedNNAddr() {
1473    return nnAddrs;
1474  }
1475}