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