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