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