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