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