DataNode读数据

DataXceiverServer接受客户端请求,从而为每个客户端开辟一个DataXceiver线程。

在run()函数中,调用readBlock()读取本地数据并发送给客户端。内部会new一个块发送器,并调用sendBlock()真正发送数据。

 

具体步骤如下:

 一、DataNode为一个Block创建BlockSender对象,会做一些初始化工作

(1)  判断block对应的meta文件是否存在,建立校验文件的输入流checksumIn,读取meta文件的文件头

(2) startoffset:要读取数据的位置;endoffset:初始化为block长度blockLength;length:客户端需要读取的长度

      offset = (startOffset - (startOffset % 512));//为了校验的需要,从文件中读取的开始位置。即startOffset落在512的中间位置时,将offset提前

      endOffset:如果startOffset + length不能被512整除,则将endOffset设置到startOffset + length偏后能整除512的位置,如果是文件尾,则endOffset为文件尾。

(3)  由于客户端需要校验,datanode返回需要包括校验的部分。meta文件记录了整个Block的校验信息。此时,需要将校验文件中跳过offset/512*4前面的长度,这部分是不需要的

(4) 创建block文件的输入流blockIn,并seek到offset的位置。至此,BlockSender构造完毕。源码如下:

BlockSender构造函数:

  1. BlockSender(Block block, long startOffset, long length, boolean corruptChecksumOk, boolean chunkOffsetOK, boolean verifyChecksum, DataNode datanode, String clientTraceFmt)  
  2.       throws IOException {  
  3.     try {  
  4.       this.block = block;  
  5.       this.chunkOffsetOK = chunkOffsetOK;  
  6.       this.corruptChecksumOk = corruptChecksumOk;  
  7.       this.verifyChecksum = verifyChecksum;  
  8.       this.blockLength = datanode.data.getLength(block);  
  9.       this.transferToAllowed = datanode.transferToAllowed;  
  10.       this.clientTraceFmt = clientTraceFmt;  
  11.   
  12.       //Block存在对应的校验和文件  
  13.       if ( !corruptChecksumOk || datanode.data.metaFileExists(block) ) {  
  14.         //创建Block对应的校验和数据读取流  
  15.         checksumIn = new DataInputStream(new BufferedInputStream(datanode.data.getMetaDataInputStream(block),BUFFER_SIZE));  
  16.   
  17.         //创建产生Block校验和文件的校验器  
  18.        BlockMetadataHeader header = BlockMetadataHeader.readHeader(checksumIn);  
  19.        short version = header.getVersion();  
  20.   
  21.         if (version != FSDataset.METADATA_VERSION) {  
  22.           LOG.warn("Wrong version (" + version + ") for metadata file for "  + block + " ignoring ...");  
  23.         }  
  24.           
  25.         checksum = header.getChecksum();  
  26.           
  27.       } else {  
  28.         LOG.warn("Could not find metadata file for " + block);  
  29.         //创建一个默认的校验器  
  30.         checksum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_NULL,16 * 1024);  
  31.       }  
  32.   
  33.       //调整校验器      
  34.       bytesPerChecksum = checksum.getBytesPerChecksum();  
  35.       if (bytesPerChecksum > 10*1024*1024 && bytesPerChecksum > blockLength){  
  36.         checksum = DataChecksum.newDataChecksum(checksum.getChecksumType(), Math.max((int)blockLength, 10*1024*1024));  
  37.         bytesPerChecksum = checksum.getBytesPerChecksum();          
  38.       }  
  39.       checksumSize = checksum.getChecksumSize();  
  40.   
  41.       if (length < 0) {  
  42.         length = blockLength;  
  43.       }  
  44.   
  45.       endOffset = blockLength;  
  46.       if (startOffset < 0 || startOffset > endOffset || (length + startOffset) > endOffset) {  
  47.         String msg = " Offset " + startOffset + " and length " + length + " don't match block " + block + " ( blockLen " + endOffset + " )";  
  48.         LOG.warn(datanode.dnRegistration + ":sendBlock() : " + msg);  
  49.         throw new IOException(msg);  
  50.       }  
  51.   
  52.       //根据校验器调整读取的开始位置和结束位置  
  53.       offset = (startOffset - (startOffset % bytesPerChecksum));  
  54.       if (length >= 0) {  
  55.         // Make sure endOffset points to end of a checksumed chunk.  
  56.         long tmpLen = startOffset + length;  
  57.         if (tmpLen % bytesPerChecksum != 0) {  
  58.           tmpLen += (bytesPerChecksum - tmpLen % bytesPerChecksum);  
  59.         }  
  60.         if (tmpLen < endOffset) {  
  61.           endOffset = tmpLen;  
  62.         }  
  63.       }  
  64.   
  65.       //根据待读取数据的开始位置定位到校验和的开始位置  
  66.       if (offset > 0) {  
  67.         long checksumSkip = (offset / bytesPerChecksum) * checksumSize;  
  68.         // note blockInStream is  seeked when created below  
  69.         if (checksumSkip > 0) {  
  70.           // Should we use seek() for checksum file as well?  
  71.           IOUtils.skipFully(checksumIn, checksumSkip);  
  72.         }  
  73.       }  
  74.       seqno = 0;  
  75.   
  76.       //定位到待去读数据的开始位置  
  77.       blockIn = datanode.data.getBlockInputStream(block, offset); // seek to offset  
  78.     } catch (IOException ioe) {  
  79.       IOUtils.closeStream(this);  
  80.       IOUtils.closeStream(blockIn);  
  81.       throw ioe;  
  82.     }  
  83.   }  

 

二、通过blockSender.sendBlock()发送数据

     如果此时读取的是整个block文件,则从流中读取状态码。如果成功校验的,则通知block扫描器此块正常,无需再次校验

(1)  发送校验头信息,包括校验类型等

(2) maxChunkPerPacket:64K的buffer向上取512的整除/512。

        pktSize = HEADER + (512 + 4)*maxChunkPerPacket,并allocate pktSize长度的pktBuf

(3) 循环通过sendChunks()发送,直到到达endOffset为止

(4) 发送“0”标示读取结束

BlockSender用数据包的方式向接收端发送数据,一个数据包可能包含若干个校验数据块,但它并不需要接收端发送对数据包的确认帧,自己也不接受这些确认帧。一个数据包的格式如下:


packetLen:数据包长度;

offset:数据包中的数据在Block中的开始位置;

seqno:数据包的编号;

endFlag:是否没有数据包标志(0/1);

len:数据包中数据的长度;

chunksum:一个校验和;

datachunk:一个校验数据块;


  1. //向接收端发送数据  
  2.   long sendBlock(DataOutputStream out, OutputStream baseStream, BlockTransferThrottler throttler) throws IOException {  
  3.         
  4.     if( out == null ) {  
  5.       throw new IOException( "out stream is null" );  
  6.     }  
  7.       
  8.     this.throttler = throttler;  
  9.   
  10.     long initialOffset = offset;  
  11.     long totalRead = 0;  
  12.     OutputStream streamForSendChunks = out;  
  13.       
  14.     try {  
  15.       try {  
  16.         checksum.writeHeader(out);//发送校验器信息  
  17.         if ( chunkOffsetOK ) {  
  18.           out.writeLong( offset );  
  19.         }  
  20.         out.flush();  
  21.       } catch (IOException e) { //socket error  
  22.         throw ioeToSocketException(e);  
  23.       }  
  24.         
  25.       int maxChunksPerPacket;  
  26.       int pktSize = DataNode.PKT_HEADER_LEN + SIZE_OF_INTEGER;  
  27.         
  28.       if (transferToAllowed && !verifyChecksum && baseStream instanceof SocketOutputStream && blockIn instanceof FileInputStream) {  
  29.           
  30.         FileChannel fileChannel = ((FileInputStream)blockIn).getChannel();  
  31.           
  32.         // blockInPosition also indicates sendChunks() uses transferTo.  
  33.         blockInPosition = fileChannel.position();  
  34.         streamForSendChunks = baseStream;  
  35.           
  36.         //计算一个数据包最多包含多少个数据校验快块  
  37.         maxChunksPerPacket = (Math.max(BUFFER_SIZE, MIN_BUFFER_WITH_TRANSFERTO) + bytesPerChecksum - 1)/bytesPerChecksum;  
  38.           
  39.         //计算一个数据包的大小   
  40.         pktSize += checksumSize * maxChunksPerPacket;  
  41.       } else {  
  42.         //计算一个数据包最多包含多少个数据检验块  
  43.         maxChunksPerPacket = Math.max(1,(BUFFER_SIZE + bytesPerChecksum - 1)/bytesPerChecksum);  
  44.         //计算一个数据包的大小  
  45.         pktSize += (bytesPerChecksum + checksumSize) * maxChunksPerPacket;  
  46.       }  
  47.   
  48.       ByteBuffer pktBuf = ByteBuffer.allocate(pktSize);  
  49.   
  50.       //一个一个数据包发送数据  
  51.       while (endOffset > offset) {  
  52.         long len = sendChunks(pktBuf, maxChunksPerPacket, streamForSendChunks);  
  53.         offset += len;  
  54.         totalRead += len + ((len + bytesPerChecksum - 1)/bytesPerChecksum* checksumSize);  
  55.         seqno++;  
  56.       }  
  57.       try {  
  58.         out.writeInt(0); //标记数据已发送完          
  59.         out.flush();  
  60.       } catch (IOException e) { //socket error  
  61.         throw ioeToSocketException(e);  
  62.       }  
  63.     } finally {  
  64.       if (clientTraceFmt != null) {  
  65.         ClientTraceLog.info(String.format(clientTraceFmt, totalRead));  
  66.       }  
  67.       close();  
  68.     }  
  69.   
  70.     blockReadFully = (initialOffset == 0 && offset >= blockLength);  
  71.   
  72.     return totalRead;  
  73.   }  

三、sendChunks():

(1)  int len = Math.min((int) (endOffset - offset), bytesPerChecksum*maxChunks);  //表示本次要发送的数据的长度

(2) int numChunks = (len + bytesPerChecksum - 1)/bytesPerChecksum;

      int packetLen = len + numChunks*checksumSize + 4

     int checksumOff = pkt.position();  

     int checksumLen = numChunks * checksumSize;

     byte[] buf = pkt.array();

     checksumIn.readFully(buf, checksumOff, checksumLen);  //将校验数据读入buf中

     sockOut.transferToFully(((FileInputStream)blockIn).getChannel(),  blockInPosition, len);  //将数据通过“零拷贝”方式输出

  1.  /*发送一个数据包*/  
  2.   private int sendChunks(ByteBuffer pkt, int maxChunks, OutputStream out) throws IOException {  
  3.     //计算数据包的长度  
  4.     int len = Math.min((int) (endOffset - offset), bytesPerChecksum*maxChunks);  
  5.     if (len == 0) {  
  6.       return 0;  
  7.     }  
  8.   
  9.     //计算这个数据包中应该包含有多少个校验数据块  
  10.     int numChunks = (len + bytesPerChecksum - 1)/bytesPerChecksum;  
  11.     int packetLen = len + numChunks*checksumSize + 4;  
  12.     pkt.clear();  
  13.       
  14.     //数据包头部信息写入缓存  
  15.     pkt.putInt(packetLen);  
  16.     pkt.putLong(offset);  
  17.     pkt.putLong(seqno);  
  18.     pkt.put((byte)((offset + len >= endOffset) ? 1 : 0));  
  19.     pkt.putInt(len);  
  20.       
  21.     int checksumOff = pkt.position();  
  22.     int checksumLen = numChunks * checksumSize;  
  23.     byte[] buf = pkt.array();  
  24.       
  25.     //数据对应的校验和信息写入缓存  
  26.     if (checksumSize > 0 && checksumIn != null) {  
  27.       try {  
  28.         checksumIn.readFully(buf, checksumOff, checksumLen);  
  29.       } catch (IOException e) {  
  30.         LOG.warn(" Could not read or failed to veirfy checksum for data" + " at offset " + offset + " for block " + block + " got : " + StringUtils.stringifyException(e));  
  31.         IOUtils.closeStream(checksumIn);  
  32.         checksumIn = null;  
  33.         if (corruptChecksumOk) {  
  34.           if (checksumOff < checksumLen) {  
  35.             // Just fill the array with zeros.  
  36.             Arrays.fill(buf, checksumOff, checksumLen, (byte0);  
  37.           }  
  38.         } else {  
  39.           throw e;  
  40.         }  
  41.       }  
  42.     }  
  43.       
  44.     int dataOff = checksumOff + checksumLen;  
  45.       
  46.     if (blockInPosition < 0) {  
  47.       //数据写入缓存  
  48.       IOUtils.readFully(blockIn, buf, dataOff, len);  
  49.   
  50.       //对发送的数据验证校验和  
  51.       if (verifyChecksum) {  
  52.         int dOff = dataOff;  
  53.         int cOff = checksumOff;  
  54.         int dLeft = len;  
  55.   
  56.         for (int i=0; i<numChunks; i++) {  
  57.           checksum.reset();  
  58.           int dLen = Math.min(dLeft, bytesPerChecksum);  
  59.           checksum.update(buf, dOff, dLen);  
  60.           if (!checksum.compare(buf, cOff)) {  
  61.             throw new ChecksumException("Checksum failed at " + (offset + len - dLeft), len);  
  62.           }  
  63.           dLeft -= dLen;  
  64.           dOff += dLen;  
  65.           cOff += checksumSize;  
  66.         }  
  67.       }  
  68.       //writing is done below (mainly to handle IOException)  
  69.     }  
  70.       
  71.     try {  
  72.       if (blockInPosition >= 0) {  
  73.         //use transferTo(). Checks on out and blockIn are already done.   
  74.   
  75.         SocketOutputStream sockOut = (SocketOutputStream)out;  
  76.         //发送缓存的数据包  
  77.         sockOut.write(buf, 0, dataOff);  
  78.         // no need to flush. since we know out is not a buffered stream.   
  79.   
  80.         sockOut.transferToFully(((FileInputStream)blockIn).getChannel(),  blockInPosition, len);  
  81.   
  82.         blockInPosition += len;  
  83.       } else {  
  84.         //发送缓存的数据包  
  85.         out.write(buf, 0, dataOff + len);  
  86.       }  
  87.         
  88.     } catch (IOException e) {  
  89.       /* exception while writing to the client (well, with transferTo(), 
  90.        * it could also be while reading from the local file). 
  91.        */  
  92.       throw ioeToSocketException(e);  
  93.     }  
  94.   
  95.     if (throttler != null) { //调整发送速度  
  96.       throttler.throttle(packetLen);  
  97.     }  
  98.   
  99.     return len;  
  100.   }  

注:由于读写同一个块的存在,写入数据文件和校验文件有先后,读取时可能会校验失败。此时判断是否block有变化,是则读取数据文件并计算校验值,更新buf中的校验信息,发送到客户端,保证正确。

 

客户端会校验数据的正确性,并发送OP_STATUS_CHECKSUM_OK给datanode,读取成功!



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值