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"
29 // sqlx needs lib/pq to talk to PostgreSQL
34 Cluster *arvados.Cluster
37 handlerStack http.Handler
39 secureClient *http.Client
40 insecureClient *http.Client
45 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
46 h.setupOnce.Do(h.setup)
47 if req.Method != "GET" && req.Method != "HEAD" {
48 // http.ServeMux returns 301 with a cleaned path if
49 // the incoming request has a double slash. Some
50 // clients (including the Go standard library) change
51 // the request method to GET when following a 301
52 // redirect if the original method was not HEAD
53 // (RFC7231 6.4.2 specifically allows this in the case
54 // of POST). Thus "POST //foo" gets misdirected to
55 // "GET /foo". To avoid this, eliminate double slashes
56 // before passing the request to ServeMux.
57 for strings.Contains(req.URL.Path, "//") {
58 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
61 if h.Cluster.API.RequestTimeout > 0 {
62 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
63 req = req.WithContext(ctx)
67 h.handlerStack.ServeHTTP(w, req)
70 func (h *Handler) CheckHealth() error {
71 h.setupOnce.Do(h.setup)
72 _, err := h.db(context.TODO())
76 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
80 func (h *Handler) Done() <-chan struct{} {
84 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
86 func (h *Handler) setup() {
87 mux := http.NewServeMux()
88 mux.Handle("/_health/", &health.Handler{
89 Token: h.Cluster.ManagementToken,
91 Routes: health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }},
94 oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
95 rtr := router.New(federation.New(h.Cluster), api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls))
96 mux.Handle("/arvados/v1/config", rtr)
97 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
99 if !h.Cluster.ForceLegacyAPI14 {
100 mux.Handle("/arvados/v1/collections", rtr)
101 mux.Handle("/arvados/v1/collections/", rtr)
102 mux.Handle("/arvados/v1/users", rtr)
103 mux.Handle("/arvados/v1/users/", rtr)
104 mux.Handle("/arvados/v1/connect/", rtr)
105 mux.Handle("/arvados/v1/container_requests", rtr)
106 mux.Handle("/arvados/v1/container_requests/", rtr)
107 mux.Handle("/login", rtr)
108 mux.Handle("/logout", rtr)
111 hs := http.NotFoundHandler()
112 hs = prepend(hs, h.proxyRailsAPI)
113 hs = h.setupProxyRemoteCluster(hs)
114 hs = prepend(hs, oidcAuthorizer.Middleware)
118 sc := *arvados.DefaultSecureClient
119 sc.CheckRedirect = neverRedirect
122 ic := *arvados.InsecureHTTPClient
123 ic.CheckRedirect = neverRedirect
124 h.insecureClient = &ic
127 Name: "arvados-controller",
131 var errDBConnection = errors.New("database connection error")
133 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
135 defer h.pgdbMtx.Unlock()
140 db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
142 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
143 return nil, errDBConnection
145 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
146 db.SetMaxOpenConns(p)
148 if err := db.Ping(); err != nil {
149 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
150 return nil, errDBConnection
156 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
158 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
159 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
160 middleware(w, req, next)
164 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
165 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
170 Scheme: urlOut.Scheme,
173 RawPath: req.URL.RawPath,
174 RawQuery: req.URL.RawQuery,
176 client := h.secureClient
178 client = h.insecureClient
180 return h.proxy.Do(req, urlOut, client)
183 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
184 resp, err := h.localClusterRequest(req)
185 n, err := h.proxy.ForwardResponse(w, resp, err)
187 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
191 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
192 // present, otherwise choose an arbitrary entry.
193 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
195 for target := range cluster.Services.RailsAPI.InternalURLs {
196 target := url.URL(target)
198 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
203 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
205 return best, cluster.TLS.Insecure, nil