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/ctxlog"
29 "git.arvados.org/arvados.git/sdk/go/health"
30 "git.arvados.org/arvados.git/sdk/go/httpserver"
32 // sqlx needs lib/pq to talk to PostgreSQL
37 Cluster *arvados.Cluster
38 BackgroundContext context.Context
41 federation *federation.Conn
42 handlerStack http.Handler
44 secureClient *http.Client
45 insecureClient *http.Client
46 dbConnector ctrlctx.DBConnector
48 cache map[string]*cacheEnt
51 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
52 h.setupOnce.Do(h.setup)
53 if req.Method != "GET" && req.Method != "HEAD" {
54 // http.ServeMux returns 301 with a cleaned path if
55 // the incoming request has a double slash. Some
56 // clients (including the Go standard library) change
57 // the request method to GET when following a 301
58 // redirect if the original method was not HEAD (RFC
59 // 7231 6.4.2 specifically allows this in the case of
60 // POST). Thus "POST //foo" gets misdirected to "GET
61 // /foo". To avoid this, eliminate double slashes
62 // before passing the request to ServeMux.
63 for strings.Contains(req.URL.Path, "//") {
64 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
67 h.handlerStack.ServeHTTP(w, req)
70 func (h *Handler) CheckHealth() error {
71 h.setupOnce.Do(h.setup)
72 _, err := h.dbConnector.GetDB(context.TODO())
76 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
80 if h.Cluster.API.VocabularyPath != "" {
81 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
85 var resp httptest.ResponseRecorder
86 h.handlerStack.ServeHTTP(&resp, req)
87 if resp.Result().StatusCode != http.StatusOK {
88 return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
94 func (h *Handler) Done() <-chan struct{} {
98 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
100 func (h *Handler) setup() {
101 mux := http.NewServeMux()
102 healthFuncs := make(map[string]health.Func)
104 h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
106 <-h.BackgroundContext.Done()
107 h.dbConnector.Close()
109 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
110 h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
111 rtr := router.New(h.federation, router.Config{
112 MaxRequestSize: h.Cluster.API.MaxRequestSize,
113 WrapCalls: api.ComposeWrappers(
114 ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
115 oidcAuthorizer.WrapCalls,
116 ctrlctx.WrapCallsWithAuth(h.Cluster)),
119 healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
120 for name, f := range healthFuncs {
121 healthRoutes[name] = f
123 mux.Handle("/_health/", &health.Handler{
124 Token: h.Cluster.ManagementToken,
126 Routes: healthRoutes,
128 mux.Handle("/arvados/v1/config", rtr)
129 mux.Handle("/arvados/v1/vocabulary", rtr)
130 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
131 mux.Handle("/arvados/v1/collections", rtr)
132 mux.Handle("/arvados/v1/collections/", rtr)
133 mux.Handle("/arvados/v1/users", rtr)
134 mux.Handle("/arvados/v1/users/", rtr)
135 mux.Handle("/arvados/v1/connect/", rtr)
136 mux.Handle("/arvados/v1/container_requests", rtr)
137 mux.Handle("/arvados/v1/container_requests/", rtr)
138 mux.Handle("/arvados/v1/groups", rtr)
139 mux.Handle("/arvados/v1/groups/", rtr)
140 mux.Handle("/arvados/v1/links", rtr)
141 mux.Handle("/arvados/v1/links/", rtr)
142 mux.Handle("/arvados/v1/authorized_keys", rtr)
143 mux.Handle("/arvados/v1/authorized_keys/", rtr)
144 mux.Handle("/login", rtr)
145 mux.Handle("/logout", rtr)
146 mux.Handle("/arvados/v1/api_client_authorizations", rtr)
147 mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
149 hs := http.NotFoundHandler()
150 hs = prepend(hs, h.proxyRailsAPI)
151 hs = prepend(hs, h.routeContainerEndpoints(rtr))
152 hs = h.setupProxyRemoteCluster(hs)
153 hs = prepend(hs, oidcAuthorizer.Middleware)
157 sc := *arvados.DefaultSecureClient
158 sc.CheckRedirect = neverRedirect
161 ic := *arvados.InsecureHTTPClient
162 ic.CheckRedirect = neverRedirect
163 h.insecureClient = &ic
166 Name: "arvados-controller",
168 h.cache = map[string]*cacheEnt{
169 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
172 go h.trashSweepWorker()
173 go h.containerLogSweepWorker()
176 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
178 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
179 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
180 middleware(w, req, next)
184 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
185 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
190 Scheme: urlOut.Scheme,
193 RawPath: req.URL.RawPath,
194 RawQuery: req.URL.RawQuery,
196 client := h.secureClient
198 client = h.insecureClient
200 // Clearing the Host field here causes the Go http client to
201 // use the host part of urlOut as the Host header in the
202 // outgoing request, instead of the Host value from the
203 // original request we received.
205 return h.proxy.Do(req, urlOut, client)
208 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
209 // .../gateway_tunnel to rtr, pass everything else to next.
211 // (http.ServeMux doesn't let us route these without also routing
212 // everything under /containers/, which we don't want yet.)
213 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
214 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
215 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
216 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
217 strings.Index(trim, "/ssh") == 27 ||
218 strings.Index(trim, "/gateway_tunnel") == 27) {
219 rtr.ServeHTTP(w, req)
221 next.ServeHTTP(w, req)
226 // cacheEnt implements a basic stale-while-revalidate cache, suitable
227 // for the Arvados discovery document.
228 type cacheEnt struct {
229 validate func(body []byte) error
233 expireAfter time.Time
234 refreshAfter time.Time
235 refreshLock sync.Mutex
239 cacheTTL = 5 * time.Minute
240 cacheExpire = 24 * time.Hour
243 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
244 ent.refreshLock.Lock()
245 defer ent.refreshLock.Unlock()
246 if header, body, needRefresh := ent.response(); !needRefresh {
247 // another goroutine refreshed successfully while we
248 // were waiting for refreshLock
249 return header, body, nil
250 } else if body != nil {
251 // Cache is present, but expired. We'll try to refresh
252 // below. Meanwhile, other refresh() calls will queue
253 // up for refreshLock -- and we don't want them to
254 // turn into N upstream requests, even if upstream is
255 // failing. (If we succeed we'll update the expiry
256 // time again below with the real cacheTTL -- this
257 // just takes care of the error case.)
259 ent.refreshAfter = time.Now().Add(time.Second)
263 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
265 // "http://localhost" is just a placeholder here -- we'll fill
266 // in req.URL.Path below, and then do(), which is
267 // localClusterRequest(), will replace the scheme and host
268 // parts with the real proxy destination.
269 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
278 if resp.StatusCode != http.StatusOK {
279 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
281 body, err := ioutil.ReadAll(resp.Body)
283 return nil, nil, fmt.Errorf("Read error: %w", err)
285 header := http.Header{}
286 for k, v := range resp.Header {
287 if !dropHeaders[k] && k != "X-Request-Id" {
291 if ent.validate != nil {
292 if err := ent.validate(body); err != nil {
295 } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
296 if !json.Valid(body) {
297 return nil, nil, errors.New("invalid JSON encoding in response")
301 defer ent.mtx.Unlock()
304 ent.refreshAfter = time.Now().Add(cacheTTL)
305 ent.expireAfter = time.Now().Add(cacheExpire)
306 return ent.header, ent.body, nil
309 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
311 defer ent.mtx.Unlock()
312 if ent.expireAfter.Before(time.Now()) {
313 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
315 return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
318 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
319 header, body, needRefresh := ent.response()
321 // need to fetch before we can return anything
323 header, body, err = ent.refresh(path, do)
325 http.Error(w, err.Error(), http.StatusBadGateway)
328 } else if needRefresh {
329 // re-fetch in background
331 _, _, err := ent.refresh(path, do)
333 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
337 for k, v := range header {
340 w.WriteHeader(http.StatusOK)
344 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
345 if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
346 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
349 resp, err := h.localClusterRequest(req)
350 n, err := h.proxy.ForwardResponse(w, resp, err)
352 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
356 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
357 // present, otherwise choose an arbitrary entry.
358 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
360 for target := range cluster.Services.RailsAPI.InternalURLs {
361 target := url.URL(target)
363 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
368 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
370 return best, cluster.TLS.Insecure, nil
373 func validateDiscoveryDoc(body []byte) error {
374 var dd arvados.DiscoveryDocument
375 err := json.Unmarshal(body, &dd)
377 return fmt.Errorf("error decoding JSON response: %w", err)
379 if dd.BasePath == "" {
380 return errors.New("error in discovery document: no value for basePath")