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) CheckHealth() error {
37 h.setupOnce.Do(h.setup)
38 _, err := findRailsAPI(h.Cluster, h.NodeProfile)
42 func (h *Handler) setup() {
43 mux := http.NewServeMux()
44 mux.Handle("/_health/", &health.Handler{
45 Token: h.Cluster.ManagementToken,
48 mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
52 // headers that shouldn't be forwarded when proxying. See
53 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
54 var dropHeaders = map[string]bool{
57 "Proxy-Authenticate": true,
58 "Proxy-Authorization": true,
61 "Transfer-Encoding": true,
65 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
66 urlOut, err := findRailsAPI(h.Cluster, h.Node)
68 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
72 Scheme: urlOut.Scheme,
75 RawPath: reqIn.URL.RawPath,
76 RawQuery: reqIn.URL.RawQuery,
79 // Copy headers from incoming request, then add/replace proxy
80 // headers like Via and X-Forwarded-For.
81 hdrOut := http.Header{}
82 for k, v := range reqIn.Header {
87 xff := reqIn.RemoteAddr
88 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
89 xff = xffIn + "," + xff
91 hdrOut.Set("X-Forwarded-For", xff)
92 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
94 ctx := reqIn.Context()
95 if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
96 var cancel context.CancelFunc
97 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
101 reqOut := (&http.Request{
102 Method: reqIn.Method,
107 resp, err := arvados.InsecureHTTPClient.Do(reqOut)
109 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
112 for k, v := range resp.Header {
113 for _, v := range v {
117 w.WriteHeader(resp.StatusCode)
118 n, err := io.Copy(w, resp.Body)
120 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
124 // For now, findRailsAPI always uses the rails API running on this
126 func findRailsAPI(cluster *arvados.Cluster, node *arvados.SystemNode) (*url.URL, error) {
127 hostport := node.RailsAPI.Listen
128 if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
129 // ":12345" => connect to indicated port on localhost
130 hostport = "localhost" + hostport
131 } else if _, _, err := net.SplitHostPort(hostport); err == nil {
132 // "[::1]:12345" => connect to indicated address & port
137 if node.RailsAPI.TLS {
140 return url.Parse(proto + "://" + hostport)