polling.go 2.0 KB

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