@marcel91200 / caddy Mirror · read-only / commits / 1136e2cf
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

Add reverse proxy

Matthew Holt committed May 4, 2019 at 10:49 UTC 1136e2cfeed5cc06a0811d39c2560c06f9dd74a2
4 files changed +1085
modules/caddyhttp/reverseproxy/healthchecker.go new
+64
@@ -0,0 +1,64 @@
1 +package reverseproxy
2 +
3 +import (
4 + "net/http"
5 + "time"
6 +)
7 +
8 +// Upstream represents the interface that must be satisfied to use the healthchecker.
9 +type Upstream interface {
10 + SetHealthiness(bool)
11 +}
12 +
13 +// HealthChecker represents a worker that periodically evaluates if proxy upstream host is healthy.
14 +type HealthChecker struct {
15 + upstream Upstream
16 + Ticker *time.Ticker
17 + HTTPClient *http.Client
18 +}
19 +
20 +// ScheduleChecks periodically runs health checks against an upstream host.
21 +func (h *HealthChecker) ScheduleChecks(url string) {
22 + // check if a host is healthy on start vs waiting for timer
23 + h.upstream.SetHealthiness(h.IsHealthy(url))
24 +
25 + for {
26 + select {
27 + case <-h.Ticker.C:
28 + h.upstream.SetHealthiness(h.IsHealthy(url))
29 + }
30 + }
31 +}
32 +
33 +// Stop stops the healthchecker from makeing further requests.
34 +func (h *HealthChecker) Stop() {
35 + h.Ticker.Stop()
36 +}
37 +
38 +// IsHealthy attempts to check if a upstream host is healthy.
39 +func (h *HealthChecker) IsHealthy(url string) bool {
40 + req, err := http.NewRequest(http.MethodGet, url, nil)
41 + if err != nil {
42 + return false
43 + }
44 +
45 + resp, err := h.HTTPClient.Do(req)
46 + if err != nil {
47 + return false
48 + }
49 +
50 + if resp.StatusCode < 200 || resp.StatusCode >= 400 {
51 + return false
52 + }
53 +
54 + return true
55 +}
56 +
57 +// NewHealthCheckWorker returns a new instance of a HealthChecker.
58 +func NewHealthCheckWorker(u Upstream, interval time.Duration, client *http.Client) *HealthChecker {
59 + return &HealthChecker{
60 + upstream: u,
61 + Ticker: time.NewTicker(interval),
62 + HTTPClient: client,
63 + }
64 +}
modules/caddyhttp/reverseproxy/module.go new
+46
@@ -0,0 +1,46 @@
1 +package reverseproxy
2 +
3 +import (
4 + "fmt"
5 +
6 + "bitbucket.org/lightcodelabs/caddy2"
7 +)
8 +
9 +// Register caddy module.
10 +func init() {
11 + caddy2.RegisterModule(caddy2.Module{
12 + Name: "http.responders.reverse_proxy",
13 + New: func() (interface{}, error) { return new(LoadBalanced), nil },
14 + OnLoad: func(instances []interface{}, _ interface{}) (interface{}, error) {
15 + // we don't need to do anything with prior state because healthcheckers are
16 + // cleaned up in OnUnload.
17 + s := &State{
18 + HealthCheckers: []*HealthChecker{},
19 + }
20 +
21 + for _, i := range instances {
22 + lb := i.(*LoadBalanced)
23 +
24 + err := NewLoadBalancedReverseProxy(lb, s)
25 + if err != nil {
26 + return nil, err
27 + }
28 + }
29 +
30 + return s, nil
31 + },
32 + OnUnload: func(state interface{}) error {
33 + s, ok := state.(*State)
34 + if !ok {
35 + return fmt.Errorf("proxy OnLoad: prior state not expected proxy.State type")
36 + }
37 +
38 + // cleanup old healthcheckers
39 + for _, hc := range s.HealthCheckers {
40 + hc.Stop()
41 + }
42 +
43 + return nil
44 + },
45 + })
46 +}
modules/caddyhttp/reverseproxy/reverseproxy.go new
+562
@@ -0,0 +1,562 @@
1 +package reverseproxy
2 +
3 +import (
4 + "context"
5 + "fmt"
6 + "io"
7 + "log"
8 + "net"
9 + "net/http"
10 + "net/url"
11 + "strings"
12 + "sync"
13 + "time"
14 +
15 + "golang.org/x/net/http/httpguts"
16 +)
17 +
18 +// ReverseProxy is an HTTP Handler that takes an incoming request and
19 +// sends it to another server, proxying the response back to the
20 +// client.
21 +type ReverseProxy struct {
22 + // Director must be a function which modifies
23 + // the request into a new request to be sent
24 + // using Transport. Its response is then copied
25 + // back to the original client unmodified.
26 + // Director must not access the provided Request
27 + // after returning.
28 + Director func(*http.Request)
29 +
30 + // The transport used to perform proxy requests.
31 + // If nil, http.DefaultTransport is used.
32 + Transport http.RoundTripper
33 +
34 + // FlushInterval specifies the flush interval
35 + // to flush to the client while copying the
36 + // response body.
37 + // If zero, no periodic flushing is done.
38 + // A negative value means to flush immediately
39 + // after each write to the client.
40 + // The FlushInterval is ignored when ReverseProxy
41 + // recognizes a response as a streaming response;
42 + // for such responses, writes are flushed to the client
43 + // immediately.
44 + FlushInterval time.Duration
45 +
46 + // ErrorLog specifies an optional logger for errors
47 + // that occur when attempting to proxy the request.
48 + // If nil, logging goes to os.Stderr via the log package's
49 + // standard logger.
50 + ErrorLog *log.Logger
51 +
52 + // BufferPool optionally specifies a buffer pool to
53 + // get byte slices for use by io.CopyBuffer when
54 + // copying HTTP response bodies.
55 + BufferPool BufferPool
56 +
57 + // ModifyResponse is an optional function that modifies the
58 + // Response from the backend. It is called if the backend
59 + // returns a response at all, with any HTTP status code.
60 + // If the backend is unreachable, the optional ErrorHandler is
61 + // called without any call to ModifyResponse.
62 + //
63 + // If ModifyResponse returns an error, ErrorHandler is called
64 + // with its error value. If ErrorHandler is nil, its default
65 + // implementation is used.
66 + ModifyResponse func(*http.Response) error
67 +
68 + // ErrorHandler is an optional function that handles errors
69 + // reaching the backend or errors from ModifyResponse.
70 + //
71 + // If nil, the default is to log the provided error and return
72 + // a 502 Status Bad Gateway response.
73 + ErrorHandler func(http.ResponseWriter, *http.Request, error)
74 +}
75 +
76 +// A BufferPool is an interface for getting and returning temporary
77 +// byte slices for use by io.CopyBuffer.
78 +type BufferPool interface {
79 + Get() []byte
80 + Put([]byte)
81 +}
82 +
83 +func singleJoiningSlash(a, b string) string {
84 + aslash := strings.HasSuffix(a, "/")
85 + bslash := strings.HasPrefix(b, "/")
86 + switch {
87 + case aslash && bslash:
88 + return a + b[1:]
89 + case !aslash && !bslash:
90 + return a + "/" + b
91 + }
92 + return a + b
93 +}
94 +
95 +// NewSingleHostReverseProxy returns a new ReverseProxy that routes
96 +// URLs to the scheme, host, and base path provided in target. If the
97 +// target's path is "/base" and the incoming request was for "/dir",
98 +// the target request will be for /base/dir.
99 +// NewSingleHostReverseProxy does not rewrite the Host header.
100 +// To rewrite Host headers, use ReverseProxy directly with a custom
101 +// Director policy.
102 +func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy {
103 + targetQuery := target.RawQuery
104 + director := func(req *http.Request) {
105 + req.URL.Scheme = target.Scheme
106 + req.URL.Host = target.Host
107 + req.URL.Path = singleJoiningSlash(target.Path, req.URL.Path)
108 + if targetQuery == "" || req.URL.RawQuery == "" {
109 + req.URL.RawQuery = targetQuery + req.URL.RawQuery
110 + } else {
111 + req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
112 + }
113 + if _, ok := req.Header["User-Agent"]; !ok {
114 + // explicitly disable User-Agent so it's not set to default value
115 + req.Header.Set("User-Agent", "")
116 + }
117 + }
118 + return &ReverseProxy{Director: director}
119 +}
120 +
121 +func copyHeader(dst, src http.Header) {
122 + for k, vv := range src {
123 + for _, v := range vv {
124 + dst.Add(k, v)
125 + }
126 + }
127 +}
128 +
129 +func cloneHeader(h http.Header) http.Header {
130 + h2 := make(http.Header, len(h))
131 + for k, vv := range h {
132 + vv2 := make([]string, len(vv))
133 + copy(vv2, vv)
134 + h2[k] = vv2
135 + }
136 + return h2
137 +}
138 +
139 +// Hop-by-hop headers. These are removed when sent to the backend.
140 +// As of RFC 7230, hop-by-hop headers are required to appear in the
141 +// Connection header field. These are the headers defined by the
142 +// obsoleted RFC 2616 (section 13.5.1) and are used for backward
143 +// compatibility.
144 +var hopHeaders = []string{
145 + "Connection",
146 + "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google
147 + "Keep-Alive",
148 + "Proxy-Authenticate",
149 + "Proxy-Authorization",
150 + "Te", // canonicalized version of "TE"
151 + "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522
152 + "Transfer-Encoding",
153 + "Upgrade",
154 +}
155 +
156 +func (p *ReverseProxy) defaultErrorHandler(rw http.ResponseWriter, req *http.Request, err error) {
157 + p.logf("http: proxy error: %v", err)
158 + rw.WriteHeader(http.StatusBadGateway)
159 +}
160 +
161 +func (p *ReverseProxy) getErrorHandler() func(http.ResponseWriter, *http.Request, error) {
162 + if p.ErrorHandler != nil {
163 + return p.ErrorHandler
164 + }
165 + return p.defaultErrorHandler
166 +}
167 +
168 +// modifyResponse conditionally runs the optional ModifyResponse hook
169 +// and reports whether the request should proceed.
170 +func (p *ReverseProxy) modifyResponse(rw http.ResponseWriter, res *http.Response, req *http.Request) bool {
171 + if p.ModifyResponse == nil {
172 + return true
173 + }
174 + if err := p.ModifyResponse(res); err != nil {
175 + res.Body.Close()
176 + p.getErrorHandler()(rw, req, err)
177 + return false
178 + }
179 + return true
180 +}
181 +
182 +func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) (*http.Response, error) {
183 + transport := p.Transport
184 + if transport == nil {
185 + transport = http.DefaultTransport
186 + }
187 +
188 + ctx := req.Context()
189 + if cn, ok := rw.(http.CloseNotifier); ok {
190 + var cancel context.CancelFunc
191 + ctx, cancel = context.WithCancel(ctx)
192 + defer cancel()
193 + notifyChan := cn.CloseNotify()
194 + go func() {
195 + select {
196 + case <-notifyChan:
197 + cancel()
198 + case <-ctx.Done():
199 + }
200 + }()
201 + }
202 +
203 + outreq := req.WithContext(ctx) // includes shallow copies of maps, but okay
204 + if req.ContentLength == 0 {
205 + outreq.Body = nil // Issue 16036: nil Body for http.Transport retries
206 + }
207 +
208 + outreq.Header = cloneHeader(req.Header)
209 +
210 + p.Director(outreq)
211 + outreq.Close = false
212 +
213 + reqUpType := upgradeType(outreq.Header)
214 + removeConnectionHeaders(outreq.Header)
215 +
216 + // Remove hop-by-hop headers to the backend. Especially
217 + // important is "Connection" because we want a persistent
218 + // connection, regardless of what the client sent to us.
219 + for _, h := range hopHeaders {
220 + hv := outreq.Header.Get(h)
221 + if hv == "" {
222 + continue
223 + }
224 + if h == "Te" && hv == "trailers" {
225 + // Issue 21096: tell backend applications that
226 + // care about trailer support that we support
227 + // trailers. (We do, but we don't go out of
228 + // our way to advertise that unless the
229 + // incoming client request thought it was
230 + // worth mentioning)
231 + continue
232 + }
233 + outreq.Header.Del(h)
234 + }
235 +
236 + // After stripping all the hop-by-hop connection headers above, add back any
237 + // necessary for protocol upgrades, such as for websockets.
238 + if reqUpType != "" {
239 + outreq.Header.Set("Connection", "Upgrade")
240 + outreq.Header.Set("Upgrade", reqUpType)
241 + }
242 +
243 + if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
244 + // If we aren't the first proxy retain prior
245 + // X-Forwarded-For information as a comma+space
246 + // separated list and fold multiple headers into one.
247 + if prior, ok := outreq.Header["X-Forwarded-For"]; ok {
248 + clientIP = strings.Join(prior, ", ") + ", " + clientIP
249 + }
250 + outreq.Header.Set("X-Forwarded-For", clientIP)
251 + }
252 +
253 + res, err := transport.RoundTrip(outreq)
254 + if err != nil {
255 + p.getErrorHandler()(rw, outreq, err)
256 + return nil, err
257 + }
258 +
259 + // Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc)
260 + if res.StatusCode == http.StatusSwitchingProtocols {
261 + if !p.modifyResponse(rw, res, outreq) {
262 + return res, nil
263 + }
264 +
265 + p.handleUpgradeResponse(rw, outreq, res)
266 + return res, nil
267 + }
268 +
269 + removeConnectionHeaders(res.Header)
270 +
271 + for _, h := range hopHeaders {
272 + res.Header.Del(h)
273 + }
274 +
275 + if !p.modifyResponse(rw, res, outreq) {
276 + return res, nil
277 + }
278 +
279 + copyHeader(rw.Header(), res.Header)
280 +
281 + // The "Trailer" header isn't included in the Transport's response,
282 + // at least for *http.Transport. Build it up from Trailer.
283 + announcedTrailers := len(res.Trailer)
284 + if announcedTrailers > 0 {
285 + trailerKeys := make([]string, 0, len(res.Trailer))
286 + for k := range res.Trailer {
287 + trailerKeys = append(trailerKeys, k)
288 + }
289 + rw.Header().Add("Trailer", strings.Join(trailerKeys, ", "))
290 + }
291 +
292 + rw.WriteHeader(res.StatusCode)
293 +
294 + err = p.copyResponse(rw, res.Body, p.flushInterval(req, res))
295 + if err != nil {
296 + defer res.Body.Close()
297 + // Since we're streaming the response, if we run into an error all we can do
298 + // is abort the request. Issue 23643: ReverseProxy should use ErrAbortHandler
299 + // on read error while copying body.
300 + if !shouldPanicOnCopyError(req) {
301 + p.logf("suppressing panic for copyResponse error in test; copy error: %v", err)
302 + return nil, err
303 + }
304 +
305 + panic(http.ErrAbortHandler)
306 + }
307 + res.Body.Close() // close now, instead of defer, to populate res.Trailer
308 +
309 + if len(res.Trailer) > 0 {
310 + // Force chunking if we saw a response trailer.
311 + // This prevents net/http from calculating the length for short
312 + // bodies and adding a Content-Length.
313 + if fl, ok := rw.(http.Flusher); ok {
314 + fl.Flush()
315 + }
316 + }
317 +
318 + if len(res.Trailer) == announcedTrailers {
319 + copyHeader(rw.Header(), res.Trailer)
320 + return res, nil
321 + }
322 +
323 + for k, vv := range res.Trailer {
324 + k = http.TrailerPrefix + k
325 + for _, v := range vv {
326 + rw.Header().Add(k, v)
327 + }
328 + }
329 +
330 + return res, nil
331 +}
332 +
333 +var inOurTests bool // whether we're in our own tests
334 +
335 +// shouldPanicOnCopyError reports whether the reverse proxy should
336 +// panic with http.ErrAbortHandler. This is the right thing to do by
337 +// default, but Go 1.10 and earlier did not, so existing unit tests
338 +// weren't expecting panics. Only panic in our own tests, or when
339 +// running under the HTTP server.
340 +func shouldPanicOnCopyError(req *http.Request) bool {
341 + if inOurTests {
342 + // Our tests know to handle this panic.
343 + return true
344 + }
345 + if req.Context().Value(http.ServerContextKey) != nil {
346 + // We seem to be running under an HTTP server, so
347 + // it'll recover the panic.
348 + return true
349 + }
350 + // Otherwise act like Go 1.10 and earlier to not break
351 + // existing tests.
352 + return false
353 +}
354 +
355 +// removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h.
356 +// See RFC 7230, section 6.1
357 +func removeConnectionHeaders(h http.Header) {
358 + if c := h.Get("Connection"); c != "" {
359 + for _, f := range strings.Split(c, ",") {
360 + if f = strings.TrimSpace(f); f != "" {
361 + h.Del(f)
362 + }
363 + }
364 + }
365 +}
366 +
367 +// flushInterval returns the p.FlushInterval value, conditionally
368 +// overriding its value for a specific request/response.
369 +func (p *ReverseProxy) flushInterval(req *http.Request, res *http.Response) time.Duration {
370 + resCT := res.Header.Get("Content-Type")
371 +
372 + // For Server-Sent Events responses, flush immediately.
373 + // The MIME type is defined in https://www.w3.org/TR/eventsource/#text-event-stream
374 + if resCT == "text/event-stream" {
375 + return -1 // negative means immediately
376 + }
377 +
378 + // TODO: more specific cases? e.g. res.ContentLength == -1?
379 + return p.FlushInterval
380 +}
381 +
382 +func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader, flushInterval time.Duration) error {
383 + if flushInterval != 0 {
384 + if wf, ok := dst.(writeFlusher); ok {
385 + mlw := &maxLatencyWriter{
386 + dst: wf,
387 + latency: flushInterval,
388 + }
389 + defer mlw.stop()
390 + dst = mlw
391 + }
392 + }
393 +
394 + var buf []byte
395 + if p.BufferPool != nil {
396 + buf = p.BufferPool.Get()
397 + defer p.BufferPool.Put(buf)
398 + }
399 + _, err := p.copyBuffer(dst, src, buf)
400 + return err
401 +}
402 +
403 +// copyBuffer returns any write errors or non-EOF read errors, and the amount
404 +// of bytes written.
405 +func (p *ReverseProxy) copyBuffer(dst io.Writer, src io.Reader, buf []byte) (int64, error) {
406 + if len(buf) == 0 {
407 + buf = make([]byte, 32*1024)
408 + }
409 + var written int64
410 + for {
411 + nr, rerr := src.Read(buf)
412 + if rerr != nil && rerr != io.EOF && rerr != context.Canceled {
413 + p.logf("httputil: ReverseProxy read error during body copy: %v", rerr)
414 + }
415 + if nr > 0 {
416 + nw, werr := dst.Write(buf[:nr])
417 + if nw > 0 {
418 + written += int64(nw)
419 + }
420 + if werr != nil {
421 + return written, werr
422 + }
423 + if nr != nw {
424 + return written, io.ErrShortWrite
425 + }
426 + }
427 + if rerr != nil {
428 + if rerr == io.EOF {
429 + rerr = nil
430 + }
431 + return written, rerr
432 + }
433 + }
434 +}
435 +
436 +func (p *ReverseProxy) logf(format string, args ...interface{}) {
437 + if p.ErrorLog != nil {
438 + p.ErrorLog.Printf(format, args...)
439 + } else {
440 + log.Printf(format, args...)
441 + }
442 +}
443 +
444 +type writeFlusher interface {
445 + io.Writer
446 + http.Flusher
447 +}
448 +
449 +type maxLatencyWriter struct {
450 + dst writeFlusher
451 + latency time.Duration // non-zero; negative means to flush immediately
452 +
453 + mu sync.Mutex // protects t, flushPending, and dst.Flush
454 + t *time.Timer
455 + flushPending bool
456 +}
457 +
458 +func (m *maxLatencyWriter) Write(p []byte) (n int, err error) {
459 + m.mu.Lock()
460 + defer m.mu.Unlock()
461 + n, err = m.dst.Write(p)
462 + if m.latency < 0 {
463 + m.dst.Flush()
464 + return
465 + }
466 + if m.flushPending {
467 + return
468 + }
469 + if m.t == nil {
470 + m.t = time.AfterFunc(m.latency, m.delayedFlush)
471 + } else {
472 + m.t.Reset(m.latency)
473 + }
474 + m.flushPending = true
475 + return
476 +}
477 +
478 +func (m *maxLatencyWriter) delayedFlush() {
479 + m.mu.Lock()
480 + defer m.mu.Unlock()
481 + if !m.flushPending { // if stop was called but AfterFunc already started this goroutine
482 + return
483 + }
484 + m.dst.Flush()
485 + m.flushPending = false
486 +}
487 +
488 +func (m *maxLatencyWriter) stop() {
489 + m.mu.Lock()
490 + defer m.mu.Unlock()
491 + m.flushPending = false
492 + if m.t != nil {
493 + m.t.Stop()
494 + }
495 +}
496 +
497 +func upgradeType(h http.Header) string {
498 + if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") {
499 + return ""
500 + }
501 + return strings.ToLower(h.Get("Upgrade"))
502 +}
503 +
504 +func (p *ReverseProxy) handleUpgradeResponse(rw http.ResponseWriter, req *http.Request, res *http.Response) {
505 + reqUpType := upgradeType(req.Header)
506 + resUpType := upgradeType(res.Header)
507 + if reqUpType != resUpType {
508 + p.getErrorHandler()(rw, req, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType))
509 + return
510 + }
511 +
512 + copyHeader(res.Header, rw.Header())
513 +
514 + hj, ok := rw.(http.Hijacker)
515 + if !ok {
516 + p.getErrorHandler()(rw, req, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw))
517 + return
518 + }
519 + backConn, ok := res.Body.(io.ReadWriteCloser)
520 + if !ok {
521 + p.getErrorHandler()(rw, req, fmt.Errorf("internal error: 101 switching protocols response with non-writable body"))
522 + return
523 + }
524 + defer backConn.Close()
525 + conn, brw, err := hj.Hijack()
526 + if err != nil {
527 + p.getErrorHandler()(rw, req, fmt.Errorf("Hijack failed on protocol switch: %v", err))
528 + return
529 + }
530 + defer conn.Close()
531 + res.Body = nil // so res.Write only writes the headers; we have res.Body in backConn above
532 + if err := res.Write(brw); err != nil {
533 + p.getErrorHandler()(rw, req, fmt.Errorf("response write: %v", err))
534 + return
535 + }
536 + if err := brw.Flush(); err != nil {
537 + p.getErrorHandler()(rw, req, fmt.Errorf("response flush: %v", err))
538 + return
539 + }
540 + errc := make(chan error, 1)
541 + spc := switchProtocolCopier{user: conn, backend: backConn}
542 + go spc.copyToBackend(errc)
543 + go spc.copyFromBackend(errc)
544 + <-errc
545 + return
546 +}
547 +
548 +// switchProtocolCopier exists so goroutines proxying data back and
549 +// forth have nice names in stacks.
550 +type switchProtocolCopier struct {
551 + user, backend io.ReadWriter
552 +}
553 +
554 +func (c switchProtocolCopier) copyFromBackend(errc chan<- error) {
555 + _, err := io.Copy(c.user, c.backend)
556 + errc <- err
557 +}
558 +
559 +func (c switchProtocolCopier) copyToBackend(errc chan<- error) {
560 + _, err := io.Copy(c.backend, c.user)
561 + errc <- err
562 +}
modules/caddyhttp/reverseproxy/upstream.go new
+413
@@ -0,0 +1,413 @@
1 +// Package reverseproxy implements a load-balanced reverse proxy.
2 +package reverseproxy
3 +
4 +import (
5 + "context"
6 + "encoding/json"
7 + "fmt"
8 + "math/rand"
9 + "net"
10 + "net/http"
11 + "net/url"
12 + "strings"
13 + "sync"
14 + "sync/atomic"
15 + "time"
16 +
17 + "bitbucket.org/lightcodelabs/caddy2"
18 +)
19 +
20 +// State represents the global state of a loadbalancer. It is used to store
21 +// references to health checkers.
22 +type State struct {
23 + HealthCheckers []*HealthChecker
24 +}
25 +
26 +// CircuitBreaker defines the functionality of a circuit breaker module.
27 +type CircuitBreaker interface {
28 + Ok() bool
29 + RecordMetric(statusCode int, latency time.Duration)
30 +}
31 +
32 +type noopCircuitBreaker struct{}
33 +
34 +func (ncb noopCircuitBreaker) RecordMetric(statusCode int, latency time.Duration) {}
35 +func (ncb noopCircuitBreaker) Ok() bool {
36 + return true
37 +}
38 +
39 +const (
40 + // TypeBalanceRoundRobin represents the value to use for configuring a load balanced reverse proxy to use round robin load balancing.
41 + TypeBalanceRoundRobin = iota
42 +
43 + // TypeBalanceRandom represents the value to use for configuring a load balanced reverse proxy to use random load balancing.
44 + TypeBalanceRandom
45 +
46 + // msgNoHealthyUpstreams is returned if there are no upstreams that are healthy to proxy a request to
47 + msgNoHealthyUpstreams = "No healthy upstreams."
48 +
49 + // by default perform health checks every 30 seconds
50 + defaultHealthCheckDur = time.Second * 30
51 +
52 + // used when an upstream is unhealthy, health checks can be configured to perform at a faster rate
53 + defaultFastHealthCheckDur = time.Second * 1
54 +)
55 +
56 +var (
57 + // defaultTransport is the default transport to use for the reverse proxy.
58 + defaultTransport = &http.Transport{
59 + Dial: (&net.Dialer{
60 + Timeout: 5 * time.Second,
61 + }).Dial,
62 + TLSHandshakeTimeout: 5 * time.Second,
63 + }
64 +
65 + // defaultHTTPClient is the default http client to use for the healthchecker.
66 + defaultHTTPClient = &http.Client{
67 + Timeout: time.Second * 10,
68 + Transport: defaultTransport,
69 + }
70 +
71 + // typeMap maps caddy load balance configuration to the internal representation of the loadbalance algorithm type.
72 + typeMap = map[string]int{
73 + "round_robin": TypeBalanceRoundRobin,
74 + "random": TypeBalanceRandom,
75 + }
76 +)
77 +
78 +// NewLoadBalancedReverseProxy returns a collection of Upstreams that are to be loadbalanced.
79 +func NewLoadBalancedReverseProxy(lb *LoadBalanced, state *State) error {
80 + // set defaults
81 + if lb.NoHealthyUpstreamsMessage == "" {
82 + lb.NoHealthyUpstreamsMessage = msgNoHealthyUpstreams
83 + }
84 +
85 + if lb.TryInterval == "" {
86 + lb.TryInterval = "20s"
87 + }
88 +
89 + // set request retry interval
90 + ti, err := time.ParseDuration(lb.TryInterval)
91 + if err != nil {
92 + return fmt.Errorf("NewLoadBalancedReverseProxy: %v", err.Error())
93 + }
94 + lb.tryInterval = ti
95 +
96 + // set load balance algorithm
97 + t, ok := typeMap[lb.LoadBalanceType]
98 + if !ok {
99 + t = TypeBalanceRandom
100 + }
101 + lb.loadBalanceType = t
102 +
103 + // setup each upstream
104 + var us []*upstream
105 + for _, uc := range lb.Upstreams {
106 + // pass the upstream decr and incr methods to keep track of unhealthy nodes
107 + nu, err := newUpstream(uc, lb.decrUnhealthy, lb.incrUnhealthy)
108 + if err != nil {
109 + return err
110 + }
111 +
112 + // setup any configured circuit breakers
113 + var cbModule = "http.responders.reverse_proxy.circuit_breaker"
114 + var cb CircuitBreaker
115 +
116 + if uc.CircuitBreaker != nil {
117 + if _, err := caddy2.GetModule(cbModule); err == nil {
118 + val, err := caddy2.LoadModule(cbModule, uc.CircuitBreaker)
119 + if err == nil {
120 + cbv, ok := val.(CircuitBreaker)
121 + if ok {
122 + cb = cbv
123 + } else {
124 + fmt.Printf("\nerr: %v; cannot load circuit_breaker, using noop", err.Error())
125 + cb = noopCircuitBreaker{}
126 + }
127 + } else {
128 + fmt.Printf("\nerr: %v; cannot load circuit_breaker, using noop", err.Error())
129 + cb = noopCircuitBreaker{}
130 + }
131 + } else {
132 + fmt.Println("circuit_breaker module not loaded, using noop")
133 + cb = noopCircuitBreaker{}
134 + }
135 + } else {
136 + cb = noopCircuitBreaker{}
137 + }
138 + nu.CB = cb
139 +
140 + // start a healthcheck worker which will periodically check to see if an upstream is healthy
141 + // to proxy requests to.
142 + nu.healthChecker = NewHealthCheckWorker(nu, defaultHealthCheckDur, defaultHTTPClient)
143 +
144 + // TODO :- if path is empty why does this empty the entire Target?
145 + // nu.Target.Path = uc.HealthCheckPath
146 +
147 + go nu.healthChecker.ScheduleChecks(nu.Target.String())
148 + state.HealthCheckers = append(state.HealthCheckers, nu.healthChecker)
149 +
150 + us = append(us, nu)
151 + }
152 +
153 + lb.upstreams = us
154 +
155 + return nil
156 +}
157 +
158 +// LoadBalanced represents a collection of upstream hosts that are loadbalanced. It
159 +// contains multiple features like health checking and circuit breaking functionality
160 +// for upstreams.
161 +type LoadBalanced struct {
162 + mu sync.Mutex
163 + numUnhealthy int32
164 + selectedServer int // used during round robin load balancing
165 + loadBalanceType int
166 + tryInterval time.Duration
167 + upstreams []*upstream
168 +
169 + // The following struct fields are set by caddy configuration.
170 + // TryInterval is the max duration for which request retrys will be performed for a request.
171 + TryInterval string `json:"try_interval"`
172 +
173 + // Upstreams are the configs for upstream hosts
174 + Upstreams []*UpstreamConfig `json:"upstreams"`
175 +
176 + // LoadBalanceType is the string representation of what loadbalancing algorithm to use. i.e. "random" or "round_robin".
177 + LoadBalanceType string `json:"load_balance_type"`
178 +
179 + // NoHealthyUpstreamsMessage is returned as a response when there are no healthy upstreams to loadbalance to.
180 + NoHealthyUpstreamsMessage string `json:"no_healthy_upstreams_message"`
181 +}
182 +
183 +// ServeHTTP implements the http.Handler interface to dispatch an http request to the proper
184 +// server.
185 +func (lb *LoadBalanced) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
186 + // ensure requests don't hang if an upstream does not respond or is not eventually healthy
187 + var u *upstream
188 + var done bool
189 +
190 + retryTimer := time.NewTicker(lb.tryInterval)
191 + defer retryTimer.Stop()
192 +
193 + go func() {
194 + select {
195 + case <-retryTimer.C:
196 + done = true
197 + }
198 + }()
199 +
200 + // keep trying to get an available upstream to process the request
201 + for {
202 + switch lb.loadBalanceType {
203 + case TypeBalanceRandom:
204 + u = lb.random()
205 + case TypeBalanceRoundRobin:
206 + u = lb.roundRobin()
207 + }
208 +
209 + // if we can't get an upstream and our retry interval has ended return an error response
210 + if u == nil && done {
211 + w.WriteHeader(http.StatusBadGateway)
212 + fmt.Fprint(w, lb.NoHealthyUpstreamsMessage)
213 +
214 + return fmt.Errorf(msgNoHealthyUpstreams)
215 + }
216 +
217 + // attempt to get an available upstream
218 + if u == nil {
219 + continue
220 + }
221 +
222 + start := time.Now()
223 +
224 + // if we get an error retry until we get a healthy upstream
225 + res, err := u.ReverseProxy.ServeHTTP(w, r)
226 + if err != nil {
227 + if err == context.Canceled {
228 + return nil
229 + }
230 +
231 + continue
232 + }
233 +
234 + // record circuit breaker metrics
235 + go u.CB.RecordMetric(res.StatusCode, time.Now().Sub(start))
236 +
237 + return nil
238 + }
239 +}
240 +
241 +// incrUnhealthy increments the amount of unhealthy nodes in a loadbalancer.
242 +func (lb *LoadBalanced) incrUnhealthy() {
243 + atomic.AddInt32(&lb.numUnhealthy, 1)
244 +}
245 +
246 +// decrUnhealthy decrements the amount of unhealthy nodes in a loadbalancer.
247 +func (lb *LoadBalanced) decrUnhealthy() {
248 + atomic.AddInt32(&lb.numUnhealthy, -1)
249 +}
250 +
251 +// roundRobin implements a round robin load balancing algorithm to select
252 +// which server to forward requests to.
253 +func (lb *LoadBalanced) roundRobin() *upstream {
254 + if atomic.LoadInt32(&lb.numUnhealthy) == int32(len(lb.upstreams)) {
255 + return nil
256 + }
257 +
258 + selected := lb.upstreams[lb.selectedServer]
259 +
260 + lb.mu.Lock()
261 + lb.selectedServer++
262 + if lb.selectedServer >= len(lb.upstreams) {
263 + lb.selectedServer = 0
264 + }
265 + lb.mu.Unlock()
266 +
267 + if selected.IsHealthy() && selected.CB.Ok() {
268 + return selected
269 + }
270 +
271 + return nil
272 +}
273 +
274 +// random implements a random server selector for load balancing.
275 +func (lb *LoadBalanced) random() *upstream {
276 + if atomic.LoadInt32(&lb.numUnhealthy) == int32(len(lb.upstreams)) {
277 + return nil
278 + }
279 +
280 + n := rand.Int() % len(lb.upstreams)
281 + selected := lb.upstreams[n]
282 +
283 + if selected.IsHealthy() && selected.CB.Ok() {
284 + return selected
285 + }
286 +
287 + return nil
288 +}
289 +
290 +// UpstreamConfig represents the config of an upstream.
291 +type UpstreamConfig struct {
292 + // Host is the host name of the upstream server.
293 + Host string `json:"host"`
294 +
295 + // FastHealthCheckDuration is the duration for which a health check is performed when a node is considered unhealthy.
296 + FastHealthCheckDuration string `json:"fast_health_check_duration"`
297 +
298 + CircuitBreaker json.RawMessage `json:"circuit_breaker"`
299 +
300 + // // CircuitBreakerConfig is the config passed to setup a circuit breaker.
301 + // CircuitBreakerConfig *circuitbreaker.Config `json:"circuit_breaker"`
302 + circuitbreaker CircuitBreaker
303 +
304 + // HealthCheckDuration is the default duration for which a health check is performed.
305 + HealthCheckDuration string `json:"health_check_duration"`
306 +
307 + // HealthCheckPath is the path at the upstream host to use for healthchecks.
308 + HealthCheckPath string `json:"health_check_path"`
309 +}
310 +
311 +// upstream represents an upstream host.
312 +type upstream struct {
313 + Healthy int32 // 0 = false, 1 = true
314 + Target *url.URL
315 + ReverseProxy *ReverseProxy
316 + Incr func()
317 + Decr func()
318 + CB CircuitBreaker
319 + healthChecker *HealthChecker
320 + healthCheckDur time.Duration
321 + fastHealthCheckDur time.Duration
322 +}
323 +
324 +// newUpstream returns a new upstream.
325 +func newUpstream(uc *UpstreamConfig, d func(), i func()) (*upstream, error) {
326 + host := strings.TrimSpace(uc.Host)
327 + protoIdx := strings.Index(host, "://")
328 + if protoIdx == -1 || len(host[:protoIdx]) == 0 {
329 + return nil, fmt.Errorf("protocol is required for host")
330 + }
331 +
332 + hostURL, err := url.Parse(host)
333 + if err != nil {
334 + return nil, err
335 + }
336 +
337 + // parse healthcheck durations
338 + hcd, err := time.ParseDuration(uc.HealthCheckDuration)
339 + if err != nil {
340 + hcd = defaultHealthCheckDur
341 + }
342 +
343 + fhcd, err := time.ParseDuration(uc.FastHealthCheckDuration)
344 + if err != nil {
345 + fhcd = defaultFastHealthCheckDur
346 + }
347 +
348 + u := upstream{
349 + healthCheckDur: hcd,
350 + fastHealthCheckDur: fhcd,
351 + Target: hostURL,
352 + Decr: d,
353 + Incr: i,
354 + Healthy: int32(0), // assume is unhealthy on start
355 + }
356 +
357 + u.ReverseProxy = newReverseProxy(hostURL, u.SetHealthiness)
358 + return &u, nil
359 +}
360 +
361 +// SetHealthiness sets whether an upstream is healthy or not. The health check worker is updated to
362 +// perform checks faster if a node is unhealthy.
363 +func (u *upstream) SetHealthiness(ok bool) {
364 + h := atomic.LoadInt32(&u.Healthy)
365 + var wasHealthy bool
366 + if h == 1 {
367 + wasHealthy = true
368 + } else {
369 + wasHealthy = false
370 + }
371 +
372 + if ok {
373 + u.healthChecker.Ticker = time.NewTicker(u.healthCheckDur)
374 +
375 + if !wasHealthy {
376 + atomic.AddInt32(&u.Healthy, 1)
377 + u.Decr()
378 + }
379 + } else {
380 + u.healthChecker.Ticker = time.NewTicker(u.fastHealthCheckDur)
381 +
382 + if wasHealthy {
383 + atomic.AddInt32(&u.Healthy, -1)
384 + u.Incr()
385 + }
386 + }
387 +}
388 +
389 +// IsHealthy returns whether an Upstream is healthy or not.
390 +func (u *upstream) IsHealthy() bool {
391 + i := atomic.LoadInt32(&u.Healthy)
392 + if i == 1 {
393 + return true
394 + }
395 +
396 + return false
397 +}
398 +
399 +// newReverseProxy returns a new reverse proxy handler.
400 +func newReverseProxy(target *url.URL, setHealthiness func(bool)) *ReverseProxy {
401 + errorHandler := func(w http.ResponseWriter, r *http.Request, err error) {
402 + // we don't need to worry about cancelled contexts since this doesn't necessarilly mean that
403 + // the upstream is unhealthy.
404 + if err != context.Canceled {
405 + setHealthiness(false)
406 + }
407 + }
408 +
409 + rp := NewSingleHostReverseProxy(target)
410 + rp.ErrorHandler = errorHandler
411 + rp.Transport = defaultTransport // use default transport that times out in 5 seconds
412 + return rp
413 +}