/
guard.go
60 lines (50 loc) · 1.26 KB
/
guard.go
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
package registry
import (
"sync"
"sync/atomic"
log "github.com/tsingson/zaplogger"
)
const (
_percentThreshold float64 = 0.85
)
// Guard count the renew of all operations for self protection
type Guard struct {
expPerMin int64
expThreshold int64
facInMin int64
facLastMin int64
lock sync.RWMutex
}
func (g *Guard) setExp(cnt int64) {
g.lock.Lock()
g.expPerMin = cnt * 2
g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
g.lock.Unlock()
}
func (g *Guard) incrExp() {
g.lock.Lock()
g.expPerMin = g.expPerMin + 2
g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
g.lock.Unlock()
}
func (g *Guard) updateFac() {
atomic.StoreInt64(&g.facLastMin, atomic.SwapInt64(&g.facInMin, 0))
}
func (g *Guard) decrExp() {
g.lock.Lock()
if g.expPerMin > 0 {
g.expPerMin = g.expPerMin - 2
g.expThreshold = int64(float64(g.expPerMin) * _percentThreshold)
}
g.lock.Unlock()
}
func (g *Guard) incrFac() {
atomic.AddInt64(&g.facInMin, 1)
}
func (g *Guard) ok() (is bool) {
is = atomic.LoadInt64(&g.facLastMin) < atomic.LoadInt64(&g.expThreshold)
if is {
log.Warningf("discovery is protected, the factual renews(%d) less than expected renews(%d)", atomic.LoadInt64(&g.facLastMin), atomic.LoadInt64(&g.expThreshold))
}
return
}