polling.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build !windows && !darwin
  4. package netmon
  5. import (
  6. "bytes"
  7. "errors"
  8. "os"
  9. "runtime"
  10. "sync"
  11. "time"
  12. "tailscale.com/net/interfaces"
  13. "tailscale.com/types/logger"
  14. )
  15. func newPollingMon(logf logger.Logf, m *Monitor) (osMon, error) {
  16. return &pollingMon{
  17. logf: logf,
  18. m: m,
  19. stop: make(chan struct{}),
  20. }, nil
  21. }
  22. // pollingMon is a bad but portable implementation of the link monitor
  23. // that works by polling the interface state every 10 seconds, in lieu
  24. // of anything to subscribe to.
  25. type pollingMon struct {
  26. logf logger.Logf
  27. m *Monitor
  28. closeOnce sync.Once
  29. stop chan struct{}
  30. }
  31. func (pm *pollingMon) IsInterestingInterface(iface string) bool {
  32. return true
  33. }
  34. func (pm *pollingMon) Close() error {
  35. pm.closeOnce.Do(func() {
  36. close(pm.stop)
  37. })
  38. return nil
  39. }
  40. func (pm *pollingMon) isCloudRun() bool {
  41. // https: //cloud.google.com/run/docs/reference/container-contract#env-vars
  42. if os.Getenv("K_REVISION") == "" || os.Getenv("K_CONFIGURATION") == "" ||
  43. os.Getenv("K_SERVICE") == "" || os.Getenv("PORT") == "" {
  44. return false
  45. }
  46. vers, err := os.ReadFile("/proc/version")
  47. if err != nil {
  48. pm.logf("Failed to read /proc/version: %v", err)
  49. return false
  50. }
  51. return string(bytes.TrimSpace(vers)) == "Linux version 4.4.0 #1 SMP Sun Jan 10 15:06:54 PST 2016"
  52. }
  53. func (pm *pollingMon) Receive() (message, error) {
  54. d := 10 * time.Second
  55. if runtime.GOOS == "android" {
  56. // We'll have Android notify the link monitor to wake up earlier,
  57. // so this can go very slowly there, to save battery.
  58. // https://github.com/tailscale/tailscale/issues/1427
  59. d = 10 * time.Minute
  60. }
  61. if pm.isCloudRun() {
  62. // Cloud Run routes never change at runtime. the containers are killed within
  63. // 15 minutes by default, set the interval long enough to be effectively infinite.
  64. pm.logf("monitor polling: Cloud Run detected, reduce polling interval to 24h")
  65. d = 24 * time.Hour
  66. }
  67. ticker := time.NewTicker(d)
  68. defer ticker.Stop()
  69. base := pm.m.InterfaceState()
  70. for {
  71. if cur, err := pm.m.interfaceStateUncached(); err == nil && !cur.EqualFiltered(base, interfaces.UseInterestingInterfaces, interfaces.UseInterestingIPs) {
  72. return unspecifiedMessage{}, nil
  73. }
  74. select {
  75. case <-ticker.C:
  76. case <-pm.stop:
  77. return nil, errors.New("stopped")
  78. }
  79. }
  80. }