From 19afdb78a53c61072c1e083ae0f36d89de1ecd0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E9=A3=9E?= Date: Wed, 19 Jun 2019 10:36:14 +0800 Subject: [PATCH] make pre-drop thread-safe in bbr --- pkg/ratelimit/bbr/bbr.go | 8 ++++---- pkg/ratelimit/bbr/bbr_test.go | 1 - 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/pkg/ratelimit/bbr/bbr.go b/pkg/ratelimit/bbr/bbr.go index fe153d52f..1cdf2cf40 100644 --- a/pkg/ratelimit/bbr/bbr.go +++ b/pkg/ratelimit/bbr/bbr.go @@ -70,7 +70,7 @@ type BBR struct { inFlight int64 winBucketPerSec int64 conf *Config - prevDrop time.Time + prevDrop int64 } // Config contains configs of bbr limiter. @@ -130,7 +130,8 @@ func (l *BBR) shouldDrop() bool { inFlight := atomic.LoadInt64(&l.inFlight) maxInflight := l.maxFlight() if l.cpu() < l.conf.CPUThreshold { - if time.Now().Sub(l.prevDrop) <= 1000*time.Millisecond { + prevDrop := atomic.LoadInt64(&l.prevDrop) + if time.Now().Unix()-prevDrop <= 1 { return inFlight > 1 && inFlight > maxInflight } return false @@ -157,7 +158,7 @@ func (l *BBR) Allow(ctx context.Context, opts ...limit.AllowOption) (func(info l opt.Apply(&allowOpts) } if l.shouldDrop() { - l.prevDrop = time.Now() + atomic.StoreInt64(&l.prevDrop, time.Now().Unix()) return nil, ecode.LimitExceed } atomic.AddInt64(&l.inFlight, 1) @@ -193,7 +194,6 @@ func newLimiter(conf *Config) limit.Limiter { passStat: passStat, rtStat: rtStat, winBucketPerSec: int64(time.Second) / (int64(conf.Window) / int64(conf.WinBucket)), - prevDrop: time.Unix(0, 0), } return limiter } diff --git a/pkg/ratelimit/bbr/bbr_test.go b/pkg/ratelimit/bbr/bbr_test.go index a4ce8628e..8de920c12 100644 --- a/pkg/ratelimit/bbr/bbr_test.go +++ b/pkg/ratelimit/bbr/bbr_test.go @@ -133,7 +133,6 @@ func TestBBRShouldDrop(t *testing.T) { passStat: passStat, rtStat: rtStat, winBucketPerSec: 10, - prevDrop: time.Unix(0, 0), conf: defaultConf, } // cpu >= 800, inflight < maxQps