Merge branch '17022-user-activity-report' refs #17022
[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         // sqlx needs lib/pq to talk to PostgreSQL
29         _ "github.com/lib/pq"
30 )
31
32 type Handler struct {
33         Cluster *arvados.Cluster
34
35         setupOnce      sync.Once
36         handlerStack   http.Handler
37         proxy          *proxy
38         secureClient   *http.Client
39         insecureClient *http.Client
40         pgdb           *sqlx.DB
41         pgdbMtx        sync.Mutex
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         if h.Cluster.API.RequestTimeout > 0 {
61                 ctx, cancel := context.WithDeadline(req.Context(), time.Now().Add(time.Duration(h.Cluster.API.RequestTimeout)))
62                 req = req.WithContext(ctx)
63                 defer cancel()
64         }
65
66         h.handlerStack.ServeHTTP(w, req)
67 }
68
69 func (h *Handler) CheckHealth() error {
70         h.setupOnce.Do(h.setup)
71         _, err := h.db(context.TODO())
72         if err != nil {
73                 return err
74         }
75         _, _, err = railsproxy.FindRailsAPI(h.Cluster)
76         return err
77 }
78
79 func (h *Handler) Done() <-chan struct{} {
80         return nil
81 }
82
83 func neverRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
84
85 func (h *Handler) setup() {
86         mux := http.NewServeMux()
87         mux.Handle("/_health/", &health.Handler{
88                 Token:  h.Cluster.ManagementToken,
89                 Prefix: "/_health/",
90                 Routes: health.Routes{"ping": func() error { _, err := h.db(context.TODO()); return err }},
91         })
92
93         oidcAuthorizer := localdb.OIDCAccessTokenAuthorizer(h.Cluster, h.db)
94         rtr := router.New(federation.New(h.Cluster), api.ComposeWrappers(ctrlctx.WrapCallsInTransactions(h.db), oidcAuthorizer.WrapCalls))
95         mux.Handle("/arvados/v1/config", rtr)
96         mux.Handle("/"+arvados.EndpointUserAuthenticate.Path, rtr)
97
98         if !h.Cluster.ForceLegacyAPI14 {
99                 mux.Handle("/arvados/v1/collections", rtr)
100                 mux.Handle("/arvados/v1/collections/", rtr)
101                 mux.Handle("/arvados/v1/users", rtr)
102                 mux.Handle("/arvados/v1/users/", rtr)
103                 mux.Handle("/login", rtr)
104                 mux.Handle("/logout", rtr)
105         }
106
107         hs := http.NotFoundHandler()
108         hs = prepend(hs, h.proxyRailsAPI)
109         hs = h.setupProxyRemoteCluster(hs)
110         hs = prepend(hs, oidcAuthorizer.Middleware)
111         mux.Handle("/", hs)
112         h.handlerStack = mux
113
114         sc := *arvados.DefaultSecureClient
115         sc.CheckRedirect = neverRedirect
116         h.secureClient = &sc
117
118         ic := *arvados.InsecureHTTPClient
119         ic.CheckRedirect = neverRedirect
120         h.insecureClient = &ic
121
122         h.proxy = &proxy{
123                 Name: "arvados-controller",
124         }
125 }
126
127 var errDBConnection = errors.New("database connection error")
128
129 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
130         h.pgdbMtx.Lock()
131         defer h.pgdbMtx.Unlock()
132         if h.pgdb != nil {
133                 return h.pgdb, nil
134         }
135
136         db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
137         if err != nil {
138                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
139                 return nil, errDBConnection
140         }
141         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
142                 db.SetMaxOpenConns(p)
143         }
144         if err := db.Ping(); err != nil {
145                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
146                 return nil, errDBConnection
147         }
148         h.pgdb = db
149         return db, nil
150 }
151
152 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
153
154 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
155         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
156                 middleware(w, req, next)
157         })
158 }
159
160 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
161         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
162         if err != nil {
163                 return nil, err
164         }
165         urlOut = &url.URL{
166                 Scheme:   urlOut.Scheme,
167                 Host:     urlOut.Host,
168                 Path:     req.URL.Path,
169                 RawPath:  req.URL.RawPath,
170                 RawQuery: req.URL.RawQuery,
171         }
172         client := h.secureClient
173         if insecure {
174                 client = h.insecureClient
175         }
176         return h.proxy.Do(req, urlOut, client)
177 }
178
179 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
180         resp, err := h.localClusterRequest(req)
181         n, err := h.proxy.ForwardResponse(w, resp, err)
182         if err != nil {
183                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
184         }
185 }
186
187 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
188 // present, otherwise choose an arbitrary entry.
189 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
190         var best *url.URL
191         for target := range cluster.Services.RailsAPI.InternalURLs {
192                 target := url.URL(target)
193                 best = &target
194                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
195                         break
196                 }
197         }
198         if best == nil {
199                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
200         }
201         return best, cluster.TLS.Insecure, nil
202 }