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