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