1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.curoverse.com/arvados.git/lib/config"
21 "git.curoverse.com/arvados.git/lib/controller/railsproxy"
22 "git.curoverse.com/arvados.git/lib/controller/router"
23 "git.curoverse.com/arvados.git/sdk/go/arvados"
24 "git.curoverse.com/arvados.git/sdk/go/health"
25 "git.curoverse.com/arvados.git/sdk/go/httpserver"
30 Cluster *arvados.Cluster
33 handlerStack http.Handler
35 secureClient *http.Client
36 insecureClient *http.Client
41 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
42 h.setupOnce.Do(h.setup)
43 if req.Method != "GET" && req.Method != "HEAD" {
44 // http.ServeMux returns 301 with a cleaned path if
45 // the incoming request has a double slash. Some
46 // clients (including the Go standard library) change
47 // the request method to GET when following a 301
48 // redirect if the original method was not HEAD
49 // (RFC7231 6.4.2 specifically allows this in the case
50 // of POST). Thus "POST //foo" gets misdirected to
51 // "GET /foo". To avoid this, eliminate double slashes
52 // before passing the request to ServeMux.
53 for strings.Contains(req.URL.Path, "//") {
54 req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
57 if h.Cluster.API.RequestTimeout > 0 {
58 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
59 req = req.WithContext(ctx)
63 h.handlerStack.ServeHTTP(w, req)
66 func (h *Handler) CheckHealth() error {
67 h.setupOnce.Do(h.setup)
68 _, _, err := railsproxy.FindRailsAPI(h.Cluster)
72 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
74 func (h *Handler) setup() {
75 mux := http.NewServeMux()
76 mux.Handle("/_health/", &health.Handler{
77 Token: h.Cluster.ManagementToken,
79 Routes: health.Routes{"ping": func() error { _, err := h.db(&http.Request{}); return err }},
82 mux.Handle("/arvados/v1/config", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
84 err := config.ExportJSON(&buf, h.Cluster)
86 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
89 w.Header().Set("Content-Type", "application/json")
93 if h.Cluster.EnableBetaController14287 {
94 rtr := router.New(h.Cluster)
95 mux.Handle("/arvados/v1/collections", rtr)
96 mux.Handle("/arvados/v1/collections/", rtr)
99 hs := http.NotFoundHandler()
100 hs = prepend(hs, h.proxyRailsAPI)
101 hs = h.setupProxyRemoteCluster(hs)
105 sc := *arvados.DefaultSecureClient
106 sc.CheckRedirect = neverRedirect
109 ic := *arvados.InsecureHTTPClient
110 ic.CheckRedirect = neverRedirect
111 h.insecureClient = &ic
114 Name: "arvados-controller",
118 var errDBConnection = errors.New("database connection error")
120 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
122 defer h.pgdbMtx.Unlock()
127 db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
129 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
130 return nil, errDBConnection
132 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
133 db.SetMaxOpenConns(p)
135 if err := db.Ping(); err != nil {
136 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
137 return nil, errDBConnection
143 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
145 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
146 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
147 middleware(w, req, next)
151 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
152 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
157 Scheme: urlOut.Scheme,
160 RawPath: req.URL.RawPath,
161 RawQuery: req.URL.RawQuery,
163 client := h.secureClient
165 client = h.insecureClient
167 return h.proxy.Do(req, urlOut, client)
170 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
171 resp, err := h.localClusterRequest(req)
172 n, err := h.proxy.ForwardResponse(w, resp, err)
174 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
178 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
179 // present, otherwise choose an arbitrary entry.
180 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
182 for target := range cluster.Services.RailsAPI.InternalURLs {
183 target := url.URL(target)
185 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
190 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
192 return best, cluster.TLS.Insecure, nil