1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "git.curoverse.com/arvados.git/sdk/go/health"
19 "git.curoverse.com/arvados.git/sdk/go/httpserver"
24 Cluster *arvados.Cluster
25 NodeProfile *arvados.NodeProfile
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 h.handlerStack.ServeHTTP(w, req)
55 func (h *Handler) CheckHealth() error {
56 h.setupOnce.Do(h.setup)
57 _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
61 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
63 func (h *Handler) setup() {
64 mux := http.NewServeMux()
65 mux.Handle("/_health/", &health.Handler{
66 Token: h.Cluster.ManagementToken,
69 hs := http.NotFoundHandler()
70 hs = prepend(hs, h.proxyRailsAPI)
71 hs = h.setupProxyRemoteCluster(hs)
75 sc := *arvados.DefaultSecureClient
76 sc.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
77 sc.CheckRedirect = neverRedirect
80 ic := *arvados.InsecureHTTPClient
81 ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
82 ic.CheckRedirect = neverRedirect
83 h.insecureClient = &ic
86 Name: "arvados-controller",
87 RequestTimeout: time.Duration(h.Cluster.HTTPRequestTimeout),
91 var errDBConnection = errors.New("database connection error")
93 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
95 defer h.pgdbMtx.Unlock()
100 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
102 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
103 return nil, errDBConnection
105 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
106 db.SetMaxOpenConns(p)
108 if err := db.Ping(); err != nil {
109 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
110 return nil, errDBConnection
116 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
118 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
119 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
120 middleware(w, req, next)
124 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
125 urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
130 Scheme: urlOut.Scheme,
133 RawPath: req.URL.RawPath,
134 RawQuery: req.URL.RawQuery,
136 client := h.secureClient
138 client = h.insecureClient
140 return h.proxy.ForwardRequest(req, urlOut, client)
143 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
144 resp, err := h.localClusterRequest(req)
145 n, err := h.proxy.ForwardResponse(w, resp, err)
147 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
151 // For now, findRailsAPI always uses the rails API running on this
153 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
154 hostport := np.RailsAPI.Listen
155 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
156 // ":12345" => connect to indicated port on localhost
157 hostport = "localhost" + hostport
158 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
159 // "[::1]:12345" => connect to indicated address & port
161 return nil, false, err
167 url, err := url.Parse(proto + "://" + hostport)
168 return url, np.RailsAPI.Insecure, err