14262: Make sure cancel() from proxy.Do() gets called
[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         "database/sql"
10         "errors"
11         "net"
12         "net/http"
13         "net/url"
14         "strings"
15         "sync"
16         "time"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19         "git.curoverse.com/arvados.git/sdk/go/health"
20         "git.curoverse.com/arvados.git/sdk/go/httpserver"
21         _ "github.com/lib/pq"
22 )
23
24 type Handler struct {
25         Cluster     *arvados.Cluster
26         NodeProfile *arvados.NodeProfile
27
28         setupOnce      sync.Once
29         handlerStack   http.Handler
30         proxy          *proxy
31         secureClient   *http.Client
32         insecureClient *http.Client
33         pgdb           *sql.DB
34         pgdbMtx        sync.Mutex
35 }
36
37 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
38         h.setupOnce.Do(h.setup)
39         if req.Method != "GET" && req.Method != "HEAD" {
40                 // http.ServeMux returns 301 with a cleaned path if
41                 // the incoming request has a double slash. Some
42                 // clients (including the Go standard library) change
43                 // the request method to GET when following a 301
44                 // redirect if the original method was not HEAD
45                 // (RFC7231 6.4.2 specifically allows this in the case
46                 // of POST). Thus "POST //foo" gets misdirected to
47                 // "GET /foo". To avoid this, eliminate double slashes
48                 // before passing the request to ServeMux.
49                 for strings.Contains(req.URL.Path, "//") {
50                         req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
51                 }
52         }
53         h.handlerStack.ServeHTTP(w, req)
54 }
55
56 func (h *Handler) CheckHealth() error {
57         h.setupOnce.Do(h.setup)
58         _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
59         return err
60 }
61
62 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
63
64 func (h *Handler) setup() {
65         mux := http.NewServeMux()
66         mux.Handle("/_health/", &health.Handler{
67                 Token:  h.Cluster.ManagementToken,
68                 Prefix: "/_health/",
69         })
70         hs := http.NotFoundHandler()
71         hs = prepend(hs, h.proxyRailsAPI)
72         hs = h.setupProxyRemoteCluster(hs)
73         mux.Handle("/", hs)
74         h.handlerStack = mux
75
76         sc := *arvados.DefaultSecureClient
77         sc.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
78         sc.CheckRedirect = neverRedirect
79         h.secureClient = &sc
80
81         ic := *arvados.InsecureHTTPClient
82         ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
83         ic.CheckRedirect = neverRedirect
84         h.insecureClient = &ic
85
86         h.proxy = &proxy{
87                 Name:           "arvados-controller",
88                 RequestTimeout: time.Duration(h.Cluster.HTTPRequestTimeout),
89         }
90 }
91
92 var errDBConnection = errors.New("database connection error")
93
94 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
95         h.pgdbMtx.Lock()
96         defer h.pgdbMtx.Unlock()
97         if h.pgdb != nil {
98                 return h.pgdb, nil
99         }
100
101         db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
102         if err != nil {
103                 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
104                 return nil, errDBConnection
105         }
106         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
107                 db.SetMaxOpenConns(p)
108         }
109         if err := db.Ping(); err != nil {
110                 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
111                 return nil, errDBConnection
112         }
113         h.pgdb = db
114         return db, nil
115 }
116
117 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
118
119 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
120         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
121                 middleware(w, req, next)
122         })
123 }
124
125 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, context.CancelFunc, error) {
126         urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
127         if err != nil {
128                 return nil, nil, err
129         }
130         urlOut = &url.URL{
131                 Scheme:   urlOut.Scheme,
132                 Host:     urlOut.Host,
133                 Path:     req.URL.Path,
134                 RawPath:  req.URL.RawPath,
135                 RawQuery: req.URL.RawQuery,
136         }
137         client := h.secureClient
138         if insecure {
139                 client = h.insecureClient
140         }
141         return h.proxy.Do(req, urlOut, client)
142 }
143
144 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
145         resp, cancel, err := h.localClusterRequest(req)
146         if cancel != nil {
147                 defer cancel()
148         }
149         n, err := h.proxy.ForwardResponse(w, resp, err)
150         if err != nil {
151                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
152         }
153 }
154
155 // For now, findRailsAPI always uses the rails API running on this
156 // node.
157 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
158         hostport := np.RailsAPI.Listen
159         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
160                 // ":12345" => connect to indicated port on localhost
161                 hostport = "localhost" + hostport
162         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
163                 // "[::1]:12345" => connect to indicated address & port
164         } else {
165                 return nil, false, err
166         }
167         proto := "http"
168         if np.RailsAPI.TLS {
169                 proto = "https"
170         }
171         url, err := url.Parse(proto + "://" + hostport)
172         return url, np.RailsAPI.Insecure, err
173 }