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 if h.Cluster.HTTPRequestTimeout > 0 {
54 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.HTTPRequestTimeout)))
55 req = req.WithContext(ctx)
59 h.handlerStack.ServeHTTP(w, req)
62 func (h *Handler) CheckHealth() error {
63 h.setupOnce.Do(h.setup)
64 _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
68 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
70 func (h *Handler) setup() {
71 mux := http.NewServeMux()
72 mux.Handle("/_health/", &health.Handler{
73 Token: h.Cluster.ManagementToken,
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, h.NodeProfile)
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 // 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