1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.curoverse.com/arvados.git/sdk/go/arvados"
16 "git.curoverse.com/arvados.git/sdk/go/health"
17 "git.curoverse.com/arvados.git/sdk/go/httpserver"
21 Cluster *arvados.Cluster
22 Node *arvados.SystemNode
25 handlerStack http.Handler
26 proxyClient *arvados.Client
29 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
30 h.setupOnce.Do(h.setup)
31 h.handlerStack.ServeHTTP(w, req)
34 func (h *Handler) setup() {
35 mux := http.NewServeMux()
36 mux.Handle("/_health/", &health.Handler{
37 Token: h.Cluster.ManagementToken,
40 mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
44 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
45 urlOut, err := findRailsAPI(h.Cluster, h.Node)
47 http.Error(w, err.Error(), http.StatusInternalServerError)
51 Scheme: urlOut.Scheme,
54 RawPath: reqIn.URL.RawPath,
55 RawQuery: reqIn.URL.RawQuery,
58 // Copy headers from incoming request, then add/replace proxy
59 // headers like Via and X-Forwarded-For.
60 hdrOut := http.Header{}
61 for k, v := range reqIn.Header {
64 xff := reqIn.RemoteAddr
65 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
66 xff = xffIn + "," + xff
68 hdrOut.Set("X-Forwarded-For", xff)
69 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
71 reqOut := (&http.Request{
75 }).WithContext(reqIn.Context())
76 resp, err := arvados.InsecureHTTPClient.Do(reqOut)
78 http.Error(w, err.Error(), http.StatusInternalServerError)
81 for k, v := range resp.Header {
86 w.WriteHeader(resp.StatusCode)
87 n, err := io.Copy(w, resp.Body)
89 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
93 // For now, findRailsAPI always uses the rails API running on this
95 func findRailsAPI(cluster *arvados.Cluster, node *arvados.SystemNode) (*url.URL, error) {
96 hostport := node.RailsAPI.Listen
97 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
98 // ":12345" => connect to indicated port on localhost
99 hostport = "localhost" + hostport
100 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
101 // "[::1]:12345" => connect to indicated address & port
106 if node.RailsAPI.TLS {
109 return url.Parse(proto + "://" + hostport)