derp_server_linux.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package derp
  4. import (
  5. "context"
  6. "crypto/tls"
  7. "net"
  8. "time"
  9. "tailscale.com/net/tcpinfo"
  10. )
  11. func (c *sclient) startStatsLoop(ctx context.Context) {
  12. // Get the RTT initially to verify it's supported.
  13. conn := c.tcpConn()
  14. if conn == nil {
  15. c.s.tcpRtt.Add("non-tcp", 1)
  16. return
  17. }
  18. if _, err := tcpinfo.RTT(conn); err != nil {
  19. c.logf("error fetching initial RTT: %v", err)
  20. c.s.tcpRtt.Add("error", 1)
  21. return
  22. }
  23. const statsInterval = 10 * time.Second
  24. // Don't launch a goroutine; use a timer instead.
  25. var gatherStats func()
  26. gatherStats = func() {
  27. // Do nothing if the context is finished.
  28. if ctx.Err() != nil {
  29. return
  30. }
  31. // Reschedule ourselves when this stats gathering is finished.
  32. defer c.s.clock.AfterFunc(statsInterval, gatherStats)
  33. // Gather TCP RTT information.
  34. rtt, err := tcpinfo.RTT(conn)
  35. if err == nil {
  36. c.s.tcpRtt.Add(durationToLabel(rtt), 1)
  37. }
  38. // TODO(andrew): more metrics?
  39. }
  40. // Kick off the initial timer.
  41. c.s.clock.AfterFunc(statsInterval, gatherStats)
  42. }
  43. // tcpConn attempts to get the underlying *net.TCPConn from this client's
  44. // Conn; if it cannot, then it will return nil.
  45. func (c *sclient) tcpConn() *net.TCPConn {
  46. nc := c.nc
  47. for {
  48. switch v := nc.(type) {
  49. case *net.TCPConn:
  50. return v
  51. case *tls.Conn:
  52. nc = v.NetConn()
  53. default:
  54. return nil
  55. }
  56. }
  57. }
  58. func durationToLabel(dur time.Duration) string {
  59. switch {
  60. case dur <= 10*time.Millisecond:
  61. return "10ms"
  62. case dur <= 20*time.Millisecond:
  63. return "20ms"
  64. case dur <= 50*time.Millisecond:
  65. return "50ms"
  66. case dur <= 100*time.Millisecond:
  67. return "100ms"
  68. case dur <= 150*time.Millisecond:
  69. return "150ms"
  70. case dur <= 250*time.Millisecond:
  71. return "250ms"
  72. case dur <= 500*time.Millisecond:
  73. return "500ms"
  74. default:
  75. return "inf"
  76. }
  77. }