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.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
84 sc.CheckRedirect = neverRedirect
87 ic := *arvados.InsecureHTTPClient
88 ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
89 ic.CheckRedirect = neverRedirect
90 h.insecureClient = &ic
93 Name: "arvados-controller",
97 var errDBConnection = errors.New("database connection error")
99 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
101 defer h.pgdbMtx.Unlock()
106 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
108 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
109 return nil, errDBConnection
111 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
112 db.SetMaxOpenConns(p)
114 if err := db.Ping(); err != nil {
115 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
116 return nil, errDBConnection
122 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
124 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
125 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
126 middleware(w, req, next)
130 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
131 urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
136 Scheme: urlOut.Scheme,
139 RawPath: req.URL.RawPath,
140 RawQuery: req.URL.RawQuery,
142 client := h.secureClient
144 client = h.insecureClient
146 return h.proxy.Do(req, urlOut, client)
149 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
150 resp, err := h.localClusterRequest(req)
151 n, err := h.proxy.ForwardResponse(w, resp, err)
153 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
157 // For now, findRailsAPI always uses the rails API running on this
159 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
160 hostport := np.RailsAPI.Listen
161 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
162 // ":12345" => connect to indicated port on localhost
163 hostport = "localhost" + hostport
164 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
165 // "[::1]:12345" => connect to indicated address & port
167 return nil, false, err
173 url, err := url.Parse(proto + "://" + hostport)
174 return url, np.RailsAPI.Insecure, err