1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
|
// Copyright 2020 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package faketime provides a fake clock that implements tcpip.Clock interface.
package faketime
import (
"container/heap"
"fmt"
"sync"
"time"
"gvisor.dev/gvisor/pkg/tcpip"
)
// NullClock implements a clock that never advances.
//
// +stateify savable
type NullClock struct{}
var _ tcpip.Clock = (*NullClock)(nil)
// Now implements tcpip.Clock.Now.
func (*NullClock) Now() time.Time {
return time.Time{}
}
// NowMonotonic implements tcpip.Clock.NowMonotonic.
func (*NullClock) NowMonotonic() tcpip.MonotonicTime {
return tcpip.MonotonicTime{}
}
// nullTimer implements a timer that never fires.
//
// +stateify savable
type nullTimer struct{}
var _ tcpip.Timer = (*nullTimer)(nil)
// Stop implements tcpip.Timer.
func (*nullTimer) Stop() bool {
return true
}
// Reset implements tcpip.Timer.
func (*nullTimer) Reset(time.Duration) {}
// AfterFunc implements tcpip.Clock.AfterFunc.
func (*NullClock) AfterFunc(time.Duration, func()) tcpip.Timer {
return &nullTimer{}
}
type notificationChannels struct {
mu struct {
sync.Mutex
ch []<-chan struct{}
}
}
func (n *notificationChannels) add(ch <-chan struct{}) {
n.mu.Lock()
defer n.mu.Unlock()
n.mu.ch = append(n.mu.ch, ch)
}
// wait returns once all the notification channels are readable.
//
// Channels that are added while waiting on existing channels will be waited on
// as well.
func (n *notificationChannels) wait() {
for {
n.mu.Lock()
ch := n.mu.ch
n.mu.ch = nil
n.mu.Unlock()
if len(ch) == 0 {
break
}
for _, c := range ch {
<-c
}
}
}
// +stateify savable
type manualClockMutex struct {
sync.RWMutex `state:"nosave"`
// now is the current (fake) time of the clock.
now time.Time
// times is min-heap of times.
times timeHeap
// timers holds the timers scheduled for each time.
timers map[time.Time]map[*manualTimer]struct{}
}
// ManualClock implements tcpip.Clock and only advances manually with Advance
// method.
//
// +stateify savable
type ManualClock struct {
// runningTimers tracks the completion of timer callbacks that began running
// immediately upon their scheduling. It is used to ensure the proper ordering
// of timer callback dispatch.
runningTimers notificationChannels
mu manualClockMutex
}
// NewManualClock creates a new ManualClock instance.
func NewManualClock() *ManualClock {
c := &ManualClock{}
c.mu.Lock()
defer c.mu.Unlock()
// Set the initial time to a non-zero value since the zero value is used to
// detect inactive timers.
c.mu.now = time.Unix(0, 0)
c.mu.timers = make(map[time.Time]map[*manualTimer]struct{})
return c
}
var _ tcpip.Clock = (*ManualClock)(nil)
// Now implements tcpip.Clock.Now.
func (mc *ManualClock) Now() time.Time {
mc.mu.RLock()
defer mc.mu.RUnlock()
return mc.mu.now
}
// NowMonotonic implements tcpip.Clock.NowMonotonic.
func (mc *ManualClock) NowMonotonic() tcpip.MonotonicTime {
var mt tcpip.MonotonicTime
return mt.Add(mc.Now().Sub(time.Unix(0, 0)))
}
// AfterFunc implements tcpip.Clock.AfterFunc.
func (mc *ManualClock) AfterFunc(d time.Duration, f func()) tcpip.Timer {
mt := &manualTimer{
clock: mc,
f: f,
}
mc.mu.Lock()
defer mc.mu.Unlock()
mt.mu.Lock()
defer mt.mu.Unlock()
mc.resetTimerLocked(mt, d)
return mt
}
// resetTimerLocked schedules a timer to be fired after the given duration.
//
// Precondition: mc.mu and mt.mu must be locked.
func (mc *ManualClock) resetTimerLocked(mt *manualTimer, d time.Duration) {
if !mt.mu.firesAt.IsZero() {
panic("tried to reset an active timer")
}
t := mc.mu.now.Add(d)
if !mc.mu.now.Before(t) {
// If the timer is scheduled to fire immediately, call its callback
// in a new goroutine immediately.
//
// It needs to be called in its own goroutine to escape its current
// execution context - like an actual timer.
ch := make(chan struct{})
mc.runningTimers.add(ch)
go func() {
defer close(ch)
mt.f()
}()
return
}
mt.mu.firesAt = t
timers, ok := mc.mu.timers[t]
if !ok {
timers = make(map[*manualTimer]struct{})
mc.mu.timers[t] = timers
heap.Push(&mc.mu.times, t)
}
timers[mt] = struct{}{}
}
// stopTimerLocked stops a timer from firing.
//
// Precondition: mc.mu and mt.mu must be locked.
func (mc *ManualClock) stopTimerLocked(mt *manualTimer) {
t := mt.mu.firesAt
mt.mu.firesAt = time.Time{}
if t.IsZero() {
panic("tried to stop an inactive timer")
}
timers, ok := mc.mu.timers[t]
if !ok {
err := fmt.Sprintf("tried to stop an active timer but the clock does not have anything scheduled for the timer @ t = %s %p\nScheduled timers @:", t.UTC(), mt)
for t := range mc.mu.timers {
err += fmt.Sprintf("%s\n", t.UTC())
}
panic(err)
}
if _, ok := timers[mt]; !ok {
panic(fmt.Sprintf("did not have an entry in timers for an active timer @ t = %s", t.UTC()))
}
delete(timers, mt)
if len(timers) == 0 {
delete(mc.mu.timers, t)
}
}
// RunImmediatelyScheduledJobs runs all jobs scheduled to run at the current
// time.
func (mc *ManualClock) RunImmediatelyScheduledJobs() {
mc.Advance(0)
}
// Advance executes all work that have been scheduled to execute within d from
// the current time. Blocks until all work has completed execution.
func (mc *ManualClock) Advance(d time.Duration) {
// We spawn goroutines for timers that were scheduled to fire at the time of
// being reset. Wait for those goroutines to complete before proceeding so
// that timer callbacks are called in the right order.
mc.runningTimers.wait()
mc.mu.Lock()
defer mc.mu.Unlock()
until := mc.mu.now.Add(d)
for mc.mu.times.Len() > 0 {
t := heap.Pop(&mc.mu.times).(time.Time)
if t.After(until) {
// No work to do
heap.Push(&mc.mu.times, t)
break
}
timers := mc.mu.timers[t]
delete(mc.mu.timers, t)
mc.mu.now = t
// Mark the timers as inactive since they will be fired.
//
// This needs to be done while holding mc's lock because we remove the entry
// in the map of timers for the current time. If an attempt to stop a
// timer is made after mc's lock was dropped but before the timer is
// marked inactive, we would panic since no entry exists for the time when
// the timer was expected to fire.
for mt := range timers {
mt.mu.Lock()
mt.mu.firesAt = time.Time{}
mt.mu.Unlock()
}
// Release the lock before calling the timer's callback fn since the
// callback fn might try to schedule a timer which requires obtaining
// mc's lock.
mc.mu.Unlock()
for mt := range timers {
mt.f()
}
// The timer callbacks may have scheduled a timer to fire immediately.
// We spawn goroutines for these timers and need to wait for them to
// finish before proceeding so that timer callbacks are called in the
// right order.
mc.runningTimers.wait()
mc.mu.Lock()
}
mc.mu.now = until
}
func (mc *ManualClock) resetTimer(mt *manualTimer, d time.Duration) {
mc.mu.Lock()
defer mc.mu.Unlock()
mt.mu.Lock()
defer mt.mu.Unlock()
if !mt.mu.firesAt.IsZero() {
mc.stopTimerLocked(mt)
}
mc.resetTimerLocked(mt, d)
}
func (mc *ManualClock) stopTimer(mt *manualTimer) bool {
mc.mu.Lock()
defer mc.mu.Unlock()
mt.mu.Lock()
defer mt.mu.Unlock()
if mt.mu.firesAt.IsZero() {
return false
}
mc.stopTimerLocked(mt)
return true
}
// +stateify savable
type manualTimerMu struct {
sync.Mutex `state:"nosave"`
// firesAt is the time when the timer will fire.
//
// Zero only when the timer is not active.
firesAt time.Time
}
// +stateify savable
type manualTimer struct {
clock *ManualClock
// TODO(b/341946753): Restore when netstack is savable.
f func() `state:"nosave"`
mu manualTimerMu
}
var _ tcpip.Timer = (*manualTimer)(nil)
// Reset implements tcpip.Timer.Reset.
func (mt *manualTimer) Reset(d time.Duration) {
mt.clock.resetTimer(mt, d)
}
// Stop implements tcpip.Timer.Stop.
func (mt *manualTimer) Stop() bool {
return mt.clock.stopTimer(mt)
}
type timeHeap []time.Time
var _ heap.Interface = (*timeHeap)(nil)
func (h timeHeap) Len() int {
return len(h)
}
func (h timeHeap) Less(i, j int) bool {
return h[i].Before(h[j])
}
func (h timeHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h *timeHeap) Push(x any) {
*h = append(*h, x.(time.Time))
}
func (h *timeHeap) Pop() any {
last := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return last
}
|