f212254d23c48724e9e86dffe3d2171ab8b88994
[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         "os/user"
16         "path/filepath"
17         "regexp"
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         vars := map[string]string{
36                 "LISTENHOST":       super.ListenHost,
37                 "SSLCERT":          filepath.Join(super.tempdir, "server.crt"),
38                 "SSLKEY":           filepath.Join(super.tempdir, "server.key"),
39                 "ACCESSLOG":        filepath.Join(super.tempdir, "nginx_access.log"),
40                 "ERRORLOG":         filepath.Join(super.tempdir, "nginx_error.log"),
41                 "TMPDIR":           super.wwwtempdir,
42                 "ARVADOS_API_HOST": super.cluster.Services.Controller.ExternalURL.Host,
43         }
44         u := url.URL(super.cluster.Services.Controller.ExternalURL)
45         ctrlHost := u.Hostname()
46         if f, err := os.Open("/var/lib/acme/live/" + ctrlHost + "/privkey"); err == nil {
47                 f.Close()
48                 vars["SSLCERT"] = "/var/lib/acme/live/" + ctrlHost + "/cert"
49                 vars["SSLKEY"] = "/var/lib/acme/live/" + ctrlHost + "/privkey"
50         }
51         for _, cmpt := range []struct {
52                 varname string
53                 svc     arvados.Service
54         }{
55                 {"CONTROLLER", super.cluster.Services.Controller},
56                 {"KEEPWEB", super.cluster.Services.WebDAV},
57                 {"KEEPWEBDL", super.cluster.Services.WebDAVDownload},
58                 {"KEEPPROXY", super.cluster.Services.Keepproxy},
59                 {"GIT", super.cluster.Services.GitHTTP},
60                 {"HEALTH", super.cluster.Services.Health},
61                 {"WORKBENCH1", super.cluster.Services.Workbench1},
62                 {"WORKBENCH2", super.cluster.Services.Workbench2},
63                 {"WS", super.cluster.Services.Websocket},
64         } {
65                 var host, port string
66                 if len(cmpt.svc.InternalURLs) == 0 {
67                         // We won't run this service, but we need an
68                         // upstream port to write in our templated
69                         // nginx config. Choose a port that will
70                         // return 502 Bad Gateway.
71                         port = "9"
72                 } else if host, port, err = internalPort(cmpt.svc); err != nil {
73                         return fmt.Errorf("%s internal port: %w (%v)", cmpt.varname, err, cmpt.svc)
74                 } else if ok, err := addrIsLocal(net.JoinHostPort(host, port)); !ok || err != nil {
75                         return fmt.Errorf("%s addrIsLocal() failed for host %q port %q: %v", cmpt.varname, host, port, err)
76                 }
77                 vars[cmpt.varname+"PORT"] = port
78
79                 port, err = externalPort(cmpt.svc)
80                 if err != nil {
81                         return fmt.Errorf("%s external port: %w (%v)", cmpt.varname, err, cmpt.svc)
82                 }
83                 listenAddr := net.JoinHostPort(super.ListenHost, port)
84                 if ok, err := addrIsLocal(listenAddr); !ok || err != nil {
85                         return fmt.Errorf("%s addrIsLocal(%q) failed: %w", cmpt.varname, listenAddr, err)
86                 }
87                 vars[cmpt.varname+"SSLPORT"] = port
88         }
89         var conftemplate string
90         if super.ClusterType == "production" {
91                 conftemplate = "/var/lib/arvados/share/nginx.conf"
92         } else {
93                 conftemplate = filepath.Join(super.SourcePath, "sdk", "python", "tests", "nginx.conf")
94         }
95         tmpl, err := ioutil.ReadFile(conftemplate)
96         if err != nil {
97                 return err
98         }
99         conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
100                 if len(src) < 4 {
101                         return src
102                 }
103                 return vars[src[2:len(src)-2]]
104         })
105         conffile := filepath.Join(super.tempdir, "nginx.conf")
106         err = ioutil.WriteFile(conffile, []byte(conf), 0755)
107         if err != nil {
108                 return err
109         }
110         nginx := "nginx"
111         if _, err := exec.LookPath(nginx); err != nil {
112                 for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
113                         if _, err = os.Stat(dir + "/nginx"); err == nil {
114                                 nginx = dir + "/nginx"
115                                 break
116                         }
117                 }
118         }
119
120         args := []string{
121                 "-g", "error_log stderr info;",
122                 "-g", "pid " + filepath.Join(super.wwwtempdir, "nginx.pid") + ";",
123                 "-c", conffile,
124         }
125         // Nginx ignores "user www-data;" when running as a non-root
126         // user... except that it causes it to ignore our other -g
127         // options. So we still have to decide for ourselves whether
128         // it's needed.
129         if u, err := user.Current(); err != nil {
130                 return fmt.Errorf("user.Current(): %w", err)
131         } else if u.Uid == "0" {
132                 args = append([]string{"-g", "user www-data;"}, args...)
133         }
134
135         super.waitShutdown.Add(1)
136         go func() {
137                 defer super.waitShutdown.Done()
138                 fail(super.RunProgram(ctx, ".", runOptions{}, nginx, args...))
139         }()
140         // Choose one of the ports where Nginx should listen, and wait
141         // here until we can connect. If ExternalURL is https://foo (with no port) then we connect to "foo:https"
142         testurl := url.URL(super.cluster.Services.Controller.ExternalURL)
143         if testurl.Port() == "" {
144                 testurl.Host = net.JoinHostPort(testurl.Host, testurl.Scheme)
145         }
146         return waitForConnect(ctx, testurl.Host)
147 }