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