1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.arvados.org/arvados.git/lib/controller/api"
18 "git.arvados.org/arvados.git/lib/controller/federation"
19 "git.arvados.org/arvados.git/lib/controller/localdb"
20 "git.arvados.org/arvados.git/lib/controller/railsproxy"
21 "git.arvados.org/arvados.git/lib/controller/router"
22 "git.arvados.org/arvados.git/lib/ctrlctx"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "git.arvados.org/arvados.git/sdk/go/health"
26 "git.arvados.org/arvados.git/sdk/go/httpserver"
27 "github.com/jmoiron/sqlx"
28 // sqlx needs lib/pq to talk to PostgreSQL
33 Cluster *arvados.Cluster
36 handlerStack http.Handler
38 secureClient *http.Client
39 insecureClient *http.Client
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 if h.Cluster.API.RequestTimeout > 0 {
61 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
62 req = req.WithContext(ctx)
66 h.handlerStack.ServeHTTP(w, req)
69 func (h *Handler) CheckHealth() error {
70 h.setupOnce.Do(h.setup)
71 _, err := h.db(context.TODO())
75 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
79 func (h *Handler) Done() <-chan struct{} {
83 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
85 func (h *Handler) setup() {
86 mux := http.NewServeMux()
87 mux.Handle("/_health/", &health.Handler{
88 Token: h.Cluster.ManagementToken,
90 Routes: health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }},
93 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
94 rtr := router.New(federation.New(h.Cluster), api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls))
95 mux.Handle("/arvados/v1/config", rtr)
96 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
98 if !h.Cluster.ForceLegacyAPI14 {
99 mux.Handle("/arvados/v1/collections", rtr)
100 mux.Handle("/arvados/v1/collections/", rtr)
101 mux.Handle("/arvados/v1/users", rtr)
102 mux.Handle("/arvados/v1/users/", rtr)
103 mux.Handle("/arvados/v1/container_requests", rtr)
104 mux.Handle("/arvados/v1/container_requests/", rtr)
105 mux.Handle("/login", rtr)
106 mux.Handle("/logout", rtr)
109 hs := http.NotFoundHandler()
110 hs = prepend(hs, h.proxyRailsAPI)
111 hs = h.setupProxyRemoteCluster(hs)
112 hs = prepend(hs, oidcAuthorizer.Middleware)
116 sc := *arvados.DefaultSecureClient
117 sc.CheckRedirect = neverRedirect
120 ic := *arvados.InsecureHTTPClient
121 ic.CheckRedirect = neverRedirect
122 h.insecureClient = &ic
125 Name: "arvados-controller",
129 var errDBConnection = errors.New("database connection error")
131 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
133 defer h.pgdbMtx.Unlock()
138 db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
140 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
141 return nil, errDBConnection
143 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
144 db.SetMaxOpenConns(p)
146 if err := db.Ping(); err != nil {
147 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
148 return nil, errDBConnection
154 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
156 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
157 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
158 middleware(w, req, next)
162 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
163 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
168 Scheme: urlOut.Scheme,
171 RawPath: req.URL.RawPath,
172 RawQuery: req.URL.RawQuery,
174 client := h.secureClient
176 client = h.insecureClient
178 return h.proxy.Do(req, urlOut, client)
181 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
182 resp, err := h.localClusterRequest(req)
183 n, err := h.proxy.ForwardResponse(w, resp, err)
185 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
189 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
190 // present, otherwise choose an arbitrary entry.
191 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
193 for target := range cluster.Services.RailsAPI.InternalURLs {
194 target := url.URL(target)
196 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
201 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
203 return best, cluster.TLS.Insecure, nil