-
Notifications
You must be signed in to change notification settings - Fork 319
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Jason Liu <jasonliu747@gmail.com>
- Loading branch information
1 parent
61b3c8c
commit 8ad6cf9
Showing
4 changed files
with
272 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
/* | ||
Copyright 2022 The Koordinator Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package cache | ||
|
||
import ( | ||
"fmt" | ||
"sync" | ||
"time" | ||
|
||
"k8s.io/apimachinery/pkg/util/runtime" | ||
"k8s.io/apimachinery/pkg/util/wait" | ||
"k8s.io/klog/v2" | ||
) | ||
|
||
const ( | ||
defaultExpiration = 2 * time.Minute | ||
defaultGCInterval = time.Minute | ||
) | ||
|
||
type item struct { | ||
object interface{} | ||
expirationTime time.Time | ||
} | ||
|
||
type Cache struct { | ||
items map[string]item | ||
defaultExpiration time.Duration | ||
gcInterval time.Duration | ||
gcStarted bool | ||
mu sync.Mutex | ||
} | ||
|
||
func NewCacheDefault() *Cache { | ||
return &Cache{ | ||
items: map[string]item{}, | ||
defaultExpiration: defaultExpiration, | ||
gcInterval: defaultGCInterval, | ||
} | ||
} | ||
|
||
func NewCache(expiration time.Duration, gcInterval time.Duration) *Cache { | ||
cache := Cache{ | ||
items: map[string]item{}, | ||
defaultExpiration: expiration, | ||
gcInterval: gcInterval, | ||
} | ||
if cache.defaultExpiration <= 0 { | ||
cache.defaultExpiration = defaultExpiration | ||
} | ||
if cache.gcInterval <= time.Second { | ||
cache.gcInterval = defaultGCInterval | ||
} | ||
return &cache | ||
} | ||
|
||
func (c *Cache) Run(stopCh <-chan struct{}) error { | ||
defer runtime.HandleCrash() | ||
c.gcStarted = true | ||
go wait.Until(func() { | ||
c.gcExpiredCache() | ||
}, c.gcInterval, stopCh) | ||
return nil | ||
} | ||
|
||
func (c *Cache) gcExpiredCache() { | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
gcTime := time.Now() | ||
var gcKeys []string | ||
for key, item := range c.items { | ||
if gcTime.After(item.expirationTime) { | ||
gcKeys = append(gcKeys, key) | ||
} | ||
} | ||
for _, key := range gcKeys { | ||
delete(c.items, key) | ||
} | ||
klog.V(5).Infof("gc resource update executor, current size %v", len(c.items)) | ||
} | ||
|
||
func (c *Cache) Set(key string, value interface{}, expiration time.Duration) error { | ||
return c.set(key, value, expiration) | ||
} | ||
|
||
func (c *Cache) SetDefault(key string, value interface{}) error { | ||
return c.set(key, value, c.defaultExpiration) | ||
} | ||
|
||
func (c *Cache) set(key string, value interface{}, expiration time.Duration) error { | ||
if !c.gcStarted { | ||
return fmt.Errorf("cache GC is not started yet") | ||
} | ||
item := item{ | ||
object: value, | ||
expirationTime: time.Now().Add(expiration), | ||
} | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
c.items[key] = item | ||
return nil | ||
} | ||
|
||
func (c *Cache) Get(key string) (interface{}, bool) { | ||
c.mu.Lock() | ||
defer c.mu.Unlock() | ||
item, ok := c.items[key] | ||
if !ok { | ||
return nil, false | ||
} | ||
if item.expirationTime.Before(time.Now()) { | ||
return nil, false | ||
} | ||
return item.object, true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
/* | ||
Copyright 2022 The Koordinator Authors. | ||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
*/ | ||
|
||
package cache | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func Test_Cache_Get(t *testing.T) { | ||
cache := NewCacheDefault() | ||
cache.gcStarted = true | ||
cache.items = map[string]item{ | ||
"keyExpire": {object: "value1", expirationTime: time.Now().Add(-1 * time.Minute)}, | ||
"keyNotExpire": {object: "value2", expirationTime: time.Now().Add(1 * time.Minute)}, | ||
} | ||
value, found := cache.Get("keyExpire") | ||
assert.True(t, !found, "value not found", "keyExpire") | ||
assert.Nil(t, value, "value must be nil", "keyExpire") | ||
|
||
value, found = cache.Get("keyNotExpire") | ||
assert.True(t, found, "value found", "keyNotExpire") | ||
assert.Equal(t, "value2", value, "keyNotExpire") | ||
} | ||
|
||
func Test_Cache_Set(t *testing.T) { | ||
cache := NewCacheDefault() | ||
cache.gcStarted = true | ||
value, found := cache.Get("key") | ||
assert.True(t, !found, "value not found") | ||
assert.Nil(t, value, "value must be nil") | ||
|
||
_ = cache.SetDefault("key", "value") | ||
value, found = cache.Get("key") | ||
assert.True(t, found, "value found", "checkSetDefault") | ||
assert.Equal(t, "value", value, "checkSetDefault") | ||
|
||
_ = cache.Set("key", "value", -1*time.Minute) | ||
value, found = cache.Get("key") | ||
assert.True(t, !found, "value not found", "checkSet") | ||
assert.Nil(t, value, "value must be nil", "checkSet") | ||
|
||
} | ||
|
||
func Test_gcExpiredCache(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
initItems map[string]item | ||
cache *Cache | ||
expectItemsAfterGC map[string]item | ||
}{ | ||
{ | ||
name: "test_gcExpiredCache_NewCacheDefault", | ||
initItems: map[string]item{ | ||
"keyNeedExpire": {object: "value1", expirationTime: time.Now().Add(-1 * time.Minute)}, | ||
"keyNotExpire": {object: "value2", expirationTime: time.Now().Add(time.Minute)}, | ||
}, | ||
cache: NewCacheDefault(), | ||
expectItemsAfterGC: map[string]item{ | ||
"keyNotExpire": {object: "value2", expirationTime: time.Now().Add(time.Minute)}, | ||
}, | ||
}, | ||
{ | ||
name: "test_gcExpiredCache_NewCache", | ||
initItems: map[string]item{ | ||
"keyNeedExpire": {object: "value1", expirationTime: time.Now().Add(-1 * time.Minute)}, | ||
"keyNotExpire": {object: "value2", expirationTime: time.Now().Add(time.Minute)}, | ||
}, | ||
cache: NewCache(time.Minute, time.Minute), | ||
expectItemsAfterGC: map[string]item{ | ||
"keyNotExpire": {object: "value2", expirationTime: time.Now().Add(time.Minute)}, | ||
}, | ||
}, | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
tt.cache.items = tt.initItems | ||
tt.cache.gcStarted = true | ||
tt.cache.gcExpiredCache() | ||
got := tt.cache.items | ||
assert.Equal(t, len(tt.expectItemsAfterGC), len(got), "checkLen") | ||
checkValueEqual(t, tt.expectItemsAfterGC, got) | ||
}) | ||
} | ||
} | ||
|
||
func checkValueEqual(t *testing.T, expect, got map[string]item) { | ||
assert.Equal(t, len(expect), len(got), "checkLen") | ||
for key, item := range expect { | ||
gotItem, ok := got[key] | ||
if !ok { | ||
assert.True(t, ok, "checkFound", key) | ||
return | ||
} | ||
assert.Equal(t, item.object, gotItem.object, "checkValue", key) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters