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