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