1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.arvados.org/arvados.git/lib/controller/federation"
18 "git.arvados.org/arvados.git/lib/controller/railsproxy"
19 "git.arvados.org/arvados.git/lib/controller/router"
20 "git.arvados.org/arvados.git/lib/ctrlctx"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/ctxlog"
23 "git.arvados.org/arvados.git/sdk/go/health"
24 "git.arvados.org/arvados.git/sdk/go/httpserver"
25 "github.com/jmoiron/sqlx"
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 := h.db(context.TODO())
72 _, _, err = railsproxy.FindRailsAPI(h.Cluster)
76 func (h *Handler) Done() <-chan struct{} {
80 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
82 func (h *Handler) setup() {
83 mux := http.NewServeMux()
84 mux.Handle("/_health/", &health.Handler{
85 Token: h.Cluster.ManagementToken,
87 Routes: health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }},
90 rtr := router.New(federation.New(h.Cluster), ctrlctx.WrapCallsInTransactions(h.db))
91 mux.Handle("/arvados/v1/config", rtr)
92 mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
94 if !h.Cluster.ForceLegacyAPI14 {
95 mux.Handle("/arvados/v1/collections", rtr)
96 mux.Handle("/arvados/v1/collections/", rtr)
97 mux.Handle("/arvados/v1/users", rtr)
98 mux.Handle("/arvados/v1/users/", rtr)
99 mux.Handle("/login", rtr)
100 mux.Handle("/logout", rtr)
103 hs := http.NotFoundHandler()
104 hs = prepend(hs, h.proxyRailsAPI)
105 hs = h.setupProxyRemoteCluster(hs)
109 sc := *arvados.DefaultSecureClient
110 sc.CheckRedirect = neverRedirect
113 ic := *arvados.InsecureHTTPClient
114 ic.CheckRedirect = neverRedirect
115 h.insecureClient = &ic
118 Name: "arvados-controller",
122 var errDBConnection = errors.New("database connection error")
124 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
126 defer h.pgdbMtx.Unlock()
131 db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
133 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
134 return nil, errDBConnection
136 if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
137 db.SetMaxOpenConns(p)
139 if err := db.Ping(); err != nil {
140 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
141 return nil, errDBConnection
147 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
149 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
150 return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
151 middleware(w, req, next)
155 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
156 urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
161 Scheme: urlOut.Scheme,
164 RawPath: req.URL.RawPath,
165 RawQuery: req.URL.RawQuery,
167 client := h.secureClient
169 client = h.insecureClient
171 return h.proxy.Do(req, urlOut, client)
174 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
175 resp, err := h.localClusterRequest(req)
176 n, err := h.proxy.ForwardResponse(w, resp, err)
178 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
182 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
183 // present, otherwise choose an arbitrary entry.
184 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
186 for target := range cluster.Services.RailsAPI.InternalURLs {
187 target := url.URL(target)
189 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
194 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
196 return best, cluster.TLS.Insecure, nil