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