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