Use fake clocks in all tests

...except TCP tests and NDP tests that mutate globals. These will be
undertaken later.

Updates #5940.

PiperOrigin-RevId: 376145608
This commit is contained in:
Tamir Duberstein
2021-05-27 05:06:04 -07:00
committed by gVisor bot
parent 93d98b874b
commit 2c1df1f445
11 changed files with 322 additions and 274 deletions
+2 -2
View File
@@ -50,7 +50,7 @@ func IPv4(t *testing.T, b []byte, checkers ...NetworkChecker) {
ipv4 := header.IPv4(b)
if !ipv4.IsValid(len(b)) {
t.Error("Not a valid IPv4 packet")
t.Fatalf("Not a valid IPv4 packet: %x", ipv4)
}
if !ipv4.IsChecksumValid() {
@@ -72,7 +72,7 @@ func IPv6(t *testing.T, b []byte, checkers ...NetworkChecker) {
ipv6 := header.IPv6(b)
if !ipv6.IsValid(len(b)) {
t.Error("Not a valid IPv6 packet")
t.Fatalf("Not a valid IPv6 packet: %x", ipv6)
}
for _, f := range checkers {
+1 -1
View File
@@ -28,13 +28,13 @@ go_test(
":arp",
"//pkg/tcpip",
"//pkg/tcpip/buffer",
"//pkg/tcpip/faketime",
"//pkg/tcpip/header",
"//pkg/tcpip/link/channel",
"//pkg/tcpip/link/sniffer",
"//pkg/tcpip/network/ipv4",
"//pkg/tcpip/stack",
"//pkg/tcpip/testutil",
"//pkg/tcpip/transport/icmp",
"@com_github_google_go_cmp//cmp:go_default_library",
"@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
],
+47 -80
View File
@@ -15,15 +15,14 @@
package arp_test
import (
"context"
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/buffer"
"gvisor.dev/gvisor/pkg/tcpip/faketime"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
"gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
@@ -31,7 +30,6 @@ import (
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/stack"
"gvisor.dev/gvisor/pkg/tcpip/testutil"
"gvisor.dev/gvisor/pkg/tcpip/transport/icmp"
)
const (
@@ -39,15 +37,6 @@ const (
stackLinkAddr = tcpip.LinkAddress("\x0a\x0a\x0b\x0b\x0c\x0c")
remoteLinkAddr = tcpip.LinkAddress("\x01\x02\x03\x04\x05\x06")
defaultChannelSize = 1
defaultMTU = 65536
// eventChanSize defines the size of event channels used by the neighbor
// cache's event dispatcher. The size chosen here needs to be sufficient to
// queue all the events received during tests before consumption.
// If eventChanSize is too small, the tests may deadlock.
eventChanSize = 32
)
var (
@@ -123,24 +112,6 @@ func (d *arpDispatcher) OnNeighborRemoved(nicID tcpip.NICID, entry stack.Neighbo
d.C <- e
}
func (d *arpDispatcher) waitForEvent(ctx context.Context, want eventInfo) error {
select {
case got := <-d.C:
if diff := cmp.Diff(want, got, cmp.AllowUnexported(got), cmpopts.IgnoreFields(stack.NeighborEntry{}, "UpdatedAt")); diff != "" {
return fmt.Errorf("got invalid event (-want +got):\n%s", diff)
}
case <-ctx.Done():
return fmt.Errorf("%s for %s", ctx.Err(), want)
}
return nil
}
func (d *arpDispatcher) waitForEventWithTimeout(want eventInfo, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return d.waitForEvent(ctx, want)
}
func (d *arpDispatcher) nextEvent() (eventInfo, bool) {
select {
case event := <-d.C:
@@ -153,55 +124,45 @@ func (d *arpDispatcher) nextEvent() (eventInfo, bool) {
type testContext struct {
s *stack.Stack
linkEP *channel.Endpoint
nudDisp *arpDispatcher
nudDisp arpDispatcher
}
func newTestContext(t *testing.T) *testContext {
c := stack.DefaultNUDConfigurations()
// Transition from Reachable to Stale almost immediately to test if receiving
// probes refreshes positive reachability.
c.BaseReachableTime = time.Microsecond
func makeTestContext(t *testing.T, eventDepth int, packetDepth int) testContext {
t.Helper()
d := arpDispatcher{
// Create an event channel large enough so the neighbor cache doesn't block
// while dispatching events. Blocking could interfere with the timing of
// NUD transitions.
C: make(chan eventInfo, eventChanSize),
tc := testContext{
nudDisp: arpDispatcher{
C: make(chan eventInfo, eventDepth),
},
}
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, arp.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol4},
NUDConfigs: c,
NUDDisp: &d,
tc.s = stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, arp.NewProtocol},
NUDDisp: &tc.nudDisp,
Clock: &faketime.NullClock{},
})
ep := channel.New(defaultChannelSize, defaultMTU, stackLinkAddr)
ep.LinkEPCapabilities |= stack.CapabilityResolutionRequired
wep := stack.LinkEndpoint(ep)
tc.linkEP = channel.New(packetDepth, header.IPv4MinimumMTU, stackLinkAddr)
tc.linkEP.LinkEPCapabilities |= stack.CapabilityResolutionRequired
wep := stack.LinkEndpoint(tc.linkEP)
if testing.Verbose() {
wep = sniffer.New(ep)
wep = sniffer.New(wep)
}
if err := s.CreateNIC(nicID, wep); err != nil {
t.Fatalf("CreateNIC failed: %v", err)
if err := tc.s.CreateNIC(nicID, wep); err != nil {
t.Fatalf("CreateNIC failed: %s", err)
}
if err := s.AddAddress(nicID, ipv4.ProtocolNumber, stackAddr); err != nil {
t.Fatalf("AddAddress for ipv4 failed: %v", err)
if err := tc.s.AddAddress(nicID, ipv4.ProtocolNumber, stackAddr); err != nil {
t.Fatalf("AddAddress for ipv4 failed: %s", err)
}
s.SetRouteTable([]tcpip.Route{{
tc.s.SetRouteTable([]tcpip.Route{{
Destination: header.IPv4EmptySubnet,
NIC: nicID,
}})
return &testContext{
s: s,
linkEP: ep,
nudDisp: &d,
}
return tc
}
func (c *testContext) cleanup() {
@@ -209,7 +170,7 @@ func (c *testContext) cleanup() {
}
func TestMalformedPacket(t *testing.T) {
c := newTestContext(t)
c := makeTestContext(t, 0, 0)
defer c.cleanup()
v := make(buffer.View, header.ARPSize)
@@ -228,7 +189,7 @@ func TestMalformedPacket(t *testing.T) {
}
func TestDisabledEndpoint(t *testing.T) {
c := newTestContext(t)
c := makeTestContext(t, 0, 0)
defer c.cleanup()
ep, err := c.s.GetNetworkEndpoint(nicID, header.ARPProtocolNumber)
@@ -253,7 +214,7 @@ func TestDisabledEndpoint(t *testing.T) {
}
func TestDirectReply(t *testing.T) {
c := newTestContext(t)
c := makeTestContext(t, 0, 0)
defer c.cleanup()
const senderMAC = "\x01\x02\x03\x04\x05\x06"
@@ -284,7 +245,7 @@ func TestDirectReply(t *testing.T) {
}
func TestDirectRequest(t *testing.T) {
c := newTestContext(t)
c := makeTestContext(t, 1, 1)
defer c.cleanup()
tests := []struct {
@@ -391,17 +352,21 @@ func TestDirectRequest(t *testing.T) {
}
// Verify the sender was saved in the neighbor cache.
wantEvent := eventInfo{
eventType: entryAdded,
nicID: nicID,
entry: stack.NeighborEntry{
Addr: test.senderAddr,
LinkAddr: test.senderLinkAddr,
State: stack.Stale,
},
}
if err := c.nudDisp.waitForEventWithTimeout(wantEvent, time.Second); err != nil {
t.Fatal(err)
if got, ok := c.nudDisp.nextEvent(); ok {
want := eventInfo{
eventType: entryAdded,
nicID: nicID,
entry: stack.NeighborEntry{
Addr: test.senderAddr,
LinkAddr: test.senderLinkAddr,
State: stack.Stale,
},
}
if diff := cmp.Diff(want, got, cmp.AllowUnexported(eventInfo{}), cmpopts.IgnoreFields(stack.NeighborEntry{}, "UpdatedAt")); diff != "" {
t.Errorf("got invalid event (-want +got):\n%s", diff)
}
} else {
t.Fatal("event didn't arrive")
}
neighbors, err := c.s.Neighbors(nicID, ipv4.ProtocolNumber)
@@ -589,7 +554,7 @@ func TestLinkAddressRequest(t *testing.T) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocol, ipv4.NewProtocol},
})
linkEP := channel.New(defaultChannelSize, defaultMTU, stackLinkAddr)
linkEP := channel.New(1, header.IPv4MinimumMTU, stackLinkAddr)
if err := s.CreateNIC(nicID, &testLinkEndpoint{LinkEndpoint: linkEP, writeErr: test.linkErr}); err != nil {
t.Fatalf("s.CreateNIC(%d, _): %s", nicID, err)
}
@@ -663,15 +628,16 @@ func TestLinkAddressRequest(t *testing.T) {
}
func TestDADARPRequestPacket(t *testing.T) {
clock := faketime.NewManualClock()
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocolWithOptions(arp.Options{
DADConfigs: stack.DADConfigurations{
DupAddrDetectTransmits: 1,
RetransmitTimer: time.Second,
},
}), ipv4.NewProtocol},
Clock: clock,
})
e := channel.New(1, defaultMTU, stackLinkAddr)
e := channel.New(1, header.IPv4MinimumMTU, stackLinkAddr)
if err := s.CreateNIC(nicID, e); err != nil {
t.Fatalf("s.CreateNIC(%d, _): %s", nicID, err)
}
@@ -682,7 +648,8 @@ func TestDADARPRequestPacket(t *testing.T) {
t.Fatalf("got s.CheckDuplicateAddress(%d, %d, %s, _) = %d, want = %d", nicID, header.IPv4ProtocolNumber, remoteAddr, res, stack.DADStarting)
}
pkt, ok := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
pkt, ok := e.Read()
if !ok {
t.Fatal("expected to send an ARP request")
}
+7 -4
View File
@@ -16,7 +16,6 @@ package ipv4_test
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"io/ioutil"
@@ -3086,7 +3085,7 @@ func TestPacketQueing(t *testing.T) {
}))
},
checkResp: func(t *testing.T, e *channel.Endpoint) {
p, ok := e.ReadContext(context.Background())
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -3129,7 +3128,7 @@ func TestPacketQueing(t *testing.T) {
}))
},
checkResp: func(t *testing.T, e *channel.Endpoint) {
p, ok := e.ReadContext(context.Background())
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -3153,9 +3152,11 @@ func TestPacketQueing(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
e := channel.New(1, defaultMTU, host1NICLinkAddr)
e.LinkEPCapabilities |= stack.CapabilityResolutionRequired
clock := faketime.NewManualClock()
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{arp.NewProtocol, ipv4.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
Clock: clock,
})
if err := s.CreateNIC(nicID, e); err != nil {
@@ -3178,7 +3179,8 @@ func TestPacketQueing(t *testing.T) {
// Wait for a ARP request since link address resolution should be
// performed.
{
p, ok := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -3219,6 +3221,7 @@ func TestPacketQueing(t *testing.T) {
}
// Expect the response now that the link address has resolved.
clock.RunImmediatelyScheduledJobs()
test.checkResp(t, e)
// Since link resolution was already performed, it shouldn't be performed
+22 -8
View File
@@ -16,7 +16,6 @@ package ipv6
import (
"bytes"
"context"
"net"
"reflect"
"strings"
@@ -26,6 +25,7 @@ import (
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/buffer"
"gvisor.dev/gvisor/pkg/tcpip/checker"
"gvisor.dev/gvisor/pkg/tcpip/faketime"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
"gvisor.dev/gvisor/pkg/tcpip/link/sniffer"
@@ -366,6 +366,8 @@ type testContext struct {
linkEP0 *channel.Endpoint
linkEP1 *channel.Endpoint
clock *faketime.ManualClock
}
type endpointWithResolutionCapability struct {
@@ -377,15 +379,19 @@ func (e endpointWithResolutionCapability) Capabilities() stack.LinkEndpointCapab
}
func newTestContext(t *testing.T) *testContext {
clock := faketime.NewManualClock()
c := &testContext{
s0: stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},
Clock: clock,
}),
s1: stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{icmp.NewProtocol6},
Clock: clock,
}),
clock: clock,
}
c.linkEP0 = channel.New(defaultChannelSize, defaultMTU, linkAddr0)
@@ -452,10 +458,14 @@ type routeArgs struct {
remoteLinkAddr tcpip.LinkAddress
}
func routeICMPv6Packet(t *testing.T, args routeArgs, fn func(*testing.T, header.ICMPv6)) {
func routeICMPv6Packet(t *testing.T, clock *faketime.ManualClock, args routeArgs, fn func(*testing.T, header.ICMPv6)) {
t.Helper()
pi, _ := args.src.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
pi, ok := args.src.Read()
if !ok {
t.Fatal("packet didn't arrive")
}
{
pkt := stack.NewPacketBuffer(stack.PacketBufferOptions{
@@ -528,7 +538,7 @@ func TestLinkResolution(t *testing.T) {
{src: c.linkEP0, dst: c.linkEP1, typ: header.ICMPv6NeighborSolicit, remoteLinkAddr: header.EthernetAddressFromMulticastIPv6Address(header.SolicitedNodeAddr(lladdr1))},
{src: c.linkEP1, dst: c.linkEP0, typ: header.ICMPv6NeighborAdvert},
} {
routeICMPv6Packet(t, args, func(t *testing.T, icmpv6 header.ICMPv6) {
routeICMPv6Packet(t, c.clock, args, func(t *testing.T, icmpv6 header.ICMPv6) {
if got, want := tcpip.Address(icmpv6[8:][:16]), lladdr1; got != want {
t.Errorf("%d: got target = %s, want = %s", icmpv6.Type(), got, want)
}
@@ -539,7 +549,7 @@ func TestLinkResolution(t *testing.T) {
{src: c.linkEP0, dst: c.linkEP1, typ: header.ICMPv6EchoRequest},
{src: c.linkEP1, dst: c.linkEP0, typ: header.ICMPv6EchoReply},
} {
routeICMPv6Packet(t, args, nil)
routeICMPv6Packet(t, c.clock, args, nil)
}
}
@@ -1320,7 +1330,7 @@ func TestPacketQueing(t *testing.T) {
}))
},
checkResp: func(t *testing.T, e *channel.Endpoint) {
p, ok := e.ReadContext(context.Background())
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -1366,7 +1376,7 @@ func TestPacketQueing(t *testing.T) {
}))
},
checkResp: func(t *testing.T, e *channel.Endpoint) {
p, ok := e.ReadContext(context.Background())
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -1391,9 +1401,11 @@ func TestPacketQueing(t *testing.T) {
e := channel.New(1, header.IPv6MinimumMTU, host1NICLinkAddr)
e.LinkEPCapabilities |= stack.CapabilityResolutionRequired
clock := faketime.NewManualClock()
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
Clock: clock,
})
if err := s.CreateNIC(nicID, e); err != nil {
@@ -1416,7 +1428,8 @@ func TestPacketQueing(t *testing.T) {
// Wait for a neighbor solicitation since link address resolution should
// be performed.
{
p, ok := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
p, ok := e.Read()
if !ok {
t.Fatalf("timed out waiting for packet")
}
@@ -1470,6 +1483,7 @@ func TestPacketQueing(t *testing.T) {
}
// Expect the response now that the link address has resolved.
clock.RunImmediatelyScheduledJobs()
test.checkResp(t, e)
// Since link resolution was already performed, it shouldn't be performed
+15 -11
View File
@@ -16,7 +16,6 @@ package ipv6
import (
"bytes"
"context"
"math/rand"
"strings"
"testing"
@@ -400,8 +399,10 @@ func TestNeighborSolicitationResponse(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
clock := faketime.NewManualClock()
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{NewProtocol},
Clock: clock,
})
e := channel.New(1, 1280, nicLinkAddr)
e.LinkEPCapabilities |= stack.CapabilityResolutionRequired
@@ -471,7 +472,8 @@ func TestNeighborSolicitationResponse(t *testing.T) {
}
if test.performsLinkResolution {
p, got := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
p, got := e.Read()
if !got {
t.Fatal("expected an NDP NS response")
}
@@ -526,7 +528,8 @@ func TestNeighborSolicitationResponse(t *testing.T) {
}))
}
p, got := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
p, got := e.Read()
if !got {
t.Fatal("expected an NDP NA response")
}
@@ -850,12 +853,12 @@ func TestNDPValidation(t *testing.T) {
routerOnly := stats.RouterOnlyPacketsDroppedByHost
typStat := typ.statCounter(stats)
icmp := header.ICMPv6(buffer.NewView(typ.size + len(typ.extraData)))
copy(icmp[typ.size:], typ.extraData)
icmp.SetType(typ.typ)
icmp.SetCode(test.code)
icmp.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
Header: icmp[:typ.size],
icmpH := header.ICMPv6(buffer.NewView(typ.size + len(typ.extraData)))
copy(icmpH[typ.size:], typ.extraData)
icmpH.SetType(typ.typ)
icmpH.SetCode(test.code)
icmpH.SetChecksum(header.ICMPv6Checksum(header.ICMPv6ChecksumParams{
Header: icmpH[:typ.size],
Src: lladdr0,
Dst: lladdr1,
PayloadCsum: header.Checksum(typ.extraData /* initial */, 0),
@@ -881,7 +884,7 @@ func TestNDPValidation(t *testing.T) {
t.FailNow()
}
handleIPv6Payload(buffer.View(icmp), test.hopLimit, test.atomicFragment, ep)
handleIPv6Payload(buffer.View(icmpH), test.hopLimit, test.atomicFragment, ep)
// Rx count of the NDP packet should have increased.
if got := typStat.Value(); got != 1 {
@@ -1260,7 +1263,8 @@ func TestCheckDuplicateAddress(t *testing.T) {
snmc := header.SolicitedNodeAddr(lladdr0)
remoteLinkAddr := header.EthernetAddressFromMulticastIPv6Address(snmc)
checkDADMsg := func() {
p, ok := e.ReadContext(context.Background())
clock.RunImmediatelyScheduledJobs()
p, ok := e.Read()
if !ok {
t.Fatalf("expected %d-th DAD message", dadPacketsSent)
}
File diff suppressed because it is too large Load Diff
+15 -9
View File
@@ -2640,15 +2640,17 @@ func TestNICAutoGenAddrDoesDAD(t *testing.T) {
const nicID = 1
ndpDisp := ndpDispatcher{
dadC: make(chan ndpDADEvent),
dadC: make(chan ndpDADEvent, 1),
}
dadConfigs := stack.DefaultDADConfigurations()
clock := faketime.NewManualClock()
opts := stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{
AutoGenLinkLocal: true,
NDPDisp: &ndpDisp,
DADConfigs: dadConfigs,
})},
Clock: clock,
}
e := channel.New(int(dadConfigs.DupAddrDetectTransmits), 1280, linkAddr1)
@@ -2666,17 +2668,18 @@ func TestNICAutoGenAddrDoesDAD(t *testing.T) {
linkLocalAddr := header.LinkLocalAddr(linkAddr1)
// Wait for DAD to resolve.
clock.Advance(time.Duration(dadConfigs.DupAddrDetectTransmits) * dadConfigs.RetransmitTimer)
select {
case <-time.After(time.Duration(dadConfigs.DupAddrDetectTransmits)*dadConfigs.RetransmitTimer + time.Second):
case e := <-ndpDisp.dadC:
if diff := checkDADEvent(e, nicID, linkLocalAddr, &stack.DADSucceeded{}); diff != "" {
t.Errorf("dad event mismatch (-want +got):\n%s", diff)
}
default:
// We should get a resolution event after 1s (default time to
// resolve as per default NDP configurations). Waiting for that
// resolution time + an extra 1s without a resolution event
// means something is wrong.
t.Fatal("timed out waiting for DAD resolution")
case e := <-ndpDisp.dadC:
if diff := checkDADEvent(e, nicID, linkLocalAddr, &stack.DADSucceeded{}); diff != "" {
t.Errorf("dad event mismatch (-want +got):\n%s", diff)
}
}
if err := checkGetMainNICAddress(s, nicID, header.IPv6ProtocolNumber, tcpip.AddressWithPrefix{Address: linkLocalAddr, PrefixLen: header.IPv6LinkLocalPrefix.PrefixLen}); err != nil {
t.Fatal(err)
@@ -3307,8 +3310,9 @@ func TestDoDADWhenNICEnabled(t *testing.T) {
const nicID = 1
ndpDisp := ndpDispatcher{
dadC: make(chan ndpDADEvent),
dadC: make(chan ndpDADEvent, 1),
}
clock := faketime.NewManualClock()
opts := stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv6.NewProtocolWithOptions(ipv6.Options{
DADConfigs: stack.DADConfigurations{
@@ -3317,6 +3321,7 @@ func TestDoDADWhenNICEnabled(t *testing.T) {
},
NDPDisp: &ndpDisp,
})},
Clock: clock,
}
e := channel.New(dadTransmits, 1280, linkAddr1)
@@ -3361,13 +3366,14 @@ func TestDoDADWhenNICEnabled(t *testing.T) {
}
// Wait for DAD to resolve.
clock.Advance(dadTransmits * retransmitTimer)
select {
case <-time.After(dadTransmits*retransmitTimer + defaultAsyncPositiveEventTimeout):
t.Fatal("timed out waiting for DAD resolution")
case e := <-ndpDisp.dadC:
if diff := checkDADEvent(e, nicID, addr.AddressWithPrefix.Address, &stack.DADSucceeded{}); diff != "" {
t.Errorf("dad event mismatch (-want +got):\n%s", diff)
}
default:
t.Fatal("timed out waiting for DAD resolution")
}
if addrs := s.AllAddresses()[nicID]; !containsV6Addr(addrs, addr.AddressWithPrefix) {
t.Fatalf("got s.AllAddresses()[%d] = %+v, want = %+v", nicID, addrs, addr)
+31 -22
View File
@@ -129,10 +129,14 @@ func TestJobReschedule(t *testing.T) {
wg.Wait()
}
func stdClockWithAfter() (tcpip.Clock, func(time.Duration) <-chan time.Time) {
return tcpip.NewStdClock(), time.After
}
func TestJobExecution(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after := stdClockWithAfter()
var lock sync.Mutex
ch := make(chan struct{})
@@ -144,7 +148,7 @@ func TestJobExecution(t *testing.T) {
// Wait for timer to fire.
select {
case <-ch:
case <-time.After(middleDuration):
case <-after(middleDuration):
t.Fatal("timed out waiting for timer to fire")
}
@@ -152,14 +156,14 @@ func TestJobExecution(t *testing.T) {
select {
case <-ch:
t.Fatal("no other timers should have fired")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
func TestCancellableTimerResetFromLongDuration(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after := stdClockWithAfter()
var lock sync.Mutex
ch := make(chan struct{})
@@ -175,7 +179,7 @@ func TestCancellableTimerResetFromLongDuration(t *testing.T) {
// Wait for timer to fire.
select {
case <-ch:
case <-time.After(middleDuration):
case <-after(middleDuration):
t.Fatal("timed out waiting for timer to fire")
}
@@ -183,14 +187,14 @@ func TestCancellableTimerResetFromLongDuration(t *testing.T) {
select {
case <-ch:
t.Fatal("no other timers should have fired")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
func TestJobRescheduleFromShortDuration(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after := stdClockWithAfter()
var lock sync.Mutex
ch := make(chan struct{})
@@ -204,7 +208,7 @@ func TestJobRescheduleFromShortDuration(t *testing.T) {
select {
case <-ch:
t.Fatal("timer fired after being stopped")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
job.Schedule(shortDuration)
@@ -212,7 +216,7 @@ func TestJobRescheduleFromShortDuration(t *testing.T) {
// Wait for timer to fire.
select {
case <-ch:
case <-time.After(middleDuration):
case <-after(middleDuration):
t.Fatal("timed out waiting for timer to fire")
}
@@ -220,14 +224,14 @@ func TestJobRescheduleFromShortDuration(t *testing.T) {
select {
case <-ch:
t.Fatal("no other timers should have fired")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
func TestJobImmediatelyCancel(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after := stdClockWithAfter()
var lock sync.Mutex
ch := make(chan struct{})
@@ -243,14 +247,19 @@ func TestJobImmediatelyCancel(t *testing.T) {
select {
case <-ch:
t.Fatal("timer fired after being stopped")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
func stdClockWithAfterAndSleep() (tcpip.Clock, func(time.Duration) <-chan time.Time, func(time.Duration)) {
clock, after := stdClockWithAfter()
return clock, after, time.Sleep
}
func TestJobCancelledRescheduleWithoutLock(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after, sleep := stdClockWithAfterAndSleep()
var lock sync.Mutex
ch := make(chan struct{})
@@ -265,7 +274,7 @@ func TestJobCancelledRescheduleWithoutLock(t *testing.T) {
lock.Lock()
// Sleep until the timer fires and gets blocked trying to take the lock.
time.Sleep(middleDuration * 2)
sleep(middleDuration * 2)
job.Cancel()
lock.Unlock()
}
@@ -275,14 +284,14 @@ func TestJobCancelledRescheduleWithoutLock(t *testing.T) {
select {
case <-ch:
t.Fatal("timer fired after being stopped")
case <-time.After(middleDuration * 2):
case <-after(middleDuration * 2):
}
}
func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after, sleep := stdClockWithAfterAndSleep()
var lock sync.Mutex
ch := make(chan struct{})
@@ -291,7 +300,7 @@ func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {
job.Schedule(shortDuration)
for i := 0; i < 10; i++ {
// Sleep until the timer fires and gets blocked trying to take the lock.
time.Sleep(middleDuration)
sleep(middleDuration)
job.Cancel()
job.Schedule(shortDuration)
}
@@ -300,7 +309,7 @@ func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {
// Wait for double the duration for the last timer to fire.
select {
case <-ch:
case <-time.After(middleDuration):
case <-after(middleDuration):
t.Fatal("timed out waiting for timer to fire")
}
@@ -308,14 +317,14 @@ func TestManyCancellableTimerResetAfterBlockedOnLock(t *testing.T) {
select {
case <-ch:
t.Fatal("no other timers should have fired")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
func TestManyJobReschedulesUnderLock(t *testing.T) {
t.Parallel()
clock := tcpip.NewStdClock()
clock, after := stdClockWithAfter()
var lock sync.Mutex
ch := make(chan struct{})
@@ -331,7 +340,7 @@ func TestManyJobReschedulesUnderLock(t *testing.T) {
// Wait for double the duration for the last timer to fire.
select {
case <-ch:
case <-time.After(middleDuration):
case <-after(middleDuration):
t.Fatal("timed out waiting for timer to fire")
}
@@ -339,6 +348,6 @@ func TestManyJobReschedulesUnderLock(t *testing.T) {
select {
case <-ch:
t.Fatal("no other timers should have fired")
case <-time.After(middleDuration):
case <-after(middleDuration):
}
}
+1
View File
@@ -49,6 +49,7 @@ go_test(
"//pkg/tcpip",
"//pkg/tcpip/buffer",
"//pkg/tcpip/checker",
"//pkg/tcpip/faketime",
"//pkg/tcpip/header",
"//pkg/tcpip/link/channel",
"//pkg/tcpip/link/loopback",
+29 -38
View File
@@ -16,17 +16,16 @@ package udp_test
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"math/rand"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/buffer"
"gvisor.dev/gvisor/pkg/tcpip/checker"
"gvisor.dev/gvisor/pkg/tcpip/faketime"
"gvisor.dev/gvisor/pkg/tcpip/header"
"gvisor.dev/gvisor/pkg/tcpip/link/channel"
"gvisor.dev/gvisor/pkg/tcpip/link/loopback"
@@ -298,16 +297,18 @@ type testContext struct {
func newDualTestContext(t *testing.T, mtu uint32) *testContext {
t.Helper()
return newDualTestContextWithOptions(t, mtu, stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, icmp.NewProtocol6, icmp.NewProtocol4},
HandleLocal: true,
})
return newDualTestContextWithHandleLocal(t, mtu, true)
}
func newDualTestContextWithOptions(t *testing.T, mtu uint32, options stack.Options) *testContext {
func newDualTestContextWithHandleLocal(t *testing.T, mtu uint32, handleLocal bool) *testContext {
t.Helper()
options := stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol, icmp.NewProtocol6, icmp.NewProtocol4},
HandleLocal: handleLocal,
Clock: &faketime.NullClock{},
}
s := stack.New(options)
ep := channel.New(256, mtu, "")
wep := stack.LinkEndpoint(ep)
@@ -378,9 +379,7 @@ func (c *testContext) createEndpointForFlow(flow testFlow) {
func (c *testContext) getPacketAndVerify(flow testFlow, checkers ...checker.NetworkChecker) []byte {
c.t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
p, ok := c.linkEP.ReadContext(ctx)
p, ok := c.linkEP.Read()
if !ok {
c.t.Fatalf("Packet wasn't written out")
return nil
@@ -534,7 +533,9 @@ func newMinPayload(minSize int) []byte {
func TestBindToDeviceOption(t *testing.T) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol}})
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
Clock: &faketime.NullClock{},
})
ep, err := s.NewEndpoint(udp.ProtocolNumber, ipv4.ProtocolNumber, &waiter.Queue{})
if err != nil {
@@ -606,7 +607,7 @@ func testReadInternal(c *testContext, flow testFlow, packetShouldBeDropped, expe
case <-ch:
res, err = c.ep.Read(&buf, tcpip.ReadOptions{NeedRemoteAddr: true})
case <-time.After(300 * time.Millisecond):
default:
if packetShouldBeDropped {
return // expected to time out
}
@@ -820,11 +821,7 @@ func TestV4ReadSelfSource(t *testing.T) {
{"NoHandleLocal", true, &tcpip.ErrWouldBlock{}, 1},
} {
t.Run(tt.name, func(t *testing.T) {
c := newDualTestContextWithOptions(t, defaultMTU, stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
HandleLocal: tt.handleLocal,
})
c := newDualTestContextWithHandleLocal(t, defaultMTU, tt.handleLocal)
defer c.cleanup()
c.createEndpointForFlow(unicastV4)
@@ -1034,17 +1031,17 @@ func testWriteAndVerifyInternal(c *testContext, flow testFlow, setDest bool, che
payload := testWriteNoVerify(c, flow, setDest)
// Received the packet and check the payload.
b := c.getPacketAndVerify(flow, checkers...)
var udp header.UDP
var udpH header.UDP
if flow.isV4() {
udp = header.UDP(header.IPv4(b).Payload())
udpH = header.IPv4(b).Payload()
} else {
udp = header.UDP(header.IPv6(b).Payload())
udpH = header.IPv6(b).Payload()
}
if !bytes.Equal(payload, udp.Payload()) {
c.t.Fatalf("Bad payload: got %x, want %x", udp.Payload(), payload)
if !bytes.Equal(payload, udpH.Payload()) {
c.t.Fatalf("Bad payload: got %x, want %x", udpH.Payload(), payload)
}
return udp.SourcePort()
return udpH.SourcePort()
}
func testDualWrite(c *testContext) uint16 {
@@ -1198,7 +1195,7 @@ func TestWriteOnConnectedInvalidPort(t *testing.T) {
r.Reset(payload)
n, err := c.ep.Write(&r, writeOpts)
if err != nil {
c.t.Fatalf("c.ep.Write(...) = %+s, want nil", err)
c.t.Fatalf("c.ep.Write(...) = %s, want nil", err)
}
if got, want := n, int64(len(payload)); got != want {
c.t.Fatalf("c.ep.Write(...) wrote %d bytes, want %d bytes", got, want)
@@ -1614,6 +1611,7 @@ func TestTTL(t *testing.T) {
}
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{p},
Clock: &faketime.NullClock{},
})
ep := s.NetworkProtocolInstance(n).NewEndpoint(&testInterface{}, nil)
wantTTL = ep.DefaultTTL()
@@ -1759,7 +1757,7 @@ func TestReceiveTosTClass(t *testing.T) {
c.t.Errorf("got GetSockOptBool(%s) = %t, want = %t", name, v, false)
}
want := true
const want = true
optionSetter(want)
got := optionGetter()
@@ -1889,18 +1887,14 @@ func TestV4UnknownDestination(t *testing.T) {
}
}
if !tc.icmpRequired {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if p, ok := c.linkEP.ReadContext(ctx); ok {
if p, ok := c.linkEP.Read(); ok {
t.Fatalf("unexpected packet received: %+v", p)
}
return
}
// ICMP required.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
p, ok := c.linkEP.ReadContext(ctx)
p, ok := c.linkEP.Read()
if !ok {
t.Fatalf("packet wasn't written out")
return
@@ -1987,18 +1981,14 @@ func TestV6UnknownDestination(t *testing.T) {
}
}
if !tc.icmpRequired {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if p, ok := c.linkEP.ReadContext(ctx); ok {
if p, ok := c.linkEP.Read(); ok {
t.Fatalf("unexpected packet received: %+v", p)
}
return
}
// ICMP required.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
p, ok := c.linkEP.ReadContext(ctx)
p, ok := c.linkEP.Read()
if !ok {
t.Fatalf("packet wasn't written out")
return
@@ -2486,6 +2476,7 @@ func TestOutgoingSubnetBroadcast(t *testing.T) {
s := stack.New(stack.Options{
NetworkProtocols: []stack.NetworkProtocolFactory{ipv4.NewProtocol, ipv6.NewProtocol},
TransportProtocols: []stack.TransportProtocolFactory{udp.NewProtocol},
Clock: &faketime.NullClock{},
})
e := channel.New(0, defaultMTU, "")
if err := s.CreateNIC(nicID1, e); err != nil {