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