13497: Proxy requests to Rails API.
[arvados.git] / lib / controller / handler.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "io"
9         "net"
10         "net/http"
11         "net/url"
12         "strings"
13         "sync"
14
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"
18 )
19
20 type Handler struct {
21         Cluster *arvados.Cluster
22         Node    *arvados.SystemNode
23
24         setupOnce    sync.Once
25         handlerStack http.Handler
26         proxyClient  *arvados.Client
27 }
28
29 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
30         h.setupOnce.Do(h.setup)
31         h.handlerStack.ServeHTTP(w, req)
32 }
33
34 func (h *Handler) setup() {
35         mux := http.NewServeMux()
36         mux.Handle("/_health/", &health.Handler{
37                 Token:  h.Cluster.ManagementToken,
38                 Prefix: "/_health/",
39         })
40         mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
41         h.handlerStack = mux
42 }
43
44 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
45         urlOut, err := findRailsAPI(h.Cluster, h.Node)
46         if err != nil {
47                 http.Error(w, err.Error(), http.StatusInternalServerError)
48                 return
49         }
50         urlOut = &url.URL{
51                 Scheme:   urlOut.Scheme,
52                 Host:     urlOut.Host,
53                 Path:     reqIn.URL.Path,
54                 RawPath:  reqIn.URL.RawPath,
55                 RawQuery: reqIn.URL.RawQuery,
56         }
57
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 {
62                 hdrOut[k] = v
63         }
64         xff := reqIn.RemoteAddr
65         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
66                 xff = xffIn + "," + xff
67         }
68         hdrOut.Set("X-Forwarded-For", xff)
69         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
70
71         reqOut := (&http.Request{
72                 Method: reqIn.Method,
73                 URL:    urlOut,
74                 Header: hdrOut,
75         }).WithContext(reqIn.Context())
76         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
77         if err != nil {
78                 http.Error(w, err.Error(), http.StatusInternalServerError)
79                 return
80         }
81         for k, v := range resp.Header {
82                 for _, v := range v {
83                         w.Header().Add(k, v)
84                 }
85         }
86         w.WriteHeader(resp.StatusCode)
87         n, err := io.Copy(w, resp.Body)
88         if err != nil {
89                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
90         }
91 }
92
93 // For now, findRailsAPI always uses the rails API running on this
94 // node.
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
102         } else {
103                 return nil, err
104         }
105         proto := "http"
106         if node.RailsAPI.TLS {
107                 proto = "https"
108         }
109         return url.Parse(proto + "://" + hostport)
110 }