1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
17 "git.curoverse.com/arvados.git/sdk/go/arvados"
18 "git.curoverse.com/arvados.git/sdk/go/health"
19 "git.curoverse.com/arvados.git/sdk/go/httpserver"
23 Cluster *arvados.Cluster
24 Node *arvados.SystemNode
27 handlerStack http.Handler
28 proxyClient *arvados.Client
31 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
32 h.setupOnce.Do(h.setup)
33 h.handlerStack.ServeHTTP(w, req)
36 func (h *Handler) setup() {
37 mux := http.NewServeMux()
38 mux.Handle("/_health/", &health.Handler{
39 Token: h.Cluster.ManagementToken,
42 mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
46 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
47 urlOut, err := findRailsAPI(h.Cluster, h.Node)
49 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
53 Scheme: urlOut.Scheme,
56 RawPath: reqIn.URL.RawPath,
57 RawQuery: reqIn.URL.RawQuery,
60 // Copy headers from incoming request, then add/replace proxy
61 // headers like Via and X-Forwarded-For.
62 hdrOut := http.Header{}
63 for k, v := range reqIn.Header {
66 xff := reqIn.RemoteAddr
67 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
68 xff = xffIn + "," + xff
70 hdrOut.Set("X-Forwarded-For", xff)
71 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
73 ctx := reqIn.Context()
74 if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
75 var cancel context.CancelFunc
76 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
80 reqOut := (&http.Request{
85 resp, err := arvados.InsecureHTTPClient.Do(reqOut)
87 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
90 for k, v := range resp.Header {
95 w.WriteHeader(resp.StatusCode)
96 n, err := io.Copy(w, resp.Body)
98 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
102 // For now, findRailsAPI always uses the rails API running on this
104 func findRailsAPI(cluster *arvados.Cluster, node *arvados.SystemNode) (*url.URL, error) {
105 hostport := node.RailsAPI.Listen
106 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
107 // ":12345" => connect to indicated port on localhost
108 hostport = "localhost" + hostport
109 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
110 // "[::1]:12345" => connect to indicated address & port
115 if node.RailsAPI.TLS {
118 return url.Parse(proto + "://" + hostport)