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