-
Notifications
You must be signed in to change notification settings - Fork 6
/
upstream.go
178 lines (155 loc) · 4.19 KB
/
upstream.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
package lb
import (
"net/http"
"net/http/httputil"
"strings"
"sync"
"sync/atomic"
"unsafe"
"get.pme.sh/pmesh/netx"
)
type Upstream struct {
Address string
Healthy atomic.Bool
LoadFactor atomic.Int32
ReverseProxy httputil.ReverseProxy
// Metrics
RequestCount atomic.Uint32
ErrorCount atomic.Uint32
ServerErrorCount atomic.Uint32
ClientErrorCount atomic.Uint32
}
func (u *Upstream) String() string {
return u.Address
}
type UpstreamMetrics struct {
Address string `json:"address,omitempty"`
Healthy bool `json:"healthy,omitempty"`
LoadFactor int32 `json:"load_factor,omitempty"`
RequestCount uint32 `json:"request_count,omitempty"`
ErrorCount uint32 `json:"error_count,omitempty"`
ServerErrorCount uint32 `json:"server_error_count,omitempty"`
ClientErrorCount uint32 `json:"client_error_count,omitempty"`
}
func (u *Upstream) Metrics() UpstreamMetrics {
return UpstreamMetrics{
Address: u.Address,
Healthy: u.Healthy.Load(),
LoadFactor: u.LoadFactor.Load(),
RequestCount: u.RequestCount.Load(),
ErrorCount: u.ErrorCount.Load(),
ServerErrorCount: u.ServerErrorCount.Load(),
ClientErrorCount: u.ClientErrorCount.Load(),
}
}
func (u *Upstream) SetHealthy(healthy bool) {
u.Healthy.Store(healthy)
}
type SuppressedHttpError struct {
http.Handler
}
func (err SuppressedHttpError) Error() string {
return "suppressed http error"
}
const bufferLen = 32 * 1024
type bufferPool struct {
sync.Pool
}
func (b *bufferPool) Get() []byte {
ptr := b.Pool.Get()
return unsafe.Slice(ptr.(*byte), bufferLen)
}
func (b *bufferPool) Put(buf []byte) {
b.Pool.Put(&buf[0])
}
var globalBufferPool = &bufferPool{
sync.Pool{
New: func() any {
buf := make([]byte, bufferLen)
return &buf[0]
},
},
}
func NewHttpUpstreamTransport(address string, director func(r *http.Request), transport http.RoundTripper) (u *Upstream) {
u = &Upstream{Address: address}
u.Healthy.Store(true)
u.ReverseProxy = httputil.ReverseProxy{
Director: director,
Transport: transport,
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if err == http.ErrAbortHandler {
netx.ResetRequestConn(w)
} else if s, ok := err.(SuppressedHttpError); ok {
s.ServeHTTP(w, r)
} else {
rctx := r.Context().Value(requestContextKey{}).(*requestContext)
u.ErrorCount.Add(1)
rctx.LoadBalancer.OnError(rctx, w, r, err)
}
},
ModifyResponse: func(r *http.Response) error {
ctx := r.Request.Context().Value(requestContextKey{}).(*requestContext)
// Fast path for non-error responses.
if !(400 <= r.StatusCode && r.StatusCode <= 599) {
return nil
}
// If upstream requested to abort the request, do so.
if r.StatusCode == 444 {
ctx.Upstream.ClientErrorCount.Add(1)
return http.ErrAbortHandler
}
// If the request is already canceled, do nothing.
if ctx.Request.Context().Err() != nil {
return nil
}
// Update metrics.
if 500 <= r.StatusCode && r.StatusCode <= 599 {
ctx.Upstream.ServerErrorCount.Add(1)
} else if 400 <= r.StatusCode && r.StatusCode <= 499 {
ctx.Upstream.ClientErrorCount.Add(1)
}
// Ask load balancer to handle the error.
if hnd := ctx.LoadBalancer.OnErrorResponse(ctx, r); hnd != nil {
r.Body.Close()
return SuppressedHttpError{hnd}
}
return nil
},
BufferPool: globalBufferPool,
}
return
}
func (p *Upstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.LoadFactor.Add(1)
p.RequestCount.Add(1)
defer p.LoadFactor.Add(-1)
p.ReverseProxy.ServeHTTP(w, r)
}
func NewHttpUpstream(address string) (u *Upstream) {
scheme := "http"
if rest, ok := strings.CutPrefix(address, "https://"); ok {
scheme = "https"
address = rest
} else if rest, ok := strings.CutPrefix(address, "http://"); ok {
address = rest
}
if ipp := netx.ParseIPPort(address); ipp.IP.IsLoopback() {
return NewHttpUpstreamTransport(
address,
func(r *http.Request) {
r.URL.Scheme = scheme
r.URL.Host = address
},
netx.LocalTransport,
)
} else {
return NewHttpUpstreamTransport(
address,
func(r *http.Request) {
r.URL.Scheme = scheme
r.URL.Host = address
},
http.DefaultTransport,
)
}
}