interface_pipeline_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //go:build darwin || send_pipeline
  2. package nebula
  3. import (
  4. "context"
  5. "errors"
  6. "net/netip"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/slackhq/nebula/overlay/tio"
  11. "github.com/slackhq/nebula/test"
  12. "github.com/slackhq/nebula/udp"
  13. "github.com/stretchr/testify/assert"
  14. "go.uber.org/goleak"
  15. )
  16. // scriptedQueue hands out reads from a script, then fails every Read with err.
  17. type scriptedQueue struct {
  18. reads [][]tio.Packet
  19. err error
  20. }
  21. func (q *scriptedQueue) Read() ([]tio.Packet, error) {
  22. if len(q.reads) == 0 {
  23. return nil, q.err
  24. }
  25. r := q.reads[0]
  26. q.reads = q.reads[1:]
  27. return r, nil
  28. }
  29. func (q *scriptedQueue) Write(b []byte) (int, error) { return len(b), nil }
  30. func (q *scriptedQueue) Close() error { return nil }
  31. type countingConn struct {
  32. udp.NoopConn
  33. mu sync.Mutex
  34. batches int
  35. }
  36. func (c *countingConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
  37. c.mu.Lock()
  38. c.batches++
  39. c.mu.Unlock()
  40. return len(bufs), nil
  41. }
  42. // TestListenInPipelinedStops pins that the pipelined reader returns when its queue fails, stopping its sender, and
  43. // reports the error as fatal only when the interface isn't shutting down.
  44. func TestListenInPipelinedStops(t *testing.T) {
  45. for _, closing := range []bool{false, true} {
  46. t.Run(map[bool]string{false: "fatal", true: "shutdown"}[closing], func(t *testing.T) {
  47. defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
  48. readErr := errors.New("tun gone")
  49. conn := &countingConn{}
  50. // Packets too short to parse are dropped before the firewall, so this reads without a hostmap.
  51. junk := tio.Packet{Bytes: []byte{0x45, 0}}
  52. q := &scriptedQueue{reads: [][]tio.Packet{{junk}, {junk, junk, junk}, {}}, err: readErr}
  53. shutdown := make(chan struct{})
  54. f := &Interface{
  55. ctx: context.Background(),
  56. l: test.NewLogger(),
  57. writers: []udp.Conn{conn},
  58. triggerShutdown: func() { close(shutdown) },
  59. }
  60. f.closed.Store(closing)
  61. done := make(chan struct{})
  62. go func() {
  63. f.listenIn(q, 0)
  64. close(done)
  65. }()
  66. select {
  67. case <-done:
  68. case <-time.After(5 * time.Second):
  69. t.Fatal("listenIn did not return after its queue failed")
  70. }
  71. if closing {
  72. assert.Nil(t, f.fatalErr.Load())
  73. } else {
  74. <-shutdown
  75. assert.Equal(t, readErr, *f.fatalErr.Load())
  76. }
  77. assert.Zero(t, conn.batches, "dropped packets must not be written")
  78. })
  79. }
  80. }