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