1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/lib/config"
21 "git.curoverse.com/arvados.git/lib/controller/federation"
22 "git.curoverse.com/arvados.git/lib/controller/railsproxy"
23 "git.curoverse.com/arvados.git/lib/controller/router"
24 "git.curoverse.com/arvados.git/sdk/go/arvados"
25 "git.curoverse.com/arvados.git/sdk/go/health"
26 "git.curoverse.com/arvados.git/sdk/go/httpserver"
31 Cluster *arvados.Cluster
34 handlerStack http.Handler
36 secureClient *http.Client
37 insecureClient *http.Client
42 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
43 h.setupOnce.Do(h.setup)
44 if req.Method != "GET" && req.Method != "HEAD" {
45 // http.ServeMux returns 301 with a cleaned path if
46 // the incoming request has a double slash. Some
47 // clients (including the Go standard library) change
48 // the request method to GET when following a 301
49 // redirect if the original method was not HEAD
50 // (RFC7231 6.4.2 specifically allows this in the case
51 // of POST). Thus "POST //foo" gets misdirected to
52 // "GET /foo". To avoid this, eliminate double slashes
53 // before passing the request to ServeMux.
54 for strings.Contains(req.URL.Path, "//") {
55 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
58 if h.Cluster.API.RequestTimeout > 0 {
59 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
60 req = req.WithContext(ctx)
64 h.handlerStack.ServeHTTP(w, req)
67 func (h *Handler) CheckHealth() error {
68 h.setupOnce.Do(h.setup)
69 _, _, err := railsproxy.FindRailsAPI(h.Cluster)
73 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
75 func (h *Handler) setup() {
76 mux := http.NewServeMux()
77 mux.Handle("/_health/", &health.Handler{
78 Token: h.Cluster.ManagementToken,
80 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
83 mux.Handle("/arvados/v1/config", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
85 err := config.ExportJSON(&buf, h.Cluster)
87 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
90 w.Header().Set("Content-Type", "application/json")
94 if h.Cluster.EnableBetaController14287 {
95 rtr := router.New(federation.New(h.Cluster))
96 mux.Handle("/arvados/v1/collections", rtr)
97 mux.Handle("/arvados/v1/collections/", rtr)
100 hs := http.NotFoundHandler()
101 hs = prepend(hs, h.proxyRailsAPI)
102 hs = h.setupProxyRemoteCluster(hs)
106 sc := *arvados.DefaultSecureClient
107 sc.CheckRedirect = neverRedirect
110 ic := *arvados.InsecureHTTPClient
111 ic.CheckRedirect = neverRedirect
112 h.insecureClient = &ic
115 Name: "arvados-controller",
119 var errDBConnection = errors.New("database connection error")
121 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
123 defer h.pgdbMtx.Unlock()
128 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
130 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
131 return nil, errDBConnection
133 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
134 db.SetMaxOpenConns(p)
136 if err := db.Ping(); err != nil {
137 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
138 return nil, errDBConnection
144 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
146 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
147 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
148 middleware(w, req, next)
152 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
153 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
158 Scheme: urlOut.Scheme,
161 RawPath: req.URL.RawPath,
162 RawQuery: req.URL.RawQuery,
164 client := h.secureClient
166 client = h.insecureClient
168 return h.proxy.Do(req, urlOut, client)
171 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
172 resp, err := h.localClusterRequest(req)
173 n, err := h.proxy.ForwardResponse(w, resp, err)
175 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
179 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
180 // present, otherwise choose an arbitrary entry.
181 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
183 for target := range cluster.Services.RailsAPI.InternalURLs {
184 target := url.URL(target)
186 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
191 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
193 return best, cluster.TLS.Insecure, nil