HDFS源码分析(一)—–INode文件节点详解大数据

前言

在linux文件系统中,i-node节点一直是一个非常重要的设计,同样在HDFS中,也存在这样的一个类似的角色,不过他是一个全新的类,INode.class,后面的目录类等等都是他的子类。最近学习了部分HDFS的源码结构,就好好理一理这方面的知识,帮助大家更好的从深层次了解Hadoop分布式系统文件。

HDFS文件相关的类设计

在HDFS中与文件相关的类主要有这么几个

1.INode–这个就是最底层的一个类,抽象类,提炼一些文件目录共有的属性。

2.INodeFile–文件节点类,继承自INode,表示一个文件

3.INodeDirectory–文件目录类,也是继承自INode.他的孩子中是文件集也可能是目录

4.INodeDirectoryWithQuota–有配额限制的目录,这是为了适应HDFS中的配额策略。

5.INodeFileUnderConstruction–处于构建状态的文件类,可以从INodeFile中转化而来。

我大体上分为了以上这么几个类,后续将从上述类中挑出部分代码,来了解作者的巧妙的设计思想。

INode

INode基础抽象类,保存了文件,目录都可能会共有的基本属性,如下

  1. /** 
  2.  * We keep an in-memory representation of the file/block hierarchy. 
  3.  * This is a base INode class containing common fields for file and  
  4.  * directory inodes. 
  5.  */  
  6. abstract class INode implements Comparable<byte[]> {  
  7.   //文件/目录名称  
  8.   protected byte[] name;  
  9.   //父目录  
  10.   protected INodeDirectory parent;  
  11.   //最近一次的修改时间  
  12.   protected long modificationTime;  
  13.   //最近访问时间  
  14.   protected long accessTime;  

INode作为基础类,在权限控制的设计方面采用了64位的存储方式,前16位保留访问权限设置,中间16~40位保留所属用户组标识符,41~63位保留所属用户标识符。如下

  1. //Only updated by updatePermissionStatus(…).  
  2.   //Other codes should not modify it.  
  3.   private long permission;  
  4.   
  5.   //使用long整数的64位保存,分3段保存,分别为mode模式控制访问权限,所属组,所属用户  
  6.   private static enum PermissionStatusFormat {  
  7.     MODE(016),  
  8.     GROUP(MODE.OFFSET + MODE.LENGTH, 25),  
  9.     USER(GROUP.OFFSET + GROUP.LENGTH, 23);  
  10.   
  11.     final int OFFSET;  
  12.     final int LENGTH; //bit length  
  13.     final long MASK;  
  14.   
  15.     PermissionStatusFormat(int offset, int length) {  
  16.       OFFSET = offset;  
  17.       LENGTH = length;  
  18.       MASK = ((-1L) >>> (64 – LENGTH)) << OFFSET;  
  19.     }  
  20.   
  21.     //与掩码计算并右移得到用户标识符  
  22.     long retrieve(long record) {  
  23.       return (record & MASK) >>> OFFSET;  
  24.     }  
  25.   
  26.     long combine(long bits, long record) {  
  27.       return (record & ~MASK) | (bits << OFFSET);  
  28.     }  
  29.   }  

要获取这些值,需要与内部的掩码值计算并作左右移操作。在这里存储标识符的好处是比纯粹的字符串省了很多的内存,那么HDFS是如何通过标识符数字获取用户组或用户名的呢,答案在下面

  1. /** Get user name */  
  2.   public String getUserName() {  
  3.     int n = (int)PermissionStatusFormat.USER.retrieve(permission);  
  4.     //根据整形标识符,SerialNumberManager对象中取出,避免存储字符串消耗大量内存  
  5.     return SerialNumberManager.INSTANCE.getUser(n);  
  6.   }  
  7.   /** Set user */  
  8.   protected void setUser(String user) {  
  9.     int n = SerialNumberManager.INSTANCE.getUserSerialNumber(user);  
  10.     updatePermissionStatus(PermissionStatusFormat.USER, n);  
  11.   }  
  12.   /** Get group name */  
  13.   public String getGroupName() {  
  14.     int n = (int)PermissionStatusFormat.GROUP.retrieve(permission);  
  15.     return SerialNumberManager.INSTANCE.getGroup(n);  
  16.   }  
  17.   /** Set group */  
  18.   protected void setGroup(String group) {  
  19.     int n = SerialNumberManager.INSTANCE.getGroupSerialNumber(group);  
  20.     updatePermissionStatus(PermissionStatusFormat.GROUP, n);  
  21.   }  

就是在同一的SerialNumberManager对象中去获取的。还有在这里定义了统一判断根目录的方法,通过判断名称长度是否为0

  1. /** 
  2.    * Check whether this is the root inode. 
  3.    * 根节点的判断标准是名字长度为0 
  4.    */  
  5.   boolean isRoot() {  
  6.     return name.length == 0;  
  7.   }  

在INode的方法中还有一个个人感觉比较特别的设计就是对于空间使用的计数,这里的空间不单单指的是磁盘空间大小这么一个,他还包括了name space命名空间,这都是为了后面的HDFS的配额机制准备的变量。详情请看

  1. /** Simple wrapper for two counters :  
  2.    *  nsCount (namespace consumed) and dsCount (diskspace consumed). 
  3.    */  
  4.   static class DirCounts {  
  5.     long nsCount = 0;  
  6.     long dsCount = 0;  
  7.       
  8.     /** returns namespace count */  
  9.     long getNsCount() {  
  10.       return nsCount;  
  11.     }  
  12.     /** returns diskspace count */  
  13.     long getDsCount() {  
  14.       return dsCount;  
  15.     }  
  16.   }  

至于怎么使用的,在后面的INodeDirectory中会提及。由于篇幅有限,在INode里还有许多的方法,比如移除自身方法,设计的都挺不错的。

  1. //移除自身节点方法  
  2.   boolean removeNode() {  
  3.     if (parent == null) {  
  4.       return false;  
  5.     } else {  
  6.         
  7.       parent.removeChild(this);  
  8.       parent = null;  
  9.       return true;  
  10.     }  
  11.   }  

.

INodeDirectory

下面来分析分析目录节点类,说到目录,当然一定会有的就是孩子节点了,下面是目录类的成员变量:

  1. /** 
  2.  * Directory INode class. 
  3.  */  
  4. class INodeDirectory extends INode {  
  5.   protected static final int DEFAULT_FILES_PER_DIRECTORY = 5;  
  6.   final static String ROOT_NAME = “”;  
  7.   
  8.   //保存子目录或子文件  
  9.   private List<INode> children;  

知道为什么判断root的依据是length==0?了吧,因为ROOT_NAME本身就被定义为空字符串了。在INodeDirectory中,普通的移除节点的方法如下,采用的是二分搜索的办法

  1. //移除节点方法  
  2.   INode removeChild(INode node) {  
  3.     assert children != null;  
  4.     //用二分法寻找文件节点  
  5.     int low = Collections.binarySearch(children, node.name);  
  6.     if (low >= 0) {  
  7.       return children.remove(low);  
  8.     } else {  
  9.       return null;  
  10.     }  
  11.   }  

如果是我,我估计马上联想到的是遍历搜寻,设计理念确实不同。添加一个孩子的方法,与此类似,不过要多做一步的验证操作

  1. /** 
  2.    * Add a child inode to the directory. 
  3.    *  
  4.    * @param node INode to insert 
  5.    * @param inheritPermission inherit permission from parent? 
  6.    * @return  null if the child with this name already exists;  
  7.    *          node, otherwise 
  8.    */  
  9.   <T extends INode> T addChild(final T node, boolean inheritPermission) {  
  10.     if (inheritPermission) {  
  11.       FsPermission p = getFsPermission();  
  12.       //make sure the  permission has wx for the user  
  13.       //判断用户是否有写权限  
  14.       if (!p.getUserAction().implies(FsAction.WRITE_EXECUTE)) {  
  15.         p = new FsPermission(p.getUserAction().or(FsAction.WRITE_EXECUTE),  
  16.             p.getGroupAction(), p.getOtherAction());  
  17.       }  
  18.       node.setPermission(p);  
  19.     }  
  20.   
  21.     if (children == null) {  
  22.       children = new ArrayList<INode>(DEFAULT_FILES_PER_DIRECTORY);  
  23.     }  
  24.     //二分查找  
  25.     int low = Collections.binarySearch(children, node.name);  
  26.     if(low >= 0)  
  27.       return null;  
  28.     node.parent = this;  
  29.     //在孩子列表中进行添加  
  30.     children.add(-low – 1, node);  
  31.     // update modification time of the parent directory  
  32.     setModificationTime(node.getModificationTime());  
  33.     if (node.getGroupName() == null) {  
  34.       node.setGroup(getGroupName());  
  35.     }  
  36.     return node;  
  37.   }  

目录的删除一般都是以递归的方式执行,同样在这里也是如此

  1. //递归删除文件目录下的所有block块  
  2.   int collectSubtreeBlocksAndClear(List<Block> v) {  
  3.     int total = 1;  
  4.     //直到是空目录的情况,才直接返回  
  5.     if (children == null) {  
  6.       return total;  
  7.     }  
  8.     for (INode child : children) {  
  9.       //递归删除  
  10.       total += child.collectSubtreeBlocksAndClear(v);  
  11.     }  
  12.       
  13.     //删除完毕之后,置为空操作,并返回文件数计数结果  
  14.     parent = null;  
  15.     children = null;  
  16.     return total;  
  17.   }  

递归调用的是子类的同名方法。下面的方法是与上面提到的某个变量有直接关系的方法,配额限制相关,不过这个是命名空间的计数,一个目录算1个,1个新的文件又算一个命名空间,你可以理解为就是文件,目录总数的限制,但是在INodeDirectory中是受限的,受限制的类叫做INodeDirectoryWithQuota,也是将要介绍的类。

  1. /** [email protected]} */  
  2.   DirCounts spaceConsumedInTree(DirCounts counts) {  
  3.     counts.nsCount += 1;  
  4.     if (children != null) {  
  5.       for (INode child : children) {  
  6.         child.spaceConsumedInTree(counts);  
  7.       }  
  8.     }  
  9.     return counts;      
  10.   }  


INodeDirectoryWithQuota

与上个类相比就多了Quota这个单词,Quota在英文中的意思就是”配额“,有容量限制,在这里的容量限制有2个维度,第一个命名空间限制,磁盘空间占用限制,前者避免你创建过多的目录文件,后者避免你占用过大的空间。变量定义如下,他是继承自目录类的

  1. /** 
  2.  * Directory INode class that has a quota restriction 
  3.  * 存在配额限制的目录节点,继承自目录节点 
  4.  */  
  5. class INodeDirectoryWithQuota extends INodeDirectory {  
  6.   //命名空间配额  
  7.   private long nsQuota; /// NameSpace quota  
  8.   //名字空间计数  
  9.   private long nsCount;  
  10.   //磁盘空间配额  
  11.   private long dsQuota; /// disk space quota  
  12.   //磁盘空间占用大小  
  13.   private long diskspace;  

一般此类都可以通过非配额类以参数的形式构造而来,如下

  1. /** Convert an existing directory inode to one with the given quota 
  2.    *  给定目录,通过传入配额限制将之转为配额目录 
  3.    * @param nsQuota Namespace quota to be assigned to this inode 
  4.    * @param dsQuota Diskspace quota to be assigned to this indoe 
  5.    * @param other The other inode from which all other properties are copied 
  6.    */  
  7.   INodeDirectoryWithQuota(long nsQuota, long dsQuota, INodeDirectory other)  
  8.   throws QuotaExceededException {  
  9.     super(other);  
  10.     INode.DirCounts counts = new INode.DirCounts();  
  11.     other.spaceConsumedInTree(counts);  
  12.     this.nsCount= counts.getNsCount();  
  13.     this.diskspace = counts.getDsCount();  
  14.     setQuota(nsQuota, dsQuota);  
  15.   }  

限制的关键方法如下,如果超出规定的配额值,则会抛异常

  1. /** Verify if the namespace count disk space satisfies the quota restriction 
  2.    * 给定一定的误差限制,验证命名空间计数和磁盘空间是否使用超出相应的配额限制,超出则抛异常 
  3.    * @throws QuotaExceededException if the given quota is less than the count 
  4.    */  
  5.   void verifyQuota(long nsDelta, long dsDelta) throws QuotaExceededException {  
  6.     //根据误差值计算新的计数值  
  7.     long newCount = nsCount + nsDelta;  
  8.     long newDiskspace = diskspace + dsDelta;  
  9.     if (nsDelta>0 || dsDelta>0) {  
  10.       //判断新的值是否超出配额的值大小  
  11.       if (nsQuota >= 0 && nsQuota < newCount) {  
  12.         throw new NSQuotaExceededException(nsQuota, newCount);  
  13.       }  
  14.       if (dsQuota >= 0 && dsQuota < newDiskspace) {  
  15.         throw new DSQuotaExceededException(dsQuota, newDiskspace);  
  16.       }  
  17.     }  
  18.   }  


INodeFile

与目录相对应的类就是文件类,在HDFS中文件对应的就是许多个block块嘛,所以比如会有block列表组,当然他也可能会定义每个block的副本数,HDFS中默认是3,

  1. class INodeFile extends INode {  
  2.   static final FsPermission UMASK = FsPermission.createImmutable((short)0111);  
  3.   
  4.   //Number of bits for Block size  
  5.   //48位存储block数据块的大小  
  6.   static final short BLOCKBITS = 48;  
  7.   
  8.   //Header mask 64-bit representation  
  9.   //Format: [16 bits for replication][48 bits for PreferredBlockSize]  
  10.   //前16位保存副本系数,后48位保存优先块大小,下面的headermask做计算时用  
  11.   static final long HEADERMASK = 0xffffL << BLOCKBITS;  
  12.   
  13.   protected long header;  
  14.   //文件数据block块  
  15.   protected BlockInfo blocks[] = null;  

仔细观察,在这里设计者又用长整型变量保存属性值,这里是用前16位保存副本系数后48位保留块大小,对于这个
PreferredBlockSize我个人结合后面的代码,猜测就是我们在hdfs-site.xml文件中设置的块大小值,默认64M.在这里的Block信息就保存在了BlockInfo.如何利用header来求得副本系数呢,在这里给出的办法还是做位运算然后位移操作:

  1. /** 
  2.    * Get block replication for the file  
  3.    * @return block replication value 
  4.    * 得到副本系数通过与掩码计算并右移48位 
  5.    */  
  6.   public short getReplication() {  
  7.     return (short) ((header & HEADERMASK) >> BLOCKBITS);  
  8.   }  

空间计数的计算如下,注意这里的磁盘空间占用计算

  1. @Override  
  2.  DirCounts spaceConsumedInTree(DirCounts counts) {  
  3.    //命名空间消耗加1  
  4.    counts.nsCount += 1;  
  5.    //累加磁盘空间消耗大小  
  6.    counts.dsCount += diskspaceConsumed();  
  7.    return counts;  
  8.  }  

因为是单个文件,命名空间只递增1,对于每个block块的大小计算,可不是简单的block.size这么简单,还要考虑副本情况和最后的文件块正在被写入的情况

  1. //计算磁盘空间消耗的大小  
  2.   long diskspaceConsumed(Block[] blkArr) {  
  3.     long size = 0;  
  4.     for (Block blk : blkArr) {  
  5.       if (blk != null) {  
  6.         size += blk.getNumBytes();  
  7.       }  
  8.     }  
  9.     /* If the last block is being written to, use prefferedBlockSize 
  10.      * rather than the actual block size. 
  11.      * 如果最后一个块正在被写,用内部设置的prefferedBlockSize的值做替换 
  12.      */  
  13.     if (blkArr.length > 0 && blkArr[blkArr.length-1] != null &&   
  14.         isUnderConstruction()) {  
  15.       size += getPreferredBlockSize() – blocks[blocks.length-1].getNumBytes();  
  16.     }  
  17.       
  18.     //每个块乘以相应的副本数  
  19.     return size * getReplication();  
  20.   }  

在block的操作中,一般都是针对最后一个block块的获取,移除操作

  1. /** 
  2.    * Return the last block in this file, or null if there are no blocks. 
  3.    * 获取文件的最后一个block块 
  4.    */  
  5.   Block getLastBlock() {  
  6.     if (this.blocks == null || this.blocks.length == 0)  
  7.       return null;  
  8.     return this.blocks[this.blocks.length – 1];  
  9.   }  
  1. /** 
  2.    * add a block to the block list 
  3.    * 往block列表中添加block块 
  4.    */  
  5.   void addBlock(BlockInfo newblock) {  
  6.     if (this.blocks == null) {  
  7.       this.blocks = new BlockInfo[1];  
  8.       this.blocks[0] = newblock;  
  9.     } else {  
  10.       int size = this.blocks.length;  
  11.       BlockInfo[] newlist = new BlockInfo[size + 1];  
  12.       System.arraycopy(this.blocks, 0, newlist, 0, size);  
  13.       newlist[size] = newblock;  
  14.       this.blocks = newlist;  
  15.     }  
  16.   }  




INodeFileUnderConstruction

这个类的名字有点长,他的意思是处于构建状态的文件类,是INodeFile的子类,就是当文件被操作的时候,就转变为此类的形式了,与block读写操作的关系比较密切些。变量定义如下

  1. //处于构建状态的文件节点  
  2. class INodeFileUnderConstruction extends INodeFile {  
  3.   //写文件的客户端名称,也是这个租约的持有者  
  4.   String clientName;         // lease holder  
  5.   //客户端所在的主机  
  6.   private final String clientMachine;  
  7.   //如果客户端同样存在于集群中,则记录所在的节点  
  8.   private final DatanodeDescriptor clientNode; // if client is a cluster node too.  
  9.     
  10.   //租约恢复时的节点  
  11.   private int primaryNodeIndex = –1//the node working on lease recovery  
  12.   //最后一个block块所处的节点组,又名数据流管道成员  
  13.   private DatanodeDescriptor[] targets = null;   //locations for last block  
  14.   //最近租约恢复时间  
  15.   private long lastRecoveryTime = 0;  

对于处于构建状态的节点来说,他的操作也是往最后一个block添加数据,设计在这里还保留了最后一个块的所在的数据节点列表。相关方法

  1. //设置新的block块,并且为最后的块赋值新的targes节点  
  2.   synchronized void setLastBlock(BlockInfo newblock, DatanodeDescriptor[] newtargets  
  3.       ) throws IOException {  
  4.     if (blocks == null || blocks.length == 0) {  
  5.       throw new IOException(“Trying to update non-existant block (newblock=”  
  6.           + newblock + “)”);  
  7.     }  
  8.     BlockInfo oldLast = blocks[blocks.length – 1];  
  9.     if (oldLast.getBlockId() != newblock.getBlockId()) {  
  10.       // This should not happen – this means that we’re performing recovery  
  11.       // on an internal block in the file!  
  12.       NameNode.stateChangeLog.error(  
  13.         “Trying to commit block synchronization for an internal block on”  
  14.         + ” inode=” + this  
  15.         + ” newblock=” + newblock + ” oldLast=” + oldLast);  
  16.       throw new IOException(“Trying to update an internal block of “ +  
  17.                             “pending file “ + this);  
  18.     }  
  19.       
  20.     //如果新的block时间比老block的还小的话,则进行警告  
  21.     if (oldLast.getGenerationStamp() > newblock.getGenerationStamp()) {  
  22.       NameNode.stateChangeLog.warn(  
  23.         “Updating last block “ + oldLast + ” of inode “ +  
  24.         “under construction “ + this + ” with a block that “ +  
  25.         “has an older generation stamp: “ + newblock);  
  26.     }  
  27.   
  28.     blocks[blocks.length – 1] = newblock;  
  29.     setTargets(newtargets);  
  30.     //重置租约恢复时间,这样操作的话,下次租约检测时将会过期  
  31.     lastRecoveryTime = 0;  
  32.   }  



移除块操作也是移除最后一个block,数据节点列表也将被清空

  1. /** 
  2.   * remove a block from the block list. This block should be 
  3.   * the last one on the list. 
  4.   * 在文件所拥有的block列表中移动掉block,这个block块应该是最后一个block块 
  5.   */  
  6.  void removeBlock(Block oldblock) throws IOException {  
  7.    if (blocks == null) {  
  8.      throw new IOException(“Trying to delete non-existant block “ + oldblock);  
  9.    }  
  10.    int size_1 = blocks.length – 1;  
  11.    if (!blocks[size_1].equals(oldblock)) {  
  12.      //如果不是最末尾一个块则将会抛异常  
  13.      throw new IOException(“Trying to delete non-last block “ + oldblock);  
  14.    }  
  15.   
  16.    //copy to a new list  
  17.    BlockInfo[] newlist = new BlockInfo[size_1];  
  18.    System.arraycopy(blocks, 0, newlist, 0, size_1);  
  19.    blocks = newlist;  
  20.      
  21.    // Remove the block locations for the last block.  
  22.    // 最后一个数据块所对应的节点组就被置为空了  
  23.    targets = null;  
  24.  }  

另外判断租约过期的方法如下

  1. /** 
  2.    * Update lastRecoveryTime if expired. 
  3.    * @return true if lastRecoveryTimeis updated.  
  4.    * 设置最近的恢复时间 
  5.    */  
  6.   synchronized boolean setLastRecoveryTime(long now) {  
  7.     boolean expired = now – lastRecoveryTime > NameNode.LEASE_RECOVER_PERIOD;  
  8.     if (expired) {  
  9.       //如果过期了则设置为传入的当前时间  
  10.       lastRecoveryTime = now;  
  11.     }  
  12.     return expired;  
  13.   }  


总结

HDFS中的INode文件相关源码分析就是上述所说的了,上面只是部分我的代码分析,全部代码链接如下

https://github.com/linyiqun/hadoop-hdfs,后续将会继续更新HDFS其他方面的代码分析。

参考文献

《Hadoop技术内部–HDFS结构设计与实现原理》.蔡斌等

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/9184.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论