1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
33 // sqlx needs lib/pq to talk to PostgreSQL
38 Cluster *arvados.Cluster
39 BackgroundContext context.Context
42 federation *federation.Conn
43 handlerStack http.Handler
46 secureClient *http.Client
47 insecureClient *http.Client
48 dbConnector ctrlctx.DBConnector
50 cache map[string]*cacheEnt
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)
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)
78 h.handlerStack.ServeHTTP(w, req)
81 func (h *Handler) CheckHealth() error {
82 h.setupOnce.Do(h.setup)
83 _, err := h.dbConnector.GetDB(context.TODO())
87 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
91 if h.Cluster.API.VocabularyPath != "" {
92 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
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)
105 func (h *Handler) Done() <-chan struct{} {
109 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
111 func (h *Handler) setup() {
112 mux := http.NewServeMux()
113 healthFuncs := make(map[string]health.Func)
115 h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
117 <-h.BackgroundContext.Done()
118 h.dbConnector.Close()
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 MaxRequestSize: h.Cluster.API.MaxRequestSize,
124 WrapCalls: api.ComposeWrappers(
125 ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
126 oidcAuthorizer.WrapCalls,
127 ctrlctx.WrapCallsWithAuth(h.Cluster)),
130 healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
131 for name, f := range healthFuncs {
132 healthRoutes[name] = f
134 mux.Handle("/_health/", &health.Handler{
135 Token: h.Cluster.ManagementToken,
137 Routes: healthRoutes,
139 mux.Handle("/arvados/v1/config", h.router)
140 mux.Handle("/arvados/v1/vocabulary", h.router)
141 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, h.router) // must come before .../users/
142 mux.Handle("/arvados/v1/collections", h.router)
143 mux.Handle("/arvados/v1/collections/", h.router)
144 mux.Handle("/arvados/v1/users", h.router)
145 mux.Handle("/arvados/v1/users/", h.router)
146 mux.Handle("/arvados/v1/connect/", h.router)
147 mux.Handle("/arvados/v1/container_requests", h.router)
148 mux.Handle("/arvados/v1/container_requests/", h.router)
149 mux.Handle("/arvados/v1/groups", h.router)
150 mux.Handle("/arvados/v1/groups/", h.router)
151 mux.Handle("/arvados/v1/links", h.router)
152 mux.Handle("/arvados/v1/links/", h.router)
153 mux.Handle("/arvados/v1/authorized_keys", h.router)
154 mux.Handle("/arvados/v1/authorized_keys/", h.router)
155 mux.Handle("/login", h.router)
156 mux.Handle("/logout", h.router)
157 mux.Handle("/arvados/v1/api_client_authorizations", h.router)
158 mux.Handle("/arvados/v1/api_client_authorizations/", h.router)
160 hs := http.NotFoundHandler()
161 hs = prepend(hs, h.proxyRailsAPI)
162 hs = prepend(hs, h.routeContainerEndpoints(h.router))
163 hs = h.setupProxyRemoteCluster(hs)
164 hs = prepend(hs, oidcAuthorizer.Middleware)
168 sc := *arvados.DefaultSecureClient
169 sc.CheckRedirect = neverRedirect
172 ic := *arvados.InsecureHTTPClient
173 ic.CheckRedirect = neverRedirect
174 h.insecureClient = &ic
177 Name: "arvados-controller",
179 h.cache = map[string]*cacheEnt{
180 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
183 go h.trashSweepWorker()
184 go h.containerLogSweepWorker()
187 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
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)
195 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
196 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
201 Scheme: urlOut.Scheme,
204 RawPath: req.URL.RawPath,
205 RawQuery: req.URL.RawQuery,
207 client := h.secureClient
209 client = h.insecureClient
211 // Clearing the Host field here causes the Go http client to
212 // use the host part of urlOut as the Host header in the
213 // outgoing request, instead of the Host value from the
214 // original request we received.
216 return h.proxy.Do(req, urlOut, client)
219 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
220 // .../gateway_tunnel to rtr, pass everything else to next.
222 // (http.ServeMux doesn't let us route these without also routing
223 // everything under /containers/, which we don't want yet.)
224 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
225 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
226 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
227 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
228 strings.Index(trim, "/ssh") == 27 ||
229 strings.Index(trim, "/gateway_tunnel") == 27) {
230 rtr.ServeHTTP(w, req)
232 next.ServeHTTP(w, req)
237 // cacheEnt implements a basic stale-while-revalidate cache, suitable
238 // for the Arvados discovery document.
239 type cacheEnt struct {
240 validate func(body []byte) error
244 expireAfter time.Time
245 refreshAfter time.Time
246 refreshLock sync.Mutex
250 cacheTTL = 5 * time.Minute
251 cacheExpire = 24 * time.Hour
254 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
255 ent.refreshLock.Lock()
256 defer ent.refreshLock.Unlock()
257 if header, body, needRefresh := ent.response(); !needRefresh {
258 // another goroutine refreshed successfully while we
259 // were waiting for refreshLock
260 return header, body, nil
261 } else if body != nil {
262 // Cache is present, but expired. We'll try to refresh
263 // below. Meanwhile, other refresh() calls will queue
264 // up for refreshLock -- and we don't want them to
265 // turn into N upstream requests, even if upstream is
266 // failing. (If we succeed we'll update the expiry
267 // time again below with the real cacheTTL -- this
268 // just takes care of the error case.)
270 ent.refreshAfter = time.Now().Add(time.Second)
274 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
276 // "http://localhost" is just a placeholder here -- we'll fill
277 // in req.URL.Path below, and then do(), which is
278 // localClusterRequest(), will replace the scheme and host
279 // parts with the real proxy destination.
280 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
289 if resp.StatusCode != http.StatusOK {
290 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
292 body, err := ioutil.ReadAll(resp.Body)
294 return nil, nil, fmt.Errorf("Read error: %w", err)
296 header := http.Header{}
297 for k, v := range resp.Header {
298 if !dropHeaders[k] && k != "X-Request-Id" {
302 if ent.validate != nil {
303 if err := ent.validate(body); err != nil {
306 } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
307 if !json.Valid(body) {
308 return nil, nil, errors.New("invalid JSON encoding in response")
312 defer ent.mtx.Unlock()
315 ent.refreshAfter = time.Now().Add(cacheTTL)
316 ent.expireAfter = time.Now().Add(cacheExpire)
317 return ent.header, ent.body, nil
320 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
322 defer ent.mtx.Unlock()
323 if ent.expireAfter.Before(time.Now()) {
324 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
326 return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
329 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
330 header, body, needRefresh := ent.response()
332 // need to fetch before we can return anything
334 header, body, err = ent.refresh(path, do)
336 http.Error(w, err.Error(), http.StatusBadGateway)
339 } else if needRefresh {
340 // re-fetch in background
342 _, _, err := ent.refresh(path, do)
344 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
348 for k, v := range header {
351 w.WriteHeader(http.StatusOK)
355 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
356 if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
357 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
360 resp, err := h.localClusterRequest(req)
361 n, err := h.proxy.ForwardResponse(w, resp, err)
363 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
367 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
368 // present, otherwise choose an arbitrary entry.
369 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
371 for target := range cluster.Services.RailsAPI.InternalURLs {
372 target := url.URL(target)
374 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
379 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
381 return best, cluster.TLS.Insecure, nil
384 func validateDiscoveryDoc(body []byte) error {
385 var dd arvados.DiscoveryDocument
386 err := json.Unmarshal(body, &dd)
388 return fmt.Errorf("error decoding JSON response: %w", err)
390 if dd.BasePath == "" {
391 return errors.New("error in discovery document: no value for basePath")