1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.arvados.org/arvados.git/lib/controller/api"
19 "git.arvados.org/arvados.git/lib/controller/federation"
20 "git.arvados.org/arvados.git/lib/controller/localdb"
21 "git.arvados.org/arvados.git/lib/controller/railsproxy"
22 "git.arvados.org/arvados.git/lib/controller/router"
23 "git.arvados.org/arvados.git/lib/ctrlctx"
24 "git.arvados.org/arvados.git/sdk/go/arvados"
25 "git.arvados.org/arvados.git/sdk/go/ctxlog"
26 "git.arvados.org/arvados.git/sdk/go/health"
27 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 "github.com/jmoiron/sqlx"
30 // sqlx needs lib/pq to talk to PostgreSQL
35 Cluster *arvados.Cluster
36 BackgroundContext context.Context
39 federation *federation.Conn
40 handlerStack http.Handler
42 secureClient *http.Client
43 insecureClient *http.Client
48 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
49 h.setupOnce.Do(h.setup)
50 if req.Method != "GET" && req.Method != "HEAD" {
51 // http.ServeMux returns 301 with a cleaned path if
52 // the incoming request has a double slash. Some
53 // clients (including the Go standard library) change
54 // the request method to GET when following a 301
55 // redirect if the original method was not HEAD
56 // (RFC7231 6.4.2 specifically allows this in the case
57 // of POST). Thus "POST //foo" gets misdirected to
58 // "GET /foo". To avoid this, eliminate double slashes
59 // before passing the request to ServeMux.
60 for strings.Contains(req.URL.Path, "//") {
61 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
64 if h.Cluster.API.RequestTimeout > 0 {
65 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
66 req = req.WithContext(ctx)
70 h.handlerStack.ServeHTTP(w, req)
73 func (h *Handler) CheckHealth() error {
74 h.setupOnce.Do(h.setup)
75 _, err := h.db(context.TODO())
79 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
83 if h.Cluster.API.VocabularyPath != "" {
84 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
88 var resp httptest.ResponseRecorder
89 h.handlerStack.ServeHTTP(&resp, req)
90 if resp.Result().StatusCode != http.StatusOK {
91 return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
97 func (h *Handler) Done() <-chan struct{} {
101 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
103 func (h *Handler) setup() {
104 mux := http.NewServeMux()
105 healthFuncs := make(map[string]health.Func)
107 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
108 h.federation = federation.New(h.Cluster, &healthFuncs)
109 rtr := router.New(h.federation, router.Config{
110 MaxRequestSize: h.Cluster.API.MaxRequestSize,
111 WrapCalls: api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls),
114 healthRoutes := health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }}
115 for name, f := range healthFuncs {
116 healthRoutes[name] = f
118 mux.Handle("/_health/", &health.Handler{
119 Token: h.Cluster.ManagementToken,
121 Routes: healthRoutes,
123 mux.Handle("/arvados/v1/config", rtr)
124 mux.Handle("/arvados/v1/vocabulary", rtr)
125 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
126 mux.Handle("/arvados/v1/collections", rtr)
127 mux.Handle("/arvados/v1/collections/", rtr)
128 mux.Handle("/arvados/v1/users", rtr)
129 mux.Handle("/arvados/v1/users/", rtr)
130 mux.Handle("/arvados/v1/connect/", rtr)
131 mux.Handle("/arvados/v1/container_requests", rtr)
132 mux.Handle("/arvados/v1/container_requests/", rtr)
133 mux.Handle("/arvados/v1/groups", rtr)
134 mux.Handle("/arvados/v1/groups/", rtr)
135 mux.Handle("/arvados/v1/links", rtr)
136 mux.Handle("/arvados/v1/links/", rtr)
137 mux.Handle("/login", rtr)
138 mux.Handle("/logout", rtr)
139 mux.Handle("/arvados/v1/api_client_authorizations", rtr)
140 mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
142 hs := http.NotFoundHandler()
143 hs = prepend(hs, h.proxyRailsAPI)
144 hs = h.setupProxyRemoteCluster(hs)
145 hs = prepend(hs, oidcAuthorizer.Middleware)
149 sc := *arvados.DefaultSecureClient
150 sc.CheckRedirect = neverRedirect
153 ic := *arvados.InsecureHTTPClient
154 ic.CheckRedirect = neverRedirect
155 h.insecureClient = &ic
158 Name: "arvados-controller",
161 go h.trashSweepWorker()
164 var errDBConnection = errors.New("database connection error")
166 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
168 defer h.pgdbMtx.Unlock()
173 db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
175 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
176 return nil, errDBConnection
178 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
179 db.SetMaxOpenConns(p)
181 if err := db.Ping(); err != nil {
182 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
183 return nil, errDBConnection
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 return h.proxy.Do(req, urlOut, client)
216 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
217 resp, err := h.localClusterRequest(req)
218 n, err := h.proxy.ForwardResponse(w, resp, err)
220 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
224 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
225 // present, otherwise choose an arbitrary entry.
226 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
228 for target := range cluster.Services.RailsAPI.InternalURLs {
229 target := url.URL(target)
231 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
236 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
238 return best, cluster.TLS.Insecure, nil