15954: Ensure stdout is copied before returning from RunProgram.
[arvados.git] / lib / boot / cmd.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         "bytes"
9         "context"
10         "crypto/rand"
11         "encoding/json"
12         "flag"
13         "fmt"
14         "io"
15         "io/ioutil"
16         "net"
17         "os"
18         "os/exec"
19         "os/signal"
20         "os/user"
21         "path/filepath"
22         "strings"
23         "sync"
24         "syscall"
25         "time"
26
27         "git.arvados.org/arvados.git/lib/cmd"
28         "git.arvados.org/arvados.git/lib/config"
29         "git.arvados.org/arvados.git/lib/service"
30         "git.arvados.org/arvados.git/sdk/go/arvados"
31         "git.arvados.org/arvados.git/sdk/go/ctxlog"
32         "git.arvados.org/arvados.git/sdk/go/health"
33         "github.com/sirupsen/logrus"
34 )
35
36 var Command cmd.Handler = bootCommand{}
37
38 type bootTask interface {
39         // Execute the task. Run should return nil when the task is
40         // done enough to satisfy a dependency relationship (e.g., the
41         // service is running and ready). If the task starts a
42         // goroutine that fails after Run returns (e.g., the service
43         // shuts down), it should call cancel.
44         Run(ctx context.Context, fail func(error), boot *Booter) error
45         String() string
46 }
47
48 type bootCommand struct{}
49
50 func (bootCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51         boot := &Booter{
52                 Stderr: stderr,
53                 logger: ctxlog.New(stderr, "json", "info"),
54         }
55
56         ctx := ctxlog.Context(context.Background(), boot.logger)
57         ctx, cancel := context.WithCancel(ctx)
58         defer cancel()
59
60         var err error
61         defer func() {
62                 if err != nil {
63                         boot.logger.WithError(err).Info("exiting")
64                 }
65         }()
66
67         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
68         flags.SetOutput(stderr)
69         loader := config.NewLoader(stdin, boot.logger)
70         loader.SetupFlags(flags)
71         versionFlag := flags.Bool("version", false, "Write version information to stdout and exit 0")
72         flags.StringVar(&boot.SourcePath, "source", ".", "arvados source tree `directory`")
73         flags.StringVar(&boot.LibPath, "lib", "/var/lib/arvados", "`directory` to install dependencies and library files")
74         flags.StringVar(&boot.ClusterType, "type", "production", "cluster `type`: development, test, or production")
75         flags.StringVar(&boot.ListenHost, "listen-host", "localhost", "host name or interface address for service listeners")
76         flags.StringVar(&boot.ControllerAddr, "controller-address", ":0", "desired controller address, `host:port` or `:port`")
77         flags.BoolVar(&boot.OwnTemporaryDatabase, "own-temporary-database", false, "bring up a postgres server and create a temporary database")
78         err = flags.Parse(args)
79         if err == flag.ErrHelp {
80                 err = nil
81                 return 0
82         } else if err != nil {
83                 return 2
84         } else if *versionFlag {
85                 return cmd.Version.RunCommand(prog, args, stdin, stdout, stderr)
86         } else if boot.ClusterType != "development" && boot.ClusterType != "test" && boot.ClusterType != "production" {
87                 err = fmt.Errorf("cluster type must be 'development', 'test', or 'production'")
88                 return 2
89         }
90
91         loader.SkipAPICalls = true
92         cfg, err := loader.Load()
93         if err != nil {
94                 return 1
95         }
96
97         boot.Start(ctx, cfg)
98         defer boot.Stop()
99         if url, ok := boot.WaitReady(); ok {
100                 fmt.Fprintln(stdout, url)
101                 // Wait for signal/crash + orderly shutdown
102                 <-boot.done
103                 return 0
104         } else {
105                 return 1
106         }
107 }
108
109 type Booter struct {
110         SourcePath           string // e.g., /home/username/src/arvados
111         LibPath              string // e.g., /var/lib/arvados
112         ClusterType          string // e.g., production
113         ListenHost           string // e.g., localhost
114         ControllerAddr       string // e.g., 127.0.0.1:8000
115         OwnTemporaryDatabase bool
116         Stderr               io.Writer
117
118         logger  logrus.FieldLogger
119         cluster *arvados.Cluster
120
121         ctx           context.Context
122         cancel        context.CancelFunc
123         done          chan struct{}
124         healthChecker *health.Aggregator
125         tasksReady    map[string]chan bool
126         waitShutdown  sync.WaitGroup
127
128         tempdir    string
129         configfile string
130         environ    []string // for child processes
131
132         setupRubyOnce sync.Once
133         setupRubyErr  error
134         goMutex       sync.Mutex
135 }
136
137 func (boot *Booter) Start(ctx context.Context, cfg *arvados.Config) {
138         boot.ctx, boot.cancel = context.WithCancel(ctx)
139         boot.done = make(chan struct{})
140
141         go func() {
142                 sigch := make(chan os.Signal)
143                 signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM)
144                 defer signal.Stop(sigch)
145                 go func() {
146                         for sig := range sigch {
147                                 boot.logger.WithField("signal", sig).Info("caught signal")
148                                 boot.cancel()
149                         }
150                 }()
151
152                 err := boot.run(cfg)
153                 if err != nil {
154                         fmt.Fprintln(boot.Stderr, err)
155                 }
156                 close(boot.done)
157         }()
158 }
159
160 func (boot *Booter) run(cfg *arvados.Config) error {
161         cwd, err := os.Getwd()
162         if err != nil {
163                 return err
164         }
165         if !strings.HasPrefix(boot.SourcePath, "/") {
166                 boot.SourcePath = filepath.Join(cwd, boot.SourcePath)
167         }
168         boot.SourcePath, err = filepath.EvalSymlinks(boot.SourcePath)
169         if err != nil {
170                 return err
171         }
172
173         boot.tempdir, err = ioutil.TempDir("", "arvados-server-boot-")
174         if err != nil {
175                 return err
176         }
177         defer os.RemoveAll(boot.tempdir)
178         if err := os.Mkdir(filepath.Join(boot.tempdir, "bin"), 0777); err != nil {
179                 return err
180         }
181
182         // Fill in any missing config keys, and write the resulting
183         // config in the temp dir for child services to use.
184         err = boot.autofillConfig(cfg, boot.logger)
185         if err != nil {
186                 return err
187         }
188         conffile, err := os.OpenFile(filepath.Join(boot.tempdir, "config.yml"), os.O_CREATE|os.O_WRONLY, 0777)
189         if err != nil {
190                 return err
191         }
192         defer conffile.Close()
193         err = json.NewEncoder(conffile).Encode(cfg)
194         if err != nil {
195                 return err
196         }
197         err = conffile.Close()
198         if err != nil {
199                 return err
200         }
201         boot.configfile = conffile.Name()
202
203         boot.environ = os.Environ()
204         boot.cleanEnv()
205         boot.setEnv("ARVADOS_CONFIG", boot.configfile)
206         boot.setEnv("RAILS_ENV", boot.ClusterType)
207         boot.setEnv("TMPDIR", boot.tempdir)
208         boot.prependEnv("PATH", filepath.Join(boot.tempdir, "bin")+":")
209         boot.prependEnv("PATH", filepath.Join(boot.LibPath, "bin")+":")
210
211         boot.cluster, err = cfg.GetCluster("")
212         if err != nil {
213                 return err
214         }
215         // Now that we have the config, replace the bootstrap logger
216         // with a new one according to the logging config.
217         loglevel := boot.cluster.SystemLogs.LogLevel
218         if s := os.Getenv("ARVADOS_DEBUG"); s != "" && s != "0" {
219                 loglevel = "debug"
220         }
221         boot.logger = ctxlog.New(boot.Stderr, boot.cluster.SystemLogs.Format, loglevel).WithFields(logrus.Fields{
222                 "PID": os.Getpid(),
223         })
224
225         for _, dir := range []string{boot.LibPath, filepath.Join(boot.LibPath, "bin")} {
226                 if _, err = os.Stat(filepath.Join(dir, ".")); os.IsNotExist(err) {
227                         err = os.Mkdir(dir, 0755)
228                         if err != nil {
229                                 return err
230                         }
231                 } else if err != nil {
232                         return err
233                 }
234         }
235         err = boot.installGoProgram(boot.ctx, "cmd/arvados-server")
236         if err != nil {
237                 return err
238         }
239         err = boot.setupRubyEnv()
240         if err != nil {
241                 return err
242         }
243
244         tasks := []bootTask{
245                 createCertificates{},
246                 runPostgreSQL{},
247                 runNginx{},
248                 runServiceCommand{name: "controller", svc: boot.cluster.Services.Controller, depends: []bootTask{runPostgreSQL{}}},
249                 runGoProgram{src: "services/arv-git-httpd"},
250                 runGoProgram{src: "services/health"},
251                 runGoProgram{src: "services/keepproxy", depends: []bootTask{runPassenger{src: "services/api"}}},
252                 runGoProgram{src: "services/keepstore", svc: boot.cluster.Services.Keepstore},
253                 runGoProgram{src: "services/keep-web"},
254                 runGoProgram{src: "services/ws", depends: []bootTask{runPostgreSQL{}}},
255                 installPassenger{src: "services/api"},
256                 runPassenger{src: "services/api", svc: boot.cluster.Services.RailsAPI, depends: []bootTask{createCertificates{}, runPostgreSQL{}, installPassenger{src: "services/api"}}},
257                 installPassenger{src: "apps/workbench", depends: []bootTask{installPassenger{src: "services/api"}}}, // dependency ensures workbench doesn't delay api startup
258                 runPassenger{src: "apps/workbench", svc: boot.cluster.Services.Workbench1, depends: []bootTask{installPassenger{src: "apps/workbench"}}},
259                 seedDatabase{},
260         }
261         if boot.ClusterType != "test" {
262                 tasks = append(tasks,
263                         runServiceCommand{name: "dispatch-cloud", svc: boot.cluster.Services.Controller},
264                         runGoProgram{src: "services/keep-balance"},
265                 )
266         }
267         boot.tasksReady = map[string]chan bool{}
268         for _, task := range tasks {
269                 boot.tasksReady[task.String()] = make(chan bool)
270         }
271         for _, task := range tasks {
272                 task := task
273                 fail := func(err error) {
274                         if boot.ctx.Err() != nil {
275                                 return
276                         }
277                         boot.cancel()
278                         boot.logger.WithField("task", task.String()).WithError(err).Error("task failed")
279                 }
280                 go func() {
281                         boot.logger.WithField("task", task.String()).Info("starting")
282                         err := task.Run(boot.ctx, fail, boot)
283                         if err != nil {
284                                 fail(err)
285                                 return
286                         }
287                         close(boot.tasksReady[task.String()])
288                 }()
289         }
290         err = boot.wait(boot.ctx, tasks...)
291         if err != nil {
292                 return err
293         }
294         boot.logger.Info("all startup tasks are complete; starting health checks")
295         boot.healthChecker = &health.Aggregator{Cluster: boot.cluster}
296         <-boot.ctx.Done()
297         boot.logger.Info("shutting down")
298         boot.waitShutdown.Wait()
299         return boot.ctx.Err()
300 }
301
302 func (boot *Booter) wait(ctx context.Context, tasks ...bootTask) error {
303         for _, task := range tasks {
304                 ch, ok := boot.tasksReady[task.String()]
305                 if !ok {
306                         return fmt.Errorf("no such task: %s", task)
307                 }
308                 boot.logger.WithField("task", task.String()).Info("waiting")
309                 select {
310                 case <-ch:
311                         boot.logger.WithField("task", task.String()).Info("ready")
312                 case <-ctx.Done():
313                         boot.logger.WithField("task", task.String()).Info("task was never ready")
314                         return ctx.Err()
315                 }
316         }
317         return nil
318 }
319
320 func (boot *Booter) Stop() {
321         boot.cancel()
322         <-boot.done
323 }
324
325 func (boot *Booter) WaitReady() (*arvados.URL, bool) {
326         ticker := time.NewTicker(time.Second)
327         defer ticker.Stop()
328         for waiting := true; waiting; {
329                 select {
330                 case <-ticker.C:
331                 case <-boot.ctx.Done():
332                         return nil, false
333                 }
334                 if boot.healthChecker == nil {
335                         // not set up yet
336                         continue
337                 }
338                 resp := boot.healthChecker.ClusterHealth()
339                 // The overall health check (resp.Health=="OK") might
340                 // never pass due to missing components (like
341                 // arvados-dispatch-cloud in a test cluster), so
342                 // instead we wait for all configured components to
343                 // pass.
344                 waiting = false
345                 for target, check := range resp.Checks {
346                         if check.Health != "OK" {
347                                 waiting = true
348                                 boot.logger.WithField("target", target).Debug("waiting")
349                         }
350                 }
351         }
352         u := boot.cluster.Services.Controller.ExternalURL
353         return &u, true
354 }
355
356 func (boot *Booter) prependEnv(key, prepend string) {
357         for i, s := range boot.environ {
358                 if strings.HasPrefix(s, key+"=") {
359                         boot.environ[i] = key + "=" + prepend + s[len(key)+1:]
360                         return
361                 }
362         }
363         boot.environ = append(boot.environ, key+"="+prepend)
364 }
365
366 var cleanEnvPrefixes = []string{
367         "GEM_HOME=",
368         "GEM_PATH=",
369         "ARVADOS_",
370 }
371
372 func (boot *Booter) cleanEnv() {
373         var cleaned []string
374         for _, s := range boot.environ {
375                 drop := false
376                 for _, p := range cleanEnvPrefixes {
377                         if strings.HasPrefix(s, p) {
378                                 drop = true
379                                 break
380                         }
381                 }
382                 if !drop {
383                         cleaned = append(cleaned, s)
384                 }
385         }
386         boot.environ = cleaned
387 }
388
389 func (boot *Booter) setEnv(key, val string) {
390         for i, s := range boot.environ {
391                 if strings.HasPrefix(s, key+"=") {
392                         boot.environ[i] = key + "=" + val
393                         return
394                 }
395         }
396         boot.environ = append(boot.environ, key+"="+val)
397 }
398
399 // Remove all but the first occurrence of each env var.
400 func dedupEnv(in []string) []string {
401         saw := map[string]bool{}
402         var out []string
403         for _, kv := range in {
404                 if split := strings.Index(kv, "="); split < 1 {
405                         panic("invalid environment var: " + kv)
406                 } else if saw[kv[:split]] {
407                         continue
408                 } else {
409                         saw[kv[:split]] = true
410                         out = append(out, kv)
411                 }
412         }
413         return out
414 }
415
416 func (boot *Booter) installGoProgram(ctx context.Context, srcpath string) error {
417         boot.goMutex.Lock()
418         defer boot.goMutex.Unlock()
419         return boot.RunProgram(ctx, filepath.Join(boot.SourcePath, srcpath), nil, []string{"GOBIN=" + boot.tempdir + "/bin"}, "go", "install")
420 }
421
422 func (boot *Booter) setupRubyEnv() error {
423         cmd := exec.Command("gem", "env", "gempath")
424         cmd.Env = boot.environ
425         buf, err := cmd.Output() // /var/lib/arvados/.gem/ruby/2.5.0/bin:...
426         if err != nil || len(buf) == 0 {
427                 return fmt.Errorf("gem env gempath: %v", err)
428         }
429         gempath := string(bytes.Split(buf, []byte{':'})[0])
430         boot.prependEnv("PATH", gempath+"/bin:")
431         boot.setEnv("GEM_HOME", gempath)
432         boot.setEnv("GEM_PATH", gempath)
433         // Passenger install doesn't work unless $HOME is ~user
434         u, err := user.Current()
435         if err != nil {
436                 return err
437         }
438         boot.setEnv("HOME", u.HomeDir)
439         return nil
440 }
441
442 func (boot *Booter) lookPath(prog string) string {
443         for _, val := range boot.environ {
444                 if strings.HasPrefix(val, "PATH=") {
445                         for _, dir := range filepath.SplitList(val[5:]) {
446                                 path := filepath.Join(dir, prog)
447                                 if fi, err := os.Stat(path); err == nil && fi.Mode()&0111 != 0 {
448                                         return path
449                                 }
450                         }
451                 }
452         }
453         return prog
454 }
455
456 // Run prog with args, using dir as working directory. If ctx is
457 // cancelled while the child is running, RunProgram terminates the
458 // child, waits for it to exit, then returns.
459 //
460 // Child's environment will have our env vars, plus any given in env.
461 //
462 // Child's stdout will be written to output if non-nil, otherwise the
463 // boot command's stderr.
464 func (boot *Booter) RunProgram(ctx context.Context, dir string, output io.Writer, env []string, prog string, args ...string) error {
465         cmdline := fmt.Sprintf("%s", append([]string{prog}, args...))
466         boot.logger.WithField("command", cmdline).WithField("dir", dir).Info("executing")
467
468         logprefix := strings.TrimPrefix(prog, boot.tempdir+"/bin/")
469         if prog == "bundle" && len(args) > 2 && args[0] == "exec" {
470                 logprefix = args[1]
471         } else if prog == "arvados-server" && len(args) > 1 {
472                 logprefix = args[0]
473         }
474         if !strings.HasPrefix(dir, "/") {
475                 logprefix = dir + ": " + logprefix
476         }
477
478         cmd := exec.Command(boot.lookPath(prog), args...)
479         stdout, err := cmd.StdoutPipe()
480         if err != nil {
481                 return err
482         }
483         stderr, err := cmd.StderrPipe()
484         if err != nil {
485                 return err
486         }
487         logwriter := &service.LogPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
488         var copiers sync.WaitGroup
489         copiers.Add(1)
490         go func() {
491                 io.Copy(logwriter, stderr)
492                 copiers.Done()
493         }()
494         copiers.Add(1)
495         go func() {
496                 if output == nil {
497                         io.Copy(logwriter, stdout)
498                 } else {
499                         io.Copy(output, stdout)
500                 }
501                 copiers.Done()
502         }()
503
504         if strings.HasPrefix(dir, "/") {
505                 cmd.Dir = dir
506         } else {
507                 cmd.Dir = filepath.Join(boot.SourcePath, dir)
508         }
509         env = append([]string(nil), env...)
510         env = append(env, boot.environ...)
511         cmd.Env = dedupEnv(env)
512
513         exited := false
514         defer func() { exited = true }()
515         go func() {
516                 <-ctx.Done()
517                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
518                 for !exited {
519                         if cmd.Process == nil {
520                                 log.Debug("waiting for child process to start")
521                                 time.Sleep(time.Second / 2)
522                         } else {
523                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
524                                 cmd.Process.Signal(syscall.SIGTERM)
525                                 time.Sleep(5 * time.Second)
526                                 if !exited {
527                                         stdout.Close()
528                                         stderr.Close()
529                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
530                                 }
531                         }
532                 }
533         }()
534
535         err = cmd.Start()
536         if err != nil {
537                 return err
538         }
539         copiers.Wait()
540         err = cmd.Wait()
541         if ctx.Err() != nil {
542                 // Return "context canceled", instead of the "killed"
543                 // error that was probably caused by the context being
544                 // canceled.
545                 return ctx.Err()
546         } else if err != nil {
547                 return fmt.Errorf("%s: error: %v", cmdline, err)
548         }
549         return nil
550 }
551
552 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
553         cluster, err := cfg.GetCluster("")
554         if err != nil {
555                 return err
556         }
557         usedPort := map[string]bool{}
558         nextPort := func() string {
559                 for {
560                         port, err := availablePort(":0")
561                         if err != nil {
562                                 panic(err)
563                         }
564                         if usedPort[port] {
565                                 continue
566                         }
567                         usedPort[port] = true
568                         return port
569                 }
570         }
571         if cluster.Services.Controller.ExternalURL.Host == "" {
572                 h, p, err := net.SplitHostPort(boot.ControllerAddr)
573                 if err != nil {
574                         return err
575                 }
576                 if h == "" {
577                         h = boot.ListenHost
578                 }
579                 if p == "0" {
580                         p, err = availablePort(":0")
581                         if err != nil {
582                                 return err
583                         }
584                         usedPort[p] = true
585                 }
586                 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
587         }
588         for _, svc := range []*arvados.Service{
589                 &cluster.Services.Controller,
590                 &cluster.Services.DispatchCloud,
591                 &cluster.Services.GitHTTP,
592                 &cluster.Services.Health,
593                 &cluster.Services.Keepproxy,
594                 &cluster.Services.Keepstore,
595                 &cluster.Services.RailsAPI,
596                 &cluster.Services.WebDAV,
597                 &cluster.Services.WebDAVDownload,
598                 &cluster.Services.Websocket,
599                 &cluster.Services.Workbench1,
600         } {
601                 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
602                         continue
603                 }
604                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
605                         svc == &cluster.Services.GitHTTP ||
606                         svc == &cluster.Services.Keepproxy ||
607                         svc == &cluster.Services.WebDAV ||
608                         svc == &cluster.Services.WebDAVDownload ||
609                         svc == &cluster.Services.Websocket ||
610                         svc == &cluster.Services.Workbench1) {
611                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
612                 }
613                 if len(svc.InternalURLs) == 0 {
614                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
615                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
616                         }
617                 }
618         }
619         if cluster.SystemRootToken == "" {
620                 cluster.SystemRootToken = randomHexString(64)
621         }
622         if cluster.ManagementToken == "" {
623                 cluster.ManagementToken = randomHexString(64)
624         }
625         if cluster.API.RailsSessionSecretToken == "" {
626                 cluster.API.RailsSessionSecretToken = randomHexString(64)
627         }
628         if cluster.Collections.BlobSigningKey == "" {
629                 cluster.Collections.BlobSigningKey = randomHexString(64)
630         }
631         if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
632                 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
633                 if err != nil {
634                         return err
635                 }
636                 cluster.Containers.DispatchPrivateKey = string(buf)
637         }
638         if boot.ClusterType != "production" {
639                 cluster.TLS.Insecure = true
640         }
641         if boot.ClusterType == "test" {
642                 // Add a second keepstore process.
643                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
644
645                 // Create a directory-backed volume for each keepstore
646                 // process.
647                 cluster.Volumes = map[string]arvados.Volume{}
648                 for url := range cluster.Services.Keepstore.InternalURLs {
649                         volnum := len(cluster.Volumes)
650                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
651                         if _, err = os.Stat(datadir + "/."); err == nil {
652                         } else if !os.IsNotExist(err) {
653                                 return err
654                         } else if err = os.Mkdir(datadir, 0777); err != nil {
655                                 return err
656                         }
657                         cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
658                                 Driver:           "Directory",
659                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
660                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
661                                         url: {},
662                                 },
663                         }
664                 }
665         }
666         if boot.OwnTemporaryDatabase {
667                 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
668                         "client_encoding": "utf8",
669                         "host":            "localhost",
670                         "port":            nextPort(),
671                         "dbname":          "arvados_test",
672                         "user":            "arvados",
673                         "password":        "insecure_arvados_test",
674                 }
675         }
676
677         cfg.Clusters[cluster.ClusterID] = *cluster
678         return nil
679 }
680
681 func randomHexString(chars int) string {
682         b := make([]byte, chars/2)
683         _, err := rand.Read(b)
684         if err != nil {
685                 panic(err)
686         }
687         return fmt.Sprintf("%x", b)
688 }
689
690 func internalPort(svc arvados.Service) (string, error) {
691         for u := range svc.InternalURLs {
692                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
693                         return "", err
694                 } else if p != "" {
695                         return p, nil
696                 } else if u.Scheme == "https" {
697                         return "443", nil
698                 } else {
699                         return "80", nil
700                 }
701         }
702         return "", fmt.Errorf("service has no InternalURLs")
703 }
704
705 func externalPort(svc arvados.Service) (string, error) {
706         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
707                 return "", err
708         } else if p != "" {
709                 return p, nil
710         } else if svc.ExternalURL.Scheme == "https" {
711                 return "443", nil
712         } else {
713                 return "80", nil
714         }
715 }
716
717 func availablePort(addr string) (string, error) {
718         ln, err := net.Listen("tcp", addr)
719         if err != nil {
720                 return "", err
721         }
722         defer ln.Close()
723         _, port, err := net.SplitHostPort(ln.Addr().String())
724         if err != nil {
725                 return "", err
726         }
727         return port, nil
728 }
729
730 // Try to connect to addr until it works, then close ch. Give up if
731 // ctx cancels.
732 func waitForConnect(ctx context.Context, addr string) error {
733         dialer := net.Dialer{Timeout: time.Second}
734         for ctx.Err() == nil {
735                 conn, err := dialer.DialContext(ctx, "tcp", addr)
736                 if err != nil {
737                         time.Sleep(time.Second / 10)
738                         continue
739                 }
740                 conn.Close()
741                 return nil
742         }
743         return ctx.Err()
744 }