1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.arvados.org/arvados.git/lib/controller/federation"
19 "git.arvados.org/arvados.git/lib/controller/railsproxy"
20 "git.arvados.org/arvados.git/lib/controller/router"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/health"
23 "git.arvados.org/arvados.git/sdk/go/httpserver"
28 Cluster *arvados.Cluster
31 handlerStack http.Handler
33 secureClient *http.Client
34 insecureClient *http.Client
39 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
40 h.setupOnce.Do(h.setup)
41 if req.Method != "GET" && req.Method != "HEAD" {
42 // http.ServeMux returns 301 with a cleaned path if
43 // the incoming request has a double slash. Some
44 // clients (including the Go standard library) change
45 // the request method to GET when following a 301
46 // redirect if the original method was not HEAD
47 // (RFC7231 6.4.2 specifically allows this in the case
48 // of POST). Thus "POST //foo" gets misdirected to
49 // "GET /foo". To avoid this, eliminate double slashes
50 // before passing the request to ServeMux.
51 for strings.Contains(req.URL.Path, "//") {
52 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
55 if h.Cluster.API.RequestTimeout > 0 {
56 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
57 req = req.WithContext(ctx)
61 h.handlerStack.ServeHTTP(w, req)
64 func (h *Handler) CheckHealth() error {
65 h.setupOnce.Do(h.setup)
66 _, _, err := railsproxy.FindRailsAPI(h.Cluster)
70 func (h *Handler) Done() <-chan struct{} {
74 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
76 func (h *Handler) setup() {
77 mux := http.NewServeMux()
78 mux.Handle("/_health/", &health.Handler{
79 Token: h.Cluster.ManagementToken,
81 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
84 rtr := router.New(federation.New(h.Cluster))
85 mux.Handle("/arvados/v1/config", rtr)
86 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
88 if !h.Cluster.ForceLegacyAPI14 {
89 mux.Handle("/arvados/v1/collections", rtr)
90 mux.Handle("/arvados/v1/collections/", rtr)
91 mux.Handle("/arvados/v1/users", rtr)
92 mux.Handle("/arvados/v1/users/", rtr)
93 mux.Handle("/login", rtr)
94 mux.Handle("/logout", rtr)
97 hs := http.NotFoundHandler()
98 hs = prepend(hs, h.proxyRailsAPI)
99 hs = h.setupProxyRemoteCluster(hs)
103 sc := *arvados.DefaultSecureClient
104 sc.CheckRedirect = neverRedirect
107 ic := *arvados.InsecureHTTPClient
108 ic.CheckRedirect = neverRedirect
109 h.insecureClient = &ic
112 Name: "arvados-controller",
116 var errDBConnection = errors.New("database connection error")
118 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
120 defer h.pgdbMtx.Unlock()
125 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
127 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
128 return nil, errDBConnection
130 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
131 db.SetMaxOpenConns(p)
133 if err := db.Ping(); err != nil {
134 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
135 return nil, errDBConnection
141 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
143 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
144 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
145 middleware(w, req, next)
149 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
150 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
155 Scheme: urlOut.Scheme,
158 RawPath: req.URL.RawPath,
159 RawQuery: req.URL.RawQuery,
161 client := h.secureClient
163 client = h.insecureClient
165 return h.proxy.Do(req, urlOut, client)
168 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
169 resp, err := h.localClusterRequest(req)
170 n, err := h.proxy.ForwardResponse(w, resp, err)
172 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
176 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
177 // present, otherwise choose an arbitrary entry.
178 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
180 for target := range cluster.Services.RailsAPI.InternalURLs {
181 target := url.URL(target)
183 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
188 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
190 return best, cluster.TLS.Insecure, nil