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