-
Notifications
You must be signed in to change notification settings - Fork 21
/
httpleakcheck.go
99 lines (83 loc) · 2.17 KB
/
httpleakcheck.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
package gocbcore
import (
"context"
"errors"
"io"
"log"
"net/http"
"runtime/debug"
"sync"
"sync/atomic"
)
var leakTrackingEnabled uint32 = 0
var trackedRespsLock sync.Mutex
var trackedResps []*leakTrackingReadCloser
// EnableHttpResponseTracking enables tracking response bodies to ensure that they are
// eventually closed.
//
// # VOLATILE
//
// This API is VOLATILE is subject to change at any time.
func EnableHttpResponseTracking() {
atomic.StoreUint32(&leakTrackingEnabled, 1)
}
func wrapHttpResponse(resp *http.Response) *http.Response {
if atomic.LoadUint32(&leakTrackingEnabled) == 0 {
return resp
}
trackingBody := &leakTrackingReadCloser{
parent: resp.Body,
stackTrace: debug.Stack(),
}
trackedRespsLock.Lock()
trackedResps = append(trackedResps, trackingBody)
trackedRespsLock.Unlock()
resp.Body = trackingBody
return resp
}
func removeTrackedHttpBodyRecord(l *leakTrackingReadCloser) {
trackedRespsLock.Lock()
recordIdx := -1
for i, tracked := range trackedResps {
if tracked == l {
recordIdx = i
}
}
if recordIdx >= 0 {
trackedResps = append(trackedResps[:recordIdx], trackedResps[recordIdx+1:]...)
}
trackedRespsLock.Unlock()
}
// ReportLeakedHttpResponses prints the stack traces of any response bodies that have not
// been closed. Returns true if all bodies have been closed, false otherwise.
//
// # VOLATILE
//
// This API is VOLATILE is subject to change at any time.
func ReportLeakedHttpResponses() bool {
if len(trackedResps) == 0 {
log.Printf("No leaked http requests")
return true
}
log.Printf("Found %d leaked http requests", len(trackedResps))
for _, leakRecord := range trackedResps {
log.Printf("Leaked http request stack: %s", leakRecord.stackTrace)
}
return false
}
type leakTrackingReadCloser struct {
parent io.ReadCloser
stackTrace []byte
}
func (l *leakTrackingReadCloser) Read(p []byte) (int, error) {
n, err := l.parent.Read(p)
if errors.Is(err, io.EOF) || errors.Is(err, context.Canceled) {
removeTrackedHttpBodyRecord(l)
}
return n, err
}
func (l *leakTrackingReadCloser) Close() error {
removeTrackedHttpBodyRecord(l)
return l.parent.Close()
}
var _ io.ReadCloser = (*leakTrackingReadCloser)(nil)