| 1 | Subject: [PATCH] tap: a connection closed by the program's cancel is not an error |
| 2 | |
| 3 | Switch.Accept logs "cannot receive packets from X, disconnecting" at error |
| 4 | level, and returns the error, when the connection's read fails. A program |
| 5 | that stops its switch by cancelling the context and closing the connection |
| 6 | gets that error each time, though it asked for it. Accept returns nil then, |
| 7 | and says nothing. |
| 8 | |
| 9 | Test: TestAcceptEndedByContext (a read failing by itself is still an error). |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | @@ -96,6 +96,10 @@ func (e *Switch) Accept(ctx context.Context, rawConn net.Conn, protocol types.Pr |
| 17 | e.disconnect(id, conn) |
| 18 | }() |
| 19 | if err := e.rx(ctx, id, conn); err != nil { |
| 20 | + if ctx.Err() != nil { |
| 21 | + // Closing the connection is how a program ends the switch. |
| 22 | + return nil |
| 23 | + } |
| 24 | err := fmt.Errorf("cannot receive packets from %s, disconnecting: %w", conn.RemoteAddr().String(), err) |
| 25 | log.Error(err) |
| 26 | return err |
| 27 | |
| 28 | new file mode 100644 |
| 29 | |
| 30 | |
| 31 | |
| 32 | @@ -0,0 +1,48 @@ |
| 33 | +package tap |
| 34 | + |
| 35 | +import ( |
| 36 | + "context" |
| 37 | + "net" |
| 38 | + "sync" |
| 39 | + "testing" |
| 40 | + |
| 41 | + "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 42 | + "github.com/stretchr/testify/require" |
| 43 | +) |
| 44 | + |
| 45 | +// readingConn says when it is first read. |
| 46 | +type readingConn struct { |
| 47 | + net.Conn |
| 48 | + reading chan struct{} |
| 49 | + once sync.Once |
| 50 | +} |
| 51 | + |
| 52 | +func (c *readingConn) Read(b []byte) (int, error) { |
| 53 | + c.once.Do(func() { close(c.reading) }) |
| 54 | + return c.Conn.Read(b) |
| 55 | +} |
| 56 | + |
| 57 | +// A connection that ends because the program cancelled the context is not an |
| 58 | +// error; one that ends by itself is. |
| 59 | +func TestAcceptEndedByContext(t *testing.T) { |
| 60 | + for _, cancelled := range []bool{true, false} { |
| 61 | + s := NewSwitch(false) |
| 62 | + ours, theirs := net.Pipe() |
| 63 | + conn := &readingConn{Conn: ours, reading: make(chan struct{})} |
| 64 | + ctx, cancel := context.WithCancel(context.Background()) |
| 65 | + done := make(chan error, 1) |
| 66 | + go func() { done <- s.Accept(ctx, conn, types.VfkitProtocol) }() |
| 67 | + <-conn.reading |
| 68 | + if cancelled { |
| 69 | + cancel() |
| 70 | + } |
| 71 | + theirs.Close() |
| 72 | + err := <-done |
| 73 | + cancel() |
| 74 | + if cancelled { |
| 75 | + require.NoError(t, err) |
| 76 | + } else { |
| 77 | + require.Error(t, err) |
| 78 | + } |
| 79 | + } |
| 80 | +} |