1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "github.com/sirupsen/logrus"
24 // Run an Nginx process that proxies the supervisor's configured
25 // ExternalURLs to the appropriate InternalURLs.
26 type runNginx struct{}
28 func (runNginx) String() string {
32 func (runNginx) Run(ctx context.Context, fail func(error), super *Supervisor) error {
33 err := super.wait(ctx, createCertificates{})
37 extListenHost := "0.0.0.0"
38 if super.ClusterType == "test" {
39 // Our dynamic port number assignment strategy (choose
40 // an available port, write it in a config file, and
41 // have another process/goroutine bind to it) is prone
42 // to races when used by concurrent supervisors. In
43 // test mode we don't accept remote connections, so we
44 // can avoid collisions by using the per-cluster
45 // loopback address instead of 0.0.0.0.
46 extListenHost = super.ListenHost
48 vars := map[string]string{
49 "LISTENHOST": extListenHost,
50 "UPSTREAMHOST": super.ListenHost,
51 "INTERNALSUBNETS": internalSubnets(super.logger),
52 "SSLCERT": filepath.Join(super.tempdir, "server.crt"),
53 "SSLKEY": filepath.Join(super.tempdir, "server.key"),
54 "ACCESSLOG": filepath.Join(super.tempdir, "nginx_access.log"),
55 "ERRORLOG": filepath.Join(super.tempdir, "nginx_error.log"),
56 "TMPDIR": super.wwwtempdir,
57 "ARVADOS_API_HOST": super.cluster.Services.Controller.ExternalURL.Host,
59 u := url.URL(super.cluster.Services.Controller.ExternalURL)
60 ctrlHost := u.Hostname()
61 if strings.HasPrefix(super.cluster.TLS.Certificate, "file:/") && strings.HasPrefix(super.cluster.TLS.Key, "file:/") {
62 vars["SSLCERT"] = filepath.Clean(super.cluster.TLS.Certificate[5:])
63 vars["SSLKEY"] = filepath.Clean(super.cluster.TLS.Key[5:])
64 } else if f, err := os.Open("/var/lib/acme/live/" + ctrlHost + "/privkey"); err == nil {
66 vars["SSLCERT"] = "/var/lib/acme/live/" + ctrlHost + "/cert"
67 vars["SSLKEY"] = "/var/lib/acme/live/" + ctrlHost + "/privkey"
69 for _, cmpt := range []struct {
73 {"CONTROLLER", super.cluster.Services.Controller},
74 {"KEEPWEB", super.cluster.Services.WebDAV},
75 {"KEEPWEBDL", super.cluster.Services.WebDAVDownload},
76 {"KEEPPROXY", super.cluster.Services.Keepproxy},
77 {"GIT", super.cluster.Services.GitHTTP},
78 {"HEALTH", super.cluster.Services.Health},
79 {"WORKBENCH1", super.cluster.Services.Workbench1},
80 {"WORKBENCH2", super.cluster.Services.Workbench2},
81 {"WS", super.cluster.Services.Websocket},
84 if len(cmpt.svc.InternalURLs) == 0 {
85 // We won't run this service, but we need an
86 // upstream port to write in our templated
87 // nginx config. Choose a port that will
88 // return 502 Bad Gateway.
90 } else if host, port, err = internalPort(cmpt.svc); err != nil {
91 return fmt.Errorf("%s internal port: %w (%v)", cmpt.varname, err, cmpt.svc)
92 } else if ok, err := addrIsLocal(net.JoinHostPort(host, port)); !ok || err != nil {
93 return fmt.Errorf("%s addrIsLocal() failed for host %q port %q: %v", cmpt.varname, host, port, err)
95 vars[cmpt.varname+"PORT"] = port
97 port, err = externalPort(cmpt.svc)
99 return fmt.Errorf("%s external port: %w (%v)", cmpt.varname, err, cmpt.svc)
101 listenAddr := net.JoinHostPort(super.ListenHost, port)
102 if ok, err := addrIsLocal(listenAddr); !ok || err != nil {
103 return fmt.Errorf("%s addrIsLocal(%q) failed: %w", cmpt.varname, listenAddr, err)
105 vars[cmpt.varname+"SSLPORT"] = port
107 var conftemplate string
108 if super.ClusterType == "production" {
109 conftemplate = "/var/lib/arvados/share/nginx.conf"
111 conftemplate = filepath.Join(super.SourcePath, "sdk", "python", "tests", "nginx.conf")
113 tmpl, err := ioutil.ReadFile(conftemplate)
117 conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
121 return vars[src[2:len(src)-2]]
123 conffile := filepath.Join(super.tempdir, "nginx.conf")
124 err = ioutil.WriteFile(conffile, []byte(conf), 0755)
129 if _, err := exec.LookPath(nginx); err != nil {
130 for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
131 if _, err = os.Stat(dir + "/nginx"); err == nil {
132 nginx = dir + "/nginx"
138 configs := "error_log stderr info; "
139 configs += "pid " + filepath.Join(super.wwwtempdir, "nginx.pid") + "; "
140 configs += "user www-data; "
142 super.waitShutdown.Add(1)
144 defer super.waitShutdown.Done()
145 fail(super.RunProgram(ctx, ".", runOptions{}, nginx, "-g", configs, "-c", conffile))
147 // Choose one of the ports where Nginx should listen, and wait
148 // here until we can connect. If ExternalURL is https://foo
149 // (with no port) then we connect to "foo:https"
150 testurl := url.URL(super.cluster.Services.Controller.ExternalURL)
151 if testurl.Port() == "" {
152 testurl.Host = net.JoinHostPort(testurl.Host, testurl.Scheme)
154 return waitForConnect(ctx, testurl.Host)
157 // Return 0 or more local subnets as "geo" fragments for Nginx config,
158 // e.g., "1.2.3.0/24 0; 10.1.0.0/16 0;".
159 func internalSubnets(logger logrus.FieldLogger) string {
160 iproutes, err := exec.Command("ip", "route").CombinedOutput()
162 logger.Warnf("treating all clients as external because `ip route` failed: %s (%q)", err, iproutes)
166 for _, line := range bytes.Split(iproutes, []byte("\n")) {
167 fields := strings.Fields(string(line))
168 if len(fields) > 2 && fields[1] == "dev" {
170 // 192.168.86.0/24 dev ens3 proto kernel scope link src 192.168.86.196
171 // gcp example (private subnet):
172 // 10.47.0.0/24 dev eth0 proto kernel scope link src 10.47.0.5
173 // gcp example (no private subnet):
174 // 10.128.0.1 dev ens4 scope link
175 subnets += fields[0] + " 0; "