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     */
018    package org.apache.hadoop.hdfs.server.namenode.web.resources;
019    
020    import java.io.FileNotFoundException;
021    import java.io.IOException;
022    import java.io.OutputStream;
023    import java.io.OutputStreamWriter;
024    import java.io.PrintWriter;
025    import java.net.InetAddress;
026    import java.net.URI;
027    import java.net.URISyntaxException;
028    import java.security.PrivilegedExceptionAction;
029    import java.util.ArrayList;
030    import java.util.EnumSet;
031    
032    import javax.servlet.ServletContext;
033    import javax.servlet.http.HttpServletRequest;
034    import javax.servlet.http.HttpServletResponse;
035    import javax.ws.rs.Consumes;
036    import javax.ws.rs.DELETE;
037    import javax.ws.rs.DefaultValue;
038    import javax.ws.rs.GET;
039    import javax.ws.rs.POST;
040    import javax.ws.rs.PUT;
041    import javax.ws.rs.Path;
042    import javax.ws.rs.PathParam;
043    import javax.ws.rs.Produces;
044    import javax.ws.rs.QueryParam;
045    import javax.ws.rs.core.Context;
046    import javax.ws.rs.core.MediaType;
047    import javax.ws.rs.core.Response;
048    import javax.ws.rs.core.StreamingOutput;
049    
050    import org.apache.commons.logging.Log;
051    import org.apache.commons.logging.LogFactory;
052    import org.apache.hadoop.conf.Configuration;
053    import org.apache.hadoop.fs.ContentSummary;
054    import org.apache.hadoop.fs.FileStatus;
055    import org.apache.hadoop.fs.Options;
056    import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
057    import org.apache.hadoop.hdfs.protocol.DirectoryListing;
058    import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
059    import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
060    import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
061    import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
062    import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
063    import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
064    import org.apache.hadoop.hdfs.server.common.JspHelper;
065    import org.apache.hadoop.hdfs.server.namenode.NameNode;
066    import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
067    import org.apache.hadoop.hdfs.web.JsonUtil;
068    import org.apache.hadoop.hdfs.web.ParamFilter;
069    import org.apache.hadoop.hdfs.web.WebHdfsFileSystem;
070    import org.apache.hadoop.hdfs.web.resources.AccessTimeParam;
071    import org.apache.hadoop.hdfs.web.resources.BlockSizeParam;
072    import org.apache.hadoop.hdfs.web.resources.BufferSizeParam;
073    import org.apache.hadoop.hdfs.web.resources.ConcatSourcesParam;
074    import org.apache.hadoop.hdfs.web.resources.CreateParentParam;
075    import org.apache.hadoop.hdfs.web.resources.DelegationParam;
076    import org.apache.hadoop.hdfs.web.resources.DeleteOpParam;
077    import org.apache.hadoop.hdfs.web.resources.DestinationParam;
078    import org.apache.hadoop.hdfs.web.resources.DoAsParam;
079    import org.apache.hadoop.hdfs.web.resources.GetOpParam;
080    import org.apache.hadoop.hdfs.web.resources.GroupParam;
081    import org.apache.hadoop.hdfs.web.resources.HttpOpParam;
082    import org.apache.hadoop.hdfs.web.resources.LengthParam;
083    import org.apache.hadoop.hdfs.web.resources.ModificationTimeParam;
084    import org.apache.hadoop.hdfs.web.resources.NamenodeRpcAddressParam;
085    import org.apache.hadoop.hdfs.web.resources.OffsetParam;
086    import org.apache.hadoop.hdfs.web.resources.OverwriteParam;
087    import org.apache.hadoop.hdfs.web.resources.OwnerParam;
088    import org.apache.hadoop.hdfs.web.resources.Param;
089    import org.apache.hadoop.hdfs.web.resources.PermissionParam;
090    import org.apache.hadoop.hdfs.web.resources.PostOpParam;
091    import org.apache.hadoop.hdfs.web.resources.PutOpParam;
092    import org.apache.hadoop.hdfs.web.resources.RecursiveParam;
093    import org.apache.hadoop.hdfs.web.resources.RenameOptionSetParam;
094    import org.apache.hadoop.hdfs.web.resources.RenewerParam;
095    import org.apache.hadoop.hdfs.web.resources.ReplicationParam;
096    import org.apache.hadoop.hdfs.web.resources.TokenArgumentParam;
097    import org.apache.hadoop.hdfs.web.resources.UriFsPathParam;
098    import org.apache.hadoop.hdfs.web.resources.UserParam;
099    import org.apache.hadoop.ipc.Server;
100    import org.apache.hadoop.net.NodeBase;
101    import org.apache.hadoop.security.Credentials;
102    import org.apache.hadoop.security.SecurityUtil;
103    import org.apache.hadoop.security.UserGroupInformation;
104    import org.apache.hadoop.security.token.Token;
105    import org.apache.hadoop.security.token.TokenIdentifier;
106    
107    import com.google.common.base.Charsets;
108    import com.sun.jersey.spi.container.ResourceFilters;
109    
110    /** Web-hdfs NameNode implementation. */
111    @Path("")
112    @ResourceFilters(ParamFilter.class)
113    public class NamenodeWebHdfsMethods {
114      public static final Log LOG = LogFactory.getLog(NamenodeWebHdfsMethods.class);
115    
116      private static final UriFsPathParam ROOT = new UriFsPathParam("");
117      
118      private static final ThreadLocal<String> REMOTE_ADDRESS = new ThreadLocal<String>(); 
119    
120      /** @return the remote client address. */
121      public static String getRemoteAddress() {
122        return REMOTE_ADDRESS.get();
123      }
124    
125      public static InetAddress getRemoteIp() {
126        try {
127          return InetAddress.getByName(getRemoteAddress());
128        } catch (Exception e) {
129          return null;
130        }
131      }
132    
133      /**
134       * Returns true if a WebHdfs request is in progress.  Akin to
135       * {@link Server#isRpcInvocation()}.
136       */
137      public static boolean isWebHdfsInvocation() {
138        return getRemoteAddress() != null;
139      }
140    
141      private @Context ServletContext context;
142      private @Context HttpServletRequest request;
143      private @Context HttpServletResponse response;
144    
145      private void init(final UserGroupInformation ugi,
146          final DelegationParam delegation,
147          final UserParam username, final DoAsParam doAsUser,
148          final UriFsPathParam path, final HttpOpParam<?> op,
149          final Param<?, ?>... parameters) {
150        if (LOG.isTraceEnabled()) {
151          LOG.trace("HTTP " + op.getValue().getType() + ": " + op + ", " + path
152              + ", ugi=" + ugi + ", " + username + ", " + doAsUser
153              + Param.toSortedString(", ", parameters));
154        }
155    
156        //clear content type
157        response.setContentType(null);
158      }
159    
160      static DatanodeInfo chooseDatanode(final NameNode namenode,
161          final String path, final HttpOpParam.Op op, final long openOffset,
162          final long blocksize, Configuration conf) throws IOException {
163        final BlockManager bm = namenode.getNamesystem().getBlockManager();
164    
165        if (op == PutOpParam.Op.CREATE) {
166          //choose a datanode near to client 
167          final DatanodeDescriptor clientNode = bm.getDatanodeManager(
168              ).getDatanodeByHost(getRemoteAddress());
169          if (clientNode != null) {
170            final DatanodeDescriptor[] datanodes = bm.getBlockPlacementPolicy()
171                .chooseTarget(path, 1, clientNode,
172                    new ArrayList<DatanodeDescriptor>(), false, null, blocksize);
173            if (datanodes.length > 0) {
174              return datanodes[0];
175            }
176          }
177        } else if (op == GetOpParam.Op.OPEN
178            || op == GetOpParam.Op.GETFILECHECKSUM
179            || op == PostOpParam.Op.APPEND) {
180          //choose a datanode containing a replica 
181          final NamenodeProtocols np = namenode.getRpcServer();
182          final HdfsFileStatus status = np.getFileInfo(path);
183          if (status == null) {
184            throw new FileNotFoundException("File " + path + " not found.");
185          }
186          final long len = status.getLen();
187          if (op == GetOpParam.Op.OPEN) {
188            if (openOffset < 0L || (openOffset >= len && len > 0)) {
189              throw new IOException("Offset=" + openOffset
190                  + " out of the range [0, " + len + "); " + op + ", path=" + path);
191            }
192          }
193    
194          if (len > 0) {
195            final long offset = op == GetOpParam.Op.OPEN? openOffset: len - 1;
196            final LocatedBlocks locations = np.getBlockLocations(path, offset, 1);
197            final int count = locations.locatedBlockCount();
198            if (count > 0) {
199              return JspHelper.bestNode(locations.get(0).getLocations(), false, conf);
200            }
201          }
202        } 
203    
204        return (DatanodeDescriptor)bm.getDatanodeManager().getNetworkTopology(
205            ).chooseRandom(NodeBase.ROOT);
206      }
207    
208      private Token<? extends TokenIdentifier> generateDelegationToken(
209          final NameNode namenode, final UserGroupInformation ugi,
210          final String renewer) throws IOException {
211        final Credentials c = DelegationTokenSecretManager.createCredentials(
212            namenode, ugi, renewer != null? renewer: ugi.getShortUserName());
213        final Token<? extends TokenIdentifier> t = c.getAllTokens().iterator().next();
214        t.setKind(WebHdfsFileSystem.TOKEN_KIND);
215        SecurityUtil.setTokenService(t, namenode.getHttpAddress());
216        return t;
217      }
218    
219      private URI redirectURI(final NameNode namenode,
220          final UserGroupInformation ugi, final DelegationParam delegation,
221          final UserParam username, final DoAsParam doAsUser,
222          final String path, final HttpOpParam.Op op, final long openOffset,
223          final long blocksize,
224          final Param<?, ?>... parameters) throws URISyntaxException, IOException {
225        final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
226        final DatanodeInfo dn = chooseDatanode(namenode, path, op, openOffset,
227            blocksize, conf);
228    
229        final String delegationQuery;
230        if (!UserGroupInformation.isSecurityEnabled()) {
231          //security disabled
232          delegationQuery = Param.toSortedString("&", doAsUser, username);
233        } else if (delegation.getValue() != null) {
234          //client has provided a token
235          delegationQuery = "&" + delegation;
236        } else {
237          //generate a token
238          final Token<? extends TokenIdentifier> t = generateDelegationToken(
239              namenode, ugi, request.getUserPrincipal().getName());
240          delegationQuery = "&" + new DelegationParam(t.encodeToUrlString());
241        }
242        final String query = op.toQueryString() + delegationQuery
243            + "&" + new NamenodeRpcAddressParam(namenode)
244            + Param.toSortedString("&", parameters);
245        final String uripath = WebHdfsFileSystem.PATH_PREFIX + path;
246    
247        final URI uri = new URI("http", null, dn.getHostName(), dn.getInfoPort(),
248            uripath, query, null);
249        if (LOG.isTraceEnabled()) {
250          LOG.trace("redirectURI=" + uri);
251        }
252        return uri;
253      }
254    
255      /** Handle HTTP PUT request for the root. */
256      @PUT
257      @Path("/")
258      @Consumes({"*/*"})
259      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
260      public Response putRoot(
261          @Context final UserGroupInformation ugi,
262          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
263              final DelegationParam delegation,
264          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
265              final UserParam username,
266          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
267              final DoAsParam doAsUser,
268          @QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
269              final PutOpParam op,
270          @QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
271              final DestinationParam destination,
272          @QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
273              final OwnerParam owner,
274          @QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
275              final GroupParam group,
276          @QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
277              final PermissionParam permission,
278          @QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
279              final OverwriteParam overwrite,
280          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
281              final BufferSizeParam bufferSize,
282          @QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
283              final ReplicationParam replication,
284          @QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
285              final BlockSizeParam blockSize,
286          @QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
287              final ModificationTimeParam modificationTime,
288          @QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
289              final AccessTimeParam accessTime,
290          @QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
291              final RenameOptionSetParam renameOptions,
292          @QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT)
293              final CreateParentParam createParent,
294          @QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT)
295              final TokenArgumentParam delegationTokenArgument
296          ) throws IOException, InterruptedException {
297        return put(ugi, delegation, username, doAsUser, ROOT, op, destination,
298            owner, group, permission, overwrite, bufferSize, replication,
299            blockSize, modificationTime, accessTime, renameOptions, createParent,
300            delegationTokenArgument);
301      }
302    
303      /** Handle HTTP PUT request. */
304      @PUT
305      @Path("{" + UriFsPathParam.NAME + ":.*}")
306      @Consumes({"*/*"})
307      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
308      public Response put(
309          @Context final UserGroupInformation ugi,
310          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
311              final DelegationParam delegation,
312          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
313              final UserParam username,
314          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
315              final DoAsParam doAsUser,
316          @PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
317          @QueryParam(PutOpParam.NAME) @DefaultValue(PutOpParam.DEFAULT)
318              final PutOpParam op,
319          @QueryParam(DestinationParam.NAME) @DefaultValue(DestinationParam.DEFAULT)
320              final DestinationParam destination,
321          @QueryParam(OwnerParam.NAME) @DefaultValue(OwnerParam.DEFAULT)
322              final OwnerParam owner,
323          @QueryParam(GroupParam.NAME) @DefaultValue(GroupParam.DEFAULT)
324              final GroupParam group,
325          @QueryParam(PermissionParam.NAME) @DefaultValue(PermissionParam.DEFAULT)
326              final PermissionParam permission,
327          @QueryParam(OverwriteParam.NAME) @DefaultValue(OverwriteParam.DEFAULT)
328              final OverwriteParam overwrite,
329          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
330              final BufferSizeParam bufferSize,
331          @QueryParam(ReplicationParam.NAME) @DefaultValue(ReplicationParam.DEFAULT)
332              final ReplicationParam replication,
333          @QueryParam(BlockSizeParam.NAME) @DefaultValue(BlockSizeParam.DEFAULT)
334              final BlockSizeParam blockSize,
335          @QueryParam(ModificationTimeParam.NAME) @DefaultValue(ModificationTimeParam.DEFAULT)
336              final ModificationTimeParam modificationTime,
337          @QueryParam(AccessTimeParam.NAME) @DefaultValue(AccessTimeParam.DEFAULT)
338              final AccessTimeParam accessTime,
339          @QueryParam(RenameOptionSetParam.NAME) @DefaultValue(RenameOptionSetParam.DEFAULT)
340              final RenameOptionSetParam renameOptions,
341          @QueryParam(CreateParentParam.NAME) @DefaultValue(CreateParentParam.DEFAULT)
342              final CreateParentParam createParent,
343          @QueryParam(TokenArgumentParam.NAME) @DefaultValue(TokenArgumentParam.DEFAULT)
344              final TokenArgumentParam delegationTokenArgument
345          ) throws IOException, InterruptedException {
346    
347        init(ugi, delegation, username, doAsUser, path, op, destination, owner,
348            group, permission, overwrite, bufferSize, replication, blockSize,
349            modificationTime, accessTime, renameOptions, delegationTokenArgument);
350    
351        return ugi.doAs(new PrivilegedExceptionAction<Response>() {
352          @Override
353          public Response run() throws IOException, URISyntaxException {
354            REMOTE_ADDRESS.set(request.getRemoteAddr());
355            try {
356              return put(ugi, delegation, username, doAsUser,
357                  path.getAbsolutePath(), op, destination, owner, group,
358                  permission, overwrite, bufferSize, replication, blockSize,
359                  modificationTime, accessTime, renameOptions, createParent,
360                  delegationTokenArgument);
361            } finally {
362              REMOTE_ADDRESS.set(null);
363            }
364          }
365        });
366      }
367    
368      private Response put(
369          final UserGroupInformation ugi,
370          final DelegationParam delegation,
371          final UserParam username,
372          final DoAsParam doAsUser,
373          final String fullpath,
374          final PutOpParam op,
375          final DestinationParam destination,
376          final OwnerParam owner,
377          final GroupParam group,
378          final PermissionParam permission,
379          final OverwriteParam overwrite,
380          final BufferSizeParam bufferSize,
381          final ReplicationParam replication,
382          final BlockSizeParam blockSize,
383          final ModificationTimeParam modificationTime,
384          final AccessTimeParam accessTime,
385          final RenameOptionSetParam renameOptions,
386          final CreateParentParam createParent,
387          final TokenArgumentParam delegationTokenArgument
388          ) throws IOException, URISyntaxException {
389    
390        final Configuration conf = (Configuration)context.getAttribute(JspHelper.CURRENT_CONF);
391        final NameNode namenode = (NameNode)context.getAttribute("name.node");
392        final NamenodeProtocols np = namenode.getRpcServer();
393    
394        switch(op.getValue()) {
395        case CREATE:
396        {
397          final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser,
398              fullpath, op.getValue(), -1L, blockSize.getValue(conf),
399              permission, overwrite, bufferSize, replication, blockSize);
400          return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
401        } 
402        case MKDIRS:
403        {
404          final boolean b = np.mkdirs(fullpath, permission.getFsPermission(), true);
405          final String js = JsonUtil.toJsonString("boolean", b);
406          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
407        }
408        case CREATESYMLINK:
409        {
410          np.createSymlink(destination.getValue(), fullpath,
411              PermissionParam.getDefaultFsPermission(), createParent.getValue());
412          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
413        }
414        case RENAME:
415        {
416          final EnumSet<Options.Rename> s = renameOptions.getValue();
417          if (s.isEmpty()) {
418            final boolean b = np.rename(fullpath, destination.getValue());
419            final String js = JsonUtil.toJsonString("boolean", b);
420            return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
421          } else {
422            np.rename2(fullpath, destination.getValue(),
423                s.toArray(new Options.Rename[s.size()]));
424            return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
425          }
426        }
427        case SETREPLICATION:
428        {
429          final boolean b = np.setReplication(fullpath, replication.getValue(conf));
430          final String js = JsonUtil.toJsonString("boolean", b);
431          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
432        }
433        case SETOWNER:
434        {
435          if (owner.getValue() == null && group.getValue() == null) {
436            throw new IllegalArgumentException("Both owner and group are empty.");
437          }
438    
439          np.setOwner(fullpath, owner.getValue(), group.getValue());
440          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
441        }
442        case SETPERMISSION:
443        {
444          np.setPermission(fullpath, permission.getFsPermission());
445          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
446        }
447        case SETTIMES:
448        {
449          np.setTimes(fullpath, modificationTime.getValue(), accessTime.getValue());
450          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
451        }
452        case RENEWDELEGATIONTOKEN:
453        {
454          final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
455          token.decodeFromUrlString(delegationTokenArgument.getValue());
456          final long expiryTime = np.renewDelegationToken(token);
457          final String js = JsonUtil.toJsonString("long", expiryTime);
458          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
459        }
460        case CANCELDELEGATIONTOKEN:
461        {
462          final Token<DelegationTokenIdentifier> token = new Token<DelegationTokenIdentifier>();
463          token.decodeFromUrlString(delegationTokenArgument.getValue());
464          np.cancelDelegationToken(token);
465          return Response.ok().type(MediaType.APPLICATION_OCTET_STREAM).build();
466        }
467        default:
468          throw new UnsupportedOperationException(op + " is not supported");
469        }
470      }
471    
472      /** Handle HTTP POST request for the root. */
473      @POST
474      @Path("/")
475      @Consumes({"*/*"})
476      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
477      public Response postRoot(
478          @Context final UserGroupInformation ugi,
479          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
480              final DelegationParam delegation,
481          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
482              final UserParam username,
483          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
484              final DoAsParam doAsUser,
485          @QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
486              final PostOpParam op,
487          @QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT)
488              final ConcatSourcesParam concatSrcs,
489          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
490              final BufferSizeParam bufferSize
491          ) throws IOException, InterruptedException {
492        return post(ugi, delegation, username, doAsUser, ROOT, op, concatSrcs, bufferSize);
493      }
494    
495      /** Handle HTTP POST request. */
496      @POST
497      @Path("{" + UriFsPathParam.NAME + ":.*}")
498      @Consumes({"*/*"})
499      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
500      public Response post(
501          @Context final UserGroupInformation ugi,
502          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
503              final DelegationParam delegation,
504          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
505              final UserParam username,
506          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
507              final DoAsParam doAsUser,
508          @PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
509          @QueryParam(PostOpParam.NAME) @DefaultValue(PostOpParam.DEFAULT)
510              final PostOpParam op,
511          @QueryParam(ConcatSourcesParam.NAME) @DefaultValue(ConcatSourcesParam.DEFAULT)
512              final ConcatSourcesParam concatSrcs,
513          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
514              final BufferSizeParam bufferSize
515          ) throws IOException, InterruptedException {
516    
517        init(ugi, delegation, username, doAsUser, path, op, concatSrcs, bufferSize);
518    
519        return ugi.doAs(new PrivilegedExceptionAction<Response>() {
520          @Override
521          public Response run() throws IOException, URISyntaxException {
522            REMOTE_ADDRESS.set(request.getRemoteAddr());
523            try {
524              return post(ugi, delegation, username, doAsUser,
525                  path.getAbsolutePath(), op, concatSrcs, bufferSize);
526            } finally {
527              REMOTE_ADDRESS.set(null);
528            }
529          }
530        });
531      }
532    
533      private Response post(
534          final UserGroupInformation ugi,
535          final DelegationParam delegation,
536          final UserParam username,
537          final DoAsParam doAsUser,
538          final String fullpath,
539          final PostOpParam op,
540          final ConcatSourcesParam concatSrcs,
541          final BufferSizeParam bufferSize
542          ) throws IOException, URISyntaxException {
543        final NameNode namenode = (NameNode)context.getAttribute("name.node");
544    
545        switch(op.getValue()) {
546        case APPEND:
547        {
548          final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser,
549              fullpath, op.getValue(), -1L, -1L, bufferSize);
550          return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
551        }
552        case CONCAT:
553        {
554          namenode.getRpcServer().concat(fullpath, concatSrcs.getAbsolutePaths());
555          return Response.ok().build();
556        }
557        default:
558          throw new UnsupportedOperationException(op + " is not supported");
559        }
560      }
561    
562      /** Handle HTTP GET request for the root. */
563      @GET
564      @Path("/")
565      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
566      public Response getRoot(
567          @Context final UserGroupInformation ugi,
568          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
569              final DelegationParam delegation,
570          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
571              final UserParam username,
572          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
573              final DoAsParam doAsUser,
574          @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
575              final GetOpParam op,
576          @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
577              final OffsetParam offset,
578          @QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
579              final LengthParam length,
580          @QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
581              final RenewerParam renewer,
582          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
583              final BufferSizeParam bufferSize
584          ) throws IOException, InterruptedException {
585        return get(ugi, delegation, username, doAsUser, ROOT, op,
586            offset, length, renewer, bufferSize);
587      }
588    
589      /** Handle HTTP GET request. */
590      @GET
591      @Path("{" + UriFsPathParam.NAME + ":.*}")
592      @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
593      public Response get(
594          @Context final UserGroupInformation ugi,
595          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
596              final DelegationParam delegation,
597          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
598              final UserParam username,
599          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
600              final DoAsParam doAsUser,
601          @PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
602          @QueryParam(GetOpParam.NAME) @DefaultValue(GetOpParam.DEFAULT)
603              final GetOpParam op,
604          @QueryParam(OffsetParam.NAME) @DefaultValue(OffsetParam.DEFAULT)
605              final OffsetParam offset,
606          @QueryParam(LengthParam.NAME) @DefaultValue(LengthParam.DEFAULT)
607              final LengthParam length,
608          @QueryParam(RenewerParam.NAME) @DefaultValue(RenewerParam.DEFAULT)
609              final RenewerParam renewer,
610          @QueryParam(BufferSizeParam.NAME) @DefaultValue(BufferSizeParam.DEFAULT)
611              final BufferSizeParam bufferSize
612          ) throws IOException, InterruptedException {
613    
614        init(ugi, delegation, username, doAsUser, path, op,
615            offset, length, renewer, bufferSize);
616    
617        return ugi.doAs(new PrivilegedExceptionAction<Response>() {
618          @Override
619          public Response run() throws IOException, URISyntaxException {
620            REMOTE_ADDRESS.set(request.getRemoteAddr());
621            try {
622              return get(ugi, delegation, username, doAsUser,
623                  path.getAbsolutePath(), op, offset, length, renewer, bufferSize);
624            } finally {
625              REMOTE_ADDRESS.set(null);
626            }
627          }
628        });
629      }
630    
631      private Response get(
632          final UserGroupInformation ugi,
633          final DelegationParam delegation,
634          final UserParam username,
635          final DoAsParam doAsUser,
636          final String fullpath,
637          final GetOpParam op,
638          final OffsetParam offset,
639          final LengthParam length,
640          final RenewerParam renewer,
641          final BufferSizeParam bufferSize
642          ) throws IOException, URISyntaxException {
643        final NameNode namenode = (NameNode)context.getAttribute("name.node");
644        final NamenodeProtocols np = namenode.getRpcServer();
645    
646        switch(op.getValue()) {
647        case OPEN:
648        {
649          final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser,
650              fullpath, op.getValue(), offset.getValue(), -1L, offset, length, bufferSize);
651          return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
652        }
653        case GET_BLOCK_LOCATIONS:
654        {
655          final long offsetValue = offset.getValue();
656          final Long lengthValue = length.getValue();
657          final LocatedBlocks locatedblocks = np.getBlockLocations(fullpath,
658              offsetValue, lengthValue != null? lengthValue: Long.MAX_VALUE);
659          final String js = JsonUtil.toJsonString(locatedblocks);
660          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
661        }
662        case GETFILESTATUS:
663        {
664          final HdfsFileStatus status = np.getFileInfo(fullpath);
665          if (status == null) {
666            throw new FileNotFoundException("File does not exist: " + fullpath);
667          }
668    
669          final String js = JsonUtil.toJsonString(status, true);
670          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
671        }
672        case LISTSTATUS:
673        {
674          final StreamingOutput streaming = getListingStream(np, fullpath);
675          return Response.ok(streaming).type(MediaType.APPLICATION_JSON).build();
676        }
677        case GETCONTENTSUMMARY:
678        {
679          final ContentSummary contentsummary = np.getContentSummary(fullpath);
680          final String js = JsonUtil.toJsonString(contentsummary);
681          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
682        }
683        case GETFILECHECKSUM:
684        {
685          final URI uri = redirectURI(namenode, ugi, delegation, username, doAsUser,
686              fullpath, op.getValue(), -1L, -1L);
687          return Response.temporaryRedirect(uri).type(MediaType.APPLICATION_OCTET_STREAM).build();
688        }
689        case GETDELEGATIONTOKEN:
690        {
691          if (delegation.getValue() != null) {
692            throw new IllegalArgumentException(delegation.getName()
693                + " parameter is not null.");
694          }
695          final Token<? extends TokenIdentifier> token = generateDelegationToken(
696              namenode, ugi, renewer.getValue());
697          final String js = JsonUtil.toJsonString(token);
698          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
699        }
700        case GETHOMEDIRECTORY:
701        {
702          final String js = JsonUtil.toJsonString(
703              org.apache.hadoop.fs.Path.class.getSimpleName(),
704              WebHdfsFileSystem.getHomeDirectoryString(ugi));
705          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
706        }
707        default:
708          throw new UnsupportedOperationException(op + " is not supported");
709        }
710      }
711    
712      private static DirectoryListing getDirectoryListing(final NamenodeProtocols np,
713          final String p, byte[] startAfter) throws IOException {
714        final DirectoryListing listing = np.getListing(p, startAfter, false);
715        if (listing == null) { // the directory does not exist
716          throw new FileNotFoundException("File " + p + " does not exist.");
717        }
718        return listing;
719      }
720      
721      private static StreamingOutput getListingStream(final NamenodeProtocols np, 
722          final String p) throws IOException {
723        final DirectoryListing first = getDirectoryListing(np, p,
724            HdfsFileStatus.EMPTY_NAME);
725    
726        return new StreamingOutput() {
727          @Override
728          public void write(final OutputStream outstream) throws IOException {
729            final PrintWriter out = new PrintWriter(new OutputStreamWriter(
730                outstream, Charsets.UTF_8));
731            out.println("{\"" + FileStatus.class.getSimpleName() + "es\":{\""
732                + FileStatus.class.getSimpleName() + "\":[");
733    
734            final HdfsFileStatus[] partial = first.getPartialListing();
735            if (partial.length > 0) {
736              out.print(JsonUtil.toJsonString(partial[0], false));
737            }
738            for(int i = 1; i < partial.length; i++) {
739              out.println(',');
740              out.print(JsonUtil.toJsonString(partial[i], false));
741            }
742    
743            for(DirectoryListing curr = first; curr.hasMore(); ) { 
744              curr = getDirectoryListing(np, p, curr.getLastName());
745              for(HdfsFileStatus s : curr.getPartialListing()) {
746                out.println(',');
747                out.print(JsonUtil.toJsonString(s, false));
748              }
749            }
750            
751            out.println();
752            out.println("]}}");
753            out.flush();
754          }
755        };
756      }
757    
758      /** Handle HTTP DELETE request for the root. */
759      @DELETE
760      @Path("/")
761      @Produces(MediaType.APPLICATION_JSON)
762      public Response deleteRoot(
763          @Context final UserGroupInformation ugi,
764          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
765              final DelegationParam delegation,
766          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
767              final UserParam username,
768          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
769              final DoAsParam doAsUser,
770          @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
771              final DeleteOpParam op,
772          @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
773              final RecursiveParam recursive
774          ) throws IOException, InterruptedException {
775        return delete(ugi, delegation, username, doAsUser, ROOT, op, recursive);
776      }
777    
778      /** Handle HTTP DELETE request. */
779      @DELETE
780      @Path("{" + UriFsPathParam.NAME + ":.*}")
781      @Produces(MediaType.APPLICATION_JSON)
782      public Response delete(
783          @Context final UserGroupInformation ugi,
784          @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT)
785              final DelegationParam delegation,
786          @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT)
787              final UserParam username,
788          @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT)
789              final DoAsParam doAsUser,
790          @PathParam(UriFsPathParam.NAME) final UriFsPathParam path,
791          @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT)
792              final DeleteOpParam op,
793          @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT)
794              final RecursiveParam recursive
795          ) throws IOException, InterruptedException {
796    
797        init(ugi, delegation, username, doAsUser, path, op, recursive);
798    
799        return ugi.doAs(new PrivilegedExceptionAction<Response>() {
800          @Override
801          public Response run() throws IOException {
802            REMOTE_ADDRESS.set(request.getRemoteAddr());
803            try {
804              return delete(ugi, delegation, username, doAsUser,
805                  path.getAbsolutePath(), op, recursive);
806            } finally {
807              REMOTE_ADDRESS.set(null);
808            }
809          }
810        });
811      }
812    
813      private Response delete(
814          final UserGroupInformation ugi,
815          final DelegationParam delegation,
816          final UserParam username,
817          final DoAsParam doAsUser,
818          final String fullpath,
819          final DeleteOpParam op,
820          final RecursiveParam recursive
821          ) throws IOException {
822        final NameNode namenode = (NameNode)context.getAttribute("name.node");
823    
824        switch(op.getValue()) {
825        case DELETE:
826        {
827          final boolean b = namenode.getRpcServer().delete(fullpath, recursive.getValue());
828          final String js = JsonUtil.toJsonString("boolean", b);
829          return Response.ok(js).type(MediaType.APPLICATION_JSON).build();
830        }
831        default:
832          throw new UnsupportedOperationException(op + " is not supported");
833        }
834      }
835    }