flow_rx.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package nebula
  2. import (
  3. "encoding/binary"
  4. "net/netip"
  5. "time"
  6. "github.com/rcrowley/go-metrics"
  7. "github.com/slackhq/nebula/header"
  8. "github.com/slackhq/nebula/udp"
  9. )
  10. // handoffConn is a udp conn that can hand each received batch over. The callback returns replacement buffers with
  11. // the same count and at least the same lengths.
  12. type handoffConn interface {
  13. ListenOutHandoff(udp.EncReader, func([][]byte) [][]byte) error
  14. }
  15. const stagedRxSlots = 6
  16. const rxChunkMin = 16
  17. // rxItem is one received packet. A data packet for an established tunnel has ci set; out and err are written by
  18. // whoever decrypts it.
  19. type rxItem struct {
  20. packet []byte
  21. hostinfo *HostInfo
  22. ci *ConnectionState
  23. counter uint64
  24. via netip.AddrPort
  25. out []byte
  26. err error
  27. }
  28. // rxChunk is a contiguous run of a batch's items for one worker to decrypt.
  29. type rxChunk struct {
  30. items []rxItem
  31. done chan struct{}
  32. }
  33. func (c *rxChunk) run(nb []byte) {
  34. decryptRxItems(c.items, nb)
  35. c.done <- struct{}{}
  36. }
  37. // decryptRxItems decrypts the data packets among items in place. The replay window is left to the ordered stage, as
  38. // are packets without a tunnel and the known replays precheck marked.
  39. func decryptRxItems(items []rxItem, nb []byte) {
  40. for i := range items {
  41. it := &items[i]
  42. if it.ci == nil || it.err != nil {
  43. continue
  44. }
  45. it.out, it.err = it.ci.decryptPacket(it.counter, it.packet, nb)
  46. }
  47. }
  48. // rxBatch is one recvmmsg batch moving through the staged receive pipeline.
  49. type rxBatch struct {
  50. // items is every packet of the batch in arrival order. Data packets are decrypted by a worker; anything else is
  51. // handled whole by the writer, in its place.
  52. items []rxItem
  53. data int
  54. // bufs is the set of recvmmsg buffers the items point into, owned by the batch from handoff until it is reused.
  55. bufs [][]byte
  56. // chunks are the decrypt jobs, nChunks of them in use. With none the writer decrypts the batch itself.
  57. chunks []rxChunk
  58. nChunks int
  59. }
  60. func (b *rxBatch) reset() {
  61. clear(b.items)
  62. b.items = b.items[:0]
  63. b.data = 0
  64. for i := range b.nChunks {
  65. b.chunks[i].items = nil
  66. }
  67. b.nChunks = 0
  68. }
  69. // stagedRx is the staged receive pipeline of one udp listener. deliver and handoff run on the listener goroutine.
  70. type stagedRx struct {
  71. f *Interface
  72. q int
  73. pool *flowPool
  74. // h and hostmapCache are the listener's own. wrxc is the commit context: the writer's, or the listener's while
  75. // nothing is in flight.
  76. h *header.H
  77. hostmapCache map[uint32]*HostInfo
  78. wrxc *rxContext
  79. started time.Time
  80. cur *rxBatch
  81. free []*rxBatch
  82. ordered chan *rxBatch
  83. returned chan *rxBatch
  84. inFlight int
  85. writerDone chan struct{}
  86. readBusy, decryptBusy, writeBusy metrics.Counter
  87. metricBatches metrics.Counter
  88. }
  89. func newStagedRx(f *Interface, q int, wrxc *rxContext) *stagedRx {
  90. p := &stagedRx{
  91. f: f,
  92. q: q,
  93. h: &header.H{},
  94. hostmapCache: map[uint32]*HostInfo{},
  95. wrxc: wrxc,
  96. ordered: make(chan *rxBatch, stagedRxSlots),
  97. returned: make(chan *rxBatch, stagedRxSlots),
  98. writerDone: make(chan struct{}),
  99. readBusy: stageBusy("rx_read", q),
  100. decryptBusy: stageBusy("rx_decrypt", q),
  101. writeBusy: stageBusy("rx_write", q),
  102. metricBatches: metrics.GetOrRegisterCounter("flow.rx.batches", nil),
  103. }
  104. workers := f.staged.workers
  105. p.pool = newFlowPool(workers, stagedRxSlots*2*workers, p.decryptBusy)
  106. for range stagedRxSlots {
  107. // Two chunks per worker, so the writer can start committing while the workers are still on the rest
  108. b := &rxBatch{items: make([]rxItem, 0, 256), chunks: make([]rxChunk, 2*workers)}
  109. for i := range b.chunks {
  110. b.chunks[i].done = make(chan struct{}, 1)
  111. }
  112. p.free = append(p.free, b)
  113. }
  114. p.cur = p.free[len(p.free)-1]
  115. p.free = p.free[:len(p.free)-1]
  116. go p.writer()
  117. return p
  118. }
  119. // listen runs the conn's receive loop through the pipeline until it fails, then drains the pipeline. The conn hands
  120. // its buffers over, so a batch moves between stages without a copy.
  121. func (p *stagedRx) listen(li handoffConn) error {
  122. defer p.close()
  123. return li.ListenOutHandoff(p.deliver, p.handoff)
  124. }
  125. // deliver is the listener's per-packet work: classify the packet and add it to the current batch. Nothing here
  126. // decrypts or touches the tun.
  127. func (p *stagedRx) deliver(via netip.AddrPort, packet []byte) {
  128. if p.started.IsZero() {
  129. p.started = time.Now()
  130. }
  131. b := p.cur
  132. it := rxItem{packet: packet, via: via}
  133. p.classify(&it)
  134. if it.ci != nil {
  135. b.data++
  136. }
  137. b.items = append(b.items, it)
  138. }
  139. // classify fills in the tunnel for a plain data packet of an established, non-relayed tunnel, leaving anything else
  140. // for the writer to handle whole. The replay pre-check waits for the end of the batch, see precheck.
  141. func (p *stagedRx) classify(it *rxItem) {
  142. f := p.f
  143. h := p.h
  144. packet := it.packet
  145. if h.Parse(packet) != nil || h.Version != header.Version || h.Type != header.Message || h.Subtype != header.MessageNone {
  146. return
  147. }
  148. if f.myVpnNetworksTable.Contains(it.via.Addr()) {
  149. return
  150. }
  151. hostinfo := f.hostMap.QueryIndexCached(h.RemoteIndex, p.hostmapCache)
  152. if hostinfo == nil || hostinfo.ConnectionState == nil {
  153. return
  154. }
  155. ci := hostinfo.ConnectionState
  156. if len(packet) < header.Len+ci.dKey.Overhead() {
  157. return
  158. }
  159. it.hostinfo, it.ci, it.counter = hostinfo, ci, h.MessageCounter
  160. }
  161. // precheck marks obvious replays before anything decrypts them, like ConnectionState.Decrypt does, taking each
  162. // tunnel's lock once per run of its packets rather than once per packet: the writer takes the same lock for its
  163. // window updates, from another core. The writer checks again when it commits. The window only moves forward in
  164. // between, so a stale check here can only let a replay through to that second check. Marked packets keep their
  165. // place: an earlier RecvError may delete their tunnel, and inline receive then replies with a RecvError rather than
  166. // dropping a replay.
  167. func (p *stagedRx) precheck(b *rxBatch) {
  168. f := p.f
  169. items := b.items
  170. for i := 0; i < len(items); {
  171. ci := items[i].ci
  172. if ci == nil {
  173. i++
  174. continue
  175. }
  176. ci.decryptLock.Lock()
  177. for ; i < len(items) && items[i].ci == ci; i++ {
  178. if ci.window.Check(f.l, items[i].counter) {
  179. continue
  180. }
  181. b.data--
  182. items[i].err = ErrAlreadySeen
  183. }
  184. ci.decryptLock.Unlock()
  185. }
  186. }
  187. // handoff ends a batch: the batch takes bufs, and the conn reads the next batch into the buffers of the next free
  188. // batch.
  189. func (p *stagedRx) handoff(bufs [][]byte) [][]byte {
  190. p.cur.bufs = bufs
  191. p.endBatch()
  192. if !p.started.IsZero() {
  193. p.readBusy.Inc(int64(time.Since(p.started)))
  194. p.started = time.Time{}
  195. }
  196. b := p.cur
  197. if len(b.bufs) != len(bufs) || len(b.bufs[0]) < len(bufs[0]) {
  198. b.bufs = make([][]byte, len(bufs))
  199. for i := range b.bufs {
  200. b.bufs[i] = make([]byte, len(bufs[0]))
  201. }
  202. }
  203. return b.bufs
  204. }
  205. // endBatch hands the batch to the workers and the ordered writer, then takes a free batch.
  206. func (p *stagedRx) endBatch() {
  207. clear(p.hostmapCache)
  208. p.reap()
  209. b := p.cur
  210. p.precheck(b)
  211. n := len(b.items)
  212. if n == 0 {
  213. b.reset()
  214. return
  215. }
  216. parts := min(len(b.chunks), b.data/rxChunkMin)
  217. p.metricBatches.Inc(1)
  218. if parts > 0 {
  219. size := (n + parts - 1) / parts
  220. for off := 0; off < n; off += size {
  221. c := &b.chunks[b.nChunks]
  222. c.items = b.items[off:min(off+size, n)]
  223. b.nChunks++
  224. }
  225. }
  226. // The jobs go out before the batch does: once the writer has it, it may finish and reset it at any moment
  227. for i := range b.nChunks {
  228. p.pool.jobs <- &b.chunks[i]
  229. }
  230. p.inFlight++
  231. p.ordered <- b
  232. if len(p.free) == 0 {
  233. // Every batch is in flight, wait for the writer: the socket buffer absorbs the backlog meanwhile. The wait is
  234. // downstream backpressure, not listener busy time.
  235. t := time.Now()
  236. p.release(<-p.returned)
  237. p.started = p.started.Add(time.Since(t))
  238. }
  239. p.cur = p.free[len(p.free)-1]
  240. p.free = p.free[:len(p.free)-1]
  241. }
  242. // reap takes back every batch the writer has finished with, without waiting.
  243. func (p *stagedRx) reap() {
  244. for {
  245. select {
  246. case b := <-p.returned:
  247. p.release(b)
  248. default:
  249. return
  250. }
  251. }
  252. }
  253. func (p *stagedRx) release(b *rxBatch) {
  254. p.inFlight--
  255. p.free = append(p.free, b)
  256. }
  257. // process is the ordered stage for one batch: decrypt whatever no worker is decrypting, commit every item in arrival
  258. // order, and flush the tun batcher. It reports how long it waited on workers.
  259. func (p *stagedRx) process(b *rxBatch, rxc *rxContext) time.Duration {
  260. var waited time.Duration
  261. if b.nChunks == 0 {
  262. decryptRxItems(b.items, rxc.nb)
  263. p.commit(b.items, rxc)
  264. } else {
  265. // Commit chunk by chunk, so the commit overlaps the workers still on later chunks
  266. for i := range b.nChunks {
  267. c := &b.chunks[i]
  268. select {
  269. case <-c.done:
  270. default:
  271. t := time.Now()
  272. <-c.done
  273. waited += time.Since(t)
  274. }
  275. p.commit(c.items, rxc)
  276. }
  277. }
  278. p.f.flushOutside(rxc)
  279. return waited
  280. }
  281. // commit runs the ordered stage over items in arrival order. A non-data packet goes through readOutsidePackets in
  282. // its place, a run of data packets on one tunnel through commitRun.
  283. func (p *stagedRx) commit(items []rxItem, rxc *rxContext) {
  284. for i := 0; i < len(items); {
  285. ci := items[i].ci
  286. if ci == nil {
  287. p.f.readOutsidePackets(ViaSender{UdpAddr: items[i].via}, items[i].packet, rxc)
  288. i++
  289. continue
  290. }
  291. j := i + 1
  292. for j < len(items) && items[j].ci == ci {
  293. j++
  294. }
  295. p.commitRun(items[i:j], rxc)
  296. i = j
  297. }
  298. }
  299. // commitRun commits a run of decrypted data packets on one tunnel. The window updates go first, under one lock, then
  300. // the rest; handling a data packet never touches the window, so that is the same as one packet at a time.
  301. func (p *stagedRx) commitRun(run []rxItem, rxc *rxContext) {
  302. f := p.f
  303. ci := run[0].ci
  304. // Classification is speculative: earlier control packets may have removed this tunnel. Resolve it through the
  305. // writer's batch-local cache, exactly where inline processing would, before touching replay state.
  306. index := binary.BigEndian.Uint32(run[0].packet[4:8])
  307. hostinfo := f.hostMap.QueryIndexCached(index, rxc.hostmapCache)
  308. if hostinfo != run[0].hostinfo || hostinfo.ConnectionState != ci {
  309. if hostinfo == nil {
  310. for i := range run {
  311. f.maybeSendRecvError(run[i].via, index)
  312. }
  313. }
  314. return
  315. }
  316. ci.decryptLock.Lock()
  317. for i := range run {
  318. // A packet that failed to decrypt does not touch the window, like ConnectionState.Decrypt
  319. if run[i].err == nil && !ci.window.Update(f.l, run[i].counter) {
  320. run[i].err = ErrAlreadySeen
  321. }
  322. }
  323. ci.decryptLock.Unlock()
  324. for i := range run {
  325. it := &run[i]
  326. if f.finishOutsideDecrypt(it.hostinfo, ViaSender{UdpAddr: it.via}, it.counter, it.err) {
  327. f.handleOutsideMessagePacket(it.hostinfo, it.counter, it.out, rxc)
  328. }
  329. }
  330. }
  331. // writer is the ordered receive stage: window, firewall, coalescer and tun write, one batch at a time in arrival
  332. // order.
  333. func (p *stagedRx) writer() {
  334. defer close(p.writerDone)
  335. for b := range p.ordered {
  336. if p.f.closed.Load() {
  337. // The tun is going away, a write would only log errors. Still wait out the workers on the batch.
  338. for i := range b.nChunks {
  339. <-b.chunks[i].done
  340. }
  341. } else {
  342. t := time.Now()
  343. waited := p.process(b, p.wrxc)
  344. p.writeBusy.Inc(int64(time.Since(t) - waited))
  345. }
  346. b.reset()
  347. p.returned <- b
  348. }
  349. }
  350. // close commits anything still in flight, in order, and stops the writer and the workers.
  351. func (p *stagedRx) close() {
  352. if len(p.cur.items) > 0 {
  353. p.endBatch()
  354. }
  355. close(p.ordered)
  356. <-p.writerDone
  357. p.pool.close()
  358. }