1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.curoverse.com/arvados.git/sdk/go/arvados"
19 "git.curoverse.com/arvados.git/sdk/go/health"
20 "git.curoverse.com/arvados.git/sdk/go/httpserver"
25 Cluster *arvados.Cluster
28 handlerStack http.Handler
30 secureClient *http.Client
31 insecureClient *http.Client
36 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
37 h.setupOnce.Do(h.setup)
38 if req.Method != "GET" && req.Method != "HEAD" {
39 // http.ServeMux returns 301 with a cleaned path if
40 // the incoming request has a double slash. Some
41 // clients (including the Go standard library) change
42 // the request method to GET when following a 301
43 // redirect if the original method was not HEAD
44 // (RFC7231 6.4.2 specifically allows this in the case
45 // of POST). Thus "POST //foo" gets misdirected to
46 // "GET /foo". To avoid this, eliminate double slashes
47 // before passing the request to ServeMux.
48 for strings.Contains(req.URL.Path, "//") {
49 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
52 if h.Cluster.API.RequestTimeout > 0 {
53 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
54 req = req.WithContext(ctx)
58 h.handlerStack.ServeHTTP(w, req)
61 func (h *Handler) CheckHealth() error {
62 h.setupOnce.Do(h.setup)
63 _, _, err := findRailsAPI(h.Cluster)
67 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
69 func (h *Handler) setup() {
70 mux := http.NewServeMux()
71 mux.Handle("/_health/", &health.Handler{
72 Token: h.Cluster.ManagementToken,
74 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
76 hs := http.NotFoundHandler()
77 hs = prepend(hs, h.proxyRailsAPI)
78 hs = h.setupProxyRemoteCluster(hs)
82 sc := *arvados.DefaultSecureClient
83 sc.CheckRedirect = neverRedirect
86 ic := *arvados.InsecureHTTPClient
87 ic.CheckRedirect = neverRedirect
88 h.insecureClient = &ic
91 Name: "arvados-controller",
95 var errDBConnection = errors.New("database connection error")
97 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
99 defer h.pgdbMtx.Unlock()
104 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
106 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
107 return nil, errDBConnection
109 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
110 db.SetMaxOpenConns(p)
112 if err := db.Ping(); err != nil {
113 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
114 return nil, errDBConnection
120 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
122 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
123 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
124 middleware(w, req, next)
128 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
129 urlOut, insecure, err := findRailsAPI(h.Cluster)
134 Scheme: urlOut.Scheme,
137 RawPath: req.URL.RawPath,
138 RawQuery: req.URL.RawQuery,
140 client := h.secureClient
142 client = h.insecureClient
144 return h.proxy.Do(req, urlOut, client)
147 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
148 resp, err := h.localClusterRequest(req)
149 n, err := h.proxy.ForwardResponse(w, resp, err)
151 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
155 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
156 // present, otherwise choose an arbitrary entry.
157 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
159 for target := range cluster.Services.RailsAPI.InternalURLs {
160 target := url.URL(target)
162 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
167 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
169 return best, cluster.TLS.Insecure, nil