tailscaled.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build linux
  4. package main
  5. import (
  6. "context"
  7. "errors"
  8. "fmt"
  9. "io/fs"
  10. "log"
  11. "os"
  12. "os/exec"
  13. "path/filepath"
  14. "reflect"
  15. "strings"
  16. "syscall"
  17. "time"
  18. "github.com/fsnotify/fsnotify"
  19. "tailscale.com/client/tailscale"
  20. )
  21. func startTailscaled(ctx context.Context, cfg *settings) (*tailscale.LocalClient, *os.Process, error) {
  22. args := tailscaledArgs(cfg)
  23. // tailscaled runs without context, since it needs to persist
  24. // beyond the startup timeout in ctx.
  25. cmd := exec.Command("tailscaled", args...)
  26. cmd.Stdout = os.Stdout
  27. cmd.Stderr = os.Stderr
  28. cmd.SysProcAttr = &syscall.SysProcAttr{
  29. Setpgid: true,
  30. }
  31. log.Printf("Starting tailscaled")
  32. if err := cmd.Start(); err != nil {
  33. return nil, nil, fmt.Errorf("starting tailscaled failed: %v", err)
  34. }
  35. // Wait for the socket file to appear, otherwise API ops will racily fail.
  36. log.Printf("Waiting for tailscaled socket")
  37. for {
  38. if ctx.Err() != nil {
  39. return nil, nil, errors.New("timed out waiting for tailscaled socket")
  40. }
  41. _, err := os.Stat(cfg.Socket)
  42. if errors.Is(err, fs.ErrNotExist) {
  43. time.Sleep(100 * time.Millisecond)
  44. continue
  45. } else if err != nil {
  46. return nil, nil, fmt.Errorf("error waiting for tailscaled socket: %w", err)
  47. }
  48. break
  49. }
  50. tsClient := &tailscale.LocalClient{
  51. Socket: cfg.Socket,
  52. UseSocketOnly: true,
  53. }
  54. return tsClient, cmd.Process, nil
  55. }
  56. // tailscaledArgs uses cfg to construct the argv for tailscaled.
  57. func tailscaledArgs(cfg *settings) []string {
  58. args := []string{"--socket=" + cfg.Socket}
  59. switch {
  60. case cfg.InKubernetes && cfg.KubeSecret != "":
  61. args = append(args, "--state=kube:"+cfg.KubeSecret)
  62. if cfg.StateDir == "" {
  63. cfg.StateDir = "/tmp"
  64. }
  65. fallthrough
  66. case cfg.StateDir != "":
  67. args = append(args, "--statedir="+cfg.StateDir)
  68. default:
  69. args = append(args, "--state=mem:", "--statedir=/tmp")
  70. }
  71. if cfg.UserspaceMode {
  72. args = append(args, "--tun=userspace-networking")
  73. } else if err := ensureTunFile(cfg.Root); err != nil {
  74. log.Fatalf("ensuring that /dev/net/tun exists: %v", err)
  75. }
  76. if cfg.SOCKSProxyAddr != "" {
  77. args = append(args, "--socks5-server="+cfg.SOCKSProxyAddr)
  78. }
  79. if cfg.HTTPProxyAddr != "" {
  80. args = append(args, "--outbound-http-proxy-listen="+cfg.HTTPProxyAddr)
  81. }
  82. if cfg.TailscaledConfigFilePath != "" {
  83. args = append(args, "--config="+cfg.TailscaledConfigFilePath)
  84. }
  85. // Once enough proxy versions have been released for all the supported
  86. // versions to understand this cfg setting, the operator can stop
  87. // setting TS_TAILSCALED_EXTRA_ARGS for the debug flag.
  88. if cfg.DebugAddrPort != "" && !strings.Contains(cfg.DaemonExtraArgs, cfg.DebugAddrPort) {
  89. args = append(args, "--debug="+cfg.DebugAddrPort)
  90. }
  91. if cfg.DaemonExtraArgs != "" {
  92. args = append(args, strings.Fields(cfg.DaemonExtraArgs)...)
  93. }
  94. return args
  95. }
  96. // tailscaleUp uses cfg to run 'tailscale up' everytime containerboot starts, or
  97. // if TS_AUTH_ONCE is set, only the first time containerboot starts.
  98. func tailscaleUp(ctx context.Context, cfg *settings) error {
  99. args := []string{"--socket=" + cfg.Socket, "up"}
  100. if cfg.AcceptDNS != nil && *cfg.AcceptDNS {
  101. args = append(args, "--accept-dns=true")
  102. } else {
  103. args = append(args, "--accept-dns=false")
  104. }
  105. if cfg.AuthKey != "" {
  106. args = append(args, "--authkey="+cfg.AuthKey)
  107. }
  108. // --advertise-routes can be passed an empty string to configure a
  109. // device (that might have previously advertised subnet routes) to not
  110. // advertise any routes. Respect an empty string passed by a user and
  111. // use it to explicitly unset the routes.
  112. if cfg.Routes != nil {
  113. args = append(args, "--advertise-routes="+*cfg.Routes)
  114. }
  115. if cfg.Hostname != "" {
  116. args = append(args, "--hostname="+cfg.Hostname)
  117. }
  118. if cfg.ExtraArgs != "" {
  119. args = append(args, strings.Fields(cfg.ExtraArgs)...)
  120. }
  121. log.Printf("Running 'tailscale up'")
  122. cmd := exec.CommandContext(ctx, "tailscale", args...)
  123. cmd.Stdout = os.Stdout
  124. cmd.Stderr = os.Stderr
  125. if err := cmd.Run(); err != nil {
  126. return fmt.Errorf("tailscale up failed: %v", err)
  127. }
  128. return nil
  129. }
  130. // tailscaleSet uses cfg to run 'tailscale set' to set any known configuration
  131. // options that are passed in via environment variables. This is run after the
  132. // node is in Running state and only if TS_AUTH_ONCE is set.
  133. func tailscaleSet(ctx context.Context, cfg *settings) error {
  134. args := []string{"--socket=" + cfg.Socket, "set"}
  135. if cfg.AcceptDNS != nil && *cfg.AcceptDNS {
  136. args = append(args, "--accept-dns=true")
  137. } else {
  138. args = append(args, "--accept-dns=false")
  139. }
  140. // --advertise-routes can be passed an empty string to configure a
  141. // device (that might have previously advertised subnet routes) to not
  142. // advertise any routes. Respect an empty string passed by a user and
  143. // use it to explicitly unset the routes.
  144. if cfg.Routes != nil {
  145. args = append(args, "--advertise-routes="+*cfg.Routes)
  146. }
  147. if cfg.Hostname != "" {
  148. args = append(args, "--hostname="+cfg.Hostname)
  149. }
  150. log.Printf("Running 'tailscale set'")
  151. cmd := exec.CommandContext(ctx, "tailscale", args...)
  152. cmd.Stdout = os.Stdout
  153. cmd.Stderr = os.Stderr
  154. if err := cmd.Run(); err != nil {
  155. return fmt.Errorf("tailscale set failed: %v", err)
  156. }
  157. return nil
  158. }
  159. func watchTailscaledConfigChanges(ctx context.Context, path string, lc *tailscale.LocalClient, errCh chan<- error) {
  160. var (
  161. tickChan <-chan time.Time
  162. tailscaledCfgDir = filepath.Dir(path)
  163. prevTailscaledCfg []byte
  164. )
  165. w, err := fsnotify.NewWatcher()
  166. if err != nil {
  167. log.Printf("tailscaled config watch: failed to create fsnotify watcher, timer-only mode: %v", err)
  168. ticker := time.NewTicker(5 * time.Second)
  169. defer ticker.Stop()
  170. tickChan = ticker.C
  171. } else {
  172. defer w.Close()
  173. if err := w.Add(tailscaledCfgDir); err != nil {
  174. errCh <- fmt.Errorf("failed to add fsnotify watch: %w", err)
  175. return
  176. }
  177. }
  178. b, err := os.ReadFile(path)
  179. if err != nil {
  180. errCh <- fmt.Errorf("error reading configfile: %w", err)
  181. return
  182. }
  183. prevTailscaledCfg = b
  184. // kubelet mounts Secrets to Pods using a series of symlinks, one of
  185. // which is <mount-dir>/..data that Kubernetes recommends consumers to
  186. // use if they need to monitor changes
  187. // https://github.com/kubernetes/kubernetes/blob/v1.28.1/pkg/volume/util/atomic_writer.go#L39-L61
  188. const kubeletMountedCfg = "..data"
  189. toWatch := filepath.Join(tailscaledCfgDir, kubeletMountedCfg)
  190. for {
  191. select {
  192. case <-ctx.Done():
  193. return
  194. case err := <-w.Errors:
  195. errCh <- fmt.Errorf("watcher error: %w", err)
  196. return
  197. case <-tickChan:
  198. case event := <-w.Events:
  199. if event.Name != toWatch {
  200. continue
  201. }
  202. }
  203. b, err := os.ReadFile(path)
  204. if err != nil {
  205. errCh <- fmt.Errorf("error reading configfile: %w", err)
  206. return
  207. }
  208. // For some proxy types the mounted volume also contains tailscaled state and other files. We
  209. // don't want to reload config unnecessarily on unrelated changes to these files.
  210. if reflect.DeepEqual(b, prevTailscaledCfg) {
  211. continue
  212. }
  213. prevTailscaledCfg = b
  214. log.Printf("tailscaled config watch: ensuring that config is up to date")
  215. ok, err := lc.ReloadConfig(ctx)
  216. if err != nil {
  217. errCh <- fmt.Errorf("error reloading tailscaled config: %w", err)
  218. return
  219. }
  220. if ok {
  221. log.Printf("tailscaled config watch: config was reloaded")
  222. }
  223. }
  224. }