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;
019    
020    import static org.apache.hadoop.hdfs.server.common.Util.now;
021    
022    import java.io.Closeable;
023    import java.io.FileNotFoundException;
024    import java.io.IOException;
025    import java.util.ArrayList;
026    import java.util.List;
027    import java.util.concurrent.TimeUnit;
028    import java.util.concurrent.locks.Condition;
029    import java.util.concurrent.locks.ReentrantReadWriteLock;
030    
031    import org.apache.hadoop.conf.Configuration;
032    import org.apache.hadoop.fs.ContentSummary;
033    import org.apache.hadoop.fs.FileAlreadyExistsException;
034    import org.apache.hadoop.fs.Options;
035    import org.apache.hadoop.fs.Options.Rename;
036    import org.apache.hadoop.fs.ParentNotDirectoryException;
037    import org.apache.hadoop.fs.Path;
038    import org.apache.hadoop.fs.UnresolvedLinkException;
039    import org.apache.hadoop.fs.permission.FsAction;
040    import org.apache.hadoop.fs.permission.FsPermission;
041    import org.apache.hadoop.fs.permission.PermissionStatus;
042    import org.apache.hadoop.hdfs.DFSConfigKeys;
043    import org.apache.hadoop.hdfs.DistributedFileSystem;
044    import org.apache.hadoop.hdfs.protocol.Block;
045    import org.apache.hadoop.hdfs.protocol.ClientProtocol;
046    import org.apache.hadoop.hdfs.protocol.DirectoryListing;
047    import org.apache.hadoop.hdfs.protocol.HdfsConstants;
048    import org.apache.hadoop.hdfs.protocol.FSLimitException;
049    import org.apache.hadoop.hdfs.protocol.FSLimitException.MaxDirectoryItemsExceededException;
050    import org.apache.hadoop.hdfs.protocol.FSLimitException.PathComponentTooLongException;
051    import org.apache.hadoop.hdfs.protocol.HdfsFileStatus;
052    import org.apache.hadoop.hdfs.protocol.HdfsLocatedFileStatus;
053    import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
054    import org.apache.hadoop.hdfs.protocol.QuotaExceededException;
055    import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
056    import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfoUnderConstruction;
057    import org.apache.hadoop.hdfs.server.blockmanagement.BlockManager;
058    import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
059    import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.BlockUCState;
060    import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
061    import org.apache.hadoop.hdfs.util.ByteArray;
062    
063    import com.google.common.annotations.VisibleForTesting;
064    import com.google.common.base.Preconditions;
065    
066    /*************************************************
067     * FSDirectory stores the filesystem directory state.
068     * It handles writing/loading values to disk, and logging
069     * changes as we go.
070     *
071     * It keeps the filename->blockset mapping always-current
072     * and logged to disk.
073     * 
074     *************************************************/
075    public class FSDirectory implements Closeable {
076    
077      INodeDirectoryWithQuota rootDir;
078      FSImage fsImage;  
079      private volatile boolean ready = false;
080      private static final long UNKNOWN_DISK_SPACE = -1;
081      private final int maxComponentLength;
082      private final int maxDirItems;
083      private final int lsLimit;  // max list limit
084    
085      // lock to protect the directory and BlockMap
086      private ReentrantReadWriteLock dirLock;
087      private Condition cond;
088    
089      // utility methods to acquire and release read lock and write lock
090      void readLock() {
091        this.dirLock.readLock().lock();
092      }
093    
094      void readUnlock() {
095        this.dirLock.readLock().unlock();
096      }
097    
098      void writeLock() {
099        this.dirLock.writeLock().lock();
100      }
101    
102      void writeUnlock() {
103        this.dirLock.writeLock().unlock();
104      }
105    
106      boolean hasWriteLock() {
107        return this.dirLock.isWriteLockedByCurrentThread();
108      }
109    
110      boolean hasReadLock() {
111        return this.dirLock.getReadHoldCount() > 0;
112      }
113    
114      /**
115       * Caches frequently used file names used in {@link INode} to reuse 
116       * byte[] objects and reduce heap usage.
117       */
118      private final NameCache<ByteArray> nameCache;
119    
120      /** Access an existing dfs name directory. */
121      FSDirectory(FSNamesystem ns, Configuration conf) throws IOException {
122        this(new FSImage(conf), ns, conf);
123      }
124    
125      FSDirectory(FSImage fsImage, FSNamesystem ns, Configuration conf) {
126        this.dirLock = new ReentrantReadWriteLock(true); // fair
127        this.cond = dirLock.writeLock().newCondition();
128        fsImage.setFSNamesystem(ns);
129        rootDir = new INodeDirectoryWithQuota(INodeDirectory.ROOT_NAME,
130            ns.createFsOwnerPermissions(new FsPermission((short)0755)),
131            Integer.MAX_VALUE, UNKNOWN_DISK_SPACE);
132        this.fsImage = fsImage;
133        int configuredLimit = conf.getInt(
134            DFSConfigKeys.DFS_LIST_LIMIT, DFSConfigKeys.DFS_LIST_LIMIT_DEFAULT);
135        this.lsLimit = configuredLimit>0 ?
136            configuredLimit : DFSConfigKeys.DFS_LIST_LIMIT_DEFAULT;
137        
138        // filesystem limits
139        this.maxComponentLength = conf.getInt(
140            DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_KEY,
141            DFSConfigKeys.DFS_NAMENODE_MAX_COMPONENT_LENGTH_DEFAULT);
142        this.maxDirItems = conf.getInt(
143            DFSConfigKeys.DFS_NAMENODE_MAX_DIRECTORY_ITEMS_KEY,
144            DFSConfigKeys.DFS_NAMENODE_MAX_DIRECTORY_ITEMS_DEFAULT);
145    
146        int threshold = conf.getInt(
147            DFSConfigKeys.DFS_NAMENODE_NAME_CACHE_THRESHOLD_KEY,
148            DFSConfigKeys.DFS_NAMENODE_NAME_CACHE_THRESHOLD_DEFAULT);
149        NameNode.LOG.info("Caching file names occuring more than " + threshold
150            + " times ");
151        nameCache = new NameCache<ByteArray>(threshold);
152      }
153        
154      private FSNamesystem getFSNamesystem() {
155        return fsImage.getFSNamesystem();
156      }
157    
158      private BlockManager getBlockManager() {
159        return getFSNamesystem().getBlockManager();
160      }
161    
162      /**
163       * Load the filesystem image into memory.
164       *
165       * @param startOpt Startup type as specified by the user.
166       * @throws IOException If image or editlog cannot be read.
167       */
168      void loadFSImage(StartupOption startOpt) 
169          throws IOException {
170        // format before starting up if requested
171        if (startOpt == StartupOption.FORMAT) {
172          fsImage.format(fsImage.getStorage().determineClusterId());// reuse current id
173    
174          startOpt = StartupOption.REGULAR;
175        }
176        boolean success = false;
177        try {
178          if (fsImage.recoverTransitionRead(startOpt)) {
179            fsImage.saveNamespace();
180          }
181          fsImage.openEditLog();
182          
183          fsImage.setCheckpointDirectories(null, null);
184          success = true;
185        } finally {
186          if (!success) {
187            fsImage.close();
188          }
189        }
190        setReady();
191      }
192      
193    
194      /**
195       * Notify that loading of this FSDirectory is complete, and
196       * it is ready for use 
197       */
198      void imageLoadComplete() {
199        Preconditions.checkState(!ready, "FSDirectory already loaded");
200        setReady();
201      }
202    
203      void setReady() {
204        if(ready) return;
205        writeLock();
206        try {
207          setReady(true);
208          this.nameCache.initialized();
209          cond.signalAll();
210        } finally {
211          writeUnlock();
212        }
213      }
214      
215      //This is for testing purposes only
216      @VisibleForTesting
217      boolean isReady() {
218        return ready;
219      }
220    
221      // exposed for unit tests
222      protected void setReady(boolean flag) {
223        ready = flag;
224      }
225    
226      private void incrDeletedFileCount(int count) {
227        if (getFSNamesystem() != null)
228          NameNode.getNameNodeMetrics().incrFilesDeleted(count);
229      }
230        
231      /**
232       * Shutdown the filestore
233       */
234      public void close() throws IOException {
235        fsImage.close();
236      }
237    
238      /**
239       * Block until the object is ready to be used.
240       */
241      void waitForReady() {
242        if (!ready) {
243          writeLock();
244          try {
245            while (!ready) {
246              try {
247                cond.await(5000, TimeUnit.MILLISECONDS);
248              } catch (InterruptedException ie) {
249              }
250            }
251          } finally {
252            writeUnlock();
253          }
254        }
255      }
256    
257      /**
258       * Add the given filename to the fs.
259       * @throws QuotaExceededException 
260       * @throws FileAlreadyExistsException 
261       */
262      INodeFileUnderConstruction addFile(String path, 
263                    PermissionStatus permissions,
264                    short replication,
265                    long preferredBlockSize,
266                    String clientName,
267                    String clientMachine,
268                    DatanodeDescriptor clientNode,
269                    long generationStamp) 
270        throws FileAlreadyExistsException, QuotaExceededException,
271          UnresolvedLinkException {
272        waitForReady();
273    
274        // Always do an implicit mkdirs for parent directory tree.
275        long modTime = now();
276        
277        Path parent = new Path(path).getParent();
278        if (parent == null) {
279          // Trying to add "/" as a file - this path has no
280          // parent -- avoids an NPE below.
281          return null;
282        }
283        
284        if (!mkdirs(parent.toString(), permissions, true, modTime)) {
285          return null;
286        }
287        INodeFileUnderConstruction newNode = new INodeFileUnderConstruction(
288                                     permissions,replication,
289                                     preferredBlockSize, modTime, clientName, 
290                                     clientMachine, clientNode);
291        writeLock();
292        try {
293          newNode = addNode(path, newNode, UNKNOWN_DISK_SPACE);
294        } finally {
295          writeUnlock();
296        }
297        if (newNode == null) {
298          NameNode.stateChangeLog.info("DIR* FSDirectory.addFile: "
299                                       +"failed to add "+path
300                                       +" to the file system");
301          return null;
302        }
303    
304        if(NameNode.stateChangeLog.isDebugEnabled()) {
305          NameNode.stateChangeLog.debug("DIR* FSDirectory.addFile: "
306              +path+" is added to the file system");
307        }
308        return newNode;
309      }
310    
311      /**
312       */
313      INode unprotectedAddFile( String path, 
314                                PermissionStatus permissions,
315                                BlockInfo[] blocks, 
316                                short replication,
317                                long modificationTime,
318                                long atime,
319                                long preferredBlockSize,
320                                String clientName,
321                                String clientMachine)
322          throws UnresolvedLinkException {
323        INode newNode;
324        assert hasWriteLock();
325        if (blocks == null)
326          newNode = new INodeDirectory(permissions, modificationTime);
327        else if(blocks.length == 0 || blocks[blocks.length-1].getBlockUCState()
328            == BlockUCState.UNDER_CONSTRUCTION) {
329          newNode = new INodeFileUnderConstruction(
330              permissions, blocks.length, replication,
331              preferredBlockSize, modificationTime, clientName, 
332              clientMachine, null);
333        } else {
334          newNode = new INodeFile(permissions, blocks.length, replication,
335                                  modificationTime, atime, preferredBlockSize);
336        }
337        writeLock();
338        try {
339          try {
340            newNode = addNode(path, newNode, UNKNOWN_DISK_SPACE);
341            if(newNode != null && blocks != null) {
342              int nrBlocks = blocks.length;
343              // Add file->block mapping
344              INodeFile newF = (INodeFile)newNode;
345              for (int i = 0; i < nrBlocks; i++) {
346                newF.setBlock(i, getBlockManager().addINode(blocks[i], newF));
347              }
348            }
349          } catch (IOException e) {
350            return null;
351          }
352          return newNode;
353        } finally {
354          writeUnlock();
355        }
356    
357      }
358    
359      /**
360       * Update files in-memory data structures with new block information.
361       * @throws IOException 
362       */
363      void updateFile(INodeFile file,
364                      String path,
365                      BlockInfo[] blocks, 
366                      long mtime,
367                      long atime) throws IOException {
368    
369        // Update the salient file attributes.
370        file.setAccessTime(atime);
371        file.setModificationTimeForce(mtime);
372    
373        // Update its block list
374        BlockInfo[] oldBlocks = file.getBlocks();
375    
376        // Are we only updating the last block's gen stamp.
377        boolean isGenStampUpdate = oldBlocks.length == blocks.length;
378    
379        // First, update blocks in common
380        BlockInfo oldBlock = null;
381        for (int i = 0; i < oldBlocks.length && i < blocks.length; i++) {
382          oldBlock = oldBlocks[i];
383          Block newBlock = blocks[i];
384    
385          boolean isLastBlock = i == oldBlocks.length - 1;
386          if (oldBlock.getBlockId() != newBlock.getBlockId() ||
387              (oldBlock.getGenerationStamp() != newBlock.getGenerationStamp() && 
388                  !(isGenStampUpdate && isLastBlock))) {
389            throw new IOException("Mismatched block IDs or generation stamps, " + 
390                "attempting to replace block " + oldBlock + " with " + newBlock +
391                " as block # " + i + "/" + blocks.length + " of " + path);
392          }
393    
394          oldBlock.setNumBytes(newBlock.getNumBytes());
395          oldBlock.setGenerationStamp(newBlock.getGenerationStamp());
396        }
397    
398        if (blocks.length < oldBlocks.length) {
399          // We're removing a block from the file, e.g. abandonBlock(...)
400          if (!file.isUnderConstruction()) {
401            throw new IOException("Trying to remove a block from file " +
402                path + " which is not under construction.");
403          }
404          if (blocks.length != oldBlocks.length - 1) {
405            throw new IOException("Trying to remove more than one block from file "
406                + path);
407          }
408          unprotectedRemoveBlock(path,
409              (INodeFileUnderConstruction)file, oldBlocks[oldBlocks.length - 1]);
410        } else if (blocks.length > oldBlocks.length) {
411          // We're adding blocks
412          // First complete last old Block
413          getBlockManager().completeBlock(file, oldBlocks.length-1, true);
414          // Add the new blocks
415          for (int i = oldBlocks.length; i < blocks.length; i++) {
416            // addBlock();
417            BlockInfo newBI = blocks[i];
418            getBlockManager().addINode(newBI, file);
419            file.addBlock(newBI);
420          }
421        }
422      }
423    
424      INodeDirectory addToParent(byte[] src, INodeDirectory parentINode,
425          INode newNode, boolean propagateModTime) throws UnresolvedLinkException {
426        // NOTE: This does not update space counts for parents
427        INodeDirectory newParent = null;
428        writeLock();
429        try {
430          try {
431            newParent = rootDir.addToParent(src, newNode, parentINode,
432                                            propagateModTime);
433            cacheName(newNode);
434          } catch (FileNotFoundException e) {
435            return null;
436          }
437          if(newParent == null)
438            return null;
439          if(!newNode.isDirectory() && !newNode.isLink()) {
440            // Add file->block mapping
441            INodeFile newF = (INodeFile)newNode;
442            BlockInfo[] blocks = newF.getBlocks();
443            for (int i = 0; i < blocks.length; i++) {
444              newF.setBlock(i, getBlockManager().addINode(blocks[i], newF));
445            }
446          }
447        } finally {
448          writeUnlock();
449        }
450        return newParent;
451      }
452    
453      /**
454       * Add a block to the file. Returns a reference to the added block.
455       */
456      BlockInfo addBlock(String path,
457                         INode[] inodes,
458                         Block block,
459                         DatanodeDescriptor targets[]
460      ) throws QuotaExceededException {
461        waitForReady();
462    
463        writeLock();
464        try {
465          assert inodes[inodes.length-1].isUnderConstruction() :
466            "INode should correspond to a file under construction";
467          INodeFileUnderConstruction fileINode = 
468            (INodeFileUnderConstruction)inodes[inodes.length-1];
469    
470          // check quota limits and updated space consumed
471          updateCount(inodes, inodes.length-1, 0,
472              fileINode.getPreferredBlockSize()*fileINode.getReplication(), true);
473    
474          // associate new last block for the file
475          BlockInfoUnderConstruction blockInfo =
476            new BlockInfoUnderConstruction(
477                block,
478                fileINode.getReplication(),
479                BlockUCState.UNDER_CONSTRUCTION,
480                targets);
481          getBlockManager().addINode(blockInfo, fileINode);
482          fileINode.addBlock(blockInfo);
483    
484          if(NameNode.stateChangeLog.isDebugEnabled()) {
485            NameNode.stateChangeLog.debug("DIR* FSDirectory.addBlock: "
486                + path + " with " + block
487                + " block is added to the in-memory "
488                + "file system");
489          }
490          return blockInfo;
491        } finally {
492          writeUnlock();
493        }
494      }
495    
496      /**
497       * Persist the block list for the inode.
498       */
499      void persistBlocks(String path, INodeFileUnderConstruction file) {
500        waitForReady();
501    
502        writeLock();
503        try {
504          fsImage.getEditLog().logOpenFile(path, file);
505          if(NameNode.stateChangeLog.isDebugEnabled()) {
506            NameNode.stateChangeLog.debug("DIR* FSDirectory.persistBlocks: "
507                +path+" with "+ file.getBlocks().length 
508                +" blocks is persisted to the file system");
509          }
510        } finally {
511          writeUnlock();
512        }
513      }
514    
515      /**
516       * Close file.
517       */
518      void closeFile(String path, INodeFile file) {
519        waitForReady();
520        long now = now();
521        writeLock();
522        try {
523          // file is closed
524          file.setModificationTimeForce(now);
525          fsImage.getEditLog().logCloseFile(path, file);
526          if (NameNode.stateChangeLog.isDebugEnabled()) {
527            NameNode.stateChangeLog.debug("DIR* FSDirectory.closeFile: "
528                +path+" with "+ file.getBlocks().length 
529                +" blocks is persisted to the file system");
530          }
531        } finally {
532          writeUnlock();
533        }
534      }
535    
536      /**
537       * Remove a block to the file.
538       */
539      boolean removeBlock(String path, INodeFileUnderConstruction fileNode, 
540                          Block block) throws IOException {
541        waitForReady();
542    
543        writeLock();
544        try {
545          unprotectedRemoveBlock(path, fileNode, block);
546          // write modified block locations to log
547          fsImage.getEditLog().logOpenFile(path, fileNode);
548        } finally {
549          writeUnlock();
550        }
551        return true;
552      }
553    
554      void unprotectedRemoveBlock(String path, INodeFileUnderConstruction fileNode, 
555          Block block) throws IOException {
556        // modify file-> block and blocksMap
557        fileNode.removeLastBlock(block);
558        getBlockManager().removeBlockFromMap(block);
559    
560        if(NameNode.stateChangeLog.isDebugEnabled()) {
561          NameNode.stateChangeLog.debug("DIR* FSDirectory.removeBlock: "
562              +path+" with "+block
563              +" block is removed from the file system");
564        }
565    
566        // update space consumed
567        INode[] pathINodes = getExistingPathINodes(path);
568        updateCount(pathINodes, pathINodes.length-1, 0,
569            -fileNode.getPreferredBlockSize()*fileNode.getReplication(), true);
570      }
571    
572      /**
573       * @see #unprotectedRenameTo(String, String, long)
574       * @deprecated Use {@link #renameTo(String, String, Rename...)} instead.
575       */
576      @Deprecated
577      boolean renameTo(String src, String dst) 
578          throws QuotaExceededException, UnresolvedLinkException, 
579          FileAlreadyExistsException {
580        if (NameNode.stateChangeLog.isDebugEnabled()) {
581          NameNode.stateChangeLog.debug("DIR* FSDirectory.renameTo: "
582              +src+" to "+dst);
583        }
584        waitForReady();
585        long now = now();
586        writeLock();
587        try {
588          if (!unprotectedRenameTo(src, dst, now))
589            return false;
590        } finally {
591          writeUnlock();
592        }
593        fsImage.getEditLog().logRename(src, dst, now);
594        return true;
595      }
596    
597      /**
598       * @see #unprotectedRenameTo(String, String, long, Options.Rename...)
599       */
600      void renameTo(String src, String dst, Options.Rename... options)
601          throws FileAlreadyExistsException, FileNotFoundException,
602          ParentNotDirectoryException, QuotaExceededException,
603          UnresolvedLinkException, IOException {
604        if (NameNode.stateChangeLog.isDebugEnabled()) {
605          NameNode.stateChangeLog.debug("DIR* FSDirectory.renameTo: " + src
606              + " to " + dst);
607        }
608        waitForReady();
609        long now = now();
610        writeLock();
611        try {
612          if (unprotectedRenameTo(src, dst, now, options)) {
613            incrDeletedFileCount(1);
614          }
615        } finally {
616          writeUnlock();
617        }
618        fsImage.getEditLog().logRename(src, dst, now, options);
619      }
620    
621      /**
622       * Change a path name
623       * 
624       * @param src source path
625       * @param dst destination path
626       * @return true if rename succeeds; false otherwise
627       * @throws QuotaExceededException if the operation violates any quota limit
628       * @throws FileAlreadyExistsException if the src is a symlink that points to dst
629       * @deprecated See {@link #renameTo(String, String)}
630       */
631      @Deprecated
632      boolean unprotectedRenameTo(String src, String dst, long timestamp)
633        throws QuotaExceededException, UnresolvedLinkException, 
634        FileAlreadyExistsException {
635        assert hasWriteLock();
636        INode[] srcInodes = rootDir.getExistingPathINodes(src, false);
637        INode srcInode = srcInodes[srcInodes.length-1];
638        
639        // check the validation of the source
640        if (srcInode == null) {
641          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
642              + "failed to rename " + src + " to " + dst
643              + " because source does not exist");
644          return false;
645        } 
646        if (srcInodes.length == 1) {
647          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
648              +"failed to rename "+src+" to "+dst+ " because source is the root");
649          return false;
650        }
651        if (isDir(dst)) {
652          dst += Path.SEPARATOR + new Path(src).getName();
653        }
654        
655        // check the validity of the destination
656        if (dst.equals(src)) {
657          return true;
658        }
659        if (srcInode.isLink() && 
660            dst.equals(((INodeSymlink)srcInode).getLinkValue())) {
661          throw new FileAlreadyExistsException(
662              "Cannot rename symlink "+src+" to its target "+dst);
663        }
664        
665        // dst cannot be directory or a file under src
666        if (dst.startsWith(src) && 
667            dst.charAt(src.length()) == Path.SEPARATOR_CHAR) {
668          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
669              + "failed to rename " + src + " to " + dst
670              + " because destination starts with src");
671          return false;
672        }
673        
674        byte[][] dstComponents = INode.getPathComponents(dst);
675        INode[] dstInodes = new INode[dstComponents.length];
676        rootDir.getExistingPathINodes(dstComponents, dstInodes, false);
677        if (dstInodes[dstInodes.length-1] != null) {
678          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
679                                       +"failed to rename "+src+" to "+dst+ 
680                                       " because destination exists");
681          return false;
682        }
683        if (dstInodes[dstInodes.length-2] == null) {
684          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
685              +"failed to rename "+src+" to "+dst+ 
686              " because destination's parent does not exist");
687          return false;
688        }
689        
690        // Ensure dst has quota to accommodate rename
691        verifyQuotaForRename(srcInodes,dstInodes);
692        
693        INode dstChild = null;
694        INode srcChild = null;
695        String srcChildName = null;
696        try {
697          // remove src
698          srcChild = removeChild(srcInodes, srcInodes.length-1);
699          if (srcChild == null) {
700            NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
701                + "failed to rename " + src + " to " + dst
702                + " because the source can not be removed");
703            return false;
704          }
705          srcChildName = srcChild.getLocalName();
706          srcChild.setLocalName(dstComponents[dstInodes.length-1]);
707          
708          // add src to the destination
709          dstChild = addChildNoQuotaCheck(dstInodes, dstInodes.length - 1,
710              srcChild, UNKNOWN_DISK_SPACE);
711          if (dstChild != null) {
712            srcChild = null;
713            if (NameNode.stateChangeLog.isDebugEnabled()) {
714              NameNode.stateChangeLog.debug("DIR* FSDirectory.unprotectedRenameTo: " 
715                  + src + " is renamed to " + dst);
716            }
717            // update modification time of dst and the parent of src
718            srcInodes[srcInodes.length-2].setModificationTime(timestamp);
719            dstInodes[dstInodes.length-2].setModificationTime(timestamp);
720            // update moved leases with new filename
721            getFSNamesystem().unprotectedChangeLease(src, dst);        
722            return true;
723          }
724        } finally {
725          if (dstChild == null && srcChild != null) {
726            // put it back
727            srcChild.setLocalName(srcChildName);
728            addChildNoQuotaCheck(srcInodes, srcInodes.length - 1, srcChild, 
729                UNKNOWN_DISK_SPACE);
730          }
731        }
732        NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
733            +"failed to rename "+src+" to "+dst);
734        return false;
735      }
736    
737      /**
738       * Rename src to dst.
739       * See {@link DistributedFileSystem#rename(Path, Path, Options.Rename...)}
740       * for details related to rename semantics and exceptions.
741       * 
742       * @param src source path
743       * @param dst destination path
744       * @param timestamp modification time
745       * @param options Rename options
746       */
747      boolean unprotectedRenameTo(String src, String dst, long timestamp,
748          Options.Rename... options) throws FileAlreadyExistsException,
749          FileNotFoundException, ParentNotDirectoryException,
750          QuotaExceededException, UnresolvedLinkException, IOException {
751        assert hasWriteLock();
752        boolean overwrite = false;
753        if (null != options) {
754          for (Rename option : options) {
755            if (option == Rename.OVERWRITE) {
756              overwrite = true;
757            }
758          }
759        }
760        String error = null;
761        final INode[] srcInodes = rootDir.getExistingPathINodes(src, false);
762        final INode srcInode = srcInodes[srcInodes.length - 1];
763        // validate source
764        if (srcInode == null) {
765          error = "rename source " + src + " is not found.";
766          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
767              + error);
768          throw new FileNotFoundException(error);
769        }
770        if (srcInodes.length == 1) {
771          error = "rename source cannot be the root";
772          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
773              + error);
774          throw new IOException(error);
775        }
776    
777        // validate the destination
778        if (dst.equals(src)) {
779          throw new FileAlreadyExistsException(
780              "The source "+src+" and destination "+dst+" are the same");
781        }
782        if (srcInode.isLink() && 
783            dst.equals(((INodeSymlink)srcInode).getLinkValue())) {
784          throw new FileAlreadyExistsException(
785              "Cannot rename symlink "+src+" to its target "+dst);
786        }
787        // dst cannot be a directory or a file under src
788        if (dst.startsWith(src) && 
789            dst.charAt(src.length()) == Path.SEPARATOR_CHAR) {
790          error = "Rename destination " + dst
791              + " is a directory or file under source " + src;
792          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
793              + error);
794          throw new IOException(error);
795        }
796        final byte[][] dstComponents = INode.getPathComponents(dst);
797        final INode[] dstInodes = new INode[dstComponents.length];
798        rootDir.getExistingPathINodes(dstComponents, dstInodes, false);
799        INode dstInode = dstInodes[dstInodes.length - 1];
800        if (dstInodes.length == 1) {
801          error = "rename destination cannot be the root";
802          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
803              + error);
804          throw new IOException(error);
805        }
806        if (dstInode != null) { // Destination exists
807          // It's OK to rename a file to a symlink and vice versa
808          if (dstInode.isDirectory() != srcInode.isDirectory()) {
809            error = "Source " + src + " and destination " + dst
810                + " must both be directories";
811            NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
812                + error);
813            throw new IOException(error);
814          }
815          if (!overwrite) { // If destination exists, overwrite flag must be true
816            error = "rename destination " + dst + " already exists";
817            NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
818                + error);
819            throw new FileAlreadyExistsException(error);
820          }
821          List<INode> children = dstInode.isDirectory() ? 
822              ((INodeDirectory) dstInode).getChildrenRaw() : null;
823          if (children != null && children.size() != 0) {
824            error = "rename cannot overwrite non empty destination directory "
825                + dst;
826            NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
827                + error);
828            throw new IOException(error);
829          }
830        }
831        if (dstInodes[dstInodes.length - 2] == null) {
832          error = "rename destination parent " + dst + " not found.";
833          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
834              + error);
835          throw new FileNotFoundException(error);
836        }
837        if (!dstInodes[dstInodes.length - 2].isDirectory()) {
838          error = "rename destination parent " + dst + " is a file.";
839          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
840              + error);
841          throw new ParentNotDirectoryException(error);
842        }
843    
844        // Ensure dst has quota to accommodate rename
845        verifyQuotaForRename(srcInodes, dstInodes);
846        INode removedSrc = removeChild(srcInodes, srcInodes.length - 1);
847        if (removedSrc == null) {
848          error = "Failed to rename " + src + " to " + dst
849              + " because the source can not be removed";
850          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
851              + error);
852          throw new IOException(error);
853        }
854        final String srcChildName = removedSrc.getLocalName();
855        String dstChildName = null;
856        INode removedDst = null;
857        try {
858          if (dstInode != null) { // dst exists remove it
859            removedDst = removeChild(dstInodes, dstInodes.length - 1);
860            dstChildName = removedDst.getLocalName();
861          }
862    
863          INode dstChild = null;
864          removedSrc.setLocalName(dstComponents[dstInodes.length - 1]);
865          // add src as dst to complete rename
866          dstChild = addChildNoQuotaCheck(dstInodes, dstInodes.length - 1,
867              removedSrc, UNKNOWN_DISK_SPACE);
868    
869          int filesDeleted = 0;
870          if (dstChild != null) {
871            removedSrc = null;
872            if (NameNode.stateChangeLog.isDebugEnabled()) {
873              NameNode.stateChangeLog.debug(
874                  "DIR* FSDirectory.unprotectedRenameTo: " + src
875                  + " is renamed to " + dst);
876            }
877            srcInodes[srcInodes.length - 2].setModificationTime(timestamp);
878            dstInodes[dstInodes.length - 2].setModificationTime(timestamp);
879            // update moved lease with new filename
880            getFSNamesystem().unprotectedChangeLease(src, dst);
881    
882            // Collect the blocks and remove the lease for previous dst
883            if (removedDst != null) {
884              INode rmdst = removedDst;
885              removedDst = null;
886              List<Block> collectedBlocks = new ArrayList<Block>();
887              filesDeleted = rmdst.collectSubtreeBlocksAndClear(collectedBlocks);
888              getFSNamesystem().removePathAndBlocks(src, collectedBlocks);
889            }
890            return filesDeleted >0;
891          }
892        } finally {
893          if (removedSrc != null) {
894            // Rename failed - restore src
895            removedSrc.setLocalName(srcChildName);
896            addChildNoQuotaCheck(srcInodes, srcInodes.length - 1, removedSrc, 
897                UNKNOWN_DISK_SPACE);
898          }
899          if (removedDst != null) {
900            // Rename failed - restore dst
901            removedDst.setLocalName(dstChildName);
902            addChildNoQuotaCheck(dstInodes, dstInodes.length - 1, removedDst, 
903                UNKNOWN_DISK_SPACE);
904          }
905        }
906        NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedRenameTo: "
907            + "failed to rename " + src + " to " + dst);
908        throw new IOException("rename from " + src + " to " + dst + " failed.");
909      }
910    
911      /**
912       * Set file replication
913       * 
914       * @param src file name
915       * @param replication new replication
916       * @param oldReplication old replication - output parameter
917       * @return array of file blocks
918       * @throws QuotaExceededException
919       */
920      Block[] setReplication(String src, short replication, short[] oldReplication)
921          throws QuotaExceededException, UnresolvedLinkException {
922        waitForReady();
923        Block[] fileBlocks = null;
924        writeLock();
925        try {
926          fileBlocks = unprotectedSetReplication(src, replication, oldReplication);
927          if (fileBlocks != null)  // log replication change
928            fsImage.getEditLog().logSetReplication(src, replication);
929          return fileBlocks;
930        } finally {
931          writeUnlock();
932        }
933      }
934    
935      Block[] unprotectedSetReplication(String src, 
936                                        short replication,
937                                        short[] oldReplication
938                                        ) throws QuotaExceededException, 
939                                        UnresolvedLinkException {
940        assert hasWriteLock();
941    
942        INode[] inodes = rootDir.getExistingPathINodes(src, true);
943        INode inode = inodes[inodes.length - 1];
944        if (inode == null) {
945          return null;
946        }
947        assert !inode.isLink();
948        if (inode.isDirectory()) {
949          return null;
950        }
951        INodeFile fileNode = (INodeFile)inode;
952        final short oldRepl = fileNode.getReplication();
953    
954        // check disk quota
955        long dsDelta = (replication - oldRepl) * (fileNode.diskspaceConsumed()/oldRepl);
956        updateCount(inodes, inodes.length-1, 0, dsDelta, true);
957    
958        fileNode.setReplication(replication);
959    
960        if (oldReplication != null) {
961          oldReplication[0] = oldRepl;
962        }
963        return fileNode.getBlocks();
964      }
965    
966      /**
967       * Get the blocksize of a file
968       * @param filename the filename
969       * @return the number of bytes 
970       */
971      long getPreferredBlockSize(String filename) throws UnresolvedLinkException,
972          FileNotFoundException, IOException {
973        readLock();
974        try {
975          INode inode = rootDir.getNode(filename, false);
976          if (inode == null) {
977            throw new FileNotFoundException("File does not exist: " + filename);
978          }
979          if (inode.isDirectory() || inode.isLink()) {
980            throw new IOException("Getting block size of non-file: "+ filename); 
981          }
982          return ((INodeFile)inode).getPreferredBlockSize();
983        } finally {
984          readUnlock();
985        }
986      }
987    
988      boolean exists(String src) throws UnresolvedLinkException {
989        src = normalizePath(src);
990        readLock();
991        try {
992          INode inode = rootDir.getNode(src, false);
993          if (inode == null) {
994             return false;
995          }
996          return inode.isDirectory() || inode.isLink() 
997            ? true 
998            : ((INodeFile)inode).getBlocks() != null;
999        } finally {
1000          readUnlock();
1001        }
1002      }
1003    
1004      void setPermission(String src, FsPermission permission)
1005          throws FileNotFoundException, UnresolvedLinkException {
1006        writeLock();
1007        try {
1008          unprotectedSetPermission(src, permission);
1009        } finally {
1010          writeUnlock();
1011        }
1012        fsImage.getEditLog().logSetPermissions(src, permission);
1013      }
1014    
1015      void unprotectedSetPermission(String src, FsPermission permissions) 
1016          throws FileNotFoundException, UnresolvedLinkException {
1017        assert hasWriteLock();
1018        INode inode = rootDir.getNode(src, true);
1019        if (inode == null) {
1020          throw new FileNotFoundException("File does not exist: " + src);
1021        }
1022        inode.setPermission(permissions);
1023      }
1024    
1025      void setOwner(String src, String username, String groupname)
1026          throws FileNotFoundException, UnresolvedLinkException {
1027        writeLock();
1028        try {
1029          unprotectedSetOwner(src, username, groupname);
1030        } finally {
1031          writeUnlock();
1032        }
1033        fsImage.getEditLog().logSetOwner(src, username, groupname);
1034      }
1035    
1036      void unprotectedSetOwner(String src, String username, String groupname) 
1037          throws FileNotFoundException, UnresolvedLinkException {
1038        assert hasWriteLock();
1039        INode inode = rootDir.getNode(src, true);
1040        if (inode == null) {
1041          throw new FileNotFoundException("File does not exist: " + src);
1042        }
1043        if (username != null) {
1044          inode.setUser(username);
1045        }
1046        if (groupname != null) {
1047          inode.setGroup(groupname);
1048        }
1049      }
1050    
1051      /**
1052       * Concat all the blocks from srcs to trg and delete the srcs files
1053       */
1054      public void concat(String target, String [] srcs) 
1055          throws UnresolvedLinkException {
1056        writeLock();
1057        try {
1058          // actual move
1059          waitForReady();
1060          long timestamp = now();
1061          unprotectedConcat(target, srcs, timestamp);
1062          // do the commit
1063          fsImage.getEditLog().logConcat(target, srcs, timestamp);
1064        } finally {
1065          writeUnlock();
1066        }
1067      }
1068      
1069    
1070      
1071      /**
1072       * Concat all the blocks from srcs to trg and delete the srcs files
1073       * @param target target file to move the blocks to
1074       * @param srcs list of file to move the blocks from
1075       * Must be public because also called from EditLogs
1076       * NOTE: - it does not update quota (not needed for concat)
1077       */
1078      public void unprotectedConcat(String target, String [] srcs, long timestamp) 
1079          throws UnresolvedLinkException {
1080        assert hasWriteLock();
1081        if (NameNode.stateChangeLog.isDebugEnabled()) {
1082          NameNode.stateChangeLog.debug("DIR* FSNamesystem.concat to "+target);
1083        }
1084        // do the move
1085        
1086        INode [] trgINodes =  getExistingPathINodes(target);
1087        INodeFile trgInode = (INodeFile) trgINodes[trgINodes.length-1];
1088        INodeDirectory trgParent = (INodeDirectory)trgINodes[trgINodes.length-2];
1089        
1090        INodeFile [] allSrcInodes = new INodeFile[srcs.length];
1091        int i = 0;
1092        int totalBlocks = 0;
1093        for(String src : srcs) {
1094          INodeFile srcInode = getFileINode(src);
1095          allSrcInodes[i++] = srcInode;
1096          totalBlocks += srcInode.blocks.length;  
1097        }
1098        trgInode.appendBlocks(allSrcInodes, totalBlocks); // copy the blocks
1099        
1100        // since we are in the same dir - we can use same parent to remove files
1101        int count = 0;
1102        for(INodeFile nodeToRemove: allSrcInodes) {
1103          if(nodeToRemove == null) continue;
1104          
1105          nodeToRemove.blocks = null;
1106          trgParent.removeChild(nodeToRemove);
1107          count++;
1108        }
1109        
1110        trgInode.setModificationTimeForce(timestamp);
1111        trgParent.setModificationTime(timestamp);
1112        // update quota on the parent directory ('count' files removed, 0 space)
1113        unprotectedUpdateCount(trgINodes, trgINodes.length-1, - count, 0);
1114      }
1115    
1116      /**
1117       * Delete the target directory and collect the blocks under it
1118       * 
1119       * @param src Path of a directory to delete
1120       * @param collectedBlocks Blocks under the deleted directory
1121       * @return true on successful deletion; else false
1122       */
1123      boolean delete(String src, List<Block>collectedBlocks) 
1124        throws UnresolvedLinkException {
1125        if (NameNode.stateChangeLog.isDebugEnabled()) {
1126          NameNode.stateChangeLog.debug("DIR* FSDirectory.delete: " + src);
1127        }
1128        waitForReady();
1129        long now = now();
1130        int filesRemoved;
1131        writeLock();
1132        try {
1133          filesRemoved = unprotectedDelete(src, collectedBlocks, now);
1134        } finally {
1135          writeUnlock();
1136        }
1137        if (filesRemoved <= 0) {
1138          return false;
1139        }
1140        incrDeletedFileCount(filesRemoved);
1141        // Blocks will be deleted later by the caller of this method
1142        getFSNamesystem().removePathAndBlocks(src, null);
1143        fsImage.getEditLog().logDelete(src, now);
1144        return true;
1145      }
1146      
1147      /** Return if a directory is empty or not **/
1148      boolean isDirEmpty(String src) throws UnresolvedLinkException {
1149        boolean dirNotEmpty = true;
1150        if (!isDir(src)) {
1151          return true;
1152        }
1153        readLock();
1154        try {
1155          INode targetNode = rootDir.getNode(src, false);
1156          assert targetNode != null : "should be taken care in isDir() above";
1157          if (((INodeDirectory)targetNode).getChildren().size() != 0) {
1158            dirNotEmpty = false;
1159          }
1160        } finally {
1161          readUnlock();
1162        }
1163        return dirNotEmpty;
1164      }
1165    
1166      boolean isEmpty() {
1167        try {
1168          return isDirEmpty("/");
1169        } catch (UnresolvedLinkException e) {
1170          if(NameNode.stateChangeLog.isDebugEnabled()) {
1171            NameNode.stateChangeLog.debug("/ cannot be a symlink");
1172          }
1173          assert false : "/ cannot be a symlink";
1174          return true;
1175        }
1176      }
1177    
1178      /**
1179       * Delete a path from the name space
1180       * Update the count at each ancestor directory with quota
1181       * <br>
1182       * Note: This is to be used by {@link FSEditLog} only.
1183       * <br>
1184       * @param src a string representation of a path to an inode
1185       * @param mtime the time the inode is removed
1186       */ 
1187      void unprotectedDelete(String src, long mtime) 
1188        throws UnresolvedLinkException {
1189        assert hasWriteLock();
1190        List<Block> collectedBlocks = new ArrayList<Block>();
1191        int filesRemoved = unprotectedDelete(src, collectedBlocks, mtime);
1192        if (filesRemoved > 0) {
1193          getFSNamesystem().removePathAndBlocks(src, collectedBlocks);
1194        }
1195      }
1196      
1197      /**
1198       * Delete a path from the name space
1199       * Update the count at each ancestor directory with quota
1200       * @param src a string representation of a path to an inode
1201       * @param collectedBlocks blocks collected from the deleted path
1202       * @param mtime the time the inode is removed
1203       * @return the number of inodes deleted; 0 if no inodes are deleted.
1204       */ 
1205      int unprotectedDelete(String src, List<Block> collectedBlocks, 
1206          long mtime) throws UnresolvedLinkException {
1207        assert hasWriteLock();
1208        src = normalizePath(src);
1209    
1210        INode[] inodes =  rootDir.getExistingPathINodes(src, false);
1211        INode targetNode = inodes[inodes.length-1];
1212    
1213        if (targetNode == null) { // non-existent src
1214          if(NameNode.stateChangeLog.isDebugEnabled()) {
1215            NameNode.stateChangeLog.debug("DIR* FSDirectory.unprotectedDelete: "
1216                +"failed to remove "+src+" because it does not exist");
1217          }
1218          return 0;
1219        }
1220        if (inodes.length == 1) { // src is the root
1221          NameNode.stateChangeLog.warn("DIR* FSDirectory.unprotectedDelete: " +
1222              "failed to remove " + src +
1223              " because the root is not allowed to be deleted");
1224          return 0;
1225        }
1226        int pos = inodes.length - 1;
1227        // Remove the node from the namespace
1228        targetNode = removeChild(inodes, pos);
1229        if (targetNode == null) {
1230          return 0;
1231        }
1232        // set the parent's modification time
1233        inodes[pos-1].setModificationTime(mtime);
1234        int filesRemoved = targetNode.collectSubtreeBlocksAndClear(collectedBlocks);
1235        if (NameNode.stateChangeLog.isDebugEnabled()) {
1236          NameNode.stateChangeLog.debug("DIR* FSDirectory.unprotectedDelete: "
1237              +src+" is removed");
1238        }
1239        return filesRemoved;
1240      }
1241    
1242      /**
1243       * Replaces the specified inode with the specified one.
1244       */
1245      public void replaceNode(String path, INodeFile oldnode, INodeFile newnode)
1246          throws IOException, UnresolvedLinkException {    
1247        writeLock();
1248        try {
1249          //
1250          // Remove the node from the namespace 
1251          //
1252          if (!oldnode.removeNode()) {
1253            NameNode.stateChangeLog.warn("DIR* FSDirectory.replaceNode: " +
1254                                         "failed to remove " + path);
1255            throw new IOException("FSDirectory.replaceNode: " +
1256                                  "failed to remove " + path);
1257          } 
1258          
1259          /* Currently oldnode and newnode are assumed to contain the same
1260           * blocks. Otherwise, blocks need to be removed from the blocksMap.
1261           */
1262          rootDir.addNode(path, newnode); 
1263    
1264          int index = 0;
1265          for (BlockInfo b : newnode.getBlocks()) {
1266            BlockInfo info = getBlockManager().addINode(b, newnode);
1267            newnode.setBlock(index, info); // inode refers to the block in BlocksMap
1268            index++;
1269          }
1270        } finally {
1271          writeUnlock();
1272        }
1273      }
1274    
1275      /**
1276       * Get a partial listing of the indicated directory
1277       *
1278       * @param src the directory name
1279       * @param startAfter the name to start listing after
1280       * @param needLocation if block locations are returned
1281       * @return a partial listing starting after startAfter
1282       */
1283      DirectoryListing getListing(String src, byte[] startAfter,
1284          boolean needLocation) throws UnresolvedLinkException, IOException {
1285        String srcs = normalizePath(src);
1286    
1287        readLock();
1288        try {
1289          INode targetNode = rootDir.getNode(srcs, true);
1290          if (targetNode == null)
1291            return null;
1292          
1293          if (!targetNode.isDirectory()) {
1294            return new DirectoryListing(
1295                new HdfsFileStatus[]{createFileStatus(HdfsFileStatus.EMPTY_NAME,
1296                    targetNode, needLocation)}, 0);
1297          }
1298          INodeDirectory dirInode = (INodeDirectory)targetNode;
1299          List<INode> contents = dirInode.getChildren();
1300          int startChild = dirInode.nextChild(startAfter);
1301          int totalNumChildren = contents.size();
1302          int numOfListing = Math.min(totalNumChildren-startChild, this.lsLimit);
1303          HdfsFileStatus listing[] = new HdfsFileStatus[numOfListing];
1304          for (int i=0; i<numOfListing; i++) {
1305            INode cur = contents.get(startChild+i);
1306            listing[i] = createFileStatus(cur.name, cur, needLocation);
1307          }
1308          return new DirectoryListing(
1309              listing, totalNumChildren-startChild-numOfListing);
1310        } finally {
1311          readUnlock();
1312        }
1313      }
1314    
1315      /** Get the file info for a specific file.
1316       * @param src The string representation of the path to the file
1317       * @param resolveLink whether to throw UnresolvedLinkException 
1318       * @return object containing information regarding the file
1319       *         or null if file not found
1320       */
1321      HdfsFileStatus getFileInfo(String src, boolean resolveLink) 
1322          throws UnresolvedLinkException {
1323        String srcs = normalizePath(src);
1324        readLock();
1325        try {
1326          INode targetNode = rootDir.getNode(srcs, resolveLink);
1327          if (targetNode == null) {
1328            return null;
1329          }
1330          else {
1331            return createFileStatus(HdfsFileStatus.EMPTY_NAME, targetNode);
1332          }
1333        } finally {
1334          readUnlock();
1335        }
1336      }
1337    
1338      /**
1339       * Get the blocks associated with the file.
1340       */
1341      Block[] getFileBlocks(String src) throws UnresolvedLinkException {
1342        waitForReady();
1343        readLock();
1344        try {
1345          INode targetNode = rootDir.getNode(src, false);
1346          if (targetNode == null)
1347            return null;
1348          if (targetNode.isDirectory())
1349            return null;
1350          if (targetNode.isLink()) 
1351            return null;
1352          return ((INodeFile)targetNode).getBlocks();
1353        } finally {
1354          readUnlock();
1355        }
1356      }
1357    
1358      /**
1359       * Get {@link INode} associated with the file.
1360       */
1361      INodeFile getFileINode(String src) throws UnresolvedLinkException {
1362        INode inode = getINode(src);
1363        if (inode == null || inode.isDirectory())
1364          return null;
1365        assert !inode.isLink();
1366        return (INodeFile) inode;
1367      }
1368      
1369      /**
1370       * Get {@link INode} associated with the file / directory.
1371       */
1372      INode getINode(String src) throws UnresolvedLinkException {
1373        readLock();
1374        try {
1375          INode iNode = rootDir.getNode(src, true);
1376          return iNode;
1377        } finally {
1378          readUnlock();
1379        }
1380      }
1381    
1382      /**
1383       * Retrieve the existing INodes along the given path.
1384       * 
1385       * @param path the path to explore
1386       * @return INodes array containing the existing INodes in the order they
1387       *         appear when following the path from the root INode to the
1388       *         deepest INodes. The array size will be the number of expected
1389       *         components in the path, and non existing components will be
1390       *         filled with null
1391       *         
1392       * @see INodeDirectory#getExistingPathINodes(byte[][], INode[])
1393       */
1394      INode[] getExistingPathINodes(String path) 
1395        throws UnresolvedLinkException {
1396        readLock();
1397        try {
1398          return rootDir.getExistingPathINodes(path, true);
1399        } finally {
1400          readUnlock();
1401        }
1402      }
1403      
1404      /**
1405       * Get the parent node of path.
1406       * 
1407       * @param path the path to explore
1408       * @return its parent node
1409       */
1410      INodeDirectory getParent(byte[][] path) 
1411        throws FileNotFoundException, UnresolvedLinkException {
1412        readLock();
1413        try {
1414          return rootDir.getParent(path);
1415        } finally {
1416          readUnlock();
1417        }
1418      }
1419      
1420      /** 
1421       * Check whether the filepath could be created
1422       */
1423      boolean isValidToCreate(String src) throws UnresolvedLinkException {
1424        String srcs = normalizePath(src);
1425        readLock();
1426        try {
1427          if (srcs.startsWith("/") && 
1428              !srcs.endsWith("/") && 
1429              rootDir.getNode(srcs, false) == null) {
1430            return true;
1431          } else {
1432            return false;
1433          }
1434        } finally {
1435          readUnlock();
1436        }
1437      }
1438    
1439      /**
1440       * Check whether the path specifies a directory
1441       */
1442      boolean isDir(String src) throws UnresolvedLinkException {
1443        src = normalizePath(src);
1444        readLock();
1445        try {
1446          INode node = rootDir.getNode(src, false);
1447          return node != null && node.isDirectory();
1448        } finally {
1449          readUnlock();
1450        }
1451      }
1452    
1453      /** Updates namespace and diskspace consumed for all
1454       * directories until the parent directory of file represented by path.
1455       * 
1456       * @param path path for the file.
1457       * @param nsDelta the delta change of namespace
1458       * @param dsDelta the delta change of diskspace
1459       * @throws QuotaExceededException if the new count violates any quota limit
1460       * @throws FileNotFound if path does not exist.
1461       */
1462      void updateSpaceConsumed(String path, long nsDelta, long dsDelta)
1463                                             throws QuotaExceededException,
1464                                                    FileNotFoundException,
1465                                                    UnresolvedLinkException {
1466        writeLock();
1467        try {
1468          INode[] inodes = rootDir.getExistingPathINodes(path, false);
1469          int len = inodes.length;
1470          if (inodes[len - 1] == null) {
1471            throw new FileNotFoundException(path + 
1472                                            " does not exist under rootDir.");
1473          }
1474          updateCount(inodes, len-1, nsDelta, dsDelta, true);
1475        } finally {
1476          writeUnlock();
1477        }
1478      }
1479      
1480      /** update count of each inode with quota
1481       * 
1482       * @param inodes an array of inodes on a path
1483       * @param numOfINodes the number of inodes to update starting from index 0
1484       * @param nsDelta the delta change of namespace
1485       * @param dsDelta the delta change of diskspace
1486       * @param checkQuota if true then check if quota is exceeded
1487       * @throws QuotaExceededException if the new count violates any quota limit
1488       */
1489      private void updateCount(INode[] inodes, int numOfINodes, 
1490                               long nsDelta, long dsDelta, boolean checkQuota)
1491                               throws QuotaExceededException {
1492        assert hasWriteLock();
1493        if (!ready) {
1494          //still initializing. do not check or update quotas.
1495          return;
1496        }
1497        if (numOfINodes>inodes.length) {
1498          numOfINodes = inodes.length;
1499        }
1500        if (checkQuota) {
1501          verifyQuota(inodes, numOfINodes, nsDelta, dsDelta, null);
1502        }
1503        for(int i = 0; i < numOfINodes; i++) {
1504          if (inodes[i].isQuotaSet()) { // a directory with quota
1505            INodeDirectoryWithQuota node =(INodeDirectoryWithQuota)inodes[i]; 
1506            node.updateNumItemsInTree(nsDelta, dsDelta);
1507          }
1508        }
1509      }
1510      
1511      /** 
1512       * update quota of each inode and check to see if quota is exceeded. 
1513       * See {@link #updateCount(INode[], int, long, long, boolean)}
1514       */ 
1515      private void updateCountNoQuotaCheck(INode[] inodes, int numOfINodes, 
1516                               long nsDelta, long dsDelta) {
1517        assert hasWriteLock();
1518        try {
1519          updateCount(inodes, numOfINodes, nsDelta, dsDelta, false);
1520        } catch (QuotaExceededException e) {
1521          NameNode.LOG.warn("FSDirectory.updateCountNoQuotaCheck - unexpected ", e);
1522        }
1523      }
1524      
1525      /**
1526       * updates quota without verification
1527       * callers responsibility is to make sure quota is not exceeded
1528       * @param inodes
1529       * @param numOfINodes
1530       * @param nsDelta
1531       * @param dsDelta
1532       */
1533       void unprotectedUpdateCount(INode[] inodes, int numOfINodes, 
1534                                          long nsDelta, long dsDelta) {
1535         assert hasWriteLock();
1536        for(int i=0; i < numOfINodes; i++) {
1537          if (inodes[i].isQuotaSet()) { // a directory with quota
1538            INodeDirectoryWithQuota node =(INodeDirectoryWithQuota)inodes[i]; 
1539            node.unprotectedUpdateNumItemsInTree(nsDelta, dsDelta);
1540          }
1541        }
1542      }
1543      
1544      /** Return the name of the path represented by inodes at [0, pos] */
1545      private static String getFullPathName(INode[] inodes, int pos) {
1546        StringBuilder fullPathName = new StringBuilder();
1547        if (inodes[0].isRoot()) {
1548          if (pos == 0) return Path.SEPARATOR;
1549        } else {
1550          fullPathName.append(inodes[0].getLocalName());
1551        }
1552        
1553        for (int i=1; i<=pos; i++) {
1554          fullPathName.append(Path.SEPARATOR_CHAR).append(inodes[i].getLocalName());
1555        }
1556        return fullPathName.toString();
1557      }
1558    
1559      /** Return the full path name of the specified inode */
1560      static String getFullPathName(INode inode) {
1561        // calculate the depth of this inode from root
1562        int depth = 0;
1563        for (INode i = inode; i != null; i = i.parent) {
1564          depth++;
1565        }
1566        INode[] inodes = new INode[depth];
1567    
1568        // fill up the inodes in the path from this inode to root
1569        for (int i = 0; i < depth; i++) {
1570          inodes[depth-i-1] = inode;
1571          inode = inode.parent;
1572        }
1573        return getFullPathName(inodes, depth-1);
1574      }
1575      
1576      /**
1577       * Create a directory 
1578       * If ancestor directories do not exist, automatically create them.
1579    
1580       * @param src string representation of the path to the directory
1581       * @param permissions the permission of the directory
1582       * @param isAutocreate if the permission of the directory should inherit
1583       *                          from its parent or not. u+wx is implicitly added to
1584       *                          the automatically created directories, and to the
1585       *                          given directory if inheritPermission is true
1586       * @param now creation time
1587       * @return true if the operation succeeds false otherwise
1588       * @throws FileNotFoundException if an ancestor or itself is a file
1589       * @throws QuotaExceededException if directory creation violates 
1590       *                                any quota limit
1591       * @throws UnresolvedLinkException if a symlink is encountered in src.                      
1592       */
1593      boolean mkdirs(String src, PermissionStatus permissions,
1594          boolean inheritPermission, long now)
1595          throws FileAlreadyExistsException, QuotaExceededException, 
1596                 UnresolvedLinkException {
1597        src = normalizePath(src);
1598        String[] names = INode.getPathNames(src);
1599        byte[][] components = INode.getPathComponents(names);
1600        INode[] inodes = new INode[components.length];
1601        final int lastInodeIndex = inodes.length - 1;
1602    
1603        writeLock();
1604        try {
1605          rootDir.getExistingPathINodes(components, inodes, false);
1606    
1607          // find the index of the first null in inodes[]
1608          StringBuilder pathbuilder = new StringBuilder();
1609          int i = 1;
1610          for(; i < inodes.length && inodes[i] != null; i++) {
1611            pathbuilder.append(Path.SEPARATOR + names[i]);
1612            if (!inodes[i].isDirectory()) {
1613              throw new FileAlreadyExistsException("Parent path is not a directory: "
1614                  + pathbuilder+ " "+inodes[i].getLocalName());
1615            }
1616          }
1617    
1618          // default to creating parent dirs with the given perms
1619          PermissionStatus parentPermissions = permissions;
1620    
1621          // if not inheriting and it's the last inode, there's no use in
1622          // computing perms that won't be used
1623          if (inheritPermission || (i < lastInodeIndex)) {
1624            // if inheriting (ie. creating a file or symlink), use the parent dir,
1625            // else the supplied permissions
1626            // NOTE: the permissions of the auto-created directories violate posix
1627            FsPermission parentFsPerm = inheritPermission
1628                ? inodes[i-1].getFsPermission() : permissions.getPermission();
1629            
1630            // ensure that the permissions allow user write+execute
1631            if (!parentFsPerm.getUserAction().implies(FsAction.WRITE_EXECUTE)) {
1632              parentFsPerm = new FsPermission(
1633                  parentFsPerm.getUserAction().or(FsAction.WRITE_EXECUTE),
1634                  parentFsPerm.getGroupAction(),
1635                  parentFsPerm.getOtherAction()
1636              );
1637            }
1638            
1639            if (!parentPermissions.getPermission().equals(parentFsPerm)) {
1640              parentPermissions = new PermissionStatus(
1641                  parentPermissions.getUserName(),
1642                  parentPermissions.getGroupName(),
1643                  parentFsPerm
1644              );
1645              // when inheriting, use same perms for entire path
1646              if (inheritPermission) permissions = parentPermissions;
1647            }
1648          }
1649          
1650          // create directories beginning from the first null index
1651          for(; i < inodes.length; i++) {
1652            pathbuilder.append(Path.SEPARATOR + names[i]);
1653            String cur = pathbuilder.toString();
1654            unprotectedMkdir(inodes, i, components[i],
1655                (i < lastInodeIndex) ? parentPermissions : permissions, now);
1656            if (inodes[i] == null) {
1657              return false;
1658            }
1659            // Directory creation also count towards FilesCreated
1660            // to match count of FilesDeleted metric.
1661            if (getFSNamesystem() != null)
1662              NameNode.getNameNodeMetrics().incrFilesCreated();
1663            fsImage.getEditLog().logMkDir(cur, inodes[i]);
1664            if(NameNode.stateChangeLog.isDebugEnabled()) {
1665              NameNode.stateChangeLog.debug(
1666                  "DIR* FSDirectory.mkdirs: created directory " + cur);
1667            }
1668          }
1669        } finally {
1670          writeUnlock();
1671        }
1672        return true;
1673      }
1674    
1675      /**
1676       */
1677      INode unprotectedMkdir(String src, PermissionStatus permissions,
1678                              long timestamp) throws QuotaExceededException,
1679                              UnresolvedLinkException {
1680        assert hasWriteLock();
1681        byte[][] components = INode.getPathComponents(src);
1682        INode[] inodes = new INode[components.length];
1683    
1684        rootDir.getExistingPathINodes(components, inodes, false);
1685        unprotectedMkdir(inodes, inodes.length-1, components[inodes.length-1],
1686            permissions, timestamp);
1687        return inodes[inodes.length-1];
1688      }
1689    
1690      /** create a directory at index pos.
1691       * The parent path to the directory is at [0, pos-1].
1692       * All ancestors exist. Newly created one stored at index pos.
1693       */
1694      private void unprotectedMkdir(INode[] inodes, int pos,
1695          byte[] name, PermissionStatus permission,
1696          long timestamp) throws QuotaExceededException {
1697        assert hasWriteLock();
1698        inodes[pos] = addChild(inodes, pos, 
1699            new INodeDirectory(name, permission, timestamp),
1700            -1);
1701      }
1702      
1703      /** Add a node child to the namespace. The full path name of the node is src.
1704       * childDiskspace should be -1, if unknown. 
1705       * QuotaExceededException is thrown if it violates quota limit */
1706      private <T extends INode> T addNode(String src, T child, 
1707            long childDiskspace) 
1708      throws QuotaExceededException, UnresolvedLinkException {
1709        byte[][] components = INode.getPathComponents(src);
1710        byte[] path = components[components.length-1];
1711        child.setLocalName(path);
1712        cacheName(child);
1713        INode[] inodes = new INode[components.length];
1714        writeLock();
1715        try {
1716          rootDir.getExistingPathINodes(components, inodes, false);
1717          return addChild(inodes, inodes.length-1, child, childDiskspace);
1718        } finally {
1719          writeUnlock();
1720        }
1721      }
1722    
1723      /**
1724       * Verify quota for adding or moving a new INode with required 
1725       * namespace and diskspace to a given position.
1726       *  
1727       * @param inodes INodes corresponding to a path
1728       * @param pos position where a new INode will be added
1729       * @param nsDelta needed namespace
1730       * @param dsDelta needed diskspace
1731       * @param commonAncestor Last node in inodes array that is a common ancestor
1732       *          for a INode that is being moved from one location to the other.
1733       *          Pass null if a node is not being moved.
1734       * @throws QuotaExceededException if quota limit is exceeded.
1735       */
1736      private void verifyQuota(INode[] inodes, int pos, long nsDelta, long dsDelta,
1737          INode commonAncestor) throws QuotaExceededException {
1738        if (!ready) {
1739          // Do not check quota if edits log is still being processed
1740          return;
1741        }
1742        if (nsDelta <= 0 && dsDelta <= 0) {
1743          // if quota is being freed or not being consumed
1744          return;
1745        }
1746        if (pos>inodes.length) {
1747          pos = inodes.length;
1748        }
1749        int i = pos - 1;
1750        try {
1751          // check existing components in the path  
1752          for(; i >= 0; i--) {
1753            if (commonAncestor == inodes[i]) {
1754              // Moving an existing node. Stop checking for quota when common
1755              // ancestor is reached
1756              return;
1757            }
1758            if (inodes[i].isQuotaSet()) { // a directory with quota
1759              INodeDirectoryWithQuota node =(INodeDirectoryWithQuota)inodes[i]; 
1760              node.verifyQuota(nsDelta, dsDelta);
1761            }
1762          }
1763        } catch (QuotaExceededException e) {
1764          e.setPathName(getFullPathName(inodes, i));
1765          throw e;
1766        }
1767      }
1768      
1769      /**
1770       * Verify quota for rename operation where srcInodes[srcInodes.length-1] moves
1771       * dstInodes[dstInodes.length-1]
1772       * 
1773       * @param srcInodes directory from where node is being moved.
1774       * @param dstInodes directory to where node is moved to.
1775       * @throws QuotaExceededException if quota limit is exceeded.
1776       */
1777      private void verifyQuotaForRename(INode[] srcInodes, INode[]dstInodes)
1778          throws QuotaExceededException {
1779        if (!ready) {
1780          // Do not check quota if edits log is still being processed
1781          return;
1782        }
1783        INode srcInode = srcInodes[srcInodes.length - 1];
1784        INode commonAncestor = null;
1785        for(int i =0;srcInodes[i] == dstInodes[i]; i++) {
1786          commonAncestor = srcInodes[i];
1787        }
1788        INode.DirCounts srcCounts = new INode.DirCounts();
1789        srcInode.spaceConsumedInTree(srcCounts);
1790        long nsDelta = srcCounts.getNsCount();
1791        long dsDelta = srcCounts.getDsCount();
1792        
1793        // Reduce the required quota by dst that is being removed
1794        INode dstInode = dstInodes[dstInodes.length - 1];
1795        if (dstInode != null) {
1796          INode.DirCounts dstCounts = new INode.DirCounts();
1797          dstInode.spaceConsumedInTree(dstCounts);
1798          nsDelta -= dstCounts.getNsCount();
1799          dsDelta -= dstCounts.getDsCount();
1800        }
1801        verifyQuota(dstInodes, dstInodes.length - 1, nsDelta, dsDelta,
1802            commonAncestor);
1803      }
1804      
1805      /**
1806       * Verify that filesystem limit constraints are not violated
1807       * @throws PathComponentTooLongException child's name is too long
1808       * @throws MaxDirectoryItemsExceededException items per directory is exceeded
1809       */
1810      protected <T extends INode> void verifyFsLimits(INode[] pathComponents,
1811          int pos, T child) throws FSLimitException {
1812        boolean includeChildName = false;
1813        try {
1814          if (maxComponentLength != 0) {
1815            int length = child.getLocalName().length();
1816            if (length > maxComponentLength) {
1817              includeChildName = true;
1818              throw new PathComponentTooLongException(maxComponentLength, length);
1819            }
1820          }
1821          if (maxDirItems != 0) {
1822            INodeDirectory parent = (INodeDirectory)pathComponents[pos-1];
1823            int count = parent.getChildren().size();
1824            if (count >= maxDirItems) {
1825              throw new MaxDirectoryItemsExceededException(maxDirItems, count);
1826            }
1827          }
1828        } catch (FSLimitException e) {
1829          String badPath = getFullPathName(pathComponents, pos-1);
1830          if (includeChildName) {
1831            badPath += Path.SEPARATOR + child.getLocalName();
1832          }
1833          e.setPathName(badPath);
1834          // Do not throw if edits log is still being processed
1835          if (ready) throw(e);
1836          // log pre-existing paths that exceed limits
1837          NameNode.LOG.error("FSDirectory.verifyFsLimits - " + e.getLocalizedMessage());
1838        }
1839      }
1840      
1841      /** Add a node child to the inodes at index pos. 
1842       * Its ancestors are stored at [0, pos-1]. 
1843       * QuotaExceededException is thrown if it violates quota limit */
1844      private <T extends INode> T addChild(INode[] pathComponents, int pos,
1845          T child, long childDiskspace,
1846          boolean checkQuota) throws QuotaExceededException {
1847            // The filesystem limits are not really quotas, so this check may appear
1848            // odd.  It's because a rename operation deletes the src, tries to add
1849            // to the dest, if that fails, re-adds the src from whence it came.
1850            // The rename code disables the quota when it's restoring to the
1851            // original location becase a quota violation would cause the the item
1852            // to go "poof".  The fs limits must be bypassed for the same reason.
1853        if (checkQuota) {
1854          verifyFsLimits(pathComponents, pos, child);
1855        }
1856        
1857        INode.DirCounts counts = new INode.DirCounts();
1858        child.spaceConsumedInTree(counts);
1859        if (childDiskspace < 0) {
1860          childDiskspace = counts.getDsCount();
1861        }
1862        updateCount(pathComponents, pos, counts.getNsCount(), childDiskspace,
1863            checkQuota);
1864        if (pathComponents[pos-1] == null) {
1865          throw new NullPointerException("Panic: parent does not exist");
1866        }
1867        T addedNode = ((INodeDirectory)pathComponents[pos-1]).addChild(
1868            child, true);
1869        if (addedNode == null) {
1870          updateCount(pathComponents, pos, -counts.getNsCount(), 
1871              -childDiskspace, true);
1872        }
1873        return addedNode;
1874      }
1875    
1876      private <T extends INode> T addChild(INode[] pathComponents, int pos,
1877          T child, long childDiskspace)
1878          throws QuotaExceededException {
1879        return addChild(pathComponents, pos, child, childDiskspace, true);
1880      }
1881      
1882      private <T extends INode> T addChildNoQuotaCheck(INode[] pathComponents,
1883          int pos, T child, long childDiskspace) {
1884        T inode = null;
1885        try {
1886          inode = addChild(pathComponents, pos, child, childDiskspace, false);
1887        } catch (QuotaExceededException e) {
1888          NameNode.LOG.warn("FSDirectory.addChildNoQuotaCheck - unexpected", e); 
1889        }
1890        return inode;
1891      }
1892      
1893      /** Remove an inode at index pos from the namespace.
1894       * Its ancestors are stored at [0, pos-1].
1895       * Count of each ancestor with quota is also updated.
1896       * Return the removed node; null if the removal fails.
1897       */
1898      private INode removeChild(INode[] pathComponents, int pos) {
1899        INode removedNode = 
1900          ((INodeDirectory)pathComponents[pos-1]).removeChild(pathComponents[pos]);
1901        if (removedNode != null) {
1902          INode.DirCounts counts = new INode.DirCounts();
1903          removedNode.spaceConsumedInTree(counts);
1904          updateCountNoQuotaCheck(pathComponents, pos,
1905                      -counts.getNsCount(), -counts.getDsCount());
1906        }
1907        return removedNode;
1908      }
1909      
1910      /**
1911       */
1912      String normalizePath(String src) {
1913        if (src.length() > 1 && src.endsWith("/")) {
1914          src = src.substring(0, src.length() - 1);
1915        }
1916        return src;
1917      }
1918    
1919      ContentSummary getContentSummary(String src) 
1920        throws FileNotFoundException, UnresolvedLinkException {
1921        String srcs = normalizePath(src);
1922        readLock();
1923        try {
1924          INode targetNode = rootDir.getNode(srcs, false);
1925          if (targetNode == null) {
1926            throw new FileNotFoundException("File does not exist: " + srcs);
1927          }
1928          else {
1929            return targetNode.computeContentSummary();
1930          }
1931        } finally {
1932          readUnlock();
1933        }
1934      }
1935    
1936      /** Update the count of each directory with quota in the namespace
1937       * A directory's count is defined as the total number inodes in the tree
1938       * rooted at the directory.
1939       * 
1940       * This is an update of existing state of the filesystem and does not
1941       * throw QuotaExceededException.
1942       */
1943      void updateCountForINodeWithQuota() {
1944        updateCountForINodeWithQuota(rootDir, new INode.DirCounts(), 
1945                                     new ArrayList<INode>(50));
1946      }
1947      
1948      /** 
1949       * Update the count of the directory if it has a quota and return the count
1950       * 
1951       * This does not throw a QuotaExceededException. This is just an update
1952       * of of existing state and throwing QuotaExceededException does not help
1953       * with fixing the state, if there is a problem.
1954       * 
1955       * @param dir the root of the tree that represents the directory
1956       * @param counters counters for name space and disk space
1957       * @param nodesInPath INodes for the each of components in the path.
1958       */
1959      private static void updateCountForINodeWithQuota(INodeDirectory dir, 
1960                                                   INode.DirCounts counts,
1961                                                   ArrayList<INode> nodesInPath) {
1962        long parentNamespace = counts.nsCount;
1963        long parentDiskspace = counts.dsCount;
1964        
1965        counts.nsCount = 1L;//for self. should not call node.spaceConsumedInTree()
1966        counts.dsCount = 0L;
1967        
1968        /* We don't need nodesInPath if we could use 'parent' field in 
1969         * INode. using 'parent' is not currently recommended. */
1970        nodesInPath.add(dir);
1971    
1972        for (INode child : dir.getChildren()) {
1973          if (child.isDirectory()) {
1974            updateCountForINodeWithQuota((INodeDirectory)child, 
1975                                         counts, nodesInPath);
1976          } else if (child.isLink()) {
1977            counts.nsCount += 1;
1978          } else { // reduce recursive calls
1979            counts.nsCount += 1;
1980            counts.dsCount += ((INodeFile)child).diskspaceConsumed();
1981          }
1982        }
1983          
1984        if (dir.isQuotaSet()) {
1985          ((INodeDirectoryWithQuota)dir).setSpaceConsumed(counts.nsCount,
1986                                                          counts.dsCount);
1987    
1988          // check if quota is violated for some reason.
1989          if ((dir.getNsQuota() >= 0 && counts.nsCount > dir.getNsQuota()) ||
1990              (dir.getDsQuota() >= 0 && counts.dsCount > dir.getDsQuota())) {
1991    
1992            // can only happen because of a software bug. the bug should be fixed.
1993            StringBuilder path = new StringBuilder(512);
1994            for (INode n : nodesInPath) {
1995              path.append('/');
1996              path.append(n.getLocalName());
1997            }
1998            
1999            NameNode.LOG.warn("Quota violation in image for " + path + 
2000                              " (Namespace quota : " + dir.getNsQuota() +
2001                              " consumed : " + counts.nsCount + ")" +
2002                              " (Diskspace quota : " + dir.getDsQuota() +
2003                              " consumed : " + counts.dsCount + ").");
2004          }            
2005        }
2006          
2007        // pop 
2008        nodesInPath.remove(nodesInPath.size()-1);
2009        
2010        counts.nsCount += parentNamespace;
2011        counts.dsCount += parentDiskspace;
2012      }
2013      
2014      /**
2015       * See {@link ClientProtocol#setQuota(String, long, long)} for the contract.
2016       * Sets quota for for a directory.
2017       * @returns INodeDirectory if any of the quotas have changed. null other wise.
2018       * @throws FileNotFoundException if the path does not exist or is a file
2019       * @throws QuotaExceededException if the directory tree size is 
2020       *                                greater than the given quota
2021       * @throws UnresolvedLinkException if a symlink is encountered in src.
2022       */
2023      INodeDirectory unprotectedSetQuota(String src, long nsQuota, long dsQuota)
2024        throws FileNotFoundException, QuotaExceededException, 
2025          UnresolvedLinkException {
2026        assert hasWriteLock();
2027        // sanity check
2028        if ((nsQuota < 0 && nsQuota != HdfsConstants.QUOTA_DONT_SET && 
2029             nsQuota < HdfsConstants.QUOTA_RESET) || 
2030            (dsQuota < 0 && dsQuota != HdfsConstants.QUOTA_DONT_SET && 
2031              dsQuota < HdfsConstants.QUOTA_RESET)) {
2032          throw new IllegalArgumentException("Illegal value for nsQuota or " +
2033                                             "dsQuota : " + nsQuota + " and " +
2034                                             dsQuota);
2035        }
2036        
2037        String srcs = normalizePath(src);
2038    
2039        INode[] inodes = rootDir.getExistingPathINodes(src, true);
2040        INode targetNode = inodes[inodes.length-1];
2041        if (targetNode == null) {
2042          throw new FileNotFoundException("Directory does not exist: " + srcs);
2043        } else if (!targetNode.isDirectory()) {
2044          throw new FileNotFoundException("Cannot set quota on a file: " + srcs);  
2045        } else if (targetNode.isRoot() && nsQuota == HdfsConstants.QUOTA_RESET) {
2046          throw new IllegalArgumentException("Cannot clear namespace quota on root.");
2047        } else { // a directory inode
2048          INodeDirectory dirNode = (INodeDirectory)targetNode;
2049          long oldNsQuota = dirNode.getNsQuota();
2050          long oldDsQuota = dirNode.getDsQuota();
2051          if (nsQuota == HdfsConstants.QUOTA_DONT_SET) {
2052            nsQuota = oldNsQuota;
2053          }
2054          if (dsQuota == HdfsConstants.QUOTA_DONT_SET) {
2055            dsQuota = oldDsQuota;
2056          }        
2057    
2058          if (dirNode instanceof INodeDirectoryWithQuota) { 
2059            // a directory with quota; so set the quota to the new value
2060            ((INodeDirectoryWithQuota)dirNode).setQuota(nsQuota, dsQuota);
2061            if (!dirNode.isQuotaSet()) {
2062              // will not come here for root because root's nsQuota is always set
2063              INodeDirectory newNode = new INodeDirectory(dirNode);
2064              INodeDirectory parent = (INodeDirectory)inodes[inodes.length-2];
2065              dirNode = newNode;
2066              parent.replaceChild(newNode);
2067            }
2068          } else {
2069            // a non-quota directory; so replace it with a directory with quota
2070            INodeDirectoryWithQuota newNode = 
2071              new INodeDirectoryWithQuota(nsQuota, dsQuota, dirNode);
2072            // non-root directory node; parent != null
2073            INodeDirectory parent = (INodeDirectory)inodes[inodes.length-2];
2074            dirNode = newNode;
2075            parent.replaceChild(newNode);
2076          }
2077          return (oldNsQuota != nsQuota || oldDsQuota != dsQuota) ? dirNode : null;
2078        }
2079      }
2080      
2081      /**
2082       * See {@link ClientProtocol#setQuota(String, long, long)} for the 
2083       * contract.
2084       * @see #unprotectedSetQuota(String, long, long)
2085       */
2086      void setQuota(String src, long nsQuota, long dsQuota) 
2087        throws FileNotFoundException, QuotaExceededException,
2088        UnresolvedLinkException { 
2089        writeLock();
2090        try {
2091          INodeDirectory dir = unprotectedSetQuota(src, nsQuota, dsQuota);
2092          if (dir != null) {
2093            fsImage.getEditLog().logSetQuota(src, dir.getNsQuota(), 
2094                                             dir.getDsQuota());
2095          }
2096        } finally {
2097          writeUnlock();
2098        }
2099      }
2100      
2101      long totalInodes() {
2102        readLock();
2103        try {
2104          return rootDir.numItemsInTree();
2105        } finally {
2106          readUnlock();
2107        }
2108      }
2109    
2110      /**
2111       * Sets the access time on the file/directory. Logs it in the transaction log.
2112       */
2113      void setTimes(String src, INode inode, long mtime, long atime, boolean force) {
2114        boolean status = false;
2115        writeLock();
2116        try {
2117          status = unprotectedSetTimes(src, inode, mtime, atime, force);
2118        } finally {
2119          writeUnlock();
2120        }
2121        if (status) {
2122          fsImage.getEditLog().logTimes(src, mtime, atime);
2123        }
2124      }
2125    
2126      boolean unprotectedSetTimes(String src, long mtime, long atime, boolean force) 
2127          throws UnresolvedLinkException {
2128        assert hasWriteLock();
2129        INode inode = getINode(src);
2130        return unprotectedSetTimes(src, inode, mtime, atime, force);
2131      }
2132    
2133      private boolean unprotectedSetTimes(String src, INode inode, long mtime,
2134                                          long atime, boolean force) {
2135        assert hasWriteLock();
2136        boolean status = false;
2137        if (mtime != -1) {
2138          inode.setModificationTimeForce(mtime);
2139          status = true;
2140        }
2141        if (atime != -1) {
2142          long inodeTime = inode.getAccessTime();
2143    
2144          // if the last access time update was within the last precision interval, then
2145          // no need to store access time
2146          if (atime <= inodeTime + getFSNamesystem().getAccessTimePrecision() && !force) {
2147            status =  false;
2148          } else {
2149            inode.setAccessTime(atime);
2150            status = true;
2151          }
2152        } 
2153        return status;
2154      }
2155    
2156      /**
2157       * Reset the entire namespace tree.
2158       */
2159      void reset() {
2160        writeLock();
2161        try {
2162          setReady(false);
2163          rootDir = new INodeDirectoryWithQuota(INodeDirectory.ROOT_NAME,
2164              getFSNamesystem().createFsOwnerPermissions(new FsPermission((short)0755)),
2165              Integer.MAX_VALUE, -1);
2166          nameCache.reset();
2167        } finally {
2168          writeUnlock();
2169        }
2170      }
2171    
2172      /**
2173       * create an hdfs file status from an inode
2174       * 
2175       * @param path the local name
2176       * @param node inode
2177       * @param needLocation if block locations need to be included or not
2178       * @return a file status
2179       * @throws IOException if any error occurs
2180       */
2181      private HdfsFileStatus createFileStatus(byte[] path, INode node,
2182          boolean needLocation) throws IOException {
2183        if (needLocation) {
2184          return createLocatedFileStatus(path, node);
2185        } else {
2186          return createFileStatus(path, node);
2187        }
2188      }
2189      /**
2190       * Create FileStatus by file INode 
2191       */
2192       private HdfsFileStatus createFileStatus(byte[] path, INode node) {
2193         long size = 0;     // length is zero for directories
2194         short replication = 0;
2195         long blocksize = 0;
2196         if (node instanceof INodeFile) {
2197           INodeFile fileNode = (INodeFile)node;
2198           size = fileNode.computeFileSize(true);
2199           replication = fileNode.getReplication();
2200           blocksize = fileNode.getPreferredBlockSize();
2201         }
2202         return new HdfsFileStatus(
2203            size, 
2204            node.isDirectory(), 
2205            replication, 
2206            blocksize,
2207            node.getModificationTime(),
2208            node.getAccessTime(),
2209            node.getFsPermission(),
2210            node.getUserName(),
2211            node.getGroupName(),
2212            node.isLink() ? ((INodeSymlink)node).getSymlink() : null,
2213            path);
2214      }
2215    
2216       /**
2217        * Create FileStatus with location info by file INode 
2218        */
2219        private HdfsLocatedFileStatus createLocatedFileStatus(
2220            byte[] path, INode node) throws IOException {
2221          assert hasReadLock();
2222          long size = 0;     // length is zero for directories
2223          short replication = 0;
2224          long blocksize = 0;
2225          LocatedBlocks loc = null;
2226          if (node instanceof INodeFile) {
2227            INodeFile fileNode = (INodeFile)node;
2228            size = fileNode.computeFileSize(true);
2229            replication = fileNode.getReplication();
2230            blocksize = fileNode.getPreferredBlockSize();
2231            loc = getFSNamesystem().getBlockManager().createLocatedBlocks(
2232                fileNode.getBlocks(), fileNode.computeFileSize(false),
2233                fileNode.isUnderConstruction(), 0L, size, false);
2234            if (loc==null) {
2235              loc = new LocatedBlocks();
2236            }
2237          }
2238          return new HdfsLocatedFileStatus(
2239              size, 
2240              node.isDirectory(), 
2241              replication, 
2242              blocksize,
2243              node.getModificationTime(),
2244              node.getAccessTime(),
2245              node.getFsPermission(),
2246              node.getUserName(),
2247              node.getGroupName(),
2248              node.isLink() ? ((INodeSymlink)node).getSymlink() : null,
2249              path,
2250              loc);
2251          }
2252    
2253        
2254      /**
2255       * Add the given symbolic link to the fs. Record it in the edits log.
2256       */
2257      INodeSymlink addSymlink(String path, String target,
2258          PermissionStatus dirPerms, boolean createParent)
2259          throws UnresolvedLinkException, FileAlreadyExistsException,
2260          QuotaExceededException, IOException {
2261        waitForReady();
2262    
2263        final long modTime = now();
2264        if (createParent) {
2265          final String parent = new Path(path).getParent().toString();
2266          if (!mkdirs(parent, dirPerms, true, modTime)) {
2267            return null;
2268          }
2269        }
2270        final String userName = dirPerms.getUserName();
2271        INodeSymlink newNode  = null;
2272        writeLock();
2273        try {
2274          newNode = unprotectedSymlink(path, target, modTime, modTime,
2275              new PermissionStatus(userName, null, FsPermission.getDefault()));
2276        } finally {
2277          writeUnlock();
2278        }
2279        if (newNode == null) {
2280          NameNode.stateChangeLog.info("DIR* FSDirectory.addSymlink: "
2281                                       +"failed to add "+path
2282                                       +" to the file system");
2283          return null;
2284        }
2285        fsImage.getEditLog().logSymlink(path, target, modTime, modTime, newNode);
2286        
2287        if(NameNode.stateChangeLog.isDebugEnabled()) {
2288          NameNode.stateChangeLog.debug("DIR* FSDirectory.addSymlink: "
2289              +path+" is added to the file system");
2290        }
2291        return newNode;
2292      }
2293    
2294      /**
2295       * Add the specified path into the namespace. Invoked from edit log processing.
2296       */
2297      INodeSymlink unprotectedSymlink(String path, String target, long modTime, 
2298                                      long atime, PermissionStatus perm) 
2299          throws UnresolvedLinkException {
2300        assert hasWriteLock();
2301        INodeSymlink newNode = new INodeSymlink(target, modTime, atime, perm);
2302        try {
2303          newNode = addNode(path, newNode, UNKNOWN_DISK_SPACE);
2304        } catch (UnresolvedLinkException e) {
2305          /* All UnresolvedLinkExceptions should have been resolved by now, but we
2306           * should re-throw them in case that changes so they are not swallowed 
2307           * by catching IOException below.
2308           */
2309          throw e;
2310        } catch (IOException e) {
2311          return null;
2312        }
2313        return newNode;
2314      }
2315      
2316      /**
2317       * Caches frequently used file names to reuse file name objects and
2318       * reduce heap size.
2319       */
2320      void cacheName(INode inode) {
2321        // Name is cached only for files
2322        if (inode.isDirectory() || inode.isLink()) {
2323          return;
2324        }
2325        ByteArray name = new ByteArray(inode.getLocalNameBytes());
2326        name = nameCache.put(name);
2327        if (name != null) {
2328          inode.setLocalName(name.getBytes());
2329        }
2330      }
2331    
2332    }