1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.arvados.org/arvados.git/lib/controller/api"
17 "git.arvados.org/arvados.git/lib/controller/federation"
18 "git.arvados.org/arvados.git/lib/controller/localdb"
19 "git.arvados.org/arvados.git/lib/controller/railsproxy"
20 "git.arvados.org/arvados.git/lib/controller/router"
21 "git.arvados.org/arvados.git/lib/ctrlctx"
22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "git.arvados.org/arvados.git/sdk/go/health"
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
26 // sqlx needs lib/pq to talk to PostgreSQL
31 Cluster *arvados.Cluster
32 BackgroundContext context.Context
35 federation *federation.Conn
36 handlerStack http.Handler
38 secureClient *http.Client
39 insecureClient *http.Client
40 dbConnector ctrlctx.DBConnector
41 limitLogCreate chan struct{}
44 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
45 h.setupOnce.Do(h.setup)
46 if req.Method != "GET" && req.Method != "HEAD" {
47 // http.ServeMux returns 301 with a cleaned path if
48 // the incoming request has a double slash. Some
49 // clients (including the Go standard library) change
50 // the request method to GET when following a 301
51 // redirect if the original method was not HEAD
52 // (RFC7231 6.4.2 specifically allows this in the case
53 // of POST). Thus "POST //foo" gets misdirected to
54 // "GET /foo". To avoid this, eliminate double slashes
55 // before passing the request to ServeMux.
56 for strings.Contains(req.URL.Path, "//") {
57 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
60 h.handlerStack.ServeHTTP(w, req)
63 func (h *Handler) CheckHealth() error {
64 h.setupOnce.Do(h.setup)
65 _, err := h.dbConnector.GetDB(context.TODO())
69 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
73 if h.Cluster.API.VocabularyPath != "" {
74 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
78 var resp httptest.ResponseRecorder
79 h.handlerStack.ServeHTTP(&resp, req)
80 if resp.Result().StatusCode != http.StatusOK {
81 return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
87 func (h *Handler) Done() <-chan struct{} {
91 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
93 func (h *Handler) setup() {
94 mux := http.NewServeMux()
95 healthFuncs := make(map[string]health.Func)
97 h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
99 <-h.BackgroundContext.Done()
100 h.dbConnector.Close()
102 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
103 h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
104 rtr := router.New(h.federation, router.Config{
105 MaxRequestSize: h.Cluster.API.MaxRequestSize,
106 WrapCalls: api.ComposeWrappers(
107 ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
108 oidcAuthorizer.WrapCalls,
109 ctrlctx.WrapCallsWithAuth(h.Cluster)),
112 healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
113 for name, f := range healthFuncs {
114 healthRoutes[name] = f
116 mux.Handle("/_health/", &health.Handler{
117 Token: h.Cluster.ManagementToken,
119 Routes: healthRoutes,
121 mux.Handle("/arvados/v1/config", rtr)
122 mux.Handle("/arvados/v1/vocabulary", rtr)
123 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
124 mux.Handle("/arvados/v1/collections", rtr)
125 mux.Handle("/arvados/v1/collections/", rtr)
126 mux.Handle("/arvados/v1/users", rtr)
127 mux.Handle("/arvados/v1/users/", rtr)
128 mux.Handle("/arvados/v1/connect/", rtr)
129 mux.Handle("/arvados/v1/container_requests", rtr)
130 mux.Handle("/arvados/v1/container_requests/", rtr)
131 mux.Handle("/arvados/v1/groups", rtr)
132 mux.Handle("/arvados/v1/groups/", rtr)
133 mux.Handle("/arvados/v1/links", rtr)
134 mux.Handle("/arvados/v1/links/", rtr)
135 mux.Handle("/login", rtr)
136 mux.Handle("/logout", rtr)
137 mux.Handle("/arvados/v1/api_client_authorizations", rtr)
138 mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
140 hs := http.NotFoundHandler()
141 hs = prepend(hs, h.proxyRailsAPI)
142 hs = prepend(hs, h.limitLogCreateRequests)
143 hs = h.setupProxyRemoteCluster(hs)
144 hs = prepend(hs, oidcAuthorizer.Middleware)
148 sc := *arvados.DefaultSecureClient
149 sc.CheckRedirect = neverRedirect
152 ic := *arvados.InsecureHTTPClient
153 ic.CheckRedirect = neverRedirect
154 h.insecureClient = &ic
156 logCreateLimit := int(float64(h.Cluster.API.MaxConcurrentRequests) * h.Cluster.API.LogCreateRequestFraction)
157 if logCreateLimit == 0 && h.Cluster.API.LogCreateRequestFraction > 0 {
160 h.limitLogCreate = make(chan struct{}, logCreateLimit)
163 Name: "arvados-controller",
166 go h.trashSweepWorker()
167 go h.containerLogSweepWorker()
170 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
172 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
173 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
174 middleware(w, req, next)
178 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
179 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
184 Scheme: urlOut.Scheme,
187 RawPath: req.URL.RawPath,
188 RawQuery: req.URL.RawQuery,
190 client := h.secureClient
192 client = h.insecureClient
194 return h.proxy.Do(req, urlOut, client)
197 func (h *Handler) limitLogCreateRequests(w http.ResponseWriter, req *http.Request, next http.Handler) {
198 if cap(h.limitLogCreate) > 0 && req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs") {
200 case h.limitLogCreate <- struct{}{}:
201 defer func() { <-h.limitLogCreate }()
202 next.ServeHTTP(w, req)
204 http.Error(w, "Excess log messages", http.StatusServiceUnavailable)
208 next.ServeHTTP(w, req)
211 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
212 resp, err := h.localClusterRequest(req)
213 n, err := h.proxy.ForwardResponse(w, resp, err)
215 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
219 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
220 // present, otherwise choose an arbitrary entry.
221 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
223 for target := range cluster.Services.RailsAPI.InternalURLs {
224 target := url.URL(target)
226 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
231 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
233 return best, cluster.TLS.Insecure, nil