BlockInfo继承自Block类,是块的信息类,含以下变量:
private INodeFile inode;//块所在的文件(在INodeFile中有INodeFile.blocks表示构成此文件的所有块)
private Object[] triplets;//此块所在的Datanodes三元组,类似于双向链表
triples的赋值方法:
this.triplets = new Object[3*replication];//replicaton是此块的副本数
可以看出triples数组存放了块的每个副本所在的Datanode,块i所在的Datanode对应为triples[3*i],而triples[3*i+1]表示此块所在Datanode上的前一个块信息,triples[3*i+2]表示此块所在的DataNode上的后一个块信息(DatanodeDescriptor将Datanode上的块串成一个表,DatanodeDescriptor上保存了表头信息BlockInfo blockList)。因此triples[3*i]为DatanodeDescriptor类型,triples[3*i+1]、triples[3*i+2]是BlockInfo类型。
通过此三元组可以实现如下的映射:INode<-->BlockInfo,BlockInfo<-->DatanodeDescriptor。由于DatanodeDescriptor上有
private volatile BlockInfo blockList = null;
可以在Datanode出现错误时,根据blockList进行块备份。
文件的每个块的BlockInfo中保存了这个块的所有副本所在的Datanode表triples,在每个Datanode的描述类DatanodeDescriptor中保存了由Datanode上的所有块构成的一个块链。Datanode上的块链是用triples实现的。
一些重要的方法:
boolean addNode(DatanodeDescriptor node);//添加一个新的Datanode到triples,即此块多备份一个副本。
int ensureCapacity(int num);//确保再添加num个块到triples时,triples长度够用。必要时对triples进行扩充(扩充是新new一个长度符合的数组,然后再System.arrayCopy。由于每个块的副本数不多,所以这种扩充方式还是可以接受的)。
int findDatanode(DatanodeDescriptor dn);//获得Datanode dn上的块在triples中的位置
BlockInfo getNext(int index);//获取在Datanode triples[3*index]上块index的下一个块信息
boolean removeNode(DatanodeDescriptor node);//将node对应的BlockInfo从triples中清除掉:将triples的最后一个块x移到node对应的块的位置,同时将x在Datanode中的前驱后继也都移过来,这样就替换掉了node。这会造成triples最后几个块空。所以用numNodes()得到triples的有效大小。
int numNodes();//获得此块有效的副本数。
int getCapacity();//返回triples的实际大小。
int listCount(DatanodeDescriptor dn);//在dn上,统计当前块后面还有几个块。
boolean listIsConsistent(DatanodeDescriptor dn);//在dn上,检测从当前块开始,后面的块之间的对应关系(双向链表)是否一致。即blockA.next.previous==blockA
BlockInfo listInsert(BlockInfo head, DatanodeDescriptor dn) {//用于将此块(本类this)插入到dn的块链最前面
int dnIndex = this.findDatanode(dn);
assert dnIndex >= 0 : "Data node is not found: current";
assert getPrevious(dnIndex) == null && getNext(dnIndex) == null :
"Block is already in the list and cannot be inserted.";
this.setPrevious(dnIndex, null);//在Datanode中,设置此块前面无块
this.setNext(dnIndex, head);//在Datanode中,设置此块下一个块为Datanode块链的块首
if(head != null)
head.setPrevious(head.findDatanode(dn), this);//设置Datanode上的块首的前一个块为当前块
return this;
}
BlockInfo listRemove(BlockInfo head, DatanodeDescriptor dn) {
//将此块从Datanode的块链中删除。类似于双向链表删除的方式,将dn对应的块从triples中‘移出’(通过修改原本的前驱后继)。
if(head == null)
return null;
int dnIndex = this.findDatanode(dn);
if(dnIndex < 0) // this block is not on the data-node list
return head;
BlockInfo next = this.getNext(dnIndex);
BlockInfo prev = this.getPrevious(dnIndex);
this.setNext(dnIndex, null);
this.setPrevious(dnIndex, null);
if(prev != null)
prev.setNext(prev.findDatanode(dn), next);
if(next != null)
next.setPrevious(next.findDatanode(dn), prev);
if(this == head) // removing the head
head = next;
return head;
}
