clock.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package clock
  14. import (
  15. "sync"
  16. "time"
  17. )
  18. // Clock allows for injecting fake or real clocks into code that
  19. // needs to do arbitrary things based on time.
  20. type Clock interface {
  21. Now() time.Time
  22. Since(time.Time) time.Duration
  23. After(time.Duration) <-chan time.Time
  24. NewTimer(time.Duration) Timer
  25. Sleep(time.Duration)
  26. NewTicker(time.Duration) Ticker
  27. }
  28. // RealClock really calls time.Now()
  29. type RealClock struct{}
  30. // Now returns the current time.
  31. func (RealClock) Now() time.Time {
  32. return time.Now()
  33. }
  34. // Since returns time since the specified timestamp.
  35. func (RealClock) Since(ts time.Time) time.Duration {
  36. return time.Since(ts)
  37. }
  38. // Same as time.After(d).
  39. func (RealClock) After(d time.Duration) <-chan time.Time {
  40. return time.After(d)
  41. }
  42. func (RealClock) NewTimer(d time.Duration) Timer {
  43. return &realTimer{
  44. timer: time.NewTimer(d),
  45. }
  46. }
  47. func (RealClock) NewTicker(d time.Duration) Ticker {
  48. return &realTicker{
  49. ticker: time.NewTicker(d),
  50. }
  51. }
  52. func (RealClock) Sleep(d time.Duration) {
  53. time.Sleep(d)
  54. }
  55. // FakeClock implements Clock, but returns an arbitrary time.
  56. type FakeClock struct {
  57. lock sync.RWMutex
  58. time time.Time
  59. // waiters are waiting for the fake time to pass their specified time
  60. waiters []fakeClockWaiter
  61. }
  62. type fakeClockWaiter struct {
  63. targetTime time.Time
  64. stepInterval time.Duration
  65. skipIfBlocked bool
  66. destChan chan time.Time
  67. fired bool
  68. }
  69. func NewFakeClock(t time.Time) *FakeClock {
  70. return &FakeClock{
  71. time: t,
  72. }
  73. }
  74. // Now returns f's time.
  75. func (f *FakeClock) Now() time.Time {
  76. f.lock.RLock()
  77. defer f.lock.RUnlock()
  78. return f.time
  79. }
  80. // Since returns time since the time in f.
  81. func (f *FakeClock) Since(ts time.Time) time.Duration {
  82. f.lock.RLock()
  83. defer f.lock.RUnlock()
  84. return f.time.Sub(ts)
  85. }
  86. // Fake version of time.After(d).
  87. func (f *FakeClock) After(d time.Duration) <-chan time.Time {
  88. f.lock.Lock()
  89. defer f.lock.Unlock()
  90. stopTime := f.time.Add(d)
  91. ch := make(chan time.Time, 1) // Don't block!
  92. f.waiters = append(f.waiters, fakeClockWaiter{
  93. targetTime: stopTime,
  94. destChan: ch,
  95. })
  96. return ch
  97. }
  98. // Fake version of time.NewTimer(d).
  99. func (f *FakeClock) NewTimer(d time.Duration) Timer {
  100. f.lock.Lock()
  101. defer f.lock.Unlock()
  102. stopTime := f.time.Add(d)
  103. ch := make(chan time.Time, 1) // Don't block!
  104. timer := &fakeTimer{
  105. fakeClock: f,
  106. waiter: fakeClockWaiter{
  107. targetTime: stopTime,
  108. destChan: ch,
  109. },
  110. }
  111. f.waiters = append(f.waiters, timer.waiter)
  112. return timer
  113. }
  114. func (f *FakeClock) NewTicker(d time.Duration) Ticker {
  115. f.lock.Lock()
  116. defer f.lock.Unlock()
  117. tickTime := f.time.Add(d)
  118. ch := make(chan time.Time, 1) // hold one tick
  119. f.waiters = append(f.waiters, fakeClockWaiter{
  120. targetTime: tickTime,
  121. stepInterval: d,
  122. skipIfBlocked: true,
  123. destChan: ch,
  124. })
  125. return &fakeTicker{
  126. c: ch,
  127. }
  128. }
  129. // Move clock by Duration, notify anyone that's called After, Tick, or NewTimer
  130. func (f *FakeClock) Step(d time.Duration) {
  131. f.lock.Lock()
  132. defer f.lock.Unlock()
  133. f.setTimeLocked(f.time.Add(d))
  134. }
  135. // Sets the time.
  136. func (f *FakeClock) SetTime(t time.Time) {
  137. f.lock.Lock()
  138. defer f.lock.Unlock()
  139. f.setTimeLocked(t)
  140. }
  141. // Actually changes the time and checks any waiters. f must be write-locked.
  142. func (f *FakeClock) setTimeLocked(t time.Time) {
  143. f.time = t
  144. newWaiters := make([]fakeClockWaiter, 0, len(f.waiters))
  145. for i := range f.waiters {
  146. w := &f.waiters[i]
  147. if !w.targetTime.After(t) {
  148. if w.skipIfBlocked {
  149. select {
  150. case w.destChan <- t:
  151. w.fired = true
  152. default:
  153. }
  154. } else {
  155. w.destChan <- t
  156. w.fired = true
  157. }
  158. if w.stepInterval > 0 {
  159. for !w.targetTime.After(t) {
  160. w.targetTime = w.targetTime.Add(w.stepInterval)
  161. }
  162. newWaiters = append(newWaiters, *w)
  163. }
  164. } else {
  165. newWaiters = append(newWaiters, f.waiters[i])
  166. }
  167. }
  168. f.waiters = newWaiters
  169. }
  170. // Returns true if After has been called on f but not yet satisfied (so you can
  171. // write race-free tests).
  172. func (f *FakeClock) HasWaiters() bool {
  173. f.lock.RLock()
  174. defer f.lock.RUnlock()
  175. return len(f.waiters) > 0
  176. }
  177. func (f *FakeClock) Sleep(d time.Duration) {
  178. f.Step(d)
  179. }
  180. // IntervalClock implements Clock, but each invocation of Now steps the clock forward the specified duration
  181. type IntervalClock struct {
  182. Time time.Time
  183. Duration time.Duration
  184. }
  185. // Now returns i's time.
  186. func (i *IntervalClock) Now() time.Time {
  187. i.Time = i.Time.Add(i.Duration)
  188. return i.Time
  189. }
  190. // Since returns time since the time in i.
  191. func (i *IntervalClock) Since(ts time.Time) time.Duration {
  192. return i.Time.Sub(ts)
  193. }
  194. // Unimplemented, will panic.
  195. // TODO: make interval clock use FakeClock so this can be implemented.
  196. func (*IntervalClock) After(d time.Duration) <-chan time.Time {
  197. panic("IntervalClock doesn't implement After")
  198. }
  199. // Unimplemented, will panic.
  200. // TODO: make interval clock use FakeClock so this can be implemented.
  201. func (*IntervalClock) NewTimer(d time.Duration) Timer {
  202. panic("IntervalClock doesn't implement NewTimer")
  203. }
  204. // Unimplemented, will panic.
  205. // TODO: make interval clock use FakeClock so this can be implemented.
  206. func (*IntervalClock) NewTicker(d time.Duration) Ticker {
  207. panic("IntervalClock doesn't implement NewTicker")
  208. }
  209. func (*IntervalClock) Sleep(d time.Duration) {
  210. panic("IntervalClock doesn't implement Sleep")
  211. }
  212. // Timer allows for injecting fake or real timers into code that
  213. // needs to do arbitrary things based on time.
  214. type Timer interface {
  215. C() <-chan time.Time
  216. Stop() bool
  217. Reset(d time.Duration) bool
  218. }
  219. // realTimer is backed by an actual time.Timer.
  220. type realTimer struct {
  221. timer *time.Timer
  222. }
  223. // C returns the underlying timer's channel.
  224. func (r *realTimer) C() <-chan time.Time {
  225. return r.timer.C
  226. }
  227. // Stop calls Stop() on the underlying timer.
  228. func (r *realTimer) Stop() bool {
  229. return r.timer.Stop()
  230. }
  231. // Reset calls Reset() on the underlying timer.
  232. func (r *realTimer) Reset(d time.Duration) bool {
  233. return r.timer.Reset(d)
  234. }
  235. // fakeTimer implements Timer based on a FakeClock.
  236. type fakeTimer struct {
  237. fakeClock *FakeClock
  238. waiter fakeClockWaiter
  239. }
  240. // C returns the channel that notifies when this timer has fired.
  241. func (f *fakeTimer) C() <-chan time.Time {
  242. return f.waiter.destChan
  243. }
  244. // Stop stops the timer and returns true if the timer has not yet fired, or false otherwise.
  245. func (f *fakeTimer) Stop() bool {
  246. f.fakeClock.lock.Lock()
  247. defer f.fakeClock.lock.Unlock()
  248. newWaiters := make([]fakeClockWaiter, 0, len(f.fakeClock.waiters))
  249. for i := range f.fakeClock.waiters {
  250. w := &f.fakeClock.waiters[i]
  251. if w != &f.waiter {
  252. newWaiters = append(newWaiters, *w)
  253. }
  254. }
  255. f.fakeClock.waiters = newWaiters
  256. return !f.waiter.fired
  257. }
  258. // Reset resets the timer to the fake clock's "now" + d. It returns true if the timer has not yet
  259. // fired, or false otherwise.
  260. func (f *fakeTimer) Reset(d time.Duration) bool {
  261. f.fakeClock.lock.Lock()
  262. defer f.fakeClock.lock.Unlock()
  263. active := !f.waiter.fired
  264. f.waiter.fired = false
  265. f.waiter.targetTime = f.fakeClock.time.Add(d)
  266. return active
  267. }
  268. type Ticker interface {
  269. C() <-chan time.Time
  270. Stop()
  271. }
  272. type realTicker struct {
  273. ticker *time.Ticker
  274. }
  275. func (t *realTicker) C() <-chan time.Time {
  276. return t.ticker.C
  277. }
  278. func (t *realTicker) Stop() {
  279. t.ticker.Stop()
  280. }
  281. type fakeTicker struct {
  282. c <-chan time.Time
  283. }
  284. func (t *fakeTicker) C() <-chan time.Time {
  285. return t.c
  286. }
  287. func (t *fakeTicker) Stop() {
  288. }