15954: Handle signals when used as module.
[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         stderr := &logPrefixer{Writer: boot.Stderr, Prefix: []byte("[" + logprefix + "] ")}
448
449         cmd := exec.Command(boot.lookPath(prog), args...)
450         if output == nil {
451                 cmd.Stdout = stderr
452         } else {
453                 cmd.Stdout = output
454         }
455         cmd.Stderr = stderr
456         if strings.HasPrefix(dir, "/") {
457                 cmd.Dir = dir
458         } else {
459                 cmd.Dir = filepath.Join(boot.SourcePath, dir)
460         }
461         cmd.Env = append(env, boot.environ...)
462
463         exited := false
464         defer func() { exited = true }()
465         go func() {
466                 <-ctx.Done()
467                 log := ctxlog.FromContext(ctx).WithFields(logrus.Fields{"dir": dir, "cmdline": cmdline})
468                 for !exited {
469                         if cmd.Process == nil {
470                                 log.Debug("waiting for child process to start")
471                                 time.Sleep(time.Second / 2)
472                         } else {
473                                 log.WithField("PID", cmd.Process.Pid).Debug("sending SIGTERM")
474                                 cmd.Process.Signal(syscall.SIGTERM)
475                                 time.Sleep(5 * time.Second)
476                                 if !exited {
477                                         log.WithField("PID", cmd.Process.Pid).Warn("still waiting for child process to exit 5s after SIGTERM")
478                                 }
479                         }
480                 }
481         }()
482
483         err := cmd.Run()
484         if err != nil && ctx.Err() == nil {
485                 // Only report errors that happen before the context ends.
486                 return fmt.Errorf("%s: error: %v", cmdline, err)
487         }
488         return nil
489 }
490
491 func (boot *Booter) autofillConfig(cfg *arvados.Config, log logrus.FieldLogger) error {
492         cluster, err := cfg.GetCluster("")
493         if err != nil {
494                 return err
495         }
496         usedPort := map[string]bool{}
497         nextPort := func() string {
498                 for {
499                         port, err := availablePort(":0")
500                         if err != nil {
501                                 panic(err)
502                         }
503                         if usedPort[port] {
504                                 continue
505                         }
506                         usedPort[port] = true
507                         return port
508                 }
509         }
510         if cluster.Services.Controller.ExternalURL.Host == "" {
511                 h, p, err := net.SplitHostPort(boot.ControllerAddr)
512                 if err != nil {
513                         return err
514                 }
515                 if h == "" {
516                         h = boot.ListenHost
517                 }
518                 if p == "0" {
519                         p, err = availablePort(":0")
520                         if err != nil {
521                                 return err
522                         }
523                         usedPort[p] = true
524                 }
525                 cluster.Services.Controller.ExternalURL = arvados.URL{Scheme: "https", Host: net.JoinHostPort(h, p)}
526         }
527         for _, svc := range []*arvados.Service{
528                 &cluster.Services.Controller,
529                 &cluster.Services.DispatchCloud,
530                 &cluster.Services.GitHTTP,
531                 &cluster.Services.Health,
532                 &cluster.Services.Keepproxy,
533                 &cluster.Services.Keepstore,
534                 &cluster.Services.RailsAPI,
535                 &cluster.Services.WebDAV,
536                 &cluster.Services.WebDAVDownload,
537                 &cluster.Services.Websocket,
538                 &cluster.Services.Workbench1,
539         } {
540                 if svc == &cluster.Services.DispatchCloud && boot.ClusterType == "test" {
541                         continue
542                 }
543                 if svc.ExternalURL.Host == "" && (svc == &cluster.Services.Controller ||
544                         svc == &cluster.Services.GitHTTP ||
545                         svc == &cluster.Services.Keepproxy ||
546                         svc == &cluster.Services.WebDAV ||
547                         svc == &cluster.Services.WebDAVDownload ||
548                         svc == &cluster.Services.Websocket ||
549                         svc == &cluster.Services.Workbench1) {
550                         svc.ExternalURL = arvados.URL{Scheme: "https", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}
551                 }
552                 if len(svc.InternalURLs) == 0 {
553                         svc.InternalURLs = map[arvados.URL]arvados.ServiceInstance{
554                                 arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}: arvados.ServiceInstance{},
555                         }
556                 }
557         }
558         if cluster.SystemRootToken == "" {
559                 cluster.SystemRootToken = randomHexString(64)
560         }
561         if cluster.ManagementToken == "" {
562                 cluster.ManagementToken = randomHexString(64)
563         }
564         if cluster.API.RailsSessionSecretToken == "" {
565                 cluster.API.RailsSessionSecretToken = randomHexString(64)
566         }
567         if cluster.Collections.BlobSigningKey == "" {
568                 cluster.Collections.BlobSigningKey = randomHexString(64)
569         }
570         if boot.ClusterType != "production" && cluster.Containers.DispatchPrivateKey == "" {
571                 buf, err := ioutil.ReadFile(filepath.Join(boot.SourcePath, "lib", "dispatchcloud", "test", "sshkey_dispatch"))
572                 if err != nil {
573                         return err
574                 }
575                 cluster.Containers.DispatchPrivateKey = string(buf)
576         }
577         if boot.ClusterType != "production" {
578                 cluster.TLS.Insecure = true
579         }
580         if boot.ClusterType == "test" {
581                 // Add a second keepstore process.
582                 cluster.Services.Keepstore.InternalURLs[arvados.URL{Scheme: "http", Host: fmt.Sprintf("%s:%s", boot.ListenHost, nextPort())}] = arvados.ServiceInstance{}
583
584                 // Create a directory-backed volume for each keepstore
585                 // process.
586                 cluster.Volumes = map[string]arvados.Volume{}
587                 for url := range cluster.Services.Keepstore.InternalURLs {
588                         volnum := len(cluster.Volumes)
589                         datadir := fmt.Sprintf("%s/keep%d.data", boot.tempdir, volnum)
590                         if _, err = os.Stat(datadir + "/."); err == nil {
591                         } else if !os.IsNotExist(err) {
592                                 return err
593                         } else if err = os.Mkdir(datadir, 0777); err != nil {
594                                 return err
595                         }
596                         cluster.Volumes[fmt.Sprintf(cluster.ClusterID+"-nyw5e-%015d", volnum)] = arvados.Volume{
597                                 Driver:           "Directory",
598                                 DriverParameters: json.RawMessage(fmt.Sprintf(`{"Root":%q}`, datadir)),
599                                 AccessViaHosts: map[arvados.URL]arvados.VolumeAccess{
600                                         url: {},
601                                 },
602                         }
603                 }
604         }
605         if boot.OwnTemporaryDatabase {
606                 cluster.PostgreSQL.Connection = arvados.PostgreSQLConnection{
607                         "client_encoding": "utf8",
608                         "host":            "localhost",
609                         "port":            nextPort(),
610                         "dbname":          "arvados_test",
611                         "user":            "arvados",
612                         "password":        "insecure_arvados_test",
613                 }
614         }
615
616         cfg.Clusters[cluster.ClusterID] = *cluster
617         return nil
618 }
619
620 func randomHexString(chars int) string {
621         b := make([]byte, chars/2)
622         _, err := rand.Read(b)
623         if err != nil {
624                 panic(err)
625         }
626         return fmt.Sprintf("%x", b)
627 }
628
629 func internalPort(svc arvados.Service) (string, error) {
630         for u := range svc.InternalURLs {
631                 if _, p, err := net.SplitHostPort(u.Host); err != nil {
632                         return "", err
633                 } else if p != "" {
634                         return p, nil
635                 } else if u.Scheme == "https" {
636                         return "443", nil
637                 } else {
638                         return "80", nil
639                 }
640         }
641         return "", fmt.Errorf("service has no InternalURLs")
642 }
643
644 func externalPort(svc arvados.Service) (string, error) {
645         if _, p, err := net.SplitHostPort(svc.ExternalURL.Host); err != nil {
646                 return "", err
647         } else if p != "" {
648                 return p, nil
649         } else if svc.ExternalURL.Scheme == "https" {
650                 return "443", nil
651         } else {
652                 return "80", nil
653         }
654 }
655
656 func availablePort(addr string) (string, error) {
657         ln, err := net.Listen("tcp", addr)
658         if err != nil {
659                 return "", err
660         }
661         defer ln.Close()
662         _, port, err := net.SplitHostPort(ln.Addr().String())
663         if err != nil {
664                 return "", err
665         }
666         return port, nil
667 }
668
669 // Try to connect to addr until it works, then close ch. Give up if
670 // ctx cancels.
671 func waitForConnect(ctx context.Context, addr string) error {
672         dialer := net.Dialer{Timeout: time.Second}
673         for ctx.Err() == nil {
674                 conn, err := dialer.DialContext(ctx, "tcp", addr)
675                 if err != nil {
676                         time.Sleep(time.Second / 10)
677                         continue
678                 }
679                 conn.Close()
680                 return nil
681         }
682         return ctx.Err()
683 }