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