forked from colinmarc/hdfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block_stream.go
324 lines (269 loc) · 7.9 KB
/
block_stream.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package rpc
import (
"bufio"
"bytes"
"code.google.com/p/goprotobuf/proto"
"encoding/binary"
"errors"
"fmt"
hdfs "github.com/colinmarc/hdfs/protocol/hadoop_hdfs"
"hash/crc32"
"io"
"io/ioutil"
"math"
"net"
)
// blockStream implements io.ReaderCloser for reading a single block from HDFS,
// from a single datanode.
type blockStream struct {
address string
block *hdfs.LocatedBlockProto
closed bool
conn net.Conn
reader *bufio.Reader
checksumTab *crc32.Table
startOffset uint64
chunkSize uint32
packet openPacket
buf bytes.Buffer
}
type openPacket struct {
numChunks int
nextChunk int
checksumBytes []byte
blockOffset uint64
packetOffset uint64
length uint64
last bool
}
// newBlockStream returns a new connected blockStream.
func newBlockStream(address string, block *hdfs.LocatedBlockProto, offset uint64) (*blockStream, error) {
s := &blockStream{
address: address,
block: block,
startOffset: offset,
}
err := s.connect()
if err != nil {
return nil, err
}
return s, nil
}
func (s *blockStream) connect() error {
conn, err := net.DialTimeout("tcp", s.address, connectionTimeout)
if err != nil {
return err
}
s.conn = conn
err = s.writeBlockReadRequest()
if err != nil {
return err
}
s.reader = bufio.NewReader(s.conn)
resp, err := s.readBlockReadResponse()
if err != nil {
return err
}
checksumInfo := resp.GetReadOpChecksumInfo().GetChecksum()
checksumType := checksumInfo.GetType()
if checksumType == hdfs.ChecksumTypeProto_CHECKSUM_CRC32 {
s.checksumTab = crc32.IEEETable
} else if checksumType == hdfs.ChecksumTypeProto_CHECKSUM_CRC32C {
s.checksumTab = crc32.MakeTable(crc32.Castagnoli)
} else {
return fmt.Errorf("Unsupported checksum type: %d", checksumType)
}
s.chunkSize = checksumInfo.GetBytesPerChecksum()
s.startNewPacket()
// The read will start aligned to a chunk boundary, so we need to seek forward
// to the requested offset.
amountToDiscard := s.startOffset - s.packet.blockOffset
if amountToDiscard > 0 {
io.CopyN(ioutil.Discard, s, int64(amountToDiscard))
}
return nil
}
func (s *blockStream) Close() {
s.conn.Close()
s.closed = true
}
func (s *blockStream) Read(b []byte) (int, error) {
if s.closed {
return 0, io.ErrClosedPipe
}
// first, read any leftover data from buf
if s.buf.Len() > 0 {
n, _ := s.buf.Read(b)
return n, nil
}
if s.packet.nextChunk >= s.packet.numChunks {
if s.packet.last {
return 0, io.EOF
}
s.startNewPacket()
}
// then, read until we fill up b or we reach the end of the packet
readOffset := 0
for s.packet.nextChunk < s.packet.numChunks {
chOff := 4 * s.packet.nextChunk
checksum := s.packet.checksumBytes[chOff : chOff+4]
remaining := s.packet.length - s.packet.packetOffset
chunkLength := int64(math.Min(float64(s.chunkSize), float64(remaining)))
chunkReader := io.LimitReader(s.reader, int64(chunkLength))
chunkBytes := b[readOffset:]
bytesToRead := int(math.Min(float64(len(chunkBytes)), float64(chunkLength)))
n, err := io.ReadAtLeast(chunkReader, chunkBytes, bytesToRead)
readOffset += n
s.packet.packetOffset += uint64(n)
s.packet.nextChunk++
if err != nil {
s.Close()
return readOffset, err
}
crc := crc32.Checksum(chunkBytes[:n], s.checksumTab)
done := false
if readOffset == len(b) {
done = true
if int64(n) < chunkLength {
// save any leftovers
s.buf.Reset()
leftover, err := s.buf.ReadFrom(chunkReader)
if err != nil {
return readOffset, err
}
s.packet.packetOffset += uint64(leftover)
// update the checksum with the leftovers
crc = crc32.Update(crc, s.checksumTab, s.buf.Bytes())
}
}
if crc != binary.BigEndian.Uint32(checksum) {
return readOffset, errors.New("Invalid checksum from the datanode!")
}
if done {
break
}
}
return readOffset, nil
}
// A read request to a datanode:
// +-----------------------------------------------------------+
// | Data Transfer Protocol Version, int16 |
// +-----------------------------------------------------------+
// | Op code, 1 byte (READ_BLOCK = 0x51) |
// +-----------------------------------------------------------+
// | varint length + OpReadBlockProto |
// +-----------------------------------------------------------+
func (s *blockStream) writeBlockReadRequest() error {
header := []byte{0x00, dataTransferVersion, readBlockOp}
needed := (s.block.GetB().GetNumBytes() - s.startOffset)
op := newBlockReadOp(s.block, s.startOffset, needed)
opBytes, err := makeDelimitedMsg(op)
if err != nil {
return err
}
req := append(header, opBytes...)
_, err = s.conn.Write(req)
if err != nil {
return err
}
return nil
}
// The initial response from the datanode:
// +-----------------------------------------------------------+
// | varint length + BlockOpResponseProto |
// +-----------------------------------------------------------+
func (s *blockStream) readBlockReadResponse() (*hdfs.BlockOpResponseProto, error) {
respLength, err := binary.ReadUvarint(s.reader)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
respBytes := make([]byte, respLength)
_, err = io.ReadFull(s.reader, respBytes)
if err != nil {
return nil, err
}
resp := &hdfs.BlockOpResponseProto{}
err = proto.Unmarshal(respBytes, resp)
if err != nil {
return nil, err
}
return resp, nil
}
// A packet from the datanode:
// +-----------------------------------------------------------+
// | uint32 length of the packet |
// +-----------------------------------------------------------+
// | size of the PacketHeaderProto, uint16 |
// +-----------------------------------------------------------+
// | PacketHeaderProto |
// +-----------------------------------------------------------+
// | N checksums, 4 bytes each |
// +-----------------------------------------------------------+
// | N chunks of payload data |
// +-----------------------------------------------------------+
func (s *blockStream) startNewPacket() error {
header, err := s.readPacketHeader()
if err != nil {
return err
}
blockOffset := uint64(header.GetOffsetInBlock())
dataLength := uint64(header.GetDataLen())
numChunks := int(math.Ceil(float64(dataLength) / float64(s.chunkSize)))
// TODO don't assume checksum size is 4
s.packet = openPacket{
numChunks: numChunks,
nextChunk: 0,
checksumBytes: make([]byte, numChunks*4),
blockOffset: blockOffset,
packetOffset: 0,
length: dataLength,
last: header.GetLastPacketInBlock(),
}
_, err = io.ReadFull(s.reader, s.packet.checksumBytes)
if err != nil {
return err
}
return nil
}
func (s *blockStream) readPacketHeader() (*hdfs.PacketHeaderProto, error) {
var packetLength uint32
err := binary.Read(s.reader, binary.BigEndian, &packetLength)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
var packetHeaderLength uint16
err = binary.Read(s.reader, binary.BigEndian, &packetHeaderLength)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
packetHeaderBytes := make([]byte, packetHeaderLength)
_, err = io.ReadFull(s.reader, packetHeaderBytes)
if err != nil {
return nil, err
}
packetHeader := &hdfs.PacketHeaderProto{}
err = proto.Unmarshal(packetHeaderBytes, packetHeader)
return packetHeader, nil
}
func newBlockReadOp(block *hdfs.LocatedBlockProto, offset, length uint64) *hdfs.OpReadBlockProto {
return &hdfs.OpReadBlockProto{
Header: &hdfs.ClientOperationHeaderProto{
BaseHeader: &hdfs.BaseHeaderProto{
Block: block.GetB(),
Token: block.GetBlockToken(),
},
ClientName: proto.String(ClientName),
},
Offset: proto.Uint64(offset),
Len: proto.Uint64(length),
}
}