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