-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathproxy.go
213 lines (178 loc) · 5.5 KB
/
proxy.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
// Package http implements a proxy that applies disruptions to HTTP requests
package http
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"strings"
"time"
"github.com/grafana/xk6-disruptor/pkg/agent/protocol"
)
// ProxyConfig configures the Proxy options
type ProxyConfig struct {
// Address to listen for incoming requests
ListenAddress string
// Address where to redirect requests
UpstreamAddress string
}
// Disruption specifies disruptions in http requests
type Disruption struct {
// Average delay introduced to requests
AverageDelay time.Duration
// Variation in the delay (with respect of the average delay)
DelayVariation time.Duration
// Fraction (in the range 0.0 to 1.0) of requests that will return an error
ErrorRate float32
// Error code to be returned by requests selected in the error rate
ErrorCode uint
// Body to be returned when an error is injected
ErrorBody string
// List of url paths to be excluded from disruptions
Excluded []string
}
// Proxy defines the parameters used by the proxy for processing http requests and its execution state
type proxy struct {
config ProxyConfig
disruption Disruption
srv *http.Server
metrics protocol.MetricMap
}
// NewProxy return a new Proxy for HTTP requests
func NewProxy(c ProxyConfig, d Disruption) (protocol.Proxy, error) {
if c.ListenAddress == "" {
return nil, fmt.Errorf("proxy's listening address must be provided")
}
if c.UpstreamAddress == "" {
return nil, fmt.Errorf("proxy's forwarding address must be provided")
}
if d.DelayVariation > d.AverageDelay {
return nil, fmt.Errorf("variation must be less that average delay")
}
if d.ErrorRate < 0.0 || d.ErrorRate > 1.0 {
return nil, fmt.Errorf("error rate must be in the range [0.0, 1.0]")
}
if d.ErrorRate > 0.0 && d.ErrorCode == 0 {
return nil, fmt.Errorf("error code must be a valid http error code")
}
return &proxy{
disruption: d,
config: c,
}, nil
}
// httpHandler implements a http.Handler for disrupting request to a upstream server
type httpHandler struct {
upstreamURL url.URL
disruption Disruption
metrics *protocol.MetricMap
}
// isExcluded checks whether a request should be proxied through without any kind of modification whatsoever.
func (h *httpHandler) isExcluded(r *http.Request) bool {
for _, excluded := range h.disruption.Excluded {
if strings.EqualFold(r.URL.Path, excluded) {
return true
}
}
return false
}
// forward forwards a request to the upstream URL.
// Request is performed immediately, but response won't be sent before the duration specified in delay.
func (h *httpHandler) forward(rw http.ResponseWriter, req *http.Request, delay time.Duration) {
timer := time.After(delay)
upstreamReq := req.Clone(context.Background())
upstreamReq.Host = h.upstreamURL.Host
upstreamReq.URL.Host = h.upstreamURL.Host
upstreamReq.URL.Scheme = h.upstreamURL.Scheme
upstreamReq.RequestURI = "" // It is an error to set this field in an HTTP client request.
response, err := http.DefaultClient.Do(upstreamReq)
<-timer
if err != nil {
rw.WriteHeader(http.StatusBadGateway)
_, _ = fmt.Fprint(rw, err)
return
}
defer func() {
// Fully consume and then close upstream response body.
_, _ = io.Copy(io.Discard, response.Body)
_ = response.Body.Close()
}()
// Mirror headers.
for key, values := range response.Header {
for _, value := range values {
rw.Header().Add(key, value)
}
}
// Mirror status code.
rw.WriteHeader(response.StatusCode)
// ignore errors writing body, nothing to do.
_, _ = io.Copy(rw, response.Body)
}
// injectError waits sleeps the duration specified in delay and then writes the configured error downstream.
func (h *httpHandler) injectError(rw http.ResponseWriter, delay time.Duration) {
time.Sleep(delay)
rw.WriteHeader(int(h.disruption.ErrorCode))
_, _ = rw.Write([]byte(h.disruption.ErrorBody))
}
func (h *httpHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h.metrics.Inc(protocol.MetricRequests)
if h.isExcluded(req) {
h.metrics.Inc(protocol.MetricRequestsExcluded)
//nolint:contextcheck // Unclear which context the linter requires us to propagate here.
h.forward(rw, req, 0)
return
}
delay := h.disruption.AverageDelay
if h.disruption.DelayVariation > 0 {
variation := int64(h.disruption.DelayVariation)
delay += time.Duration(variation - 2*rand.Int63n(variation))
}
if h.disruption.ErrorRate > 0 && rand.Float32() <= h.disruption.ErrorRate {
h.metrics.Inc(protocol.MetricRequestsDisrupted)
h.injectError(rw, delay)
return
}
//nolint:contextcheck // Unclear which context the linter requires us to propagate here.
h.forward(rw, req, delay)
}
// Start starts the execution of the proxy
func (p *proxy) Start() error {
upstreamURL, err := url.Parse(p.config.UpstreamAddress)
if err != nil {
return err
}
handler := &httpHandler{
upstreamURL: *upstreamURL,
disruption: p.disruption,
metrics: &p.metrics,
}
p.srv = &http.Server{
Addr: p.config.ListenAddress,
Handler: handler,
}
err = p.srv.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
// Stop stops the execution of the proxy
func (p *proxy) Stop() error {
if p.srv != nil {
return p.srv.Shutdown(context.Background())
}
return nil
}
// Metrics returns runtime metrics for the proxy.
func (p *proxy) Metrics() map[string]uint {
return p.metrics.Map()
}
// Force stops the proxy without waiting for connections to drain
func (p *proxy) Force() error {
if p.srv != nil {
return p.srv.Close()
}
return nil
}