15954: Add health/proxy/dav services.
authorTom Clegg <tom@tomclegg.ca>
Fri, 24 Jan 2020 20:28:28 +0000 (15:28 -0500)
committerTom Clegg <tom@tomclegg.ca>
Mon, 27 Jan 2020 15:14:19 +0000 (10:14 -0500)
Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tom@tomclegg.ca>

lib/boot/cmd.go
lib/boot/nginx.go [new file with mode: 0644]
sdk/python/tests/nginx.conf
sdk/python/tests/run_test_server.py

index 4ac6d4a2141fcd079f937ddbf6ee265aa98cbef4..8d20e5f6c66792cb052873fe7d41404d524ec0b3 100644 (file)
@@ -39,8 +39,11 @@ type bootCommand struct {
        libPath     string // e.g., /var/lib/arvados
        clusterType string // e.g., production
 
-       stdout io.Writer
-       stderr io.Writer
+       cluster *arvados.Cluster
+       stdout  io.Writer
+       stderr  io.Writer
+
+       tempdir string
 
        setupRubyOnce sync.Once
        setupRubyErr  error
@@ -98,11 +101,11 @@ func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader,
                return 1
        }
 
-       tempdir, err := ioutil.TempDir("", "arvados-server-boot-")
+       boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
        if err != nil {
                return 1
        }
-       defer os.RemoveAll(tempdir)
+       defer os.RemoveAll(boot.tempdir)
 
        // Fill in any missing config keys, and write the resulting
        // config in the temp dir for child services to use.
@@ -110,7 +113,7 @@ func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader,
        if err != nil {
                return 1
        }
-       conffile, err := os.OpenFile(filepath.Join(tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
+       conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
        if err != nil {
                return 1
        }
@@ -124,16 +127,16 @@ func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader,
                return 1
        }
        os.Setenv("ARVADOS_CONFIG", conffile.Name())
-
+       arvados.DefaultConfigFile = conffile.Name()
        os.Setenv("RAILS_ENV", boot.clusterType)
 
        // Now that we have the config, replace the bootstrap logger
        // with a new one according to the logging config.
-       cluster, err := cfg.GetCluster("")
+       boot.cluster, err = cfg.GetCluster("")
        if err != nil {
                return 1
        }
-       log = ctxlog.New(stderr, cluster.SystemLogs.Format, cluster.SystemLogs.LogLevel)
+       log = ctxlog.New(stderr, boot.cluster.SystemLogs.Format, boot.cluster.SystemLogs.LogLevel)
        logger := log.WithFields(logrus.Fields{
                "PID": os.Getpid(),
        })
@@ -169,10 +172,15 @@ func (boot *bootCommand) RunCommand(prog string, args []string, stdin io.Reader,
 
        var wg sync.WaitGroup
        for _, cmpt := range []component{
+               {name: "nginx", runFunc: runNginx},
                {name: "controller", cmdHandler: controller.Command},
                {name: "dispatchcloud", cmdHandler: dispatchcloud.Command, notIfTest: true},
+               {name: "git-httpd", goProg: "services/arv-git-httpd"},
+               {name: "health", goProg: "services/health"},
+               {name: "keep-balance", goProg: "services/keep-balance", notIfTest: true},
                {name: "keepproxy", goProg: "services/keepproxy"},
-               {name: "railsAPI", svc: cluster.Services.RailsAPI, railsApp: "services/api"},
+               {name: "keep-web", goProg: "services/keep-web"},
+               {name: "railsAPI", svc: boot.cluster.Services.RailsAPI, railsApp: "services/api"},
        } {
                cmpt := cmpt
                wg.Add(1)
@@ -233,13 +241,13 @@ func (boot *bootCommand) RunProgram(ctx context.Context, dir string, output io.W
        go func() {
                <-ctx.Done()
                log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
-               for cmd.ProcessState != nil {
+               for cmd.ProcessState == nil {
                        if cmd.Process == nil {
                                log.Infof("waiting for child process to start")
                                time.Sleep(time.Second)
                        } else {
-                               cmd.Process.Signal(syscall.SIGINT)
-                               log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGINT")
+                               cmd.Process.Signal(syscall.SIGTERM)
+                               log.WithField("PID", cmd.Process.Pid).Infof("waiting for child process to exit after SIGTERM")
                                time.Sleep(5 * time.Second)
                        }
                }
@@ -255,6 +263,7 @@ type component struct {
        name       string
        svc        arvados.Service
        cmdHandler cmd.Handler
+       runFunc    func(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error
        railsApp   string // source dir in arvados tree, e.g., "services/api"
        goProg     string // source dir in arvados tree, e.g., "services/keepstore"
        notIfTest  bool   // don't run this component on a test cluster
@@ -262,7 +271,7 @@ type component struct {
 
 func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
        if cmpt.notIfTest && boot.clusterType == "test" {
-               fmt.Fprintf(stderr, "skipping component %q\n", cmpt.name)
+               fmt.Fprintf(stderr, "skipping component %q in %s mode\n", cmpt.name, boot.clusterType)
                <-ctx.Done()
                return nil
        }
@@ -289,25 +298,15 @@ func (cmpt *component) Run(ctx context.Context, boot *bootCommand, stdout, stder
        if cmpt.goProg != "" {
                return boot.RunProgram(ctx, cmpt.goProg, nil, nil, "go", "run", ".")
        }
+       if cmpt.runFunc != nil {
+               return cmpt.runFunc(ctx, boot, stdout, stderr)
+       }
        if cmpt.railsApp != "" {
-               port := "-"
-               for u := range cmpt.svc.InternalURLs {
-                       if _, p, err := net.SplitHostPort(u.Host); err != nil {
-                               return err
-                       } else if p != "" {
-                               port = p
-                       } else if u.Scheme == "https" {
-                               port = "443"
-                       } else {
-                               port = "80"
-                       }
-                       break
-               }
-               if port == "-" {
+               port, err := internalPort(cmpt.svc)
+               if err != nil {
                        return fmt.Errorf("bug: no InternalURLs for component %q: %v", cmpt.name, cmpt.svc.InternalURLs)
                }
-
-               err := boot.setupRubyEnv()
+               err = boot.setupRubyEnv()
                if err != nil {
                        return err
                }
@@ -358,7 +357,14 @@ func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLog
        for _, svc := range []*arvados.Service{
                &cluster.Services.Controller,
                &cluster.Services.DispatchCloud,
+               &cluster.Services.GitHTTP,
+               &cluster.Services.Health,
+               &cluster.Services.Keepproxy,
+               &cluster.Services.Keepstore,
                &cluster.Services.RailsAPI,
+               &cluster.Services.WebDAV,
+               &cluster.Services.WebDAVDownload,
+               &cluster.Services.Websocket,
        } {
                if len(svc.InternalURLs) == 0 {
                        port++
@@ -366,15 +372,22 @@ func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLog
                                arvados.URL{Scheme: "http", Host: fmt.Sprintf("localhost:%d", port)}: arvados.ServiceInstance{},
                        }
                }
-       }
-       if cluster.Services.Controller.ExternalURL.Host == "" {
-               for k := range cluster.Services.Controller.InternalURLs {
-                       cluster.Services.Controller.ExternalURL = k
+               if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
+                       svc == &cluster.Services.GitHTTP ||
+                       svc == &cluster.Services.Keepproxy ||
+                       svc == &cluster.Services.WebDAV ||
+                       svc == &cluster.Services.WebDAVDownload ||
+                       svc == &cluster.Services.Websocket) {
+                       port++
+                       svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("localhost:%d", port)}
                }
        }
        if cluster.SystemRootToken == "" {
                cluster.SystemRootToken = randomHexString(64)
        }
+       if cluster.ManagementToken == "" {
+               cluster.ManagementToken = randomHexString(64)
+       }
        if cluster.API.RailsSessionSecretToken == "" {
                cluster.API.RailsSessionSecretToken = randomHexString(64)
        }
@@ -388,6 +401,17 @@ func (boot *bootCommand) autofillConfig(cfg *arvados.Config, log logrus.FieldLog
                }
                cluster.Containers.DispatchPrivateKey = string(buf)
        }
+       if boot.clusterType != "production" {
+               cluster.TLS.Insecure = true
+       }
+       if boot.clusterType == "test" && len(cluster.Volumes) == 0 {
+               cluster.Volumes = map[string]arvados.Volume{
+                       "zzzzz-nyw5e-000000000000000": arvados.Volume{
+                               Driver:           "Directory",
+                               DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, boot.tempdir+"/keep0")),
+                       },
+               }
+       }
        cfg.Clusters[cluster.ClusterID] = *cluster
        return nil
 }
@@ -400,3 +424,30 @@ func randomHexString(chars int) string {
        }
        return fmt.Sprintf("%x", b)
 }
+
+func internalPort(svc arvados.Service) (string, error) {
+       for u := range svc.InternalURLs {
+               if _, p, err := net.SplitHostPort(u.Host); err != nil {
+                       return "", err
+               } else if p != "" {
+                       return p, nil
+               } else if u.Scheme == "https" {
+                       return "443", nil
+               } else {
+                       return "80", nil
+               }
+       }
+       return "", fmt.Errorf("service has no InternalURLs")
+}
+
+func externalPort(svc arvados.Service) (string, error) {
+       if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
+               return "", err
+       } else if p != "" {
+               return p, nil
+       } else if svc.ExternalURL.Scheme == "https" {
+               return "443", nil
+       } else {
+               return "80", nil
+       }
+}
diff --git a/lib/boot/nginx.go b/lib/boot/nginx.go
new file mode 100644 (file)
index 0000000..11d823f
--- /dev/null
@@ -0,0 +1,77 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
+package boot
+
+import (
+       "context"
+       "fmt"
+       "io"
+       "io/ioutil"
+       "os"
+       "os/exec"
+       "path/filepath"
+       "regexp"
+
+       "git.arvados.org/arvados.git/sdk/go/arvados"
+)
+
+func runNginx(ctx context.Context, boot *bootCommand, stdout, stderr io.Writer) error {
+       vars := map[string]string{
+               "SSLCERT":   filepath.Join(boot.sourcePath, "services", "api", "tmp", "self-signed.pem"), // TODO: root ca
+               "SSLKEY":    filepath.Join(boot.sourcePath, "services", "api", "tmp", "self-signed.key"), // TODO: root ca
+               "ACCESSLOG": filepath.Join(boot.tempdir, "nginx_access.log"),
+               "ERRORLOG":  filepath.Join(boot.tempdir, "nginx_error.log"),
+               "TMPDIR":    boot.tempdir,
+       }
+       var err error
+       for _, cmpt := range []struct {
+               varname string
+               svc     arvados.Service
+       }{
+               {"CONTROLLER", boot.cluster.Services.Controller},
+               {"KEEPWEB", boot.cluster.Services.WebDAV},
+               {"KEEPWEBDL", boot.cluster.Services.WebDAVDownload},
+               {"KEEPPROXY", boot.cluster.Services.Keepproxy},
+               {"GIT", boot.cluster.Services.GitHTTP},
+               {"WS", boot.cluster.Services.Websocket},
+       } {
+               vars[cmpt.varname+"PORT"], err = internalPort(cmpt.svc)
+               if err != nil {
+                       return fmt.Errorf("%s internal port: %s (%v)", cmpt.varname, err, cmpt.svc)
+               }
+               vars[cmpt.varname+"SSLPORT"], err = externalPort(cmpt.svc)
+               if err != nil {
+                       return fmt.Errorf("%s external port: %s (%v)", cmpt.varname, err, cmpt.svc)
+               }
+       }
+       tmpl, err := ioutil.ReadFile(filepath.Join(boot.sourcePath, "sdk", "python", "tests", "nginx.conf"))
+       if err != nil {
+               return err
+       }
+       conf := regexp.MustCompile(`{{.*?}}`).ReplaceAllStringFunc(string(tmpl), func(src string) string {
+               if len(src) < 4 {
+                       return src
+               }
+               return vars[src[2:len(src)-2]]
+       })
+       conffile := filepath.Join(boot.tempdir, "nginx.conf")
+       err = ioutil.WriteFile(conffile, []byte(conf), 0755)
+       if err != nil {
+               return err
+       }
+       nginx := "nginx"
+       if _, err := exec.LookPath(nginx); err != nil {
+               for _, dir := range []string{"/sbin", "/usr/sbin", "/usr/local/sbin"} {
+                       if _, err = os.Stat(dir + "/nginx"); err == nil {
+                               nginx = dir + "/nginx"
+                               break
+                       }
+               }
+       }
+       return boot.RunProgram(ctx, ".", nil, nil, nginx,
+               "-g", "error_log stderr info;",
+               "-g", "pid "+filepath.Join(boot.tempdir, "nginx.pid")+";",
+               "-c", conffile)
+}
index 6010ee4bf73e0fc0278c672b41a20c0ecaa35532..e9be122354c933dbea9b828b093a1ca295c087e7 100644 (file)
@@ -92,7 +92,7 @@ http {
     server localhost:{{WSPORT}};
   }
   server {
-    listen *:{{WSSPORT}} ssl default_server;
+    listen *:{{WSSSLPORT}} ssl default_server;
     server_name websocket;
     ssl_certificate "{{SSLCERT}}";
     ssl_certificate_key "{{SSLKEY}}";
index 9e9b12f98ca6d09ed1fb65eb5c768acf23454bf5..5c05c124c642c7467d6252b8bcb420c8ca271767 100644 (file)
@@ -616,7 +616,7 @@ def run_nginx():
     nginxconf['GITPORT'] = internal_port_from_config("GitHTTP")
     nginxconf['GITSSLPORT'] = external_port_from_config("GitHTTP")
     nginxconf['WSPORT'] = internal_port_from_config("Websocket")
-    nginxconf['WSSPORT'] = external_port_from_config("Websocket")
+    nginxconf['WSSSLPORT'] = external_port_from_config("Websocket")
     nginxconf['SSLCERT'] = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'self-signed.pem')
     nginxconf['SSLKEY'] = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'self-signed.key')
     nginxconf['ACCESSLOG'] = _logfilename('nginx_access')