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