15003: Merge branch 'master' into 15003-preprocess-config
[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         if h.Cluster.HTTPRequestTimeout > 0 {
54                 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.HTTPRequestTimeout)))
55                 req = req.WithContext(ctx)
56                 defer cancel()
57         }
58
59         h.handlerStack.ServeHTTP(w, req)
60 }
61
62 func (h *Handler) CheckHealth() error {
63         h.setupOnce.Do(h.setup)
64         _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
65         return err
66 }
67
68 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
69
70 func (h *Handler) setup() {
71         mux := http.NewServeMux()
72         mux.Handle("/_health/", &health.Handler{
73                 Token:  h.Cluster.ManagementToken,
74                 Prefix: "/_health/",
75                 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
76         })
77         hs := http.NotFoundHandler()
78         hs = prepend(hs, h.proxyRailsAPI)
79         hs = h.setupProxyRemoteCluster(hs)
80         mux.Handle("/", hs)
81         h.handlerStack = mux
82
83         sc := *arvados.DefaultSecureClient
84         sc.CheckRedirect = neverRedirect
85         h.secureClient = &sc
86
87         ic := *arvados.InsecureHTTPClient
88         ic.CheckRedirect = neverRedirect
89         h.insecureClient = &ic
90
91         h.proxy = &proxy{
92                 Name: "arvados-controller",
93         }
94 }
95
96 var errDBConnection = errors.New("database connection error")
97
98 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
99         h.pgdbMtx.Lock()
100         defer h.pgdbMtx.Unlock()
101         if h.pgdb != nil {
102                 return h.pgdb, nil
103         }
104
105         db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
106         if err != nil {
107                 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
108                 return nil, errDBConnection
109         }
110         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
111                 db.SetMaxOpenConns(p)
112         }
113         if err := db.Ping(); err != nil {
114                 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
115                 return nil, errDBConnection
116         }
117         h.pgdb = db
118         return db, nil
119 }
120
121 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
122
123 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
124         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
125                 middleware(w, req, next)
126         })
127 }
128
129 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
130         urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
131         if err != nil {
132                 return nil, err
133         }
134         urlOut = &url.URL{
135                 Scheme:   urlOut.Scheme,
136                 Host:     urlOut.Host,
137                 Path:     req.URL.Path,
138                 RawPath:  req.URL.RawPath,
139                 RawQuery: req.URL.RawQuery,
140         }
141         client := h.secureClient
142         if insecure {
143                 client = h.insecureClient
144         }
145         return h.proxy.Do(req, urlOut, client)
146 }
147
148 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
149         resp, err := h.localClusterRequest(req)
150         n, err := h.proxy.ForwardResponse(w, resp, err)
151         if err != nil {
152                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
153         }
154 }
155
156 // For now, findRailsAPI always uses the rails API running on this
157 // node.
158 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
159         hostport := np.RailsAPI.Listen
160         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
161                 // ":12345" => connect to indicated port on localhost
162                 hostport = "localhost" + hostport
163         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
164                 // "[::1]:12345" => connect to indicated address & port
165         } else {
166                 return nil, false, err
167         }
168         proto := "http"
169         if np.RailsAPI.TLS {
170                 proto = "https"
171         }
172         url, err := url.Parse(proto + "://" + hostport)
173         return url, np.RailsAPI.Insecure, err
174 }