forked from colinmarc/hdfs
/
block_write_stream.go
370 lines (307 loc) · 8.6 KB
/
block_write_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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package transfer
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"math"
"sync"
"time"
hdfs "github.com/aristanetworks/hdfs/v2/internal/protocol/hadoop_hdfs"
"github.com/golang/protobuf/proto"
)
const (
outboundPacketSize = 65536
outboundChunkSize = 512
maxPacketsInQueue = 5
heartbeatSeqno = -1
heartbeatInterval = 30 * time.Second
)
// heartbeatPacket is sent every 30 seconds to keep the stream alive. It's
// always the same.
var heartbeatPacket []byte
func init() {
b, err := proto.Marshal(&hdfs.PacketHeaderProto{
OffsetInBlock: proto.Int64(0),
Seqno: proto.Int64(heartbeatSeqno),
LastPacketInBlock: proto.Bool(false),
DataLen: proto.Int32(0),
})
if err != nil {
panic(err)
}
header := make([]byte, 6)
binary.BigEndian.PutUint32(header, 4)
binary.BigEndian.PutUint16(header[4:], uint16(len(b)))
heartbeatPacket = append(header, b...)
}
// blockWriteStream writes data out to a datanode, and reads acks back.
type blockWriteStream struct {
block *hdfs.LocatedBlockProto
conn io.ReadWriter
buf bytes.Buffer
offset int64
closed bool
packets chan outboundPacket
seqno int
ackError error
acksDone chan struct{}
lastPacketSeqno int
heartbeats chan struct{}
writeLock sync.Mutex
}
type outboundPacket struct {
seqno int
offset int64
last bool
checksums []byte
data []byte
}
type ackError struct {
pipelineIndex int
seqno int
status hdfs.Status
}
func (ae ackError) Error() string {
return fmt.Sprintf("Ack error from datanode: %s", ae.status.String())
}
var ErrInvalidSeqno = errors.New("invalid ack sequence number")
func newBlockWriteStream(conn io.ReadWriter, offset int64) *blockWriteStream {
s := &blockWriteStream{
conn: conn,
offset: offset,
seqno: 1,
packets: make(chan outboundPacket, maxPacketsInQueue),
acksDone: make(chan struct{}),
heartbeats: make(chan struct{}),
}
// Send idle heartbeats every 30 seconds.
go s.writeHeartbeats()
// Ack packets in the background.
go func() {
s.ackPackets()
close(s.acksDone)
}()
return s
}
// func newBlockWriteStreamForRecovery(conn io.ReadWriter, oldWriteStream *blockWriteStream) {
// s := &blockWriteStream{
// conn: conn,
// buf: oldWriteStream.buf,
// packets: oldWriteStream.packets,
// offset: oldWriteStream.offset,
// seqno: oldWriteStream.seqno,
// packets
// }
// go s.ackPackets()
// return s
// }
func (s *blockWriteStream) Write(b []byte) (int, error) {
if s.closed {
return 0, io.ErrClosedPipe
}
if err := s.getAckError(); err != nil {
return 0, err
}
n, _ := s.buf.Write(b)
err := s.flush(false)
return n, err
}
// finish flushes the rest of the buffered bytes, and then sends a final empty
// packet signifying the end of the block.
func (s *blockWriteStream) finish() error {
if s.closed {
return nil
}
s.closed = true
// Stop sending heartbeats.
close(s.heartbeats)
if err := s.getAckError(); err != nil {
return err
}
if err := s.flush(true); err != nil {
return err
}
// The last packet has no data; it's just a marker that the block is finished.
lastPacket := outboundPacket{
seqno: s.seqno,
offset: s.offset,
last: true,
checksums: []byte{},
data: []byte{},
}
s.packets <- lastPacket
err := s.writePacket(lastPacket)
if err != nil {
return err
}
// Wait for the ack loop to finish.
close(s.packets)
<-s.acksDone
// Check one more time for any ack errors.
if err := s.getAckError(); err != nil {
return err
}
return nil
}
// flush parcels out the buffered bytes into packets, which it then flushes to
// the datanode. We keep around a reference to the packet, in case the ack
// fails, and we need to send it again later.
func (s *blockWriteStream) flush(force bool) error {
s.writeLock.Lock()
defer s.writeLock.Unlock()
for s.buf.Len() > 0 && (force || s.buf.Len() >= outboundPacketSize) {
packet := s.makePacket()
s.packets <- packet
s.offset += int64(len(packet.data))
s.seqno++
err := s.writePacket(packet)
if err != nil {
return err
}
}
return nil
}
func (s *blockWriteStream) makePacket() outboundPacket {
packetLength := outboundPacketSize
if s.buf.Len() < outboundPacketSize {
packetLength = s.buf.Len()
}
// If we're starting from a weird offset (usually because of an Append), HDFS
// gets unhappy unless we first align to a chunk boundary with a small packet.
// Otherwise it yells at us with "a partial chunk must be sent in an
// individual packet" or just complains about a corrupted block.
alignment := int(s.offset) % outboundChunkSize
if alignment > 0 && packetLength > (outboundChunkSize-alignment) {
packetLength = outboundChunkSize - alignment
}
numChunks := int(math.Ceil(float64(packetLength) / float64(outboundChunkSize)))
packet := outboundPacket{
seqno: s.seqno,
offset: s.offset,
last: false,
checksums: make([]byte, numChunks*4),
data: make([]byte, packetLength),
}
// TODO: we shouldn't actually need this extra copy. We should also be able
// to "reuse" packets.
io.ReadFull(&s.buf, packet.data)
// Fill in the checksum for each chunk of data.
for i := 0; i < numChunks; i++ {
chunkOff := i * outboundChunkSize
chunkEnd := chunkOff + outboundChunkSize
if chunkEnd >= len(packet.data) {
chunkEnd = len(packet.data)
}
checksum := crc32.Checksum(packet.data[chunkOff:chunkEnd], crc32.IEEETable)
binary.BigEndian.PutUint32(packet.checksums[i*4:], checksum)
}
return packet
}
// ackPackets is meant to run in the background, reading acks and setting
// ackError if one fails.
func (s *blockWriteStream) ackPackets() {
reader := bufio.NewReader(s.conn)
Acks:
for {
p, ok := <-s.packets
if !ok {
// All packets all acked.
return
}
var seqno int
for {
// If we fail to read the ack at all, that counts as a failure from the
// first datanode (the one we're connected to).
ack := &hdfs.PipelineAckProto{}
err := readPrefixedMessage(reader, ack)
if err != nil {
s.ackError = err
break Acks
}
seqno = int(ack.GetSeqno())
for i, status := range ack.GetReply() {
if status != hdfs.Status_SUCCESS {
s.ackError = ackError{status: status, seqno: seqno, pipelineIndex: i}
break Acks
}
}
if seqno != heartbeatSeqno {
break
}
}
if seqno != p.seqno {
s.ackError = ErrInvalidSeqno
break Acks
}
}
// Once we've seen an error, just keep reading packets off the channel (but
// not off the socket) until the writing thread figures it out. If we don't,
// the upstream thread could deadlock waiting for the channel to have space.
for _ = range s.packets {
}
}
func (s *blockWriteStream) getAckError() error {
select {
case <-s.acksDone:
if s.ackError != nil {
return s.ackError
}
default:
}
return nil
}
// A packet for 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 *blockWriteStream) writePacket(p outboundPacket) error {
headerInfo := &hdfs.PacketHeaderProto{
OffsetInBlock: proto.Int64(p.offset),
Seqno: proto.Int64(int64(p.seqno)),
LastPacketInBlock: proto.Bool(p.last),
DataLen: proto.Int32(int32(len(p.data))),
}
// Don't ask me why this doesn't include the header proto...
totalLength := len(p.data) + len(p.checksums) + 4
header := make([]byte, 6, 6+totalLength)
infoBytes, err := proto.Marshal(headerInfo)
if err != nil {
return err
}
binary.BigEndian.PutUint32(header, uint32(totalLength))
binary.BigEndian.PutUint16(header[4:], uint16(len(infoBytes)))
header = append(header, infoBytes...)
header = append(header, p.checksums...)
header = append(header, p.data...)
_, err = s.conn.Write(header)
if err != nil {
return err
}
return nil
}
func (s *blockWriteStream) writeHeartbeats() {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.writeLock.Lock()
s.conn.Write(heartbeatPacket)
s.writeLock.Unlock()
case <-s.heartbeats:
return
}
}
}