13493: Test OPTIONS method.
[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         "database/sql"
9         "errors"
10         "net"
11         "net/http"
12         "net/url"
13         "strings"
14         "sync"
15         "time"
16
17         "git.curoverse.com/arvados.git/sdk/go/arvados"
18         "git.curoverse.com/arvados.git/sdk/go/health"
19         "git.curoverse.com/arvados.git/sdk/go/httpserver"
20         _ "github.com/lib/pq"
21 )
22
23 type Handler struct {
24         Cluster     *arvados.Cluster
25         NodeProfile *arvados.NodeProfile
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         h.handlerStack.ServeHTTP(w, req)
39 }
40
41 func (h *Handler) CheckHealth() error {
42         h.setupOnce.Do(h.setup)
43         _, _, err := findRailsAPI(h.Cluster, h.NodeProfile)
44         return err
45 }
46
47 func (h *Handler) setup() {
48         mux := http.NewServeMux()
49         mux.Handle("/_health/", &health.Handler{
50                 Token:  h.Cluster.ManagementToken,
51                 Prefix: "/_health/",
52         })
53         hs := http.NotFoundHandler()
54         hs = prepend(hs, h.proxyRailsAPI)
55         hs = prepend(hs, h.proxyRemoteCluster)
56         mux.Handle("/", hs)
57         h.handlerStack = mux
58
59         sc := *arvados.DefaultSecureClient
60         sc.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
61         h.secureClient = &sc
62
63         ic := *arvados.InsecureHTTPClient
64         ic.Timeout = time.Duration(h.Cluster.HTTPRequestTimeout)
65         h.insecureClient = &ic
66
67         h.proxy = &proxy{
68                 Name:           "arvados-controller",
69                 RequestTimeout: time.Duration(h.Cluster.HTTPRequestTimeout),
70         }
71 }
72
73 var errDBConnection = errors.New("database connection error")
74
75 func (h *Handler) db(req *http.Request) (*sql.DB, error) {
76         h.pgdbMtx.Lock()
77         defer h.pgdbMtx.Unlock()
78         if h.pgdb != nil {
79                 return h.pgdb, nil
80         }
81
82         db, err := sql.Open("postgres", h.Cluster.PostgreSQL.Connection.String())
83         if err != nil {
84                 httpserver.Logger(req).WithError(err).Error("postgresql connect failed")
85                 return nil, errDBConnection
86         }
87         if p := h.Cluster.PostgreSQL.ConnectionPool; p > 0 {
88                 db.SetMaxOpenConns(p)
89         }
90         if err := db.Ping(); err != nil {
91                 httpserver.Logger(req).WithError(err).Error("postgresql connect succeeded but ping failed")
92                 return nil, errDBConnection
93         }
94         h.pgdb = db
95         return db, nil
96 }
97
98 type middlewareFunc func(http.ResponseWriter, *http.Request, http.Handler)
99
100 func prepend(next http.Handler, middleware middlewareFunc) http.Handler {
101         return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
102                 middleware(w, req, next)
103         })
104 }
105
106 func (h *Handler) proxyRailsAPI(w http.ResponseWriter, req *http.Request, next http.Handler) {
107         urlOut, insecure, err := findRailsAPI(h.Cluster, h.NodeProfile)
108         if err != nil {
109                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
110                 return
111         }
112         urlOut = &url.URL{
113                 Scheme:   urlOut.Scheme,
114                 Host:     urlOut.Host,
115                 Path:     req.URL.Path,
116                 RawPath:  req.URL.RawPath,
117                 RawQuery: req.URL.RawQuery,
118         }
119         client := h.secureClient
120         if insecure {
121                 client = h.insecureClient
122         }
123         h.proxy.Do(w, req, urlOut, client)
124 }
125
126 // For now, findRailsAPI always uses the rails API running on this
127 // node.
128 func findRailsAPI(cluster *arvados.Cluster, np *arvados.NodeProfile) (*url.URL, bool, error) {
129         hostport := np.RailsAPI.Listen
130         if len(hostport) > 1 && hostport[0] == ':' && strings.TrimRight(hostport[1:], "0123456789") == "" {
131                 // ":12345" => connect to indicated port on localhost
132                 hostport = "localhost" + hostport
133         } else if _, _, err := net.SplitHostPort(hostport); err == nil {
134                 // "[::1]:12345" => connect to indicated address & port
135         } else {
136                 return nil, false, err
137         }
138         proto := "http"
139         if np.RailsAPI.TLS {
140                 proto = "https"
141         }
142         url, err := url.Parse(proto + "://" + hostport)
143         return url, np.RailsAPI.Insecure, err
144 }