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.API.RequestTimeout > 0 {
54 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
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,
75 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
77 hs := http.NotFoundHandler()
78 hs = prepend(hs, h.proxyRailsAPI)
79 hs = h.setupProxyRemoteCluster(hs)
83 sc := *arvados.DefaultSecureClient
84 sc.CheckRedirect = neverRedirect
87 ic := *arvados.InsecureHTTPClient
88 ic.CheckRedirect = neverRedirect
89 h.insecureClient = &ic
92 Name: "arvados-controller",
96 var errDBConnection = errors.New("database connection error")
98 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
100 defer h.pgdbMtx.Unlock()
105 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
107 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
108 return nil, errDBConnection
110 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
111 db.SetMaxOpenConns(p)
113 if err := db.Ping(); err != nil {
114 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
115 return nil, errDBConnection
121 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
123 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
124 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
125 middleware(w, req, next)
129 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
130 urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
135 Scheme: urlOut.Scheme,
138 RawPath: req.URL.RawPath,
139 RawQuery: req.URL.RawQuery,
141 client := h.secureClient
143 client = h.insecureClient
145 return h.proxy.Do(req, urlOut, client)
148 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
149 resp, err := h.localClusterRequest(req)
150 n, err := h.proxy.ForwardResponse(w, resp, err)
152 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
156 // For now, findRailsAPI always uses the rails API running on this
158 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
159 hostport := np.RailsAPI.Listen
160 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
161 // ":12345" => connect to indicated port on localhost
162 hostport = "localhost" + hostport
163 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
164 // "[::1]:12345" => connect to indicated address & port
166 return nil, false, err
172 url, err := url.Parse(proto + "://" + hostport)
173 return url, np.RailsAPI.Insecure, err