Debian Codegraph @

clock/testing/fake_clock.go

raw
1 /*
2 Copyright 2014 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package testing
18
19 import (
20 "sync"
21 "time"
22
23 "k8s.io/utils/clock"
24 )
25
26 var (
27 _ = clock.PassiveClock(&FakePassiveClock{})
28 _ = clock.WithTicker(&FakeClock{})
29 _ = clock.Clock(&IntervalClock{})
30 )
31
32 // FakePassiveClock implements PassiveClock, but returns an arbitrary time.
33 type FakePassiveClock struct {
34 lock sync.RWMutex
35 time time.Time
36 }
37
38 // FakeClock implements clock.Clock, but returns an arbitrary time.
39 type FakeClock struct {
40 FakePassiveClock
41
42 // waiters are waiting for the fake time to pass their specified time
43 waiters []*fakeClockWaiter
44 }
45
46 type fakeClockWaiter struct {
47 targetTime time.Time
48 stepInterval time.Duration
49 skipIfBlocked bool
50 destChan chan time.Time
51 afterFunc func()
52 }
53
54 // NewFakePassiveClock returns a new FakePassiveClock.
55 func NewFakePassiveClock(t time.Time) *FakePassiveClock {
56 return &FakePassiveClock{
57 time: t,
58 }
59 }
60
61 // NewFakeClock constructs a fake clock set to the provided time.
62 func NewFakeClock(t time.Time) *FakeClock {
63 return &FakeClock{
64 FakePassiveClock: *NewFakePassiveClock(t),
65 }
66 }
67
68 // Now returns f's time.
69 func (f *FakePassiveClock) Now() time.Time {
70 f.lock.RLock()
71 defer f.lock.RUnlock()
72 return f.time
73 }
74
75 // Since returns time since the time in f.
76 func (f *FakePassiveClock) Since(ts time.Time) time.Duration {
77 f.lock.RLock()
78 defer f.lock.RUnlock()
79 return f.time.Sub(ts)
80 }
81
82 // SetTime sets the time on the FakePassiveClock.
83 func (f *FakePassiveClock) SetTime(t time.Time) {
84 f.lock.Lock()
85 defer f.lock.Unlock()
86 f.time = t
87 }
88
89 // After is the fake version of time.After(d).
90 func (f *FakeClock) After(d time.Duration) <-chan time.Time {
91 f.lock.Lock()
92 defer f.lock.Unlock()
93 stopTime := f.time.Add(d)
94 ch := make(chan time.Time, 1) // Don't block!
95 f.waiters = append(f.waiters, &fakeClockWaiter{
96 targetTime: stopTime,
97 destChan: ch,
98 })
99 return ch
100 }
101
102 // NewTimer constructs a fake timer, akin to time.NewTimer(d).
103 func (f *FakeClock) NewTimer(d time.Duration) clock.Timer {
104 f.lock.Lock()
105 defer f.lock.Unlock()
106 stopTime := f.time.Add(d)
107 ch := make(chan time.Time, 1) // Don't block!
108 timer := &fakeTimer{
109 fakeClock: f,
110 waiter: fakeClockWaiter{
111 targetTime: stopTime,
112 destChan: ch,
113 },
114 }
115 f.waiters = append(f.waiters, &timer.waiter)
116 return timer
117 }
118
119 // AfterFunc is the Fake version of time.AfterFunc(d, cb).
120 func (f *FakeClock) AfterFunc(d time.Duration, cb func()) clock.Timer {
121 f.lock.Lock()
122 defer f.lock.Unlock()
123 stopTime := f.time.Add(d)
124 ch := make(chan time.Time, 1) // Don't block!
125
126 timer := &fakeTimer{
127 fakeClock: f,
128 waiter: fakeClockWaiter{
129 targetTime: stopTime,
130 destChan: ch,
131 afterFunc: cb,
132 },
133 }
134 f.waiters = append(f.waiters, &timer.waiter)
135 return timer
136 }
137
138 // Tick constructs a fake ticker, akin to time.Tick
139 func (f *FakeClock) Tick(d time.Duration) <-chan time.Time {
140 if d <= 0 {
141 return nil
142 }
143 f.lock.Lock()
144 defer f.lock.Unlock()
145 tickTime := f.time.Add(d)
146 ch := make(chan time.Time, 1) // hold one tick
147 f.waiters = append(f.waiters, &fakeClockWaiter{
148 targetTime: tickTime,
149 stepInterval: d,
150 skipIfBlocked: true,
151 destChan: ch,
152 })
153
154 return ch
155 }
156
157 // NewTicker returns a new Ticker.
158 func (f *FakeClock) NewTicker(d time.Duration) clock.Ticker {
159 f.lock.Lock()
160 defer f.lock.Unlock()
161 tickTime := f.time.Add(d)
162 ch := make(chan time.Time, 1) // hold one tick
163 f.waiters = append(f.waiters, &fakeClockWaiter{
164 targetTime: tickTime,
165 stepInterval: d,
166 skipIfBlocked: true,
167 destChan: ch,
168 })
169
170 return &fakeTicker{
171 c: ch,
172 }
173 }
174
175 // Step moves the clock by Duration and notifies anyone that's called After,
176 // Tick, or NewTimer.
177 func (f *FakeClock) Step(d time.Duration) {
178 f.lock.Lock()
179 defer f.lock.Unlock()
180 f.setTimeLocked(f.time.Add(d))
181 }
182
183 // SetTime sets the time.
184 func (f *FakeClock) SetTime(t time.Time) {
185 f.lock.Lock()
186 defer f.lock.Unlock()
187 f.setTimeLocked(t)
188 }
189
190 // Actually changes the time and checks any waiters. f must be write-locked.
191 func (f *FakeClock) setTimeLocked(t time.Time) {
192 f.time = t
193 newWaiters := make([]*fakeClockWaiter, 0, len(f.waiters))
194 for i := range f.waiters {
195 w := f.waiters[i]
196 if !w.targetTime.After(t) {
197 if w.skipIfBlocked {
198 select {
199 case w.destChan <- t:
200 default:
201 }
202 } else {
203 w.destChan <- t
204 }
205
206 if w.afterFunc != nil {
207 w.afterFunc()
208 }
209
210 if w.stepInterval > 0 {
211 for !w.targetTime.After(t) {
212 w.targetTime = w.targetTime.Add(w.stepInterval)
213 }
214 newWaiters = append(newWaiters, w)
215 }
216
217 } else {
218 newWaiters = append(newWaiters, f.waiters[i])
219 }
220 }
221 f.waiters = newWaiters
222 }
223
224 // HasWaiters returns true if Waiters() returns non-0 (so you can write race-free tests).
225 func (f *FakeClock) HasWaiters() bool {
226 f.lock.RLock()
227 defer f.lock.RUnlock()
228 return len(f.waiters) > 0
229 }
230
231 // Waiters returns the number of "waiters" on the clock (so you can write race-free
232 // tests). A waiter exists for:
233 // - every call to After that has not yet signaled its channel.
234 // - every call to AfterFunc that has not yet called its callback.
235 // - every timer created with NewTimer which is currently ticking.
236 // - every ticker created with NewTicker which is currently ticking.
237 // - every ticker created with Tick.
238 func (f *FakeClock) Waiters() int {
239 f.lock.RLock()
240 defer f.lock.RUnlock()
241 return len(f.waiters)
242 }
243
244 // Sleep is akin to time.Sleep
245 func (f *FakeClock) Sleep(d time.Duration) {
246 f.Step(d)
247 }
248
249 // IntervalClock implements clock.PassiveClock, but each invocation of Now steps the clock forward the specified duration.
250 // IntervalClock technically implements the other methods of clock.Clock, but each implementation is just a panic.
251 //
252 // Deprecated: See SimpleIntervalClock for an alternative that only has the methods of PassiveClock.
253 type IntervalClock struct {
254 Time time.Time
255 Duration time.Duration
256 }
257
258 // Now returns i's time.
259 func (i *IntervalClock) Now() time.Time {
260 i.Time = i.Time.Add(i.Duration)
261 return i.Time
262 }
263
264 // Since returns time since the time in i.
265 func (i *IntervalClock) Since(ts time.Time) time.Duration {
266 return i.Time.Sub(ts)
267 }
268
269 // After is unimplemented, will panic.
270 // TODO: make interval clock use FakeClock so this can be implemented.
271 func (*IntervalClock) After(_ time.Duration) <-chan time.Time {
272 panic("IntervalClock doesn't implement After")
273 }
274
275 // NewTimer is unimplemented, will panic.
276 // TODO: make interval clock use FakeClock so this can be implemented.
277 func (*IntervalClock) NewTimer(_ time.Duration) clock.Timer {
278 panic("IntervalClock doesn't implement NewTimer")
279 }
280
281 // AfterFunc is unimplemented, will panic.
282 // TODO: make interval clock use FakeClock so this can be implemented.
283 func (*IntervalClock) AfterFunc(_ time.Duration, _ func()) clock.Timer {
284 panic("IntervalClock doesn't implement AfterFunc")
285 }
286
287 // Tick is unimplemented, will panic.
288 // TODO: make interval clock use FakeClock so this can be implemented.
289 func (*IntervalClock) Tick(_ time.Duration) <-chan time.Time {
290 panic("IntervalClock doesn't implement Tick")
291 }
292
293 // NewTicker has no implementation yet and is omitted.
294 // TODO: make interval clock use FakeClock so this can be implemented.
295 func (*IntervalClock) NewTicker(_ time.Duration) clock.Ticker {
296 panic("IntervalClock doesn't implement NewTicker")
297 }
298
299 // Sleep is unimplemented, will panic.
300 func (*IntervalClock) Sleep(_ time.Duration) {
301 panic("IntervalClock doesn't implement Sleep")
302 }
303
304 var _ = clock.Timer(&fakeTimer{})
305
306 // fakeTimer implements clock.Timer based on a FakeClock.
307 type fakeTimer struct {
308 fakeClock *FakeClock
309 waiter fakeClockWaiter
310 }
311
312 // C returns the channel that notifies when this timer has fired.
313 func (f *fakeTimer) C() <-chan time.Time {
314 return f.waiter.destChan
315 }
316
317 // Stop prevents the Timer from firing. It returns true if the call stops the
318 // timer, false if the timer has already expired or been stopped.
319 func (f *fakeTimer) Stop() bool {
320 f.fakeClock.lock.Lock()
321 defer f.fakeClock.lock.Unlock()
322
323 active := false
324 newWaiters := make([]*fakeClockWaiter, 0, len(f.fakeClock.waiters))
325 for i := range f.fakeClock.waiters {
326 w := f.fakeClock.waiters[i]
327 if w != &f.waiter {
328 newWaiters = append(newWaiters, w)
329 continue
330 }
331 // If timer is found, it has not been fired yet.
332 active = true
333 }
334
335 f.fakeClock.waiters = newWaiters
336
337 return active
338 }
339
340 // Reset changes the timer to expire after duration d. It returns true if the
341 // timer had been active, false if the timer had expired or been stopped.
342 func (f *fakeTimer) Reset(d time.Duration) bool {
343 f.fakeClock.lock.Lock()
344 defer f.fakeClock.lock.Unlock()
345
346 active := false
347
348 f.waiter.targetTime = f.fakeClock.time.Add(d)
349
350 for i := range f.fakeClock.waiters {
351 w := f.fakeClock.waiters[i]
352 if w == &f.waiter {
353 // If timer is found, it has not been fired yet.
354 active = true
355 break
356 }
357 }
358 if !active {
359 f.fakeClock.waiters = append(f.fakeClock.waiters, &f.waiter)
360 }
361
362 return active
363 }
364
365 type fakeTicker struct {
366 c <-chan time.Time
367 }
368
369 func (t *fakeTicker) C() <-chan time.Time {
370 return t.c
371 }
372
373 func (t *fakeTicker) Stop() {
374 }