13493: Merge branch 'master' into 13493-federation-proxy
[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         "database/sql"
9         "errors"
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         _ "github.com/lib/pq"
21 )
22
23 type Handler struct {
24         Cluster     *arvados.Cluster
25         NodeProfile *arvados.NodeProfile
26
27         setupOnce      sync.Once
28         handlerStack   http.Handler
29         proxy          *proxy
30         secureClient   *http.Client
31         insecureClient *http.Client
32         pgdb           *sql.DB
33         pgdbMtx        sync.Mutex
34 }
35
36 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
37         h.setupOnce.Do(h.setup)
38         if req.Method != "GET" && req.Method != "HEAD" {
39                 // http.ServeMux returns 301 with a cleaned path if
40                 // the incoming request has a double slash. Some
41                 // clients (including the Go standard library) change
42                 // the request method to GET when following a 301
43                 // redirect if the original method was not HEAD
44                 // (RFC7231 6.4.2 specifically allows this in the case
45                 // of POST). Thus "POST //foo" gets misdirected to
46                 // "GET /foo". To avoid this, eliminate double slashes
47                 // before passing the request to ServeMux.
48                 for strings.Contains(req.URL.Path, "//") {
49                         req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
50                 }
51         }
52         h.handlerStack.ServeHTTP(w, req)
53 }
54
55 func (h *Handler) CheckHealth() error {
56         h.setupOnce.Do(h.setup)
57         _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
58         return err
59 }
60
61 func (h *Handler) setup() {
62         mux := http.NewServeMux()
63         mux.Handle("/_health/", &health.Handler{
64                 Token:  h.Cluster.ManagementToken,
65                 Prefix: "/_health/",
66         })
67         hs := http.NotFoundHandler()
68         hs = prepend(hs, h.proxyRailsAPI)
69         hs = prepend(hs, h.proxyRemoteCluster)
70         mux.Handle("/", hs)
71         h.handlerStack = mux
72
73         sc := *arvados.DefaultSecureClient
74         sc.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
75         h.secureClient = &sc
76
77         ic := *arvados.InsecureHTTPClient
78         ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
79         h.insecureClient = &ic
80
81         h.proxy = &proxy{
82                 Name:           "arvados-controller",
83                 RequestTimeout: time.Duration(h.Cluster.HTTPRequestTimeout),
84         }
85
86         // Changing the global isn't the right way to do this, but a
87         // proper solution would conflict with an impending 13493
88         // merge anyway, so this will do for now.
89         arvados.InsecureHTTPClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
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) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
126         urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
127         if err != nil {
128                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
129                 return
130         }
131         urlOut = &url.URL{
132                 Scheme:   urlOut.Scheme,
133                 Host:     urlOut.Host,
134                 Path:     req.URL.Path,
135                 RawPath:  req.URL.RawPath,
136                 RawQuery: req.URL.RawQuery,
137         }
138         client := h.secureClient
139         if insecure {
140                 client = h.insecureClient
141         }
142         h.proxy.Do(w, req, urlOut, client)
143 }
144
145 // For now, findRailsAPI always uses the rails API running on this
146 // node.
147 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
148         hostport := np.RailsAPI.Listen
149         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
150                 // ":12345" => connect to indicated port on localhost
151                 hostport = "localhost" + hostport
152         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
153                 // "[::1]:12345" => connect to indicated address & port
154         } else {
155                 return nil, false, err
156         }
157         proto := "http"
158         if np.RailsAPI.TLS {
159                 proto = "https"
160         }
161         url, err := url.Parse(proto + "://" + hostport)
162         return url, np.RailsAPI.Insecure, err
163 }