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 ContainerWebServicesURL: h.Cluster.Services.ContainerWebServices.ExternalURL,
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 = h.setupProxyRemoteCluster(hs)
165 hs = prepend(hs, oidcAuthorizer.Middleware)
169 sc := *arvados.DefaultSecureClient
170 sc.CheckRedirect = neverRedirect
173 ic := *arvados.InsecureHTTPClient
174 ic.CheckRedirect = neverRedirect
175 h.insecureClient = &ic
178 Name: "arvados-controller",
180 h.cache = map[string]*cacheEnt{
181 "/discovery/v1/apis/arvados/v1/rest": &cacheEnt{validate: validateDiscoveryDoc},
184 go h.trashSweepWorker()
185 go h.containerLogSweepWorker()
188 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
190 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
191 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
192 middleware(w, req, next)
196 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
197 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
202 Scheme: urlOut.Scheme,
205 RawPath: req.URL.RawPath,
206 RawQuery: req.URL.RawQuery,
208 client := h.secureClient
210 client = h.insecureClient
212 // Clearing the Host field here causes the Go http client to
213 // use the host part of urlOut as the Host header in the
214 // outgoing request, instead of the Host value from the
215 // original request we received.
217 return h.proxy.Do(req, urlOut, client)
220 // Route /arvados/v1/containers/{uuid}/log*, .../ssh, and
221 // .../gateway_tunnel to rtr, pass everything else to next.
223 // (http.ServeMux doesn't let us route these without also routing
224 // everything under /containers/, which we don't want yet.)
225 func (h *Handler) routeContainerEndpoints(rtr http.Handler) middlewareFunc {
226 return func(w http.ResponseWriter, req *http.Request, next http.Handler) {
227 trim := strings.TrimPrefix(req.URL.Path, "/arvados/v1/containers/")
228 if trim != req.URL.Path && (strings.Index(trim, "/log") == 27 ||
229 strings.Index(trim, "/ssh") == 27 ||
230 strings.Index(trim, "/gateway_tunnel") == 27) {
231 rtr.ServeHTTP(w, req)
233 next.ServeHTTP(w, req)
238 // cacheEnt implements a basic stale-while-revalidate cache, suitable
239 // for the Arvados discovery document.
240 type cacheEnt struct {
241 validate func(body []byte) error
245 expireAfter time.Time
246 refreshAfter time.Time
247 refreshLock sync.Mutex
251 cacheTTL = 5 * time.Minute
252 cacheExpire = 24 * time.Hour
255 func (ent *cacheEnt) refresh(path string, do func(*http.Request) (*http.Response, error)) (http.Header, []byte, error) {
256 ent.refreshLock.Lock()
257 defer ent.refreshLock.Unlock()
258 if header, body, needRefresh := ent.response(); !needRefresh {
259 // another goroutine refreshed successfully while we
260 // were waiting for refreshLock
261 return header, body, nil
262 } else if body != nil {
263 // Cache is present, but expired. We'll try to refresh
264 // below. Meanwhile, other refresh() calls will queue
265 // up for refreshLock -- and we don't want them to
266 // turn into N upstream requests, even if upstream is
267 // failing. (If we succeed we'll update the expiry
268 // time again below with the real cacheTTL -- this
269 // just takes care of the error case.)
271 ent.refreshAfter = time.Now().Add(time.Second)
275 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute))
277 // "http://localhost" is just a placeholder here -- we'll fill
278 // in req.URL.Path below, and then do(), which is
279 // localClusterRequest(), will replace the scheme and host
280 // parts with the real proxy destination.
281 req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost", nil)
290 if resp.StatusCode != http.StatusOK {
291 return nil, nil, fmt.Errorf("HTTP status %d", resp.StatusCode)
293 body, err := ioutil.ReadAll(resp.Body)
295 return nil, nil, fmt.Errorf("Read error: %w", err)
297 header := http.Header{}
298 for k, v := range resp.Header {
299 if !dropHeaders[k] && k != "X-Request-Id" {
303 if ent.validate != nil {
304 if err := ent.validate(body); err != nil {
307 } else if mediatype, _, err := mime.ParseMediaType(header.Get("Content-Type")); err == nil && mediatype == "application/json" {
308 if !json.Valid(body) {
309 return nil, nil, errors.New("invalid JSON encoding in response")
313 defer ent.mtx.Unlock()
316 ent.refreshAfter = time.Now().Add(cacheTTL)
317 ent.expireAfter = time.Now().Add(cacheExpire)
318 return ent.header, ent.body, nil
321 func (ent *cacheEnt) response() (http.Header, []byte, bool) {
323 defer ent.mtx.Unlock()
324 if ent.expireAfter.Before(time.Now()) {
325 ent.header, ent.body, ent.refreshAfter = nil, nil, time.Time{}
327 return ent.header, ent.body, ent.refreshAfter.Before(time.Now())
330 func (ent *cacheEnt) ServeHTTP(ctx context.Context, w http.ResponseWriter, path string, do func(*http.Request) (*http.Response, error)) {
331 header, body, needRefresh := ent.response()
333 // need to fetch before we can return anything
335 header, body, err = ent.refresh(path, do)
337 http.Error(w, err.Error(), http.StatusBadGateway)
340 } else if needRefresh {
341 // re-fetch in background
343 _, _, err := ent.refresh(path, do)
345 ctxlog.FromContext(ctx).WithError(err).WithField("path", path).Warn("error refreshing cache")
349 for k, v := range header {
352 w.WriteHeader(http.StatusOK)
356 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
357 if ent, ok := h.cache[req.URL.Path]; ok && req.Method == http.MethodGet {
358 ent.ServeHTTP(req.Context(), w, req.URL.Path, h.localClusterRequest)
361 resp, err := h.localClusterRequest(req)
362 n, err := h.proxy.ForwardResponse(w, resp, err)
364 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
368 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
369 // present, otherwise choose an arbitrary entry.
370 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
372 for target := range cluster.Services.RailsAPI.InternalURLs {
373 target := url.URL(target)
375 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
380 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
382 return best, cluster.TLS.Insecure, nil
385 func validateDiscoveryDoc(body []byte) error {
386 var dd arvados.DiscoveryDocument
387 err := json.Unmarshal(body, &dd)
389 return fmt.Errorf("error decoding JSON response: %w", err)
391 if dd.BasePath == "" {
392 return errors.New("error in discovery document: no value for basePath")