本文来学习一下HDFS中的块状态和副本状态。
参考资料:《Hadoop 2.X HDFS源码剖析》--徐鹏
HDFS是个分布式存储系统,分布式系统都会遇到各种各样的节点故障问题。试想一下,有个client向hdfs中写数据,这个写数据的过程中会存在各种各样的问题,比如已经建立好的pipeline中有一个datanode挂掉了,那此时向每个datanode写入的数据块长度可能不一致,就需要进行pipeline recovery和block recovery来选择一个新的datanode替代刚才挂掉的节点,并且把block的长度变得一致。这些过程都依赖于数据块的状态和副本状态来实现。
介绍数据块和副本之前,我们要明白这样一个概念:在Namenode中的数据块信息叫做数据块(Block),Datanode中保存的数据块称为副本(Replica)。
首先来看副本的状态,HDFS定义的副本主要有5种状态:
enum ReplicaState {
/** Replica is finalized. The state when replica is not modified. */
FINALIZED(0),
/** Replica is being written to. */
RBW(1),
/** Replica is waiting to be recovered. */
RWR(2),
/** Replica is under recovery. */
RUR(3),
/** Temporary replica: created for replication and relocation only. */
TEMPORARY(4);
//省略其他非关键代码
FINALIZED:
Datanode上的副本已完成写操作,不再修改。FINALIZED状态的副本使用FinalizedReplica类描述。RBW(ReplicaBeingWritten):
刚刚被创建或者追加写的副本,处于写操作的数据流管道中,正在被写入,且已写入副本的内容还是可读的。RUR(ReplicaUnderRecovery):
租约过期之后发生租约恢复和数据块恢复时副本所处的状态。RUR状态的副本使用ReplicaUnderRecovery类描述。
RWR(ReplicaWaitingToBeRecoverd):
如果一个Datanode挂掉并且重启之后,所有RBW状态的副本都将转换为RWR状态。RWR状态的副本不会出现在数据流管道中,结果就是等着进行租约恢复操作。TEMPORARY(ReplicaInPipeline):
Datanode之间传输副本时,正在传输的副本就处于TEMPORARY状态。和RBW状态不同的是,TEMPORARY状态的副本内容是不可读,如果datanode重启,会直接删除处于TEMPORARY状态的副本。
接下来看看HDFS中数据块都有哪些状态吧:
/**
* States, which a block can go through while it is under construction.
*/
enum BlockUCState {
/**
* Block construction completed.<br>
* The block has at least the configured minimal replication number
* of {@link ReplicaState#FINALIZED} replica(s), and is not going to be
* modified.
* NOTE, in some special cases, a block may be forced to COMPLETE state,
* even if it doesn't have required minimal replications.
*/
COMPLETE,
/**
* The block is under construction.<br>
* It has been recently allocated for write or append.
*/
UNDER_CONSTRUCTION,
/**
* The block is under recovery.<br>
* When a file lease expires its last block may not be {@link #COMPLETE}
* and needs to go through a recovery procedure,
* which synchronizes the existing replicas contents.
*/
UNDER_RECOVERY,
/**
* The block is committed.<br>
* The client reported that all bytes are written to data-nodes
* with the given generation stamp and block length, but no
* {@link ReplicaState#FINALIZED}
* replicas has yet been reported by data-nodes themselves.
*/
COMMITTED
}
COMPLETE:
数据块的length(长度)和gc(时间戳)不再发生变化,并且Namenode已经收到至少一个Datanode报告有FINALIZED状态的副本(Datanode上的副本状态发生变化时会通过blockReveivedAndDeleted()方法向Namenode汇报)。只有当HDFS文件的所有数据块都处于COMPLETE状态时,该HDFS文件才能被关闭。UNDER_CONSTRUCTION:
顾名思义,在构建中。文件被创建或者进行追加写操作时,正在被写入的数据块处于此状态,处于此状态的数据块的length(长度)和gc(时间戳)都是可变的,处于该状态的数据块对于读取操作来说是可见的。UNDER_RECOVERY:
如果一个文件的最后一个数据块处于UNDER_CONSTRUCTION状态时,客户端异常退出,该文件的租约超过softLimit过期,该数据块就需要进行租约恢复和数据块恢复来释放租约并关闭文件。进行租约恢复和块恢复流程的数据块就处于UNDER_RECOVERY状态。COMMITTED:
客户端在写文件中,每次请求新的数据块(addBlock RPC)或者关闭文件时,都会顺带对上一个数据块进行提交操作(上一个数据块从UNDER_CONSTRUCTION变为COMMITTED状态)。COMMITTED状态的数据块表明客户端已经把该数据块的所有数据都发送到了Datanode所组成的数据流管道(pipeline)中,并且已经收到了下游的ACK回应,但是Namenode还没有收到任何一个Datanode汇报有FINALIZED副本。