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