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
47 limitLogCreate chan struct{}
49 cache map[string]*cacheEnt
52 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
53 h.setupOnce.Do(h.setup)
54 if req.Method != "GET" && req.Method != "HEAD" {
55 // http.ServeMux returns 301 with a cleaned path if
56 // the incoming request has a double slash. Some
57 // clients (including the Go standard library) change
58 // the request method to GET when following a 301
59 // redirect if the original method was not HEAD
60 // (RFC7231 6.4.2 specifically allows this in the case
61 // of POST). Thus "POST //foo" gets misdirected to
62 // "GET /foo". To avoid this, eliminate double slashes
63 // before passing the request to ServeMux.
64 for strings.Contains(req.URL.Path, "//") {
65 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
68 h.handlerStack.ServeHTTP(w, req)
71 func (h *Handler) CheckHealth() error {
72 h.setupOnce.Do(h.setup)
73 _, err := h.dbConnector.GetDB(context.TODO())
77 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
81 if h.Cluster.API.VocabularyPath != "" {
82 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
86 var resp httptest.ResponseRecorder
87 h.handlerStack.ServeHTTP(&resp, req)
88 if resp.Result().StatusCode != http.StatusOK {
89 return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
95 func (h *Handler) Done() <-chan struct{} {
99 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
101 func (h *Handler) setup() {
102 mux := http.NewServeMux()
103 healthFuncs := make(map[string]health.Func)
105 h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
107 <-h.BackgroundContext.Done()
108 h.dbConnector.Close()
110 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
111 h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
112 rtr := router.New(h.federation, router.Config{
113 MaxRequestSize: h.Cluster.API.MaxRequestSize,
114 WrapCalls: api.ComposeWrappers(
115 ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
116 oidcAuthorizer.WrapCalls,
117 ctrlctx.WrapCallsWithAuth(h.Cluster)),
120 healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
121 for name, f := range healthFuncs {
122 healthRoutes[name] = f
124 mux.Handle("/_health/", &health.Handler{
125 Token: h.Cluster.ManagementToken,
127 Routes: healthRoutes,
129 mux.Handle("/arvados/v1/config", rtr)
130 mux.Handle("/arvados/v1/vocabulary", rtr)
131 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
132 mux.Handle("/arvados/v1/collections", rtr)
133 mux.Handle("/arvados/v1/collections/", rtr)
134 mux.Handle("/arvados/v1/users", rtr)
135 mux.Handle("/arvados/v1/users/", rtr)
136 mux.Handle("/arvados/v1/connect/", rtr)
137 mux.Handle("/arvados/v1/container_requests", rtr)
138 mux.Handle("/arvados/v1/container_requests/", rtr)
139 mux.Handle("/arvados/v1/groups", rtr)
140 mux.Handle("/arvados/v1/groups/", rtr)
141 mux.Handle("/arvados/v1/links", rtr)
142 mux.Handle("/arvados/v1/links/", rtr)
143 mux.Handle("/arvados/v1/authorized_keys", rtr)
144 mux.Handle("/arvados/v1/authorized_keys/", rtr)
145 mux.Handle("/login", rtr)
146 mux.Handle("/logout", rtr)
147 mux.Handle("/arvados/v1/api_client_authorizations", rtr)
148 mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
150 hs := http.NotFoundHandler()
151 hs = prepend(hs, h.proxyRailsAPI)
152 hs = prepend(hs, h.routeContainerEndpoints(rtr))
153 hs = prepend(hs, h.limitLogCreateRequests)
154 hs = h.setupProxyRemoteCluster(hs)
155 hs = prepend(hs, oidcAuthorizer.Middleware)
159 sc := *arvados.DefaultSecureClient
160 sc.CheckRedirect = neverRedirect
163 ic := *arvados.InsecureHTTPClient
164 ic.CheckRedirect = neverRedirect
165 h.insecureClient = &ic
167 logCreateLimit := int(float64(h.Cluster.API.MaxConcurrentRequests) * h.Cluster.API.LogCreateRequestFraction)
168 if logCreateLimit == 0 && h.Cluster.API.LogCreateRequestFraction > 0 {
171 h.limitLogCreate = make(chan struct{}, logCreateLimit)
174 Name: "arvados-controller",
176 h.cache = map[string]*cacheEnt{
177 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
180 go h.trashSweepWorker()
181 go h.containerLogSweepWorker()
184 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
186 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
187 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
188 middleware(w, req, next)
192 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
193 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
198 Scheme: urlOut.Scheme,
201 RawPath: req.URL.RawPath,
202 RawQuery: req.URL.RawQuery,
204 client := h.secureClient
206 client = h.insecureClient
208 // Clearing the Host field here causes the Go http client to
209 // use the host part of urlOut as the Host header in the
210 // outgoing request, instead of the Host value from the
211 // original request we received.
213 return h.proxy.Do(req, urlOut, client)
216 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
217 // .../gateway_tunnel to rtr, pass everything else to next.
219 // (http.ServeMux doesn't let us route these without also routing
220 // everything under /containers/, which we don't want yet.)
221 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
222 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
223 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
224 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
225 strings.Index(trim, "/ssh") == 27 ||
226 strings.Index(trim, "/gateway_tunnel") == 27) {
227 rtr.ServeHTTP(w, req)
229 next.ServeHTTP(w, req)
234 func (h *Handler) limitLogCreateRequests(w http.ResponseWriter, req *http.Request, next http.Handler) {
235 if cap(h.limitLogCreate) > 0 && req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs") {
237 case h.limitLogCreate <- struct{}{}:
238 defer func() { <-h.limitLogCreate }()
239 next.ServeHTTP(w, req)
241 http.Error(w, "Excess log messages", http.StatusServiceUnavailable)
245 next.ServeHTTP(w, req)
248 // cacheEnt implements a basic stale-while-revalidate cache, suitable
249 // for the Arvados discovery document.
250 type cacheEnt struct {
251 validate func(body []byte) error
255 expireAfter time.Time
256 refreshAfter time.Time
257 refreshLock sync.Mutex
261 cacheTTL = 5 * time.Minute
262 cacheExpire = 24 * time.Hour
265 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
266 ent.refreshLock.Lock()
267 defer ent.refreshLock.Unlock()
268 if header, body, needRefresh := ent.response(); !needRefresh {
269 // another goroutine refreshed successfully while we
270 // were waiting for refreshLock
271 return header, body, nil
272 } else if body != nil {
273 // Cache is present, but expired. We'll try to refresh
274 // below. Meanwhile, other refresh() calls will queue
275 // up for refreshLock -- and we don't want them to
276 // turn into N upstream requests, even if upstream is
277 // failing. (If we succeed we'll update the expiry
278 // time again below with the real cacheTTL -- this
279 // just takes care of the error case.)
281 ent.refreshAfter = time.Now().Add(time.Second)
285 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
287 // "http://localhost" is just a placeholder here -- we'll fill
288 // in req.URL.Path below, and then do(), which is
289 // localClusterRequest(), will replace the scheme and host
290 // parts with the real proxy destination.
291 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
300 if resp.StatusCode != http.StatusOK {
301 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
303 body, err := ioutil.ReadAll(resp.Body)
305 return nil, nil, fmt.Errorf("Read error: %w", err)
307 header := http.Header{}
308 for k, v := range resp.Header {
309 if !dropHeaders[k] && k != "X-Request-Id" {
313 if ent.validate != nil {
314 if err := ent.validate(body); err != nil {
317 } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
318 if !json.Valid(body) {
319 return nil, nil, errors.New("invalid JSON encoding in response")
323 defer ent.mtx.Unlock()
326 ent.refreshAfter = time.Now().Add(cacheTTL)
327 ent.expireAfter = time.Now().Add(cacheExpire)
328 return ent.header, ent.body, nil
331 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
333 defer ent.mtx.Unlock()
334 if ent.expireAfter.Before(time.Now()) {
335 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
337 return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
340 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
341 header, body, needRefresh := ent.response()
343 // need to fetch before we can return anything
345 header, body, err = ent.refresh(path, do)
347 http.Error(w, err.Error(), http.StatusBadGateway)
350 } else if needRefresh {
351 // re-fetch in background
353 _, _, err := ent.refresh(path, do)
355 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
359 for k, v := range header {
362 w.WriteHeader(http.StatusOK)
366 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
367 if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
368 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
371 resp, err := h.localClusterRequest(req)
372 n, err := h.proxy.ForwardResponse(w, resp, err)
374 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
378 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
379 // present, otherwise choose an arbitrary entry.
380 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
382 for target := range cluster.Services.RailsAPI.InternalURLs {
383 target := url.URL(target)
385 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
390 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
392 return best, cluster.TLS.Insecure, nil
395 func validateDiscoveryDoc(body []byte) error {
396 var dd arvados.DiscoveryDocument
397 err := json.Unmarshal(body, &dd)
399 return fmt.Errorf("error decoding JSON response: %w", err)
401 if dd.BasePath == "" {
402 return errors.New("error in discovery document: no value for basePath")