17154: Add comment. Use strings.HasPrefix
[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("/arvados/v1/container_requests", rtr)
103                 mux.Handle("/arvados/v1/container_requests/", rtr)
104                 mux.Handle("/login", rtr)
105                 mux.Handle("/logout", rtr)
106         }
107
108         hs := http.NotFoundHandler()
109         hs = prepend(hs, h.proxyRailsAPI)
110         hs = h.setupProxyRemoteCluster(hs)
111         hs = prepend(hs, oidcAuthorizer.Middleware)
112         mux.Handle("/", hs)
113         h.handlerStack = mux
114
115         sc := *arvados.DefaultSecureClient
116         sc.CheckRedirect = neverRedirect
117         h.secureClient = &sc
118
119         ic := *arvados.InsecureHTTPClient
120         ic.CheckRedirect = neverRedirect
121         h.insecureClient = &ic
122
123         h.proxy = &proxy{
124                 Name: "arvados-controller",
125         }
126 }
127
128 var errDBConnection = errors.New("database connection error")
129
130 func (h *Handler) db(ctx context.Context) (*sqlx.DB, error) {
131         h.pgdbMtx.Lock()
132         defer h.pgdbMtx.Unlock()
133         if h.pgdb != nil {
134                 return h.pgdb, nil
135         }
136
137         db, err := sqlx.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
138         if err != nil {
139                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect failed")
140                 return nil, errDBConnection
141         }
142         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
143                 db.SetMaxOpenConns(p)
144         }
145         if err := db.Ping(); err != nil {
146                 ctxlog.FromContext(ctx).WithError(err).Error("postgresql connect succeeded but ping failed")
147                 return nil, errDBConnection
148         }
149         h.pgdb = db
150         return db, nil
151 }
152
153 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
154
155 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
156         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
157                 middleware(w, req, next)
158         })
159 }
160
161 func (h *Handler) localClusterRequest(req *http.Request) (*http.Response, error) {
162         urlOut, insecure, err := railsproxy.FindRailsAPI(h.Cluster)
163         if err != nil {
164                 return nil, err
165         }
166         urlOut = &url.URL{
167                 Scheme:   urlOut.Scheme,
168                 Host:     urlOut.Host,
169                 Path:     req.URL.Path,
170                 RawPath:  req.URL.RawPath,
171                 RawQuery: req.URL.RawQuery,
172         }
173         client := h.secureClient
174         if insecure {
175                 client = h.insecureClient
176         }
177         return h.proxy.Do(req, urlOut, client)
178 }
179
180 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
181         resp, err := h.localClusterRequest(req)
182         n, err := h.proxy.ForwardResponse(w, resp, err)
183         if err != nil {
184                 httpserver.Logger(req).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
185         }
186 }
187
188 // Use a localhost entry from Services.RailsAPI.InternalURLs if one is
189 // present, otherwise choose an arbitrary entry.
190 func findRailsAPI(cluster *arvados.Cluster) (*url.URL, bool, error) {
191         var best *url.URL
192         for target := range cluster.Services.RailsAPI.InternalURLs {
193                 target := url.URL(target)
194                 best = &target
195                 if strings.HasPrefix(target.Host, "localhost:") || strings.HasPrefix(target.Host, "127.0.0.1:") || strings.HasPrefix(target.Host, "[::1]:") {
196                         break
197                 }
198         }
199         if best == nil {
200                 return nil, false, fmt.Errorf("Services.RailsAPI.InternalURLs is empty")
201         }
202         return best, cluster.TLS.Insecure, nil
203 }