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