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
26 NodeProfile *arvados.NodeProfile
29 handlerStack http.Handler
31 secureClient *http.Client
32 insecureClient *http.Client
37 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
38 h.setupOnce.Do(h.setup)
39 if req.Method != "GET" && req.Method != "HEAD" {
40 // http.ServeMux returns 301 with a cleaned path if
41 // the incoming request has a double slash. Some
42 // clients (including the Go standard library) change
43 // the request method to GET when following a 301
44 // redirect if the original method was not HEAD
45 // (RFC7231 6.4.2 specifically allows this in the case
46 // of POST). Thus "POST //foo" gets misdirected to
47 // "GET /foo". To avoid this, eliminate double slashes
48 // before passing the request to ServeMux.
49 for strings.Contains(req.URL.Path, "//") {
50 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
53 h.handlerStack.ServeHTTP(w, req)
56 func (h *Handler) CheckHealth() error {
57 h.setupOnce.Do(h.setup)
58 _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
62 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
64 func (h *Handler) setup() {
65 mux := http.NewServeMux()
66 mux.Handle("/_health/", &health.Handler{
67 Token: h.Cluster.ManagementToken,
70 hs := http.NotFoundHandler()
71 hs = prepend(hs, h.proxyRailsAPI)
72 hs = h.setupProxyRemoteCluster(hs)
76 sc := *arvados.DefaultSecureClient
77 sc.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
78 sc.CheckRedirect = neverRedirect
81 ic := *arvados.InsecureHTTPClient
82 ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
83 ic.CheckRedirect = neverRedirect
84 h.insecureClient = &ic
87 Name: "arvados-controller",
88 RequestTimeout: time.Duration(h.Cluster.HTTPRequestTimeout),
92 var errDBConnection = errors.New("database connection error")
94 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
96 defer h.pgdbMtx.Unlock()
101 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
103 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
104 return nil, errDBConnection
106 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
107 db.SetMaxOpenConns(p)
109 if err := db.Ping(); err != nil {
110 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
111 return nil, errDBConnection
117 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
119 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
120 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
121 middleware(w, req, next)
125 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, context.CancelFunc, error) {
126 urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
131 Scheme: urlOut.Scheme,
134 RawPath: req.URL.RawPath,
135 RawQuery: req.URL.RawQuery,
137 client := h.secureClient
139 client = h.insecureClient
141 return h.proxy.Do(req, urlOut, client)
144 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
145 resp, cancel, 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 // For now, findRailsAPI always uses the rails API running on this
157 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
158 hostport := np.RailsAPI.Listen
159 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
160 // ":12345" => connect to indicated port on localhost
161 hostport = "localhost" + hostport
162 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
163 // "[::1]:12345" => connect to indicated address & port
165 return nil, false, err
171 url, err := url.Parse(proto + "://" + hostport)
172 return url, np.RailsAPI.Insecure, err