]> git.arvados.org - arvados.git/blob - lib/controller/handler.go
Merge branch '23009-multiselect-bug' into main. Closes #23009
[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         "encoding/json"
10         "errors"
11         "fmt"
12         "io/ioutil"
13         "mime"
14         "net/http"
15         "net/http/httptest"
16         "net/url"
17         "strings"
18         "sync"
19         "time"
20
21         "git.arvados.org/arvados.git/lib/controller/api"
22         "git.arvados.org/arvados.git/lib/controller/federation"
23         "git.arvados.org/arvados.git/lib/controller/localdb"
24         "git.arvados.org/arvados.git/lib/controller/railsproxy"
25         "git.arvados.org/arvados.git/lib/controller/router"
26         "git.arvados.org/arvados.git/lib/ctrlctx"
27         "git.arvados.org/arvados.git/sdk/go/arvados"
28         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
29         "git.arvados.org/arvados.git/sdk/go/ctxlog"
30         "git.arvados.org/arvados.git/sdk/go/health"
31         "git.arvados.org/arvados.git/sdk/go/httpserver"
32
33         // sqlx needs lib/pq to talk to PostgreSQL
34         _ "github.com/lib/pq"
35 )
36
37 type Handler struct {
38         Cluster           *arvados.Cluster
39         BackgroundContext context.Context
40
41         setupOnce      sync.Once
42         federation     *federation.Conn
43         handlerStack   http.Handler
44         router         http.Handler
45         proxy          *proxy
46         secureClient   *http.Client
47         insecureClient *http.Client
48         dbConnector    ctrlctx.DBConnector
49
50         cache map[string]*cacheEnt
51 }
52
53 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
54         h.setupOnce.Do(h.setup)
55         if req.Method != "GET" && req.Method != "HEAD" {
56                 // http.ServeMux returns 301 with a cleaned path if
57                 // the incoming request has a double slash. Some
58                 // clients (including the Go standard library) change
59                 // the request method to GET when following a 301
60                 // redirect if the original method was not HEAD (RFC
61                 // 7231 6.4.2 specifically allows this in the case of
62                 // POST). Thus "POST //foo" gets misdirected to "GET
63                 // /foo". To avoid this, eliminate double slashes
64                 // before passing the request to ServeMux.
65                 for strings.Contains(req.URL.Path, "//") {
66                         req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
67                 }
68         }
69         if len(req.Host) > 28 && arvadosclient.UUIDMatch(req.Host[:27]) && req.Host[27] == '-' {
70                 // Requests to a vhost like
71                 // "{ctr-uuid}-{port}.example.com" go straight to
72                 // controller-specific routing, bypassing
73                 // handlerStack's logic about proxying
74                 // non-controller-specific paths through to RailsAPI.
75                 h.router.ServeHTTP(w, req)
76                 return
77         }
78         h.handlerStack.ServeHTTP(w, req)
79 }
80
81 func (h *Handler) CheckHealth() error {
82         h.setupOnce.Do(h.setup)
83         _, err := h.dbConnector.GetDB(context.TODO())
84         if err != nil {
85                 return err
86         }
87         _, _, err = railsproxy.FindRailsAPI(h.Cluster)
88         if err != nil {
89                 return err
90         }
91         if h.Cluster.API.VocabularyPath != "" {
92                 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
93                 if err != nil {
94                         return err
95                 }
96                 var resp httptest.ResponseRecorder
97                 h.handlerStack.ServeHTTP(&resp, req)
98                 if resp.Result().StatusCode != http.StatusOK {
99                         return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
100                 }
101         }
102         return nil
103 }
104
105 func (h *Handler) Done() <-chan struct{} {
106         return nil
107 }
108
109 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
110
111 func (h *Handler) setup() {
112         mux := http.NewServeMux()
113         healthFuncs := make(map[string]health.Func)
114
115         h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
116         go func() {
117                 <-h.BackgroundContext.Done()
118                 h.dbConnector.Close()
119         }()
120         oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
121         h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
122         h.router = router.New(h.federation, router.Config{
123                 ContainerWebServices: &h.Cluster.Services.ContainerWebServices,
124                 MaxRequestSize:       h.Cluster.API.MaxRequestSize,
125                 WrapCalls: api.ComposeWrappers(
126                         ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
127                         oidcAuthorizer.WrapCalls,
128                         ctrlctx.WrapCallsWithAuth(h.Cluster)),
129         })
130
131         healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
132         for name, f := range healthFuncs {
133                 healthRoutes[name] = f
134         }
135         mux.Handle("/_health/", &health.Handler{
136                 Token:  h.Cluster.ManagementToken,
137                 Prefix: "/_health/",
138                 Routes: healthRoutes,
139         })
140         mux.Handle("/arvados/v1/config", h.router)
141         mux.Handle("/arvados/v1/vocabulary", h.router)
142         mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, h.router) // must come before .../users/
143         mux.Handle("/arvados/v1/collections", h.router)
144         mux.Handle("/arvados/v1/collections/", h.router)
145         mux.Handle("/arvados/v1/users", h.router)
146         mux.Handle("/arvados/v1/users/", h.router)
147         mux.Handle("/arvados/v1/connect/", h.router)
148         mux.Handle("/arvados/v1/container_requests", h.router)
149         mux.Handle("/arvados/v1/container_requests/", h.router)
150         mux.Handle("/arvados/v1/groups", h.router)
151         mux.Handle("/arvados/v1/groups/", h.router)
152         mux.Handle("/arvados/v1/links", h.router)
153         mux.Handle("/arvados/v1/links/", h.router)
154         mux.Handle("/arvados/v1/authorized_keys", h.router)
155         mux.Handle("/arvados/v1/authorized_keys/", h.router)
156         mux.Handle("/login", h.router)
157         mux.Handle("/logout", h.router)
158         mux.Handle("/arvados/v1/api_client_authorizations", h.router)
159         mux.Handle("/arvados/v1/api_client_authorizations/", h.router)
160
161         hs := http.NotFoundHandler()
162         hs = prepend(hs, h.proxyRailsAPI)
163         hs = prepend(hs, h.routeContainerEndpoints(h.router))
164         hs = prepend(hs, h.routeServiceContainerPorts(h.router))
165         hs = h.setupProxyRemoteCluster(hs)
166         hs = prepend(hs, oidcAuthorizer.Middleware)
167         mux.Handle("/", hs)
168         h.handlerStack = mux
169
170         sc := *arvados.DefaultSecureClient
171         sc.CheckRedirect = neverRedirect
172         h.secureClient = &sc
173
174         ic := *arvados.InsecureHTTPClient
175         ic.CheckRedirect = neverRedirect
176         h.insecureClient = &ic
177
178         h.proxy = &proxy{
179                 Name: "arvados-controller",
180         }
181         h.cache = map[string]*cacheEnt{
182                 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
183         }
184
185         go h.trashSweepWorker()
186         go h.containerLogSweepWorker()
187 }
188
189 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
190
191 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
192         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
193                 middleware(w, req, next)
194         })
195 }
196
197 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
198         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
199         if err != nil {
200                 return nil, err
201         }
202         urlOut = &url.URL{
203                 Scheme:   urlOut.Scheme,
204                 Host:     urlOut.Host,
205                 Path:     req.URL.Path,
206                 RawPath:  req.URL.RawPath,
207                 RawQuery: req.URL.RawQuery,
208         }
209         client := h.secureClient
210         if insecure {
211                 client = h.insecureClient
212         }
213         // Clearing the Host field here causes the Go http client to
214         // use the host part of urlOut as the Host header in the
215         // outgoing request, instead of the Host value from the
216         // original request we received.
217         req.Host = ""
218         return h.proxy.Do(req, urlOut, client)
219 }
220
221 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
222 // .../gateway_tunnel to rtr, pass everything else to next.
223 //
224 // (http.ServeMux doesn't let us route these without also routing
225 // everything under /containers/, which we don't want yet.)
226 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
227         return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
228                 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
229                 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
230                         strings.Index(trim, "/ssh") == 27 ||
231                         strings.Index(trim, "/gateway_tunnel") == 27) {
232                         rtr.ServeHTTP(w, req)
233                 } else {
234                         next.ServeHTTP(w, req)
235                 }
236         }
237 }
238
239 // Route ContainerWebServices requests through rtr, pass through
240 // everything else.
241 func (h *Handler) routeServiceContainerPorts(rtr http.Handler) middlewareFunc {
242         return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
243                 if router.ContainerHTTPProxyTarget(&h.Cluster.Services.ContainerWebServices, req) != "" {
244                         rtr.ServeHTTP(w, req)
245                 } else {
246                         next.ServeHTTP(w, req)
247                 }
248         }
249 }
250
251 // cacheEnt implements a basic stale-while-revalidate cache, suitable
252 // for the Arvados discovery document.
253 type cacheEnt struct {
254         validate     func(body []byte) error
255         mtx          sync.Mutex
256         header       http.Header
257         body         []byte
258         expireAfter  time.Time
259         refreshAfter time.Time
260         refreshLock  sync.Mutex
261 }
262
263 const (
264         cacheTTL    = 5 * time.Minute
265         cacheExpire = 24 * time.Hour
266 )
267
268 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
269         ent.refreshLock.Lock()
270         defer ent.refreshLock.Unlock()
271         if header, body, needRefresh := ent.response(); !needRefresh {
272                 // another goroutine refreshed successfully while we
273                 // were waiting for refreshLock
274                 return header, body, nil
275         } else if body != nil {
276                 // Cache is present, but expired. We'll try to refresh
277                 // below. Meanwhile, other refresh() calls will queue
278                 // up for refreshLock -- and we don't want them to
279                 // turn into N upstream requests, even if upstream is
280                 // failing.  (If we succeed we'll update the expiry
281                 // time again below with the real cacheTTL -- this
282                 // just takes care of the error case.)
283                 ent.mtx.Lock()
284                 ent.refreshAfter = time.Now().Add(time.Second)
285                 ent.mtx.Unlock()
286         }
287
288         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
289         defer cancel()
290         // "http://localhost" is just a placeholder here -- we'll fill
291         // in req.URL.Path below, and then do(), which is
292         // localClusterRequest(), will replace the scheme and host
293         // parts with the real proxy destination.
294         req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
295         if err != nil {
296                 return nil, nil, err
297         }
298         req.URL.Path = path
299         resp, err := do(req)
300         if err != nil {
301                 return nil, nil, err
302         }
303         if resp.StatusCode != http.StatusOK {
304                 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
305         }
306         body, err := ioutil.ReadAll(resp.Body)
307         if err != nil {
308                 return nil, nil, fmt.Errorf("Read error: %w", err)
309         }
310         header := http.Header{}
311         for k, v := range resp.Header {
312                 if !dropHeaders[k] && k != "X-Request-Id" {
313                         header[k] = v
314                 }
315         }
316         if ent.validate != nil {
317                 if err := ent.validate(body); err != nil {
318                         return nil, nil, err
319                 }
320         } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
321                 if !json.Valid(body) {
322                         return nil, nil, errors.New("invalid JSON encoding in response")
323                 }
324         }
325         ent.mtx.Lock()
326         defer ent.mtx.Unlock()
327         ent.header = header
328         ent.body = body
329         ent.refreshAfter = time.Now().Add(cacheTTL)
330         ent.expireAfter = time.Now().Add(cacheExpire)
331         return ent.header, ent.body, nil
332 }
333
334 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
335         ent.mtx.Lock()
336         defer ent.mtx.Unlock()
337         if ent.expireAfter.Before(time.Now()) {
338                 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
339         }
340         return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
341 }
342
343 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
344         header, body, needRefresh := ent.response()
345         if body == nil {
346                 // need to fetch before we can return anything
347                 var err error
348                 header, body, err = ent.refresh(path, do)
349                 if err != nil {
350                         http.Error(w, err.Error(), http.StatusBadGateway)
351                         return
352                 }
353         } else if needRefresh {
354                 // re-fetch in background
355                 go func() {
356                         _, _, err := ent.refresh(path, do)
357                         if err != nil {
358                                 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
359                         }
360                 }()
361         }
362         for k, v := range header {
363                 w.Header()[k] = v
364         }
365         w.WriteHeader(http.StatusOK)
366         w.Write(body)
367 }
368
369 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
370         if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
371                 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
372                 return
373         }
374         resp, err := h.localClusterRequest(req)
375         n, err := h.proxy.ForwardResponse(w, resp, err)
376         if err != nil {
377                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
378         }
379 }
380
381 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
382 // present, otherwise choose an arbitrary entry.
383 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
384         var best *url.URL
385         for target := range cluster.Services.RailsAPI.InternalURLs {
386                 target := url.URL(target)
387                 best = &target
388                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
389                         break
390                 }
391         }
392         if best == nil {
393                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
394         }
395         return best, cluster.TLS.Insecure, nil
396 }
397
398 func validateDiscoveryDoc(body []byte) error {
399         var dd arvados.DiscoveryDocument
400         err := json.Unmarshal(body, &dd)
401         if err != nil {
402                 return fmt.Errorf("error decoding JSON response: %w", err)
403         }
404         if dd.BasePath == "" {
405                 return errors.New("error in discovery document: no value for basePath")
406         }
407         return nil
408 }