forked from cloudwego/shmipc-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol_manager.go
407 lines (358 loc) · 12.5 KB
/
protocol_manager.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
* Copyright 2023 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shmipc
import (
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"runtime"
"strings"
"sync/atomic"
"syscall"
)
// Ensure that the index of the handler matches the message type
var (
protocolHandlers = []protocolHandler{
typePolling: handlePolling,
typeStreamClose: handleStreamClose,
typeFallbackData: handleFallbackData,
typeHotRestart: handleHotRestart,
typeHotRestartAck: handleHotRestartAck,
}
protocolTraceMode = false
)
type protocolHandler func(s *Session, eventHeader header, buf []byte) (consumed int, stop bool, err error)
func init() {
if os.Getenv("SHMIPC_PROTOCOL_TRACE") != "" {
protocolTraceMode = true
}
}
type protocolAdaptor struct {
session *Session
}
func newProtocolAdaptor(session *Session) (pm *protocolAdaptor) {
return &protocolAdaptor{session: session}
}
func createProtoVersionInitializer(session *Session, version uint8, firstEvent header) (protocolInitializer, error) {
if f, ok := protocolVersionInitializersFactory[int(version)]; ok {
return f(session, firstEvent), nil
}
return nil, fmt.Errorf("not support the protocol version:%d, maxSupportVersion is %d",
version, maxSupportProtoVersion)
}
func (p *protocolAdaptor) getProtocolInitializer() (protocolInitializer, error) {
if p.session.isClient {
return p.clientGetProtocolInitializer()
}
return p.serverGetProtocolInitializer()
}
func (p *protocolAdaptor) clientGetProtocolInitializer() (initializer protocolInitializer, err error) {
//temporarily ensure version compatibility.
//when all server upgrade to new version, delete this following codes.
if p.session.config.MemMapType == MemMapTypeDevShmFile {
return &protocolInitializerV2{session: p.session}, nil
}
//send version to peer
h := header(make([]byte, headerSize))
clientVersion := int(maxSupportProtoVersion)
h.encode(headerSize, uint8(clientVersion), typeExchangeProtoVersion)
protocolTrace(h, nil, true)
if err := blockWriteFull(p.session.connFd, h); err != nil {
return nil, err
}
// recv peer's version
var recvHeader header
if recvHeader, err = waitEventHeader(p.session.connFd, typeExchangeProtoVersion); err != nil {
return nil, errors.New("protocolInitializerV3 clientInit failed,reason:" + err.Error())
}
serverVersion := recvHeader.Version()
chosenVersion := uint8(minInt(clientVersion, int(serverVersion)))
initializer, err = createProtoVersionInitializer(p.session, chosenVersion, nil)
if err != nil {
return nil, err
}
return
}
func (p *protocolAdaptor) serverGetProtocolInitializer() (protocolInitializer, error) {
//ensure version compatibility
h, err := blockReadEventHeader(p.session.connFd)
if err != nil {
return nil, err
}
initializer, err := createProtoVersionInitializer(p.session, h.Version(), h)
if err != nil {
return nil, err
}
return initializer, nil
}
// handleShareMemoryByFilePath
func handleShareMemoryByFilePath(s *Session, hdr header) error {
s.logger.infof("handleShareMemoryMetadata head:%+v", hdr)
body := make([]byte, hdr.Length()-headerSize)
err := blockReadFull(s.connFd, body)
if err != nil {
//todo
if err != io.EOF && !strings.Contains(err.Error(), "closed") && !strings.Contains(err.Error(), "reset by peer") {
s.logger.errorf("shmipc: Failed to read pathlen: %s", err.Error())
}
return err
}
bufferPath, queuePath := s.extractShmMetadata(body)
qm, err := mappingQueueManager(queuePath)
if err != nil {
return fmt.Errorf("handleShareMemoryByFilePath mappingQueueManager failed,queuePathLen:%d path:%s err=%s",
len(queuePath), queuePath, err.Error())
}
s.queueManager = qm
bm, err := getGlobalBufferManager(bufferPath, 0, false, nil)
if err != nil {
return fmt.Errorf("handleShareMemoryByFilePath mappingBufferManager failed, bufferPathLen:%d path:%s err=%s",
len(bufferPath), bufferPath, err.Error())
}
s.bufferManager = bm
s.handshakeDone = true
return nil
}
// todo with stream'timeout
func handleFallbackData(s *Session, h header, buf []byte) (int, bool, error) {
eventLen := int(h.Length())
payloadLen := eventLen - headerSize
if len(buf) < payloadLen {
return 0, true, nil
}
data := make([]byte, payloadLen)
copy(data, buf[:payloadLen])
const fallbackDataHeader = 8
// fallback data layout: eventHeader | seqID | status | payload
seqID := binary.BigEndian.Uint32(data[:4])
// now the first byte of status is streamState, and the other byte of status is undefined .
status := binary.BigEndian.Uint32(data[4:8]) & 0xff
s.logger.warnf("receive fallback data , length:%d seqID:%d status:%d",
h.Length()-headerSize-fallbackDataHeader, seqID, status)
s.openCircuitBreaker()
fallbackSlice := newBufferSlice(nil, data[fallbackDataHeader:], 0, false)
fallbackSlice.writeIndex = len(data[fallbackDataHeader:])
atomic.AddUint64(&s.stats.fallbackReadCount, 1)
stream := s.getStream(seqID, streamState(status))
if stream == nil {
return eventLen, false, nil
}
return eventLen, false, s.handleStreamMessage(stream, bufferSliceWrapper{fallbackSlice: fallbackSlice}, streamState(status))
}
func handleExchangeVersion(s *Session, h header) error {
respHeader := header(make([]byte, headerSize))
respHeader.encode(headerSize, maxSupportProtoVersion, typeExchangeProtoVersion)
s.communicationVersion = uint8(minInt(int(h.Version()), int(maxSupportProtoVersion)))
protocolTrace(respHeader, nil, true)
return blockWriteFull(s.connFd, respHeader)
}
func handleShareMemoryByMemFd(s *Session, h header) error {
s.logger.infof("recv memfd, header:%s", h.String())
//1.recv shm metadata
body := make([]byte, h.Length()-headerSize)
err := blockReadFull(s.connFd, body)
if err != nil {
return errors.New("read shm metadata failed,reason:" + err.Error())
}
bufferPath, queuePath := s.extractShmMetadata(body)
//2.send AckReadyRecvFD
ack := header(make([]byte, headerSize))
ack.encode(headerSize, s.communicationVersion, typeAckReadyRecvFD)
s.logger.infof("response typeAckReadyRecvFD")
if err := blockWriteFull(s.connFd, ack); err != nil {
return errors.New("send ack typeAckReadyRecvFD failed reason:" + err.Error())
}
s.logger.infof("typeAckReadyRecvFD send finished")
//3.recv fd
oob := make([]byte, syscall.CmsgSpace(memfdCount*memfdDataLen))
s.logger.infof("send ack finished")
oobn, err := blockReadOutOfBoundForFd(s.connFd, oob)
s.logger.infof("recvmsg finished, oob expect len:%d, len:%d", len(oob), oobn)
if err != nil {
return errors.New("try recv fd from peer failed,reason:" + err.Error())
}
if oobn != len(oob) {
return fmt.Errorf("handleShareMemoryByMemFd failed,reason:"+
"ReadOutOfBoundForFd ,expect oobnLen:%d, but oobnLen:%d",
len(oob), oobn)
}
msgs, err := syscall.ParseSocketControlMessage(oob)
if err != nil {
return errors.New("parse socket control message failed,reason:" + err.Error())
}
if len(msgs) == 0 {
return errors.New("parse socket control message ret is nil")
}
fds, err := syscall.ParseUnixRights(&msgs[0])
if err != nil {
return errors.New("parse fd from unix domain failed,reason:" + err.Error())
}
if len(fds) < memfdCount {
s.logger.warnf("ParseUnixRights len fds:%d", len(fds))
return errors.New("the number of memfd received is wrong")
}
bufferFd, queueFd := fds[0], fds[1]
s.logger.infof("recv memfd, bufferPath:%s queuePath:%s bufferFd:%d queueFd:%d",
bufferPath, queuePath, bufferFd, queueFd)
//4.mapping share memory
qm, err := mappingQueueManagerMemfd(queuePath, queueFd)
if err != nil {
return err
}
s.queueManager = qm
bm, err := getGlobalBufferManagerWithMemFd(bufferPath, bufferFd, 0, false, nil)
if err != nil {
return err
}
s.bufferManager = bm
s.handshakeDone = true
s.logger.infof("handleShareMemoryByMemFd done")
return nil
}
func handlePolling(s *Session, hdr header, buf []byte) (int, bool, error) {
atomic.AddUint64(&s.stats.recvPollingEventCount, 1)
consumedCount := 0
var retErr error
for {
for ele, err := s.queueManager.recvQueue.pop(); err == nil; ele, err = s.queueManager.recvQueue.pop() {
consumedCount++
state := streamState(ele.status & 0xff)
stream := s.getStream(ele.seqID, state)
if stream == nil && state == streamOpened {
slice, err := s.bufferManager.readBufferSlice(ele.offsetInShmBuf)
if err != nil {
return headerSize, false, err
}
s.bufferManager.recycleBuffers(slice)
continue
}
if stream == nil {
continue
}
retErr = s.handleStreamMessage(stream, bufferSliceWrapper{offset: ele.offsetInShmBuf}, state)
}
runtime.Gosched()
if s.queueManager.recvQueue.markNotWorking() {
break
}
}
//followings code will bring runtime.convT64, which maybe result in GC.
//s.logger.infof("queue consumer consume size:%d on path:%s now wait", consumedCount, s.queueManager.path)
return headerSize, false, retErr
}
func handleHotRestart(s *Session, hdr header, buf []byte) (int, bool, error) {
if len(buf) < epochIDLen {
return 0, true, nil
}
epochID := binary.BigEndian.Uint64(buf[:epochIDLen])
s.logger.warnf("%s [epoch:%d] receive hot restart", s.sessionName(), epochID)
s.dispatcher.post(func() {
s.manager.handleEvent(typeHotRestart, &sessionManagerHotRestartParams{epoch: epochID, session: s})
})
return headerSize + epochIDLen, false, nil
}
func handleHotRestartAck(s *Session, hdr header, buf []byte) (int, bool, error) {
if len(buf) < epochIDLen {
return 0, true, nil
}
epochID := binary.BigEndian.Uint64(buf[:epochIDLen])
s.logger.warnf("%s [epoch:%d] receive hot restart ack", s.name, epochID)
s.listener.mu.Lock()
defer s.listener.mu.Unlock()
if epochID == s.listener.epoch {
s.listener.hotRestartAckCount--
s.state = hotRestartDoneState
}
return headerSize + epochIDLen, false, nil
}
func handleStreamClose(s *Session, hdr header, buf []byte) (int, bool, error) {
const idLen = 4
if len(buf) < idLen {
return 0, true, nil
}
id := binary.BigEndian.Uint32(buf[:4])
s.logger.debugf("receive peer stream[%d] goaway.", id)
stream := s.getStreamById(id)
if stream == nil {
s.logger.warnf("missing stream: %d", id)
return headerSize + idLen, false, nil
}
stream.halfClose()
return headerSize + idLen, false, nil
}
func protocolTrace(h header, body []byte, send bool) {
if !protocolTraceMode {
return
}
if len(h) < headerSize {
return
}
if send {
protocolLogger.warnf("send, header:%s body:%s", h.String(), string(body))
} else {
protocolLogger.warnf("recv, header:%s body:%s", h.String(), string(body))
}
}
func sendShareMemoryByFilePath(s *Session) error {
data := s.generateShmMetadata(typeShareMemoryByFilePath)
s.logger.infof("send share memory address to peer, size:%d queuePath:%s cap:%d bufferPath:%s cap:%d ",
len(data), s.queueManager.path, len(s.queueManager.mem), s.bufferManager.path, len(s.bufferManager.mem))
protocolTrace(data[:headerSize], data[headerSize:], true)
if err := blockWriteFull(s.connFd, data); err != nil {
return err
}
return nil
}
func sendMemFdToPeer(s *Session) error {
event := s.generateShmMetadata(typeShareMemoryByMemfd)
s.logger.infof("sendMemFdToPeer buffer fd:%d queue fd:%d header:%s",
s.bufferManager.memFd, s.queueManager.memFd, header(event).String())
protocolTrace(event[:headerSize], event[headerSize:], true)
//1. client send the message with typeShareMemoryByMemfd
//2. server reply the message with typeAckReadyRecvFD
//3. client send memfd to server.
if err := blockWriteFull(s.connFd, event); err != nil {
return err
}
if _, err := waitEventHeader(s.connFd, typeAckReadyRecvFD); err != nil {
return err
}
return sendFd(s.connFd, syscall.UnixRights(s.bufferManager.memFd, s.queueManager.memFd))
}
func waitEventHeader(connFd int, expectEventType eventType) (header, error) {
h, err := blockReadEventHeader(connFd)
if err != nil {
return nil, err
}
if h.MsgType() != expectEventType {
return nil, fmt.Errorf("expect eventType:%d %s, but:%d", expectEventType, expectEventType.String(), h.MsgType())
}
return h, nil
}
func blockReadEventHeader(connFd int) (header, error) {
buf := make([]byte, headerSize)
if err := blockReadFull(connFd, buf); err != nil {
return nil, err
}
h := header(buf)
if err := checkEventValid(h); err != nil {
return nil, err
}
protocolTrace(h, nil, false)
return h, nil
}