16552: Avoid port collision due to port assignment races in tests.
[arvados.git] / lib / boot / nginx.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package boot
6
7 import (
8         "context"
9         "fmt"
10         "io/ioutil"
11         "net"
12         "net/url"
13         "os"
14         "os/exec"
15         "path/filepath"
16         "regexp"
17         "strings"
18
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20 )
21
22 // Run an Nginx process that proxies the supervisor's configured
23 // ExternalURLs to the appropriate InternalURLs.
24 type runNginx struct{}
25
26 func (runNginx) String() string {
27         return "nginx"
28 }
29
30 func (runNginx) Run(ctx context.Context, fail func(error), super *Supervisor) error {
31         err := super.wait(ctx, createCertificates{})
32         if err != nil {
33                 return err
34         }
35         extListenHost := "0.0.0.0"
36         if super.ClusterType == "test" {
37                 // Our dynamic port number assignment strategy (choose
38                 // an available port, write it in a config file, and
39                 // have another process/goroutine bind to it) is prone
40                 // to races when used by concurrent supervisors. In
41                 // test mode we don't accept remote connections, so we
42                 // can avoid collisions by using the per-cluster
43                 // loopback address instead of 0.0.0.0.
44                 extListenHost = super.ListenHost
45         }
46         vars := map[string]string{
47                 "LISTENHOST":       extListenHost,
48                 "UPSTREAMHOST":     super.ListenHost,
49                 "SSLCERT":          filepath.Join(super.tempdir, "server.crt"),
50                 "SSLKEY":           filepath.Join(super.tempdir, "server.key"),
51                 "ACCESSLOG":        filepath.Join(super.tempdir, "nginx_access.log"),
52                 "ERRORLOG":         filepath.Join(super.tempdir, "nginx_error.log"),
53                 "TMPDIR":           super.wwwtempdir,
54                 "ARVADOS_API_HOST": super.cluster.Services.Controller.ExternalURL.Host,
55         }
56         u := url.URL(super.cluster.Services.Controller.ExternalURL)
57         ctrlHost := u.Hostname()
58         if strings.HasPrefix(super.cluster.TLS.Certificate, "file:/") && strings.HasPrefix(super.cluster.TLS.Key, "file:/") {
59                 vars["SSLCERT"] = filepath.Clean(super.cluster.TLS.Certificate[5:])
60                 vars["SSLKEY"] = filepath.Clean(super.cluster.TLS.Key[5:])
61         } else if f, err := os.Open("/var/lib/acme/live/" + ctrlHost + "/privkey"); err == nil {
62                 f.Close()
63                 vars["SSLCERT"] = "/var/lib/acme/live/" + ctrlHost + "/cert"
64                 vars["SSLKEY"] = "/var/lib/acme/live/" + ctrlHost + "/privkey"
65         }
66         for _, cmpt := range []struct {
67                 varname string
68                 svc     arvados.Service
69         }{
70                 {"CONTROLLER", super.cluster.Services.Controller},
71                 {"KEEPWEB", super.cluster.Services.WebDAV},
72                 {"KEEPWEBDL", super.cluster.Services.WebDAVDownload},
73                 {"KEEPPROXY", super.cluster.Services.Keepproxy},
74                 {"GIT", super.cluster.Services.GitHTTP},
75                 {"HEALTH", super.cluster.Services.Health},
76                 {"WORKBENCH1", super.cluster.Services.Workbench1},
77                 {"WORKBENCH2", super.cluster.Services.Workbench2},
78                 {"WS", super.cluster.Services.Websocket},
79         } {
80                 var host, port string
81                 if len(cmpt.svc.InternalURLs) == 0 {
82                         // We won't run this service, but we need an
83                         // upstream port to write in our templated
84                         // nginx config. Choose a port that will
85                         // return 502 Bad Gateway.
86                         port = "9"
87                 } else if host, port, err = internalPort(cmpt.svc); err != nil {
88                         return fmt.Errorf("%s internal port: %w (%v)", cmpt.varname, err, cmpt.svc)
89                 } else if ok, err := addrIsLocal(net.JoinHostPort(host, port)); !ok || err != nil {
90                         return fmt.Errorf("%s addrIsLocal() failed for host %q port %q: %v", cmpt.varname, host, port, err)
91                 }
92                 vars[cmpt.varname+"PORT"] = port
93
94                 port, err = externalPort(cmpt.svc)
95                 if err != nil {
96                         return fmt.Errorf("%s external port: %w (%v)", cmpt.varname, err, cmpt.svc)
97                 }
98                 listenAddr := net.JoinHostPort(super.ListenHost, port)
99                 if ok, err := addrIsLocal(listenAddr); !ok || err != nil {
100                         return fmt.Errorf("%s addrIsLocal(%q) failed: %w", cmpt.varname, listenAddr, err)
101                 }
102                 vars[cmpt.varname+"SSLPORT"] = port
103         }
104         var conftemplate string
105         if super.ClusterType == "production" {
106                 conftemplate = "/var/lib/arvados/share/nginx.conf"
107         } else {
108                 conftemplate = filepath.Join(super.SourcePath, "sdk", "python", "tests", "nginx.conf")
109         }
110         tmpl, err := ioutil.ReadFile(conftemplate)
111         if err != nil {
112                 return err
113         }
114         conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
115                 if len(src) < 4 {
116                         return src
117                 }
118                 return vars[src[2:len(src)-2]]
119         })
120         conffile := filepath.Join(super.tempdir, "nginx.conf")
121         err = ioutil.WriteFile(conffile, []byte(conf), 0755)
122         if err != nil {
123                 return err
124         }
125         nginx := "nginx"
126         if _, err := exec.LookPath(nginx); err != nil {
127                 for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
128                         if _, err = os.Stat(dir + "/nginx"); err == nil {
129                                 nginx = dir + "/nginx"
130                                 break
131                         }
132                 }
133         }
134
135         configs := "error_log stderr info; "
136         configs += "pid " + filepath.Join(super.wwwtempdir, "nginx.pid") + "; "
137         configs += "user www-data; "
138
139         super.waitShutdown.Add(1)
140         go func() {
141                 defer super.waitShutdown.Done()
142                 fail(super.RunProgram(ctx, ".", runOptions{}, nginx, "-g", configs, "-c", conffile))
143         }()
144         // Choose one of the ports where Nginx should listen, and wait
145         // here until we can connect. If ExternalURL is https://foo
146         // (with no port) then we connect to "foo:https"
147         testurl := url.URL(super.cluster.Services.Controller.ExternalURL)
148         if testurl.Port() == "" {
149                 testurl.Host = net.JoinHostPort(testurl.Host, testurl.Scheme)
150         }
151         return waitForConnect(ctx, testurl.Host)
152 }