derp_server_linux.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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) statsLoop(ctx context.Context) error {
  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 nil
  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 nil
  22. }
  23. const statsInterval = 10 * time.Second
  24. ticker := time.NewTicker(statsInterval)
  25. defer ticker.Stop()
  26. statsLoop:
  27. for {
  28. select {
  29. case <-ticker.C:
  30. rtt, err := tcpinfo.RTT(conn)
  31. if err != nil {
  32. continue statsLoop
  33. }
  34. // TODO(andrew): more metrics?
  35. c.s.tcpRtt.Add(durationToLabel(rtt), 1)
  36. case <-ctx.Done():
  37. return ctx.Err()
  38. }
  39. }
  40. }
  41. // tcpConn attempts to get the underlying *net.TCPConn from this client's
  42. // Conn; if it cannot, then it will return nil.
  43. func (c *sclient) tcpConn() *net.TCPConn {
  44. nc := c.nc
  45. for {
  46. switch v := nc.(type) {
  47. case *net.TCPConn:
  48. return v
  49. case *tls.Conn:
  50. nc = v.NetConn()
  51. default:
  52. return nil
  53. }
  54. }
  55. }
  56. func durationToLabel(dur time.Duration) string {
  57. switch {
  58. case dur <= 10*time.Millisecond:
  59. return "10ms"
  60. case dur <= 20*time.Millisecond:
  61. return "20ms"
  62. case dur <= 50*time.Millisecond:
  63. return "50ms"
  64. case dur <= 100*time.Millisecond:
  65. return "100ms"
  66. case dur <= 150*time.Millisecond:
  67. return "150ms"
  68. case dur <= 250*time.Millisecond:
  69. return "250ms"
  70. case dur <= 500*time.Millisecond:
  71. return "500ms"
  72. default:
  73. return "inf"
  74. }
  75. }