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)
140 hs := http.NotFoundHandler()
141 hs = prepend(hs, h.proxyRailsAPI)
142 hs = h.setupProxyRemoteCluster(hs)
143 hs = prepend(hs, oidcAuthorizer.Middleware)
147 sc := *arvados.DefaultSecureClient
148 sc.CheckRedirect = neverRedirect
151 ic := *arvados.InsecureHTTPClient
152 ic.CheckRedirect = neverRedirect
153 h.insecureClient = &ic
156 Name: "arvados-controller",
159 go h.trashSweepWorker()
162 var errDBConnection = errors.New("database connection error")
164 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
166 defer h.pgdbMtx.Unlock()
171 db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
173 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
174 return nil, errDBConnection
176 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
177 db.SetMaxOpenConns(p)
179 if err := db.Ping(); err != nil {
180 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
181 return nil, errDBConnection
187 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
189 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
190 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
191 middleware(w, req, next)
195 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
196 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
201 Scheme: urlOut.Scheme,
204 RawPath: req.URL.RawPath,
205 RawQuery: req.URL.RawQuery,
207 client := h.secureClient
209 client = h.insecureClient
211 return h.proxy.Do(req, urlOut, client)
214 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
215 resp, err := h.localClusterRequest(req)
216 n, err := h.proxy.ForwardResponse(w, resp, err)
218 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
222 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
223 // present, otherwise choose an arbitrary entry.
224 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
226 for target := range cluster.Services.RailsAPI.InternalURLs {
227 target := url.URL(target)
229 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
234 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
236 return best, cluster.TLS.Insecure, nil