flow_rx.go 12 KB

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