19175: Merge branch 'main' into 19175-doc-refactor-multi-host-installation
[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
18         "git.arvados.org/arvados.git/sdk/go/arvados"
19 )
20
21 // Run an Nginx process that proxies the supervisor's configured
22 // ExternalURLs to the appropriate InternalURLs.
23 type runNginx struct{}
24
25 func (runNginx) String() string {
26         return "nginx"
27 }
28
29 func (runNginx) Run(ctx context.Context, fail func(error), super *Supervisor) error {
30         err := super.wait(ctx, createCertificates{})
31         if err != nil {
32                 return err
33         }
34         vars := map[string]string{
35                 "LISTENHOST":       super.ListenHost,
36                 "SSLCERT":          filepath.Join(super.tempdir, "server.crt"),
37                 "SSLKEY":           filepath.Join(super.tempdir, "server.key"),
38                 "ACCESSLOG":        filepath.Join(super.tempdir, "nginx_access.log"),
39                 "ERRORLOG":         filepath.Join(super.tempdir, "nginx_error.log"),
40                 "TMPDIR":           super.wwwtempdir,
41                 "ARVADOS_API_HOST": super.cluster.Services.Controller.ExternalURL.Host,
42         }
43         u := url.URL(super.cluster.Services.Controller.ExternalURL)
44         ctrlHost := u.Hostname()
45         if f, err := os.Open("/var/lib/acme/live/" + ctrlHost + "/privkey"); err == nil {
46                 f.Close()
47                 vars["SSLCERT"] = "/var/lib/acme/live/" + ctrlHost + "/cert"
48                 vars["SSLKEY"] = "/var/lib/acme/live/" + ctrlHost + "/privkey"
49         }
50         for _, cmpt := range []struct {
51                 varname string
52                 svc     arvados.Service
53         }{
54                 {"CONTROLLER", super.cluster.Services.Controller},
55                 {"KEEPWEB", super.cluster.Services.WebDAV},
56                 {"KEEPWEBDL", super.cluster.Services.WebDAVDownload},
57                 {"KEEPPROXY", super.cluster.Services.Keepproxy},
58                 {"GIT", super.cluster.Services.GitHTTP},
59                 {"HEALTH", super.cluster.Services.Health},
60                 {"WORKBENCH1", super.cluster.Services.Workbench1},
61                 {"WORKBENCH2", super.cluster.Services.Workbench2},
62                 {"WS", super.cluster.Services.Websocket},
63         } {
64                 var host, port string
65                 if len(cmpt.svc.InternalURLs) == 0 {
66                         // We won't run this service, but we need an
67                         // upstream port to write in our templated
68                         // nginx config. Choose a port that will
69                         // return 502 Bad Gateway.
70                         port = "9"
71                 } else if host, port, err = internalPort(cmpt.svc); err != nil {
72                         return fmt.Errorf("%s internal port: %w (%v)", cmpt.varname, err, cmpt.svc)
73                 } else if ok, err := addrIsLocal(net.JoinHostPort(host, port)); !ok || err != nil {
74                         return fmt.Errorf("%s addrIsLocal() failed for host %q port %q: %v", cmpt.varname, host, port, err)
75                 }
76                 vars[cmpt.varname+"PORT"] = port
77
78                 port, err = externalPort(cmpt.svc)
79                 if err != nil {
80                         return fmt.Errorf("%s external port: %w (%v)", cmpt.varname, err, cmpt.svc)
81                 }
82                 listenAddr := net.JoinHostPort(super.ListenHost, port)
83                 if ok, err := addrIsLocal(listenAddr); !ok || err != nil {
84                         return fmt.Errorf("%s addrIsLocal(%q) failed: %w", cmpt.varname, listenAddr, err)
85                 }
86                 vars[cmpt.varname+"SSLPORT"] = port
87         }
88         var conftemplate string
89         if super.ClusterType == "production" {
90                 conftemplate = "/var/lib/arvados/share/nginx.conf"
91         } else {
92                 conftemplate = filepath.Join(super.SourcePath, "sdk", "python", "tests", "nginx.conf")
93         }
94         tmpl, err := ioutil.ReadFile(conftemplate)
95         if err != nil {
96                 return err
97         }
98         conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
99                 if len(src) < 4 {
100                         return src
101                 }
102                 return vars[src[2:len(src)-2]]
103         })
104         conffile := filepath.Join(super.tempdir, "nginx.conf")
105         err = ioutil.WriteFile(conffile, []byte(conf), 0755)
106         if err != nil {
107                 return err
108         }
109         nginx := "nginx"
110         if _, err := exec.LookPath(nginx); err != nil {
111                 for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
112                         if _, err = os.Stat(dir + "/nginx"); err == nil {
113                                 nginx = dir + "/nginx"
114                                 break
115                         }
116                 }
117         }
118
119         configs := "error_log stderr info; "
120         configs += "pid " + filepath.Join(super.wwwtempdir, "nginx.pid") + "; "
121         configs += "user www-data; "
122
123         super.waitShutdown.Add(1)
124         go func() {
125                 defer super.waitShutdown.Done()
126                 fail(super.RunProgram(ctx, ".", runOptions{}, nginx, "-g", configs, "-c", conffile))
127         }()
128         // Choose one of the ports where Nginx should listen, and wait
129         // here until we can connect. If ExternalURL is https://foo
130         // (with no port) then we connect to "foo:https"
131         testurl := url.URL(super.cluster.Services.Controller.ExternalURL)
132         if testurl.Port() == "" {
133                 testurl.Host = net.JoinHostPort(testurl.Host, testurl.Scheme)
134         }
135         return waitForConnect(ctx, testurl.Host)
136 }