Merge branch '13164-fix-zero-priority-after-race'
[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         "context"
9         "io"
10         "net"
11         "net/http"
12         "net/url"
13         "strings"
14         "sync"
15         "time"
16
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"
20 )
21
22 type Handler struct {
23         Cluster     *arvados.Cluster
24         NodeProfile *arvados.NodeProfile
25
26         setupOnce    sync.Once
27         handlerStack http.Handler
28         proxyClient  *arvados.Client
29 }
30
31 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
32         h.setupOnce.Do(h.setup)
33         h.handlerStack.ServeHTTP(w, req)
34 }
35
36 func (h *Handler) CheckHealth() error {
37         h.setupOnce.Do(h.setup)
38         _, err := findRailsAPI(h.Cluster, h.NodeProfile)
39         return err
40 }
41
42 func (h *Handler) setup() {
43         mux := http.NewServeMux()
44         mux.Handle("/_health/", &health.Handler{
45                 Token:  h.Cluster.ManagementToken,
46                 Prefix: "/_health/",
47         })
48         mux.Handle("/", http.HandlerFunc(h.proxyRailsAPI))
49         h.handlerStack = mux
50 }
51
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{
55         "Connection":          true,
56         "Keep-Alive":          true,
57         "Proxy-Authenticate":  true,
58         "Proxy-Authorization": true,
59         "TE":                true,
60         "Trailer":           true,
61         "Transfer-Encoding": true,
62         "Upgrade":           true,
63 }
64
65 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, reqIn *http.Request) {
66         urlOut, err := findRailsAPI(h.Cluster, h.NodeProfile)
67         if err != nil {
68                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
69                 return
70         }
71         urlOut = &url.URL{
72                 Scheme:   urlOut.Scheme,
73                 Host:     urlOut.Host,
74                 Path:     reqIn.URL.Path,
75                 RawPath:  reqIn.URL.RawPath,
76                 RawQuery: reqIn.URL.RawQuery,
77         }
78
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 {
83                 if !dropHeaders[k] {
84                         hdrOut[k] = v
85                 }
86         }
87         xff := reqIn.RemoteAddr
88         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
89                 xff = xffIn + "," + xff
90         }
91         hdrOut.Set("X-Forwarded-For", xff)
92         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
93
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)))
98                 defer cancel()
99         }
100
101         reqOut := (&http.Request{
102                 Method: reqIn.Method,
103                 URL:    urlOut,
104                 Header: hdrOut,
105                 Body:   reqIn.Body,
106         }).WithContext(ctx)
107         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
108         if err != nil {
109                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
110                 return
111         }
112         for k, v := range resp.Header {
113                 for _, v := range v {
114                         w.Header().Add(k, v)
115                 }
116         }
117         w.WriteHeader(resp.StatusCode)
118         n, err := io.Copy(w, resp.Body)
119         if err != nil {
120                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
121         }
122 }
123
124 // For now, findRailsAPI always uses the rails API running on this
125 // node.
126 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, error) {
127         hostport := np.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
133         } else {
134                 return nil, err
135         }
136         proto := "http"
137         if np.RailsAPI.TLS {
138                 proto = "https"
139         }
140         return url.Parse(proto + "://" + hostport)
141 }