contention.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2016 The etcd Authors
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package contention
  15. import (
  16. "sync"
  17. "time"
  18. )
  19. // TimeoutDetector detects routine starvations by
  20. // observing the actual time duration to finish an action
  21. // or between two events that should happen in a fixed
  22. // interval. If the observed duration is longer than
  23. // the expectation, the detector will report the result.
  24. type TimeoutDetector struct {
  25. mu sync.Mutex // protects all
  26. maxDuration time.Duration
  27. // map from event to time
  28. // time is the last seen time of the event.
  29. records map[uint64]time.Time
  30. }
  31. // NewTimeoutDetector creates the TimeoutDetector.
  32. func NewTimeoutDetector(maxDuration time.Duration) *TimeoutDetector {
  33. return &TimeoutDetector{
  34. maxDuration: maxDuration,
  35. records: make(map[uint64]time.Time),
  36. }
  37. }
  38. // Reset resets the NewTimeoutDetector.
  39. func (td *TimeoutDetector) Reset() {
  40. td.mu.Lock()
  41. defer td.mu.Unlock()
  42. td.records = make(map[uint64]time.Time)
  43. }
  44. // Observe observes an event for given id. It returns false and exceeded duration
  45. // if the interval is longer than the expectation.
  46. func (td *TimeoutDetector) Observe(which uint64) (bool, time.Duration) {
  47. td.mu.Lock()
  48. defer td.mu.Unlock()
  49. ok := true
  50. now := time.Now()
  51. exceed := time.Duration(0)
  52. if pt, found := td.records[which]; found {
  53. exceed = now.Sub(pt) - td.maxDuration
  54. if exceed > 0 {
  55. ok = false
  56. }
  57. }
  58. td.records[which] = now
  59. return ok, exceed
  60. }