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 ContainerWebServices: &h.Cluster.Services.ContainerWebServices,
124 MaxRequestSize: h.Cluster.API.MaxRequestSize,
125 WrapCalls: api.ComposeWrappers(
126 ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
127 oidcAuthorizer.WrapCalls,
128 ctrlctx.WrapCallsWithAuth(h.Cluster)),
131 healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
132 for name, f := range healthFuncs {
133 healthRoutes[name] = f
135 mux.Handle("/_health/", &health.Handler{
136 Token: h.Cluster.ManagementToken,
138 Routes: healthRoutes,
140 mux.Handle("/arvados/v1/config", h.router)
141 mux.Handle("/arvados/v1/vocabulary", h.router)
142 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, h.router) // must come before .../users/
143 mux.Handle("/arvados/v1/collections", h.router)
144 mux.Handle("/arvados/v1/collections/", h.router)
145 mux.Handle("/arvados/v1/users", h.router)
146 mux.Handle("/arvados/v1/users/", h.router)
147 mux.Handle("/arvados/v1/connect/", h.router)
148 mux.Handle("/arvados/v1/container_requests", h.router)
149 mux.Handle("/arvados/v1/container_requests/", h.router)
150 mux.Handle("/arvados/v1/groups", h.router)
151 mux.Handle("/arvados/v1/groups/", h.router)
152 mux.Handle("/arvados/v1/links", h.router)
153 mux.Handle("/arvados/v1/links/", h.router)
154 mux.Handle("/arvados/v1/authorized_keys", h.router)
155 mux.Handle("/arvados/v1/authorized_keys/", h.router)
156 mux.Handle("/login", h.router)
157 mux.Handle("/logout", h.router)
158 mux.Handle("/arvados/v1/api_client_authorizations", h.router)
159 mux.Handle("/arvados/v1/api_client_authorizations/", h.router)
161 hs := http.NotFoundHandler()
162 hs = prepend(hs, h.proxyRailsAPI)
163 hs = prepend(hs, h.routeContainerEndpoints(h.router))
164 hs = prepend(hs, h.routeServiceContainerPorts(h.router))
165 hs = h.setupProxyRemoteCluster(hs)
166 hs = prepend(hs, oidcAuthorizer.Middleware)
170 sc := *arvados.DefaultSecureClient
171 sc.CheckRedirect = neverRedirect
174 ic := *arvados.InsecureHTTPClient
175 ic.CheckRedirect = neverRedirect
176 h.insecureClient = &ic
179 Name: "arvados-controller",
181 h.cache = map[string]*cacheEnt{
182 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
185 go h.trashSweepWorker()
186 go h.containerLogSweepWorker()
189 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
191 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
192 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
193 middleware(w, req, next)
197 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
198 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
203 Scheme: urlOut.Scheme,
206 RawPath: req.URL.RawPath,
207 RawQuery: req.URL.RawQuery,
209 client := h.secureClient
211 client = h.insecureClient
213 // Clearing the Host field here causes the Go http client to
214 // use the host part of urlOut as the Host header in the
215 // outgoing request, instead of the Host value from the
216 // original request we received.
218 return h.proxy.Do(req, urlOut, client)
221 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
222 // .../gateway_tunnel to rtr, pass everything else to next.
224 // (http.ServeMux doesn't let us route these without also routing
225 // everything under /containers/, which we don't want yet.)
226 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
227 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
228 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
229 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
230 strings.Index(trim, "/ssh") == 27 ||
231 strings.Index(trim, "/gateway_tunnel") == 27) {
232 rtr.ServeHTTP(w, req)
234 next.ServeHTTP(w, req)
239 // Route ContainerWebServices requests through rtr, pass through
241 func (h *Handler) routeServiceContainerPorts(rtr http.Handler) middlewareFunc {
242 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
243 if router.ContainerHTTPProxyTarget(&h.Cluster.Services.ContainerWebServices, req) != "" {
244 rtr.ServeHTTP(w, req)
246 next.ServeHTTP(w, req)
251 // cacheEnt implements a basic stale-while-revalidate cache, suitable
252 // for the Arvados discovery document.
253 type cacheEnt struct {
254 validate func(body []byte) error
258 expireAfter time.Time
259 refreshAfter time.Time
260 refreshLock sync.Mutex
264 cacheTTL = 5 * time.Minute
265 cacheExpire = 24 * time.Hour
268 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
269 ent.refreshLock.Lock()
270 defer ent.refreshLock.Unlock()
271 if header, body, needRefresh := ent.response(); !needRefresh {
272 // another goroutine refreshed successfully while we
273 // were waiting for refreshLock
274 return header, body, nil
275 } else if body != nil {
276 // Cache is present, but expired. We'll try to refresh
277 // below. Meanwhile, other refresh() calls will queue
278 // up for refreshLock -- and we don't want them to
279 // turn into N upstream requests, even if upstream is
280 // failing. (If we succeed we'll update the expiry
281 // time again below with the real cacheTTL -- this
282 // just takes care of the error case.)
284 ent.refreshAfter = time.Now().Add(time.Second)
288 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
290 // "http://localhost" is just a placeholder here -- we'll fill
291 // in req.URL.Path below, and then do(), which is
292 // localClusterRequest(), will replace the scheme and host
293 // parts with the real proxy destination.
294 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
303 if resp.StatusCode != http.StatusOK {
304 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
306 body, err := ioutil.ReadAll(resp.Body)
308 return nil, nil, fmt.Errorf("Read error: %w", err)
310 header := http.Header{}
311 for k, v := range resp.Header {
312 if !dropHeaders[k] && k != "X-Request-Id" {
316 if ent.validate != nil {
317 if err := ent.validate(body); err != nil {
320 } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
321 if !json.Valid(body) {
322 return nil, nil, errors.New("invalid JSON encoding in response")
326 defer ent.mtx.Unlock()
329 ent.refreshAfter = time.Now().Add(cacheTTL)
330 ent.expireAfter = time.Now().Add(cacheExpire)
331 return ent.header, ent.body, nil
334 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
336 defer ent.mtx.Unlock()
337 if ent.expireAfter.Before(time.Now()) {
338 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
340 return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
343 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
344 header, body, needRefresh := ent.response()
346 // need to fetch before we can return anything
348 header, body, err = ent.refresh(path, do)
350 http.Error(w, err.Error(), http.StatusBadGateway)
353 } else if needRefresh {
354 // re-fetch in background
356 _, _, err := ent.refresh(path, do)
358 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
362 for k, v := range header {
365 w.WriteHeader(http.StatusOK)
369 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
370 if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
371 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
374 resp, err := h.localClusterRequest(req)
375 n, err := h.proxy.ForwardResponse(w, resp, err)
377 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
381 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
382 // present, otherwise choose an arbitrary entry.
383 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
385 for target := range cluster.Services.RailsAPI.InternalURLs {
386 target := url.URL(target)
388 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
393 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
395 return best, cluster.TLS.Insecure, nil
398 func validateDiscoveryDoc(body []byte) error {
399 var dd arvados.DiscoveryDocument
400 err := json.Unmarshal(body, &dd)
402 return fmt.Errorf("error decoding JSON response: %w", err)
404 if dd.BasePath == "" {
405 return errors.New("error in discovery document: no value for basePath")