guard.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package dao
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "go-common/library/log"
  6. )
  7. const (
  8. _percentThreshold float64 = 0.85
  9. )
  10. // Guard count the renew of all operations for self protection
  11. type Guard struct {
  12. expPerMin int64
  13. expThreshold int64
  14. facInMin int64
  15. facLastMin int64
  16. lock sync.RWMutex
  17. }
  18. func (g *Guard) setExp(cnt int64) {
  19. g.lock.Lock()
  20. g.expPerMin = cnt * 2
  21. g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
  22. g.lock.Unlock()
  23. }
  24. func (g *Guard) incrExp() {
  25. g.lock.Lock()
  26. g.expPerMin = g.expPerMin + 2
  27. g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
  28. g.lock.Unlock()
  29. }
  30. func (g *Guard) updateFac() {
  31. atomic.StoreInt64(&g.facLastMin, atomic.SwapInt64(&g.facInMin, 0))
  32. }
  33. func (g *Guard) decrExp() {
  34. g.lock.Lock()
  35. if g.expPerMin > 0 {
  36. g.expPerMin = g.expPerMin - 2
  37. g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
  38. }
  39. g.lock.Unlock()
  40. }
  41. func (g *Guard) incrFac() {
  42. atomic.AddInt64(&g.facInMin, 1)
  43. }
  44. func (g *Guard) ok() (is bool) {
  45. is = atomic.LoadInt64(&g.facLastMin) < atomic.LoadInt64(&g.expThreshold)
  46. if is {
  47. log.Warn("discovery is protected, the factual renews(%d) less than expected renews(%d)", atomic.LoadInt64(&g.facLastMin), atomic.LoadInt64(&g.expThreshold))
  48. }
  49. return
  50. }