20259: Add documentation for banner and tooltip features
[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         "fmt"
10         "net/http"
11         "net/http/httptest"
12         "net/url"
13         "strings"
14         "sync"
15
16         "git.arvados.org/arvados.git/lib/controller/api"
17         "git.arvados.org/arvados.git/lib/controller/federation"
18         "git.arvados.org/arvados.git/lib/controller/localdb"
19         "git.arvados.org/arvados.git/lib/controller/railsproxy"
20         "git.arvados.org/arvados.git/lib/controller/router"
21         "git.arvados.org/arvados.git/lib/ctrlctx"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "git.arvados.org/arvados.git/sdk/go/health"
24         "git.arvados.org/arvados.git/sdk/go/httpserver"
25
26         // sqlx needs lib/pq to talk to PostgreSQL
27         _ "github.com/lib/pq"
28 )
29
30 type Handler struct {
31         Cluster           *arvados.Cluster
32         BackgroundContext context.Context
33
34         setupOnce      sync.Once
35         federation     *federation.Conn
36         handlerStack   http.Handler
37         proxy          *proxy
38         secureClient   *http.Client
39         insecureClient *http.Client
40         dbConnector    ctrlctx.DBConnector
41         limitLogCreate chan struct{}
42 }
43
44 func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
45         h.setupOnce.Do(h.setup)
46         if req.Method != "GET" && req.Method != "HEAD" {
47                 // http.ServeMux returns 301 with a cleaned path if
48                 // the incoming request has a double slash. Some
49                 // clients (including the Go standard library) change
50                 // the request method to GET when following a 301
51                 // redirect if the original method was not HEAD
52                 // (RFC7231 6.4.2 specifically allows this in the case
53                 // of POST). Thus "POST //foo" gets misdirected to
54                 // "GET /foo". To avoid this, eliminate double slashes
55                 // before passing the request to ServeMux.
56                 for strings.Contains(req.URL.Path, "//") {
57                         req.URL.Path = strings.Replace(req.URL.Path, "//", "/", -1)
58                 }
59         }
60         h.handlerStack.ServeHTTP(w, req)
61 }
62
63 func (h *Handler) CheckHealth() error {
64         h.setupOnce.Do(h.setup)
65         _, err := h.dbConnector.GetDB(context.TODO())
66         if err != nil {
67                 return err
68         }
69         _, _, err = railsproxy.FindRailsAPI(h.Cluster)
70         if err != nil {
71                 return err
72         }
73         if h.Cluster.API.VocabularyPath != "" {
74                 req, err := http.NewRequest("GET", "/arvados/v1/vocabulary", nil)
75                 if err != nil {
76                         return err
77                 }
78                 var resp httptest.ResponseRecorder
79                 h.handlerStack.ServeHTTP(&resp, req)
80                 if resp.Result().StatusCode != http.StatusOK {
81                         return fmt.Errorf("%d %s", resp.Result().StatusCode, resp.Result().Status)
82                 }
83         }
84         return nil
85 }
86
87 func (h *Handler) Done() <-chan struct{} {
88         return nil
89 }
90
91 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
92
93 func (h *Handler) setup() {
94         mux := http.NewServeMux()
95         healthFuncs := make(map[string]health.Func)
96
97         h.dbConnector = ctrlctx.DBConnector{PostgreSQL: h.Cluster.PostgreSQL}
98         go func() {
99                 <-h.BackgroundContext.Done()
100                 h.dbConnector.Close()
101         }()
102         oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.dbConnector.GetDB)
103         h.federation = federation.New(h.BackgroundContext, h.Cluster, &healthFuncs, h.dbConnector.GetDB)
104         rtr := router.New(h.federation, router.Config{
105                 MaxRequestSize: h.Cluster.API.MaxRequestSize,
106                 WrapCalls: api.ComposeWrappers(
107                         ctrlctx.WrapCallsInTransactions(h.dbConnector.GetDB),
108                         oidcAuthorizer.WrapCalls,
109                         ctrlctx.WrapCallsWithAuth(h.Cluster)),
110         })
111
112         healthRoutes := health.Routes{"ping": func() error { _, err := h.dbConnector.GetDB(context.TODO()); return err }}
113         for name, f := range healthFuncs {
114                 healthRoutes[name] = f
115         }
116         mux.Handle("/_health/", &health.Handler{
117                 Token:  h.Cluster.ManagementToken,
118                 Prefix: "/_health/",
119                 Routes: healthRoutes,
120         })
121         mux.Handle("/arvados/v1/config", rtr)
122         mux.Handle("/arvados/v1/vocabulary", rtr)
123         mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr) // must come before .../users/
124         mux.Handle("/arvados/v1/collections", rtr)
125         mux.Handle("/arvados/v1/collections/", rtr)
126         mux.Handle("/arvados/v1/users", rtr)
127         mux.Handle("/arvados/v1/users/", rtr)
128         mux.Handle("/arvados/v1/connect/", rtr)
129         mux.Handle("/arvados/v1/container_requests", rtr)
130         mux.Handle("/arvados/v1/container_requests/", rtr)
131         mux.Handle("/arvados/v1/groups", rtr)
132         mux.Handle("/arvados/v1/groups/", rtr)
133         mux.Handle("/arvados/v1/links", rtr)
134         mux.Handle("/arvados/v1/links/", rtr)
135         mux.Handle("/login", rtr)
136         mux.Handle("/logout", rtr)
137         mux.Handle("/arvados/v1/api_client_authorizations", rtr)
138         mux.Handle("/arvados/v1/api_client_authorizations/", rtr)
139
140         hs := http.NotFoundHandler()
141         hs = prepend(hs, h.proxyRailsAPI)
142         hs = prepend(hs, h.limitLogCreateRequests)
143         hs = h.setupProxyRemoteCluster(hs)
144         hs = prepend(hs, oidcAuthorizer.Middleware)
145         mux.Handle("/", hs)
146         h.handlerStack = mux
147
148         sc := *arvados.DefaultSecureClient
149         sc.CheckRedirect = neverRedirect
150         h.secureClient = &sc
151
152         ic := *arvados.InsecureHTTPClient
153         ic.CheckRedirect = neverRedirect
154         h.insecureClient = &ic
155
156         logCreateLimit := int(float64(h.Cluster.API.MaxConcurrentRequests) * h.Cluster.API.LogCreateRequestFraction)
157         if logCreateLimit == 0 && h.Cluster.API.LogCreateRequestFraction > 0 {
158                 logCreateLimit = 1
159         }
160         h.limitLogCreate = make(chan struct{}, logCreateLimit)
161
162         h.proxy = &proxy{
163                 Name: "arvados-controller",
164         }
165
166         go h.trashSweepWorker()
167         go h.containerLogSweepWorker()
168 }
169
170 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
171
172 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
173         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
174                 middleware(w, req, next)
175         })
176 }
177
178 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
179         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
180         if err != nil {
181                 return nil, err
182         }
183         urlOut = &url.URL{
184                 Scheme:   urlOut.Scheme,
185                 Host:     urlOut.Host,
186                 Path:     req.URL.Path,
187                 RawPath:  req.URL.RawPath,
188                 RawQuery: req.URL.RawQuery,
189         }
190         client := h.secureClient
191         if insecure {
192                 client = h.insecureClient
193         }
194         return h.proxy.Do(req, urlOut, client)
195 }
196
197 func (h *Handler) limitLogCreateRequests(w http.ResponseWriter, req *http.Request, next http.Handler) {
198         if cap(h.limitLogCreate) > 0 && req.Method == http.MethodPost && strings.HasPrefix(req.URL.Path, "/arvados/v1/logs") {
199                 select {
200                 case h.limitLogCreate <- struct{}{}:
201                         defer func() { <-h.limitLogCreate }()
202                         next.ServeHTTP(w, req)
203                 default:
204                         http.Error(w, "Excess log messages", http.StatusServiceUnavailable)
205                 }
206                 return
207         }
208         next.ServeHTTP(w, req)
209 }
210
211 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
212         resp, err := h.localClusterRequest(req)
213         n, err := h.proxy.ForwardResponse(w, resp, err)
214         if err != nil {
215                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
216         }
217 }
218
219 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
220 // present, otherwise choose an arbitrary entry.
221 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
222         var best *url.URL
223         for target := range cluster.Services.RailsAPI.InternalURLs {
224                 target := url.URL(target)
225                 best = &target
226                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
227                         break
228                 }
229         }
230         if best == nil {
231                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
232         }
233         return best, cluster.TLS.Insecure, nil
234 }