Skip to content

Commit

Permalink
fixed cache clean race
Browse files Browse the repository at this point in the history
  • Loading branch information
zensh committed Apr 10, 2020
1 parent a67bfa9 commit e69e336
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 4 deletions.
2 changes: 1 addition & 1 deletion pkg/middlewares/canary/canary.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ type Canary struct {
// New returns a Canary instance.
func New(ctx context.Context, next http.Handler, cfg dynamic.Canary, name string) (*Canary, error) {
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
logger.Debug("Add canary middleware")

if cfg.Product == "" {
return nil, fmt.Errorf("product name required for Canary middleware")
Expand Down Expand Up @@ -79,6 +78,7 @@ func New(ctx context.Context, next http.Handler, cfg dynamic.Canary, name string
if c.loadLabels {
c.ls = NewLabelStore(logger, cfg, expiration, cacheCleanDuration)
}
logger.Infof("Add canary middleware: %v, %v, %v", cfg, expiration, cacheCleanDuration)
return c, nil
}

Expand Down
7 changes: 4 additions & 3 deletions pkg/middlewares/canary/label.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,9 @@ func (s *LabelStore) MustLoadLabels(ctx context.Context, uid, requestID string)
func (s *LabelStore) mustLoadEntry(key string, now time.Time) *entry {
s.mu.RLock()
e, ok := s.liveMap[key]
shouldRound := len(s.liveMap) > s.maxCacheSize || s.shouldRound.Before(now)
s.mu.RUnlock()

shouldRound := len(s.liveMap) > s.maxCacheSize || s.shouldRound.Before(now)
if ok && !shouldRound {
return e
}
Expand All @@ -134,8 +134,9 @@ func (s *LabelStore) mustLoadEntry(key string, now time.Time) *entry {
s.liveMap[key] = e
}

if shouldRound || len(s.liveMap) > s.maxCacheSize {
s.logger.Infof("Round cache, stale cache size: %d, live cache size: %d", len(s.staleMap), len(s.liveMap))
if len(s.liveMap) > s.maxCacheSize || s.shouldRound.Before(now) {
s.logger.Infof("Round cache, stale cache size: %d, live cache size: %d, trigger: %s, shouldRound: %s",
len(s.staleMap), len(s.liveMap), key, s.shouldRound.Format(time.RFC3339))
s.shouldRound = now.Add(s.cacheCleanDuration)
// make a round: drop staleMap and create new liveMap
s.staleMap = s.liveMap
Expand Down

0 comments on commit e69e336

Please sign in to comment.