Up connects the server to the tailnet and waits until it is running. On success it returns the current status, including a Tailscale IP address.
(ctx context.Context)
| 532 | // Up connects the server to the tailnet and waits until it is running. |
| 533 | // On success it returns the current status, including a Tailscale IP address. |
| 534 | func (s *Server) Up(ctx context.Context) (*ipnstate.Status, error) { |
| 535 | lc, err := s.LocalClient() // calls Start |
| 536 | if err != nil { |
| 537 | return nil, fmt.Errorf("tsnet.Up: %w", err) |
| 538 | } |
| 539 | |
| 540 | watcher, err := lc.WatchIPNBus(ctx, ipn.NotifyInitialState) |
| 541 | if err != nil { |
| 542 | return nil, fmt.Errorf("tsnet.Up: %w", err) |
| 543 | } |
| 544 | defer watcher.Close() |
| 545 | |
| 546 | for { |
| 547 | n, err := watcher.Next() |
| 548 | if err != nil { |
| 549 | return nil, fmt.Errorf("tsnet.Up: %w", err) |
| 550 | } |
| 551 | if n.ErrMessage != nil { |
| 552 | return nil, fmt.Errorf("tsnet.Up: backend: %s", *n.ErrMessage) |
| 553 | } |
| 554 | if st := n.State; st != nil { |
| 555 | if *st == ipn.Running { |
| 556 | status, err := lc.Status(ctx) |
| 557 | if err != nil { |
| 558 | return nil, fmt.Errorf("tsnet.Up: %w", err) |
| 559 | } |
| 560 | if len(status.TailscaleIPs) == 0 { |
| 561 | return nil, errors.New("tsnet.Up: running, but no ip") |
| 562 | } |
| 563 | |
| 564 | // The first time Up is run, clear the persisted serve config |
| 565 | // and Service advertisements. We do this to prevent messy |
| 566 | // interactions with stale config in the face of code changes. |
| 567 | var srvCfgErr error |
| 568 | var svcAdErr error |
| 569 | s.resetServeStateOnce.Do(func() { |
| 570 | if err := lc.SetServeConfig(ctx, new(ipn.ServeConfig)); err != nil { |
| 571 | srvCfgErr = fmt.Errorf("clearing serve config: %w", err) |
| 572 | } |
| 573 | _, err := s.lb.EditPrefs(&ipn.MaskedPrefs{ |
| 574 | AdvertiseServicesSet: true, |
| 575 | Prefs: ipn.Prefs{ |
| 576 | AdvertiseServices: []string{}, |
| 577 | }, |
| 578 | }) |
| 579 | if err != nil { |
| 580 | svcAdErr = fmt.Errorf("clearing Service advertisements: %w", err) |
| 581 | } |
| 582 | }) |
| 583 | if err := errors.Join(srvCfgErr, svcAdErr); err != nil { |
| 584 | return nil, fmt.Errorf("tsnet.Up: %w", err) |
| 585 | } |
| 586 | |
| 587 | return status, nil |
| 588 | } |
| 589 | // TODO: in the future, return an error on ipn.NeedsLogin |
| 590 | // and ipn.NeedsMachineAuth to improve the UX of trying |
| 591 | // out the tsnet package. |