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