flow.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. package nebula
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "runtime"
  6. "sync"
  7. "time"
  8. "github.com/rcrowley/go-metrics"
  9. "github.com/slackhq/nebula/config"
  10. "github.com/slackhq/nebula/noiseutil"
  11. )
  12. // Staged processing (tun.staged.workers) moves crypto off each tun reader and udp listener onto worker goroutines,
  13. // behind which an ordered stage sends or writes every batch in read order. It reuses the inline packet handlers:
  14. // staging changes ownership and scheduling, not policy. Each routine has its own workers and ordered stages, so order
  15. // is per routine. Full queues block the reader. A read error drains the batches in flight, while shutdown waits for
  16. // the crypto and then drops packets whose destination has closed. A TX slot holds one tun read and its ciphertext,
  17. // about 1.1 MiB; there are eight, or two more than the workers. An RX slot holds one recvmmsg batch, listen.batch
  18. // times 64 KiB with GRO, and the count keeps up to 384 entries in flight in four to six slots: six and 24 MiB at
  19. // listen.batch=64.
  20. // tun.staged.tx_slots and rx_slots override the counts. Small-MSS TX arenas can grow.
  21. //
  22. // Metrics are registered only for active pipelines. flow.{tx,rx}.batches counts reads handed to the ordered stage and
  23. // flow.{tx,rx}.inline those an idle reader handled itself (TX inline also counts oversized reads); their rates show
  24. // whether staging is used. flow.stage.<stage>.q<queue>.busy_ns locates the limiting stage: tx_read, tx_encrypt,
  25. // tx_send, rx_read, rx_decrypt or rx_write. Take rates; 1e9 ns/s fills a serial stage. These are elapsed times that
  26. // exclude read syscalls and downstream waits; descheduling inflates them and worker times add up across the pool.
  27. // Inline work counts at the reader; small RX batches sent to the writer include decryption in writer time.
  28. // stagedConfig is tun.staged. workers is per routine and direction; zero keeps processing inline.
  29. type stagedConfig struct {
  30. workers int
  31. tx bool
  32. rx bool
  33. // inlineBelow is the TX segment or RX packet count below which an idle reader skips the worker handoff
  34. inlineBelow int
  35. // txSlots and rxSlots are how many batches each routine can have in flight per direction
  36. txSlots, rxSlots int
  37. }
  38. const (
  39. // stagedTxSlots is the default TX slot count, unless the workers need more
  40. stagedTxSlots = 8
  41. // stagedRxEntries is how many recvmmsg entries the RX slots hold in flight by default
  42. stagedRxEntries = 6 * 64
  43. // stagedMinSlots lets the reader fill one batch while another is in flight
  44. stagedMinSlots = 2
  45. // stagedMinRxSlots keeps the default RX pipeline deep enough for large listen.batch values
  46. stagedMinRxSlots = 4
  47. // stagedMaxRxSlots is the measured default, a smaller listen.batch does not take more slots
  48. stagedMaxRxSlots = 6
  49. )
  50. // stagedSlots sizes the TX and RX slots. TX reads are bounded by the tun queue, so one slot per worker plus the one
  51. // being read and the one being sent, and at least the eight measured. RX slots keep stagedRxEntries in flight, four
  52. // to six, so a larger listen.batch means fewer slots and RX memory never exceeds the six measured. A positive override replaces either, down to stagedMinSlots.
  53. func stagedSlots(workers, batch, txOverride, rxOverride int) (tx, rx int) {
  54. tx = max(stagedTxSlots, workers+2)
  55. rx = min(max(stagedMinRxSlots, (stagedRxEntries+batch-1)/max(batch, 1)), stagedMaxRxSlots)
  56. if txOverride > 0 {
  57. tx = max(txOverride, stagedMinSlots)
  58. }
  59. if rxOverride > 0 {
  60. rx = max(rxOverride, stagedMinSlots)
  61. }
  62. return tx, rx
  63. }
  64. // parseStagedConfig enables staging on Linux only; queues and conns that cannot hand off batches also stay inline.
  65. func parseStagedConfig(c *config.C, l *slog.Logger) stagedConfig {
  66. sc := stagedConfig{workers: c.GetInt("tun.staged.workers", 0)}
  67. if sc.workers <= 0 {
  68. return stagedConfig{}
  69. }
  70. if runtime.GOOS != "linux" {
  71. l.Warn("tun.staged is only supported on Linux; packet processing stays inline")
  72. return stagedConfig{}
  73. }
  74. sc.tx, sc.rx = true, true
  75. // 256 is the measured crossover
  76. sc.inlineBelow = 256
  77. if noiseutil.EncryptLockNeeded {
  78. l.Warn("tun.staged cannot encrypt in parallel with boringcrypto or fips140; transmit stays inline")
  79. sc.tx = false
  80. }
  81. sc.txSlots, sc.rxSlots = stagedSlots(sc.workers, c.GetInt("listen.batch", 64),
  82. c.GetInt("tun.staged.tx_slots", 0), c.GetInt("tun.staged.rx_slots", 0))
  83. l.Info("Staged packet processing enabled", "workers", sc.workers, "tx", sc.tx, "rx", sc.rx,
  84. "txSlots", sc.txSlots, "rxSlots", sc.rxSlots)
  85. return sc
  86. }
  87. // flowJob is one batch of crypto work. It owns its packet buffers until run returns; jobs and queues are reused.
  88. type flowJob interface{ run(nb []byte) }
  89. // flowPool runs one reader's crypto jobs. The reader is the only producer and closes the pool once its ordered stage
  90. // has drained.
  91. type flowPool struct {
  92. jobs chan flowJob
  93. wg sync.WaitGroup
  94. }
  95. func newFlowPool(workers, queueLen int, busy metrics.Counter) *flowPool {
  96. p := &flowPool{jobs: make(chan flowJob, queueLen)}
  97. for range workers {
  98. p.wg.Go(func() {
  99. nb := make([]byte, 12)
  100. for job := range p.jobs {
  101. t := time.Now()
  102. job.run(nb)
  103. busy.Inc(int64(time.Since(t)))
  104. }
  105. })
  106. }
  107. return p
  108. }
  109. func (p *flowPool) close() { close(p.jobs); p.wg.Wait() }
  110. // stageBusy is the busy time counter of one stage of routine q.
  111. func stageBusy(stage string, q int) metrics.Counter {
  112. return metrics.GetOrRegisterCounter(fmt.Sprintf("flow.stage.%s.q%d.busy_ns", stage, q), nil)
  113. }