13497: Add timeout for proxy requests.
[arvados.git] / lib / controller / handler.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "context"
9         "io"
10         "net"
11         "net/http"
12         "net/url"
13         "strings"
14         "sync"
15         "time"
16
17         "git.curoverse.com/arvados.git/sdk/go/arvados"
18         "git.curoverse.com/arvados.git/sdk/go/health"
19         "git.curoverse.com/arvados.git/sdk/go/httpserver"
20 )
21
22 type Handler struct {
23         Cluster *arvados.Cluster
24         Node    *arvados.SystemNode
25
26         setupOnce    sync.Once
27         handlerStack http.Handler
28         proxyClient  *arvados.Client
29 }
30
31 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
32         h.setupOnce.Do(h.setup)
33         h.handlerStack.ServeHTTP(w, req)
34 }
35
36 func (h *Handler) setup() {
37         mux := http.NewServeMux()
38         mux.Handle("/_health/", &health.Handler{
39                 Token:  h.Cluster.ManagementToken,
40                 Prefix: "/_health/",
41         })
42         mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
43         h.handlerStack = mux
44 }
45
46 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
47         urlOut, err := findRailsAPI(h.Cluster, h.Node)
48         if err != nil {
49                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
50                 return
51         }
52         urlOut = &url.URL{
53                 Scheme:   urlOut.Scheme,
54                 Host:     urlOut.Host,
55                 Path:     reqIn.URL.Path,
56                 RawPath:  reqIn.URL.RawPath,
57                 RawQuery: reqIn.URL.RawQuery,
58         }
59
60         // Copy headers from incoming request, then add/replace proxy
61         // headers like Via and X-Forwarded-For.
62         hdrOut := http.Header{}
63         for k, v := range reqIn.Header {
64                 hdrOut[k] = v
65         }
66         xff := reqIn.RemoteAddr
67         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
68                 xff = xffIn + "," + xff
69         }
70         hdrOut.Set("X-Forwarded-For", xff)
71         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
72
73         ctx := reqIn.Context()
74         if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
75                 var cancel context.CancelFunc
76                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
77                 defer cancel()
78         }
79
80         reqOut := (&http.Request{
81                 Method: reqIn.Method,
82                 URL:    urlOut,
83                 Header: hdrOut,
84         }).WithContext(ctx)
85         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
86         if err != nil {
87                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
88                 return
89         }
90         for k, v := range resp.Header {
91                 for _, v := range v {
92                         w.Header().Add(k, v)
93                 }
94         }
95         w.WriteHeader(resp.StatusCode)
96         n, err := io.Copy(w, resp.Body)
97         if err != nil {
98                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
99         }
100 }
101
102 // For now, findRailsAPI always uses the rails API running on this
103 // node.
104 func findRailsAPI(cluster *arvados.Cluster, node *arvados.SystemNode) (*url.URL, error) {
105         hostport := node.RailsAPI.Listen
106         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
107                 // ":12345" => connect to indicated port on localhost
108                 hostport = "localhost" + hostport
109         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
110                 // "[::1]:12345" => connect to indicated address & port
111         } else {
112                 return nil, err
113         }
114         proto := "http"
115         if node.RailsAPI.TLS {
116                 proto = "https"
117         }
118         return url.Parse(proto + "://" + hostport)
119 }