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