forked from didi/rdebug
/
thread.go
381 lines (355 loc) · 11.3 KB
/
thread.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
package sut
import (
"bytes"
"context"
"net"
"os"
"strings"
"sync"
"time"
"unsafe"
"github.com/didi/rdebug/koala/envarg"
"github.com/didi/rdebug/koala/recording"
"github.com/didi/rdebug/koala/replaying"
"github.com/v2pro/plz/countlog"
)
// InboundRequestPrefix is used to recognize php-fpm FCGI_BEGIN_REQUEST packet.
// fastcgi_finish_request() will send STDOUT first, then recv STDIN (if POST body has not been read before)
// this behavior will trigger session shutdown as we are going to think the recv STDIN
// is the beginning of next request.
// Set InboundRequestPrefix to []byte{1, 1} to only begin new session for FCGI_BEGIN_REQUEST.
// First 0x01 is the version field of fastcgi protocol, second 0x01 is FCGI_BEGIN_REQUEST.
var InboundRequestPrefix = []byte{}
type Thread struct {
context.Context
mutex *sync.Mutex
threadID ThreadID
socks map[SocketFD]*socket
files map[FileFD]*file
recordingSession *recording.Session
replayingSession *replaying.ReplayingSession
lastAccessedAt time.Time
helperResponse []byte
ignoreSocks map[SocketFD]net.TCPAddr
}
type SendFlags int
type RecvFlags int
func (thread *Thread) ExportState() map[string]interface{} {
thread.mutex.Lock()
defer thread.mutex.Unlock()
state := map[string]interface{}{
"ThreadID": thread.threadID,
"LastAccessedAt": thread.lastAccessedAt,
"RecordingSession": thread.recordingSession,
}
return state
}
func (thread *Thread) OnSend(socketFD SocketFD, span []byte, flags SendFlags, extraHeaderSentSize int) {
if len(span) == 0 {
countlog.Debug("event!sut.send-ignore", "threadID", thread.threadID, "socketFD", socketFD)
return
}
if _, ok := thread.ignoreSocks[socketFD]; ok {
return
}
sock := thread.lookupSocket(socketFD)
if sock == nil {
countlog.Warn("event!sut.unknown-send", "threadID", thread.threadID, "socketFD", socketFD)
return
}
event := "event!sut.inbound_send"
if sock.isServer {
thread.recordingSession.SendToInbound(thread, span, sock.addr)
} else {
event = "event!sut.outbound_send"
thread.recordingSession.SendToOutbound(thread, span, sock.addr, sock.localAddr, int(sock.socketFD))
if thread.replayingSession != nil {
if sock.localAddr != nil {
replaying.StoreTmp(*sock.localAddr, thread.replayingSession)
} else {
countlog.Error("event!sut.can not store replaying session due to no local addr",
"threadID", thread.threadID)
}
}
}
countlog.Trace(event,
"threadID", thread.threadID,
"socketFD", socketFD,
"recordingSessionPtr", uintptr(unsafe.Pointer(thread.recordingSession)),
"addr", &sock.addr,
"flags", flags,
"content", span,
"contentLen", len(span))
}
func (thread *Thread) OnRecv(socketFD SocketFD, span []byte, flags RecvFlags) []byte {
if _, ok := thread.ignoreSocks[socketFD]; ok {
countlog.Debug("event!sut.recv-ignore", "threadID", thread.threadID, "socketFD", socketFD)
return span
}
sock := thread.lookupSocket(socketFD)
if sock == nil {
countlog.Warn("event!sut.unknown-recv", "threadID", thread.threadID, "socketFD", socketFD)
return span
}
if !sock.isServer {
countlog.Trace("event!sut.outbound_recv",
"threadID", thread.threadID,
"socketFD", socketFD,
"recordingSessionPtr", uintptr(unsafe.Pointer(thread.recordingSession)),
"addr", &sock.addr,
"content", span,
"contentLen", len(span))
thread.recordingSession.RecvFromOutbound(thread, span, sock.addr, sock.localAddr, int(sock.socketFD))
return span
}
countlog.Trace("event!sut.inbound_recv",
"threadID", thread.threadID,
"socketFD", socketFD,
"recordingSessionPtr", uintptr(unsafe.Pointer(thread.recordingSession)),
"addr", &sock.addr,
"content", span,
"contentLen", len(span))
if span == nil {
return nil
}
if thread.recordingSession.HasResponded() && bytes.HasPrefix(span, InboundRequestPrefix) {
countlog.Trace("event!sut.recv_from_inbound_found_responded",
"threadID", thread.threadID,
"socketFD", socketFD)
thread.shutdownRecordingSession()
}
thread.recordingSession.RecvFromInbound(thread, span, sock.addr, sock.unixAddr)
replayingSession := replaying.RetrieveTmp(sock.addr)
if replayingSession != nil {
nanoOffset := replayingSession.CallFromInbound.GetOccurredAt() - time.Now().UnixNano()
SetTimeOffset(int(time.Duration(nanoOffset) / time.Second))
thread.replayingSession = replayingSession
thread.ignoreSocks = map[SocketFD]net.TCPAddr{}
countlog.Trace("event!sut.received_replaying_session",
"threadID", thread.threadID,
"replayingSessionId", thread.replayingSession.SessionId,
"addr", &sock.addr)
}
return span
}
func (thread *Thread) OnAccept(serverSocketFD SocketFD, clientSocketFD SocketFD, addr net.TCPAddr) {
thread.socks[clientSocketFD] = &socket{
socketFD: clientSocketFD,
isServer: true,
addr: addr,
}
setGlobalSock(clientSocketFD, thread.socks[clientSocketFD])
thread.delReusedIgnoreFD(clientSocketFD, addr)
countlog.Debug("event!sut.accept",
"threadID", thread.threadID,
"serverSocketFD", serverSocketFD,
"socketFD", clientSocketFD,
"addr", &addr)
}
func (thread *Thread) OnAcceptUnix(serverSocketFD SocketFD, clientSocketFD SocketFD, addr net.UnixAddr) {
thread.socks[clientSocketFD] = &socket{
socketFD: clientSocketFD,
isServer: true,
unixAddr: addr,
}
setGlobalSock(clientSocketFD, thread.socks[clientSocketFD])
thread.delReusedIgnoreFD(clientSocketFD, net.TCPAddr{})
countlog.Debug("event!sut.accept_unix",
"threadID", thread.threadID,
"serverSocketFD", serverSocketFD,
"clientSocketFD", clientSocketFD,
"unixAddr", addr)
}
func (thread *Thread) OnBind(socketFD SocketFD, addr net.TCPAddr) {
thread.socks[socketFD] = &socket{
socketFD: socketFD,
isServer: false,
addr: addr,
}
countlog.Debug("event!sut.bind",
"threadID", thread.threadID,
"socketFD", socketFD,
"addr", &addr)
}
func (thread *Thread) OnBindUnix(socketFD SocketFD, addr net.UnixAddr) {
thread.socks[socketFD] = &socket{
socketFD: socketFD,
isServer: false,
unixAddr: addr,
}
countlog.Debug("event!sut.bind",
"threadID", thread.threadID,
"socketFD", socketFD,
"unixAddr", addr)
}
func (thread *Thread) OnConnect(socketFD SocketFD, remoteAddr net.TCPAddr) {
thread.socks[socketFD] = &socket{
socketFD: socketFD,
isServer: false,
addr: remoteAddr,
}
setGlobalSock(socketFD, thread.socks[socketFD])
if envarg.IsReplaying() {
localAddr, err := bindFDToLocalAddr(int(socketFD))
if err != nil {
countlog.Error("event!sut.failed to bind local addr", "err", err)
return
}
thread.socks[socketFD].localAddr = localAddr
replaying.StoreTmp(*localAddr, thread.replayingSession)
thread.delReusedIgnoreFD(socketFD, *localAddr)
}
countlog.Trace("event!sut.connect",
"threadID", thread.threadID,
"socketFD", socketFD,
"addr", &remoteAddr,
"localAddr", thread.socks[socketFD].localAddr)
}
func (thread *Thread) OnConnectUnix(socketFD SocketFD, remoteAddr net.UnixAddr) {
thread.socks[socketFD] = &socket{
socketFD: socketFD,
isServer: false,
unixAddr: remoteAddr,
}
setGlobalSock(socketFD, thread.socks[socketFD])
//TODO: replaying
if envarg.IsReplaying() {
localAddr, err := bindFDToLocalAddr(int(socketFD))
if err != nil {
countlog.Error("event!sut.failed to bind local addr", "err", err)
return
}
thread.socks[socketFD].localAddr = localAddr
replaying.StoreTmp(*localAddr, thread.replayingSession)
thread.delReusedIgnoreFD(socketFD, *localAddr)
}
countlog.Trace("event!sut.connect",
"threadID", thread.threadID,
"socketFD", socketFD,
"unixAddr", thread.socks[socketFD].unixAddr)
}
type SendToFlags int
func (thread *Thread) OnSendTo(socketFD SocketFD, span []byte, flags SendToFlags, addr net.UDPAddr) {
countlog.Trace("event!sut.sendto",
"threadID", thread.threadID,
"socketFD", socketFD,
"addr", &addr,
"flags", flags,
"content", span)
thread.recordingSession.SendUDP(thread, span, addr)
thread.replayingSession.SendUDP(thread, span, addr)
}
func (thread *Thread) OnOpeningFile(fileName string, flags int) string {
countlog.Trace("event!sut.opening_file",
"threadID", thread.threadID,
"fileName", fileName,
"flags", flags)
if thread.replayingSession == nil {
return ""
}
originalFileName := fileName
fileName = thread.tryMockFile(fileName)
fileName = thread.tryRedirectFile(fileName)
fileName = thread.tryMockFile(fileName)
countlog.Trace("event!sut.opening_file",
"threadID", thread.threadID,
"replayingSessionId", thread.replayingSession.SessionId,
"originalFile", originalFileName,
"finalFile", fileName)
return fileName
}
func (thread *Thread) tryRedirectFile(fileName string) string {
for redirectFrom, redirectTo := range thread.replayingSession.RedirectDirs {
if strings.HasPrefix(fileName, redirectFrom) {
redirectedFileName := strings.Replace(fileName, redirectFrom,
redirectTo, 1)
if redirectedFileName != "" {
return redirectedFileName
}
}
}
return fileName
}
func (thread *Thread) tryMockFile(fileName string) string {
if thread.replayingSession.MockFiles != nil {
mockContent := thread.replayingSession.MockFiles[fileName]
if mockContent != nil {
countlog.Trace("event!sut.mock_file",
"fileName", fileName,
"content", mockContent)
mockedFileName := mockFile(mockContent)
if mockedFileName != "" {
return mockedFileName
}
}
}
return fileName
}
func (thread *Thread) OnOpenedFile(fileFD FileFD, fileName string, flags int) {
countlog.Trace("event!sut.opened_file",
"threadID", thread.threadID,
"fileFD", fileFD,
"fileName", fileName,
"flags", flags)
thread.files[fileFD] = &file{
fileFD: fileFD,
fileName: fileName,
flags: flags,
}
}
func (thread *Thread) OnWrite(fileFD FileFD, content []byte) {
file := thread.files[fileFD]
if file == nil {
return
}
if file.flags&os.O_APPEND == 0 {
return
}
countlog.Trace("event!sut.fileAppend",
"threadID", thread.threadID,
"fileFD", fileFD,
"fileName", file.fileName,
"content", content)
thread.recordingSession.AppendFile(thread, content, file.fileName)
thread.replayingSession.AppendFile(thread, content, file.fileName)
}
func (thread *Thread) OnShutdown() {
countlog.Trace("event!sut.shutdown_thread",
"threadID", thread.threadID)
thread.shutdownRecordingSession()
}
func (thread *Thread) OnAccess() {
if thread.recordingSession != nil && len(thread.recordingSession.Actions) > 500 {
countlog.Warn("event!sut.recorded_too_many_actions",
"threadID", thread.threadID,
"sessionId", thread.recordingSession.SessionId)
thread.shutdownRecordingSession()
}
}
func (thread *Thread) shutdownRecordingSession() {
if !envarg.IsRecording() {
return
}
newSession := recording.NewSession(int32(thread.threadID))
thread.recordingSession.Shutdown(thread, newSession)
thread.socks = map[SocketFD]*socket{} // socks on thread is a temp cache
thread.recordingSession = newSession
}
func (thread *Thread) IgnoreSocketFD(socketFD SocketFD, remoteAddr net.TCPAddr) {
countlog.Trace("event!sut.ignoreSocket",
"threadID", thread.threadID,
"socketFD", socketFD,
"addr", &remoteAddr)
thread.ignoreSocks[socketFD] = remoteAddr
}
// in case of fd reused
// multiple consecutive requests, each request need clear thread.ignoreSocks
// because clientFD maybe reuse, check fd is in ignoreSockFD and addr is same
// if not same and delete
func (thread *Thread) delReusedIgnoreFD(socketFD SocketFD, newAddr net.TCPAddr) {
if val, ok := thread.ignoreSocks[socketFD]; ok {
if val.String() != newAddr.String() {
delete(thread.ignoreSocks, socketFD)
}
}
}