diff --git a/wgengine/bench/trafficgen.go b/wgengine/bench/trafficgen.go
index ce79c616f..6f86c8b03 100644
--- a/wgengine/bench/trafficgen.go
+++ b/wgengine/bench/trafficgen.go
@@ -12,9 +12,12 @@ import (
"time"
"tailscale.com/net/packet"
+ "tailscale.com/tstime"
"tailscale.com/types/ipproto"
)
+var clock = tstime.StdClock{}
+
type Snapshot struct {
WhenNsec int64 // current time
timeAcc int64 // accumulated time (+NSecPerTx per transmit)
@@ -122,7 +125,7 @@ func (t *TrafficGen) Snap() Snapshot {
t.mu.Lock()
defer t.mu.Unlock()
- t.cur.WhenNsec = time.Now().UnixNano()
+ t.cur.WhenNsec = clock.Now().UnixNano()
return t.cur
}
@@ -144,7 +147,7 @@ func (t *TrafficGen) Running() bool {
func (t *TrafficGen) Generate(b []byte, ofs int) int {
t.mu.Lock()
- now := time.Now().UnixNano()
+ now := clock.Now().UnixNano()
if t.nsPerPacket == 0 || t.cur.timeAcc == 0 {
t.cur.timeAcc = now - 1
}
diff --git a/wgengine/capture/capture.go b/wgengine/capture/capture.go
index 6ea5a9549..4b0fdc925 100644
--- a/wgengine/capture/capture.go
+++ b/wgengine/capture/capture.go
@@ -16,6 +16,7 @@ import (
_ "embed"
"tailscale.com/net/packet"
+ "tailscale.com/tstime"
"tailscale.com/util/set"
)
@@ -37,6 +38,8 @@ var bufferPool = sync.Pool{
const flushPeriod = 100 * time.Millisecond
+var clock = tstime.StdClock{}
+
func writePcapHeader(w io.Writer) {
binary.Write(w, binary.LittleEndian, uint32(0xA1B2C3D4)) // pcap magic number
binary.Write(w, binary.LittleEndian, uint16(2)) // version major
@@ -96,7 +99,7 @@ type Sink struct {
mu sync.Mutex
outputs set.HandleSet[io.Writer]
- flushTimer *time.Timer // or nil if none running
+ flushTimer tstime.TimerController // or nil if none running
}
// RegisterOutput connects an output to this sink, which
@@ -224,7 +227,7 @@ func (s *Sink) LogPacket(path Path, when time.Time, data []byte, meta packet.Cap
}
if s.flushTimer == nil {
- s.flushTimer = time.AfterFunc(flushPeriod, func() {
+ s.flushTimer = clock.AfterFunc(flushPeriod, func() {
s.mu.Lock()
defer s.mu.Unlock()
for _, o := range s.outputs {
diff --git a/wgengine/magicsock/debughttp.go b/wgengine/magicsock/debughttp.go
index a1f17b560..8b6e9c16b 100644
--- a/wgengine/magicsock/debughttp.go
+++ b/wgengine/magicsock/debughttp.go
@@ -27,7 +27,7 @@ func (c *Conn) ServeHTTPDebug(w http.ResponseWriter, r *http.Request) {
c.mu.Lock()
defer c.mu.Unlock()
- now := time.Now()
+ now := clock.Now()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "
magicsock
")
@@ -132,7 +132,7 @@ func printEndpointHTML(w io.Writer, ep *endpoint) {
return // no activity ever
}
- now := time.Now()
+ now := clock.Now()
mnow := mono.Now()
fmtMono := func(m mono.Time) string {
if m == 0 {
diff --git a/wgengine/magicsock/magicsock.go b/wgengine/magicsock/magicsock.go
index c52df03f0..5190a9211 100644
--- a/wgengine/magicsock/magicsock.go
+++ b/wgengine/magicsock/magicsock.go
@@ -73,6 +73,8 @@ const (
socketBufferSize = 7 << 20
)
+var clock = tstime.StdClock{}
+
// A Conn routes UDP packets and actively manages a list of its endpoints.
type Conn struct {
// This block mirrors the contents and field order of the Options
@@ -189,7 +191,7 @@ type Conn struct {
// derpCleanupTimer is the timer that fires to occasionally clean
// up idle DERP connections. It's only used when there is a non-home
// DERP connection in use.
- derpCleanupTimer *time.Timer
+ derpCleanupTimer tstime.TimerController
// derpCleanupTimerArmed is whether derpCleanupTimer is
// scheduled to fire within derpCleanStaleInterval.
@@ -197,7 +199,7 @@ type Conn struct {
// periodicReSTUNTimer, when non-nil, is an AfterFunc timer
// that will call Conn.doPeriodicSTUN.
- periodicReSTUNTimer *time.Timer
+ periodicReSTUNTimer tstime.TimerController
// endpointsUpdateActive indicates that updateEndpoints is
// currently running. It's used to deduplicate concurrent endpoint
@@ -495,7 +497,7 @@ func (c *Conn) updateEndpoints(why string) {
if debugReSTUNStopOnIdle() {
c.logf("scheduling periodicSTUN to run in %v", d)
}
- c.periodicReSTUNTimer = time.AfterFunc(d, c.doPeriodicSTUN)
+ c.periodicReSTUNTimer = clock.AfterFunc(d, c.doPeriodicSTUN)
}
} else {
if debugReSTUNStopOnIdle() {
@@ -559,7 +561,7 @@ func (c *Conn) setEndpoints(endpoints []tailcfg.Endpoint) (changed bool) {
return false
}
- c.lastEndpointsTime = time.Now()
+ c.lastEndpointsTime = clock.Now()
for de, fn := range c.onEndpointRefreshed {
go fn()
delete(c.onEndpointRefreshed, de)
@@ -861,7 +863,7 @@ func (c *Conn) determineEndpoints(ctx context.Context) ([]tailcfg.Endpoint, erro
// endpoints if they do actually time out without being rediscovered.
// For now, though, rely on a minor LinkChange event causing this to
// re-run.
- eps = c.endpointTracker.update(time.Now(), eps)
+ eps = c.endpointTracker.update(clock.Now(), eps)
if localAddr := c.pconn4.LocalAddr(); localAddr.IP.IsUnspecified() {
ips, loopback, err := interfaces.LocalAddresses()
@@ -1365,7 +1367,7 @@ func (c *Conn) handleDiscoMessage(msg []byte, src netip.AddrPort, derpNodeSrc ke
// Emit information about the disco frame into the pcap stream
// if a capture hook is installed.
if cb := c.captureHook.Load(); cb != nil {
- cb(capture.PathDisco, time.Now(), disco.ToPCAPFrame(src, derpNodeSrc, payload), packet.CaptureMeta{})
+ cb(capture.PathDisco, clock.Now(), disco.ToPCAPFrame(src, derpNodeSrc, payload), packet.CaptureMeta{})
}
dm, err := disco.Parse(payload)
@@ -1479,7 +1481,7 @@ func (c *Conn) unambiguousNodeKeyOfPingLocked(dm *disco.Ping, dk key.DiscoPublic
func (c *Conn) handlePingLocked(dm *disco.Ping, src netip.AddrPort, di *discoInfo, derpNodeSrc key.NodePublic) {
likelyHeartBeat := src == di.lastPingFrom && time.Since(di.lastPingTime) < 5*time.Second
di.lastPingFrom = src
- di.lastPingTime = time.Now()
+ di.lastPingTime = clock.Now()
isDerp := src.Addr() == tailcfg.DerpMagicIPAddr
// If we can figure out with certainty which node key this disco
@@ -1571,7 +1573,7 @@ func (c *Conn) enqueueCallMeMaybe(derpAddr netip.AddrPort, de *endpoint) {
return
}
- if !c.lastEndpointsTime.After(time.Now().Add(-endpointsFreshEnoughDuration)) {
+ if !c.lastEndpointsTime.After(clock.Now().Add(-endpointsFreshEnoughDuration)) {
c.dlogf("[v1] magicsock: want call-me-maybe but endpoints stale; restunning")
mak.Set(&c.onEndpointRefreshed, de, func() {
diff --git a/wgengine/magicsock/magicsock_linux.go b/wgengine/magicsock/magicsock_linux.go
index a4101ccba..e2ec7590d 100644
--- a/wgengine/magicsock/magicsock_linux.go
+++ b/wgengine/magicsock/magicsock_linux.go
@@ -185,7 +185,7 @@ func (c *Conn) listenRawDisco(family string) (io.Closer, error) {
pc.Close()
return nil, fmt.Errorf("writing disco test packet: %w", err)
}
- pc.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
+ pc.SetReadDeadline(clock.Now().Add(100 * time.Millisecond))
var buf [1500]byte
for {
n, _, err := pc.ReadFrom(buf[:])
diff --git a/wgengine/netstack/netstack.go b/wgengine/netstack/netstack.go
index b89c6e898..a13184155 100644
--- a/wgengine/netstack/netstack.go
+++ b/wgengine/netstack/netstack.go
@@ -44,6 +44,7 @@ import (
"tailscale.com/net/tsdial"
"tailscale.com/net/tstun"
"tailscale.com/syncs"
+ "tailscale.com/tstime"
"tailscale.com/types/ipproto"
"tailscale.com/types/logger"
"tailscale.com/types/netmap"
@@ -63,6 +64,8 @@ var (
magicDNSIPv6 = tsaddr.TailscaleServiceIPv6()
)
+var clock = tstime.StdClock{}
+
func init() {
mode := envknob.String("TS_DEBUG_NETSTACK_LEAK_MODE")
if mode == "" {
@@ -615,7 +618,7 @@ func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
}
defer userPingSem.Release()
- t0 := time.Now()
+ t0 := clock.Now()
var err error
switch runtime.GOOS {
case "windows":
@@ -654,7 +657,7 @@ func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
}
err = cmd.Run()
}
- d := time.Since(t0)
+ d := clock.Since(t0)
if err != nil {
if d < time.Second/2 {
// If it failed quicker than the 3 second
@@ -668,7 +671,7 @@ func (ns *Impl) userPing(dstIP netip.Addr, pingResPkt []byte) {
return
}
if debugNetstack() {
- ns.logf("exec pinged %v in %v", dstIP, time.Since(t0))
+ ns.logf("exec pinged %v in %v", dstIP, clock.Since(t0))
}
if err := ns.tundev.InjectOutbound(pingResPkt); err != nil {
ns.logf("InjectOutbound ping response: %v", err)
@@ -1061,7 +1064,7 @@ func (ns *Impl) handleMagicDNSUDP(srcAddr netip.AddrPort, c *gonet.UDPConn) {
//
// See: https://github.com/bminor/glibc/blob/f7fbb99652eceb1b6b55e4be931649df5946497c/resolv/res_send.c#L995
for {
- c.SetReadDeadline(time.Now().Add(readDeadline))
+ c.SetReadDeadline(clock.Now().Add(readDeadline))
n, _, err := c.ReadFrom(q)
if err != nil {
if oe, ok := err.(*net.OpError); !(ok && oe.Timeout()) {
@@ -1138,7 +1141,7 @@ func (ns *Impl) forwardUDP(client *gonet.UDPConn, clientAddr, dstAddr netip.Addr
// wait a few seconds (or zero, really)
idleTimeout = 30 * time.Second
}
- timer := time.AfterFunc(idleTimeout, func() {
+ timer := clock.AfterFunc(idleTimeout, func() {
if isLocal {
ns.e.UnregisterIPPortIdentity(backendLocalIPPort)
}
diff --git a/wgengine/pendopen.go b/wgengine/pendopen.go
index af5d3d8a7..8a19c404d 100644
--- a/wgengine/pendopen.go
+++ b/wgengine/pendopen.go
@@ -12,6 +12,7 @@ import (
"tailscale.com/net/packet"
"tailscale.com/net/tsaddr"
"tailscale.com/net/tstun"
+ "tailscale.com/tstime"
"tailscale.com/types/ipproto"
"tailscale.com/util/mak"
"tailscale.com/wgengine/filter"
@@ -19,8 +20,10 @@ import (
const tcpTimeoutBeforeDebug = 5 * time.Second
+var clock = tstime.StdClock{}
+
type pendingOpenFlow struct {
- timer *time.Timer // until giving up on the flow
+ timer tstime.TimerController // until giving up on the flow
// guarded by userspaceEngine.mu:
@@ -108,7 +111,7 @@ func (e *userspaceEngine) trackOpenPostFilterOut(pp *packet.Parsed, t *tstun.Wra
}
}
- timer := time.AfterFunc(tcpTimeoutBeforeDebug, func() {
+ timer := e.clock.AfterFunc(tcpTimeoutBeforeDebug, func() {
e.onOpenTimeout(flow)
})
@@ -214,7 +217,7 @@ func durFmt(t time.Time) string {
if t.IsZero() {
return "never"
}
- d := time.Since(t).Round(time.Second)
+ d := clock.Since(t).Round(time.Second)
if d < 10*time.Minute {
// node.LastSeen times are rounded very coarsely, and
// we compare times from different clocks (server vs
diff --git a/wgengine/router/router_linux.go b/wgengine/router/router_linux.go
index 8a7273bd2..3dfb743ca 100644
--- a/wgengine/router/router_linux.go
+++ b/wgengine/router/router_linux.go
@@ -24,6 +24,7 @@ import (
"tailscale.com/envknob"
"tailscale.com/hostinfo"
"tailscale.com/net/netmon"
+ "tailscale.com/tstime"
"tailscale.com/types/logger"
"tailscale.com/types/preftype"
"tailscale.com/util/linuxfw"
@@ -37,6 +38,8 @@ const (
netfilterOn = preftype.NetfilterOn
)
+var clock = tstime.StdClock{}
+
// netfilterRunner abstracts helpers to run netfilter commands. It is
// implemented by linuxfw.IPTablesRunner and linuxfw.NfTablesRunner.
type netfilterRunner interface {
@@ -422,7 +425,7 @@ func (r *linuxRouter) onIPRuleDeleted(table uint8, priority uint32) {
r.ruleRestorePending.Swap(false)
return
}
- time.AfterFunc(rr.Delay()+250*time.Millisecond, func() {
+ clock.AfterFunc(rr.Delay()+250*time.Millisecond, func() {
if r.ruleRestorePending.Swap(false) && !r.closed.Load() {
r.logf("somebody (likely systemd-networkd) deleted ip rules; restoring Tailscale's")
r.justAddIPRules()
diff --git a/wgengine/router/router_windows.go b/wgengine/router/router_windows.go
index 155c29b46..59e9d8146 100644
--- a/wgengine/router/router_windows.go
+++ b/wgengine/router/router_windows.go
@@ -23,6 +23,7 @@ import (
"tailscale.com/logtail/backoff"
"tailscale.com/net/dns"
"tailscale.com/net/netmon"
+ "tailscale.com/tstime"
"tailscale.com/types/logger"
)
@@ -34,6 +35,8 @@ type winRouter struct {
firewall *firewallTweaker
}
+var clock = tstime.StdClock{}
+
func newUserspaceRouter(logf logger.Logf, tundev tun.Device, netMon *netmon.Monitor) (Router, error) {
nativeTun := tundev.(*tun.NativeTun)
luid := winipcfg.LUID(nativeTun.LUID())
@@ -57,9 +60,9 @@ func (r *winRouter) Up() error {
r.firewall.clear()
var err error
- t0 := time.Now()
+ t0 := clock.Now()
r.routeChangeCallback, err = monitorDefaultRoutes(r.nativeTun)
- d := time.Since(t0).Round(time.Millisecond)
+ d := clock.Since(t0).Round(time.Millisecond)
if err != nil {
return fmt.Errorf("monitorDefaultRoutes, after %v: %v", d, err)
}
@@ -178,7 +181,7 @@ func (ft *firewallTweaker) set(cidrs []string, routes, localRoutes []netip.Prefi
}
func (ft *firewallTweaker) runFirewall(args ...string) (time.Duration, error) {
- t0 := time.Now()
+ t0 := clock.Now()
args = append([]string{"advfirewall", "firewall"}, args...)
cmd := exec.Command("netsh", args...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
@@ -186,7 +189,7 @@ func (ft *firewallTweaker) runFirewall(args ...string) (time.Duration, error) {
if err != nil {
err = fmt.Errorf("%w: %v", err, string(b))
}
- return time.Since(t0).Round(time.Millisecond), err
+ return clock.Since(t0).Round(time.Millisecond), err
}
func (ft *firewallTweaker) doAsyncSet() {
diff --git a/wgengine/userspace.go b/wgengine/userspace.go
index ce7815177..170e6054f 100644
--- a/wgengine/userspace.go
+++ b/wgengine/userspace.go
@@ -35,6 +35,7 @@ import (
"tailscale.com/net/tstun"
"tailscale.com/syncs"
"tailscale.com/tailcfg"
+ "tailscale.com/tstime"
"tailscale.com/tstime/mono"
"tailscale.com/types/dnstype"
"tailscale.com/types/ipproto"
@@ -147,6 +148,8 @@ type userspaceEngine struct {
networkLogger netlog.Logger
// Lock ordering: magicsock.Conn.mu, wgLock, then mu.
+
+ clock tstime.Clock
}
// BIRDClient handles communication with the BIRD Internet Routing Daemon.
@@ -271,6 +274,7 @@ func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error)
router: conf.Router,
confListenPort: conf.ListenPort,
birdClient: conf.BIRDClient,
+ clock: tstime.StdClock{},
}
if e.birdClient != nil {
@@ -1014,7 +1018,7 @@ func (e *userspaceEngine) getStatus() (*Status, error) {
}
return &Status{
- AsOf: time.Now(),
+ AsOf: e.clock.Now(),
LocalAddrs: localAddrs,
Peers: peers,
DERPs: derpConns,
@@ -1286,13 +1290,13 @@ func (e *userspaceEngine) sendICMPEchoRequest(destIP netip.Addr, peer tailcfg.No
idSeq, payload := packet.ICMPEchoPayload(nil)
- expireTimer := time.AfterFunc(10*time.Second, func() {
+ expireTimer := e.clock.AfterFunc(10*time.Second, func() {
e.setICMPEchoResponseCallback(idSeq, nil)
})
- t0 := time.Now()
+ t0 := e.clock.Now()
e.setICMPEchoResponseCallback(idSeq, func() {
expireTimer.Stop()
- d := time.Since(t0)
+ d := e.clock.Since(t0)
res.LatencySeconds = d.Seconds()
res.NodeIP = destIP.String()
res.NodeName = peer.ComputedName()
@@ -1328,13 +1332,13 @@ func (e *userspaceEngine) sendTSMPPing(ip netip.Addr, peer tailcfg.NodeView, res
var data [8]byte
crand.Read(data[:])
- expireTimer := time.AfterFunc(10*time.Second, func() {
+ expireTimer := e.clock.AfterFunc(10*time.Second, func() {
e.setTSMPPongCallback(data, nil)
})
- t0 := time.Now()
+ t0 := e.clock.Now()
e.setTSMPPongCallback(data, func(pong packet.TSMPPongReply) {
expireTimer.Stop()
- d := time.Since(t0)
+ d := e.clock.Since(t0)
res.LatencySeconds = d.Seconds()
res.NodeIP = ip.String()
res.NodeName = peer.ComputedName()
diff --git a/wgengine/watchdog.go b/wgengine/watchdog.go
index 5209566cd..6620eb938 100644
--- a/wgengine/watchdog.go
+++ b/wgengine/watchdog.go
@@ -18,6 +18,7 @@ import (
"tailscale.com/ipn/ipnstate"
"tailscale.com/net/dns"
"tailscale.com/tailcfg"
+ "tailscale.com/tstime"
"tailscale.com/types/key"
"tailscale.com/types/netmap"
"tailscale.com/wgengine/capture"
@@ -40,6 +41,7 @@ func NewWatchdog(e Engine) Engine {
fatalf: log.Fatalf,
maxWait: 45 * time.Second,
inFlight: make(map[inFlightKey]time.Time),
+ clock: tstime.StdClock{},
}
}
@@ -58,6 +60,8 @@ type watchdogEngine struct {
inFlightMu sync.Mutex
inFlight map[inFlightKey]time.Time
inFlightCtr uint64
+
+ clock tstime.Clock
}
func (e *watchdogEngine) watchdogErr(name string, fn func() error) error {
@@ -69,7 +73,7 @@ func (e *watchdogEngine) watchdogErr(name string, fn func() error) error {
ctr: e.inFlightCtr,
}
e.inFlightCtr++
- e.inFlight[key] = time.Now()
+ e.inFlight[key] = e.clock.Now()
e.inFlightMu.Unlock()
defer func() {
@@ -82,12 +86,12 @@ func (e *watchdogEngine) watchdogErr(name string, fn func() error) error {
go func() {
errCh <- fn()
}()
- t := time.NewTimer(e.maxWait)
+ t, tChannel := e.clock.NewTimer(e.maxWait)
select {
case err := <-errCh:
t.Stop()
return err
- case <-t.C:
+ case <-tChannel:
buf := new(strings.Builder)
pprof.Lookup("goroutine").WriteTo(buf, 1)
e.logf("wgengine watchdog stacks:\n%s", buf.String())
@@ -95,7 +99,7 @@ func (e *watchdogEngine) watchdogErr(name string, fn func() error) error {
// Collect the list of in-flight operations for debugging.
var (
b []byte
- now = time.Now()
+ now = e.clock.Now()
)
e.inFlightMu.Lock()
for k, t := range e.inFlight {