1. Fix lint errors for the whole directory staging/src/k8s.io/client-go/tools/cache;

2. Remove staging/src/k8s.io/client-go/tools/cache from .golint_failures;
3. Fix some typo from comments.

Kubernetes-commit: 0e0e1f7daba0a6ae6dd59df0a1bb643c323ad8cb
This commit is contained in:
RainbowMango 2019-07-10 12:00:52 +08:00 committed by Kubernetes Publisher
parent 579ad46bdc
commit 2b8d87c082
16 changed files with 52 additions and 29 deletions

View File

@ -79,6 +79,7 @@ type controller struct {
clock clock.Clock clock clock.Clock
} }
// Controller is a generic controller framework.
type Controller interface { type Controller interface {
Run(stopCh <-chan struct{}) Run(stopCh <-chan struct{})
HasSynced() bool HasSynced() bool
@ -149,7 +150,7 @@ func (c *controller) processLoop() {
for { for {
obj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process)) obj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process))
if err != nil { if err != nil {
if err == FIFOClosedError { if err == ErrFIFOClosed {
return return
} }
if c.config.RetryOnError { if c.config.RetryOnError {

View File

@ -160,7 +160,7 @@ func (f *DeltaFIFO) KeyOf(obj interface{}) (string, error) {
return f.keyFunc(obj) return f.keyFunc(obj)
} }
// Return true if an Add/Update/Delete/AddIfNotPresent are called first, // HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,
// or an Update called first but the first batch of items inserted by Replace() has been popped // or an Update called first but the first batch of items inserted by Replace() has been popped
func (f *DeltaFIFO) HasSynced() bool { func (f *DeltaFIFO) HasSynced() bool {
f.lock.Lock() f.lock.Lock()
@ -389,7 +389,7 @@ func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err err
return d, exists, nil return d, exists, nil
} }
// Checks if the queue is closed // IsClosed checks if the queue is closed
func (f *DeltaFIFO) IsClosed() bool { func (f *DeltaFIFO) IsClosed() bool {
f.closedLock.Lock() f.closedLock.Lock()
defer f.closedLock.Unlock() defer f.closedLock.Unlock()
@ -417,7 +417,7 @@ func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) {
// When Close() is called, the f.closed is set and the condition is broadcasted. // When Close() is called, the f.closed is set and the condition is broadcasted.
// Which causes this loop to continue and return from the Pop(). // Which causes this loop to continue and return from the Pop().
if f.IsClosed() { if f.IsClosed() {
return nil, FIFOClosedError return nil, ErrFIFOClosed
} }
f.cond.Wait() f.cond.Wait()
@ -593,6 +593,7 @@ type KeyGetter interface {
// DeltaType is the type of a change (addition, deletion, etc) // DeltaType is the type of a change (addition, deletion, etc)
type DeltaType string type DeltaType string
// Change type definition
const ( const (
Added DeltaType = "Added" Added DeltaType = "Added"
Updated DeltaType = "Updated" Updated DeltaType = "Updated"

View File

@ -55,7 +55,7 @@ type ExpirationPolicy interface {
type TTLPolicy struct { type TTLPolicy struct {
// >0: Expire entries with an age > ttl // >0: Expire entries with an age > ttl
// <=0: Don't expire any entry // <=0: Don't expire any entry
Ttl time.Duration TTL time.Duration
// Clock used to calculate ttl expiration // Clock used to calculate ttl expiration
Clock clock.Clock Clock clock.Clock
@ -64,7 +64,7 @@ type TTLPolicy struct {
// IsExpired returns true if the given object is older than the ttl, or it can't // IsExpired returns true if the given object is older than the ttl, or it can't
// determine its age. // determine its age.
func (p *TTLPolicy) IsExpired(obj *TimestampedEntry) bool { func (p *TTLPolicy) IsExpired(obj *TimestampedEntry) bool {
return p.Ttl > 0 && p.Clock.Since(obj.Timestamp) > p.Ttl return p.TTL > 0 && p.Clock.Since(obj.Timestamp) > p.TTL
} }
// TimestampedEntry is the only type allowed in a ExpirationCache. // TimestampedEntry is the only type allowed in a ExpirationCache.

View File

@ -33,16 +33,19 @@ func (c *fakeThreadSafeMap) Delete(key string) {
} }
} }
// FakeExpirationPolicy keeps the list for keys which never expires.
type FakeExpirationPolicy struct { type FakeExpirationPolicy struct {
NeverExpire sets.String NeverExpire sets.String
RetrieveKeyFunc KeyFunc RetrieveKeyFunc KeyFunc
} }
// IsExpired used to check if object is expired.
func (p *FakeExpirationPolicy) IsExpired(obj *TimestampedEntry) bool { func (p *FakeExpirationPolicy) IsExpired(obj *TimestampedEntry) bool {
key, _ := p.RetrieveKeyFunc(obj) key, _ := p.RetrieveKeyFunc(obj)
return !p.NeverExpire.Has(key) return !p.NeverExpire.Has(key)
} }
// NewFakeExpirationStore creates a new instance for the ExpirationCache.
func NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store { func NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store {
cacheStorage := NewThreadSafeStore(Indexers{}, Indices{}) cacheStorage := NewThreadSafeStore(Indexers{}, Indices{})
return &ExpirationCache{ return &ExpirationCache{

View File

@ -181,7 +181,7 @@ func TestTTLPolicy(t *testing.T) {
t.Errorf("TTL Cache should expire entries older than ttl") t.Errorf("TTL Cache should expire entries older than ttl")
} }
for _, ttl = range []time.Duration{0, -1} { for _, ttl = range []time.Duration{0, -1} {
policy.Ttl = ttl policy.TTL = ttl
if policy.IsExpired(fakeTimestampedEntry) { if policy.IsExpired(fakeTimestampedEntry) {
t.Errorf("TTL policy should only expire entries when initialized with a ttl > 0") t.Errorf("TTL policy should only expire entries when initialized with a ttl > 0")
} }

View File

@ -16,7 +16,7 @@ limitations under the License.
package cache package cache
// FakeStore lets you define custom functions for store operations // FakeCustomStore lets you define custom functions for store operations.
type FakeCustomStore struct { type FakeCustomStore struct {
AddFunc func(obj interface{}) error AddFunc func(obj interface{}) error
UpdateFunc func(obj interface{}) error UpdateFunc func(obj interface{}) error

11
tools/cache/fifo.go vendored
View File

@ -34,7 +34,8 @@ type ErrRequeue struct {
Err error Err error
} }
var FIFOClosedError error = errors.New("DeltaFIFO: manipulating with closed queue") // ErrFIFOClosed used when FIFO is closed
var ErrFIFOClosed = errors.New("DeltaFIFO: manipulating with closed queue")
func (e ErrRequeue) Error() string { func (e ErrRequeue) Error() string {
if e.Err == nil { if e.Err == nil {
@ -66,7 +67,7 @@ type Queue interface {
Close() Close()
} }
// Helper function for popping from Queue. // Pop is helper function for popping from Queue.
// WARNING: Do NOT use this function in non-test code to avoid races // WARNING: Do NOT use this function in non-test code to avoid races
// unless you really really really really know what you are doing. // unless you really really really really know what you are doing.
func Pop(queue Queue) interface{} { func Pop(queue Queue) interface{} {
@ -126,7 +127,7 @@ func (f *FIFO) Close() {
f.cond.Broadcast() f.cond.Broadcast()
} }
// Return true if an Add/Update/Delete/AddIfNotPresent are called first, // HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,
// or an Update called first but the first batch of items inserted by Replace() has been popped // or an Update called first but the first batch of items inserted by Replace() has been popped
func (f *FIFO) HasSynced() bool { func (f *FIFO) HasSynced() bool {
f.lock.Lock() f.lock.Lock()
@ -242,7 +243,7 @@ func (f *FIFO) GetByKey(key string) (item interface{}, exists bool, err error) {
return item, exists, nil return item, exists, nil
} }
// Checks if the queue is closed // IsClosed checks if the queue is closed
func (f *FIFO) IsClosed() bool { func (f *FIFO) IsClosed() bool {
f.closedLock.Lock() f.closedLock.Lock()
defer f.closedLock.Unlock() defer f.closedLock.Unlock()
@ -267,7 +268,7 @@ func (f *FIFO) Pop(process PopProcessFunc) (interface{}, error) {
// When Close() is called, the f.closed is set and the condition is broadcasted. // When Close() is called, the f.closed is set and the condition is broadcasted.
// Which causes this loop to continue and return from the Pop(). // Which causes this loop to continue and return from the Pop().
if f.IsClosed() { if f.IsClosed() {
return nil, FIFOClosedError return nil, ErrFIFOClosed
} }
f.cond.Wait() f.cond.Wait()

10
tools/cache/heap.go vendored
View File

@ -28,7 +28,9 @@ const (
closedMsg = "heap is closed" closedMsg = "heap is closed"
) )
// LessFunc is used to compare two objects in the heap.
type LessFunc func(interface{}, interface{}) bool type LessFunc func(interface{}, interface{}) bool
type heapItem struct { type heapItem struct {
obj interface{} // The object which is stored in the heap. obj interface{} // The object which is stored in the heap.
index int // The index of the object's key in the Heap.queue. index int // The index of the object's key in the Heap.queue.
@ -158,7 +160,7 @@ func (h *Heap) Add(obj interface{}) error {
return nil return nil
} }
// Adds all the items in the list to the queue and then signals the condition // BulkAdd adds all the items in the list to the queue and then signals the condition
// variable. It is useful when the caller would like to add all of the items // variable. It is useful when the caller would like to add all of the items
// to the queue before consumer starts processing them. // to the queue before consumer starts processing them.
func (h *Heap) BulkAdd(list []interface{}) error { func (h *Heap) BulkAdd(list []interface{}) error {
@ -249,11 +251,11 @@ func (h *Heap) Pop() (interface{}, error) {
h.cond.Wait() h.cond.Wait()
} }
obj := heap.Pop(h.data) obj := heap.Pop(h.data)
if obj != nil { if obj == nil {
return obj, nil
} else {
return nil, fmt.Errorf("object was removed from heap data") return nil, fmt.Errorf("object was removed from heap data")
} }
return obj, nil
} }
// List returns a list of all the items. // List returns a list of all the items.

View File

@ -75,6 +75,7 @@ func IndexFuncToKeyFuncAdapter(indexFunc IndexFunc) KeyFunc {
} }
const ( const (
// NamespaceIndex is the lookup name for the most comment index function, which is to index by the namespace field.
NamespaceIndex string = "namespace" NamespaceIndex string = "namespace"
) )

View File

@ -30,6 +30,7 @@ import (
// AppendFunc is used to add a matching item to whatever list the caller is using // AppendFunc is used to add a matching item to whatever list the caller is using
type AppendFunc func(interface{}) type AppendFunc func(interface{})
// ListAll calls appendFn with each value retrieved from store which matches the selector.
func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error { func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error {
selectAll := selector.Empty() selectAll := selector.Empty()
for _, m := range store.List() { for _, m := range store.List() {
@ -50,6 +51,7 @@ func ListAll(store Store, selector labels.Selector, appendFn AppendFunc) error {
return nil return nil
} }
// ListAllByNamespace used to list items belongs to namespace from Indexer.
func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error { func ListAllByNamespace(indexer Indexer, namespace string, selector labels.Selector, appendFn AppendFunc) error {
selectAll := selector.Empty() selectAll := selector.Empty()
if namespace == metav1.NamespaceAll { if namespace == metav1.NamespaceAll {
@ -124,6 +126,7 @@ type GenericNamespaceLister interface {
Get(name string) (runtime.Object, error) Get(name string) (runtime.Object, error)
} }
// NewGenericLister creates a new instance for the genericLister.
func NewGenericLister(indexer Indexer, resource schema.GroupResource) GenericLister { func NewGenericLister(indexer Indexer, resource schema.GroupResource) GenericLister {
return &genericLister{indexer: indexer, resource: resource} return &genericLister{indexer: indexer, resource: resource}
} }

View File

@ -42,6 +42,7 @@ type MutationCache interface {
Mutation(interface{}) Mutation(interface{})
} }
// ResourceVersionComparator is able to compare object versions.
type ResourceVersionComparator interface { type ResourceVersionComparator interface {
CompareResourceVersion(lhs, rhs runtime.Object) int CompareResourceVersion(lhs, rhs runtime.Object) int
} }

View File

@ -36,12 +36,14 @@ func init() {
mutationDetectionEnabled, _ = strconv.ParseBool(os.Getenv("KUBE_CACHE_MUTATION_DETECTOR")) mutationDetectionEnabled, _ = strconv.ParseBool(os.Getenv("KUBE_CACHE_MUTATION_DETECTOR"))
} }
type CacheMutationDetector interface { // MutationDetector is able to monitor if the object be modified outside.
type MutationDetector interface {
AddObject(obj interface{}) AddObject(obj interface{})
Run(stopCh <-chan struct{}) Run(stopCh <-chan struct{})
} }
func NewCacheMutationDetector(name string) CacheMutationDetector { // NewCacheMutationDetector creates a new instance for the defaultCacheMutationDetector.
func NewCacheMutationDetector(name string) MutationDetector {
if !mutationDetectionEnabled { if !mutationDetectionEnabled {
return dummyMutationDetector{} return dummyMutationDetector{}
} }

View File

@ -34,7 +34,7 @@ import (
// SharedInformer provides eventually consistent linkage of its // SharedInformer provides eventually consistent linkage of its
// clients to the authoritative state of a given collection of // clients to the authoritative state of a given collection of
// objects. An object is identified by its API group, kind/resource, // objects. An object is identified by its API group, kind/resource,
// namespace, and name. One SharedInfomer provides linkage to objects // namespace, and name. One SharedInformer provides linkage to objects
// of a particular API group and kind/resource. The linked object // of a particular API group and kind/resource. The linked object
// collection of a SharedInformer may be further restricted to one // collection of a SharedInformer may be further restricted to one
// namespace and/or by label selector and/or field selector. // namespace and/or by label selector and/or field selector.
@ -44,7 +44,7 @@ import (
// A state is either "absent" or present with a ResourceVersion and // A state is either "absent" or present with a ResourceVersion and
// other appropriate content. // other appropriate content.
// //
// A SharedInformer maintains a local cache, exposed by Store(), of // A SharedInformer maintains a local cache, exposed by GetStore(), of
// the state of each relevant object. This cache is eventually // the state of each relevant object. This cache is eventually
// consistent with the authoritative state. This means that, unless // consistent with the authoritative state. This means that, unless
// prevented by persistent communication problems, if ever a // prevented by persistent communication problems, if ever a
@ -67,10 +67,10 @@ import (
// non-absent state for some object ID and the object is eventually // non-absent state for some object ID and the object is eventually
// removed from the authoritative state then eventually the object is // removed from the authoritative state then eventually the object is
// removed from the local cache (unless the SharedInformer is stopped // removed from the local cache (unless the SharedInformer is stopped
// too soon, the authoritative state service emnds, or communication // too soon, the authoritative state service ends, or communication
// problems persistently thwart the desired result). // problems persistently thwart the desired result).
// //
// The keys in Store() are of the form namespace/name for namespaced // The keys in GetStore() are of the form namespace/name for namespaced
// objects, and are simply the name for non-namespaced objects. // objects, and are simply the name for non-namespaced objects.
// //
// A client is identified here by a ResourceEventHandler. For every // A client is identified here by a ResourceEventHandler. For every
@ -116,6 +116,7 @@ type SharedInformer interface {
LastSyncResourceVersion() string LastSyncResourceVersion() string
} }
// SharedIndexInformer provides add and get Indexers ability based on SharedInformer.
type SharedIndexInformer interface { type SharedIndexInformer interface {
SharedInformer SharedInformer
// AddIndexers add indexers to the informer before it starts. // AddIndexers add indexers to the informer before it starts.
@ -182,7 +183,7 @@ type sharedIndexInformer struct {
controller Controller controller Controller
processor *sharedProcessor processor *sharedProcessor
cacheMutationDetector CacheMutationDetector cacheMutationDetector MutationDetector
// This block is tracked to handle late initialization of the controller // This block is tracked to handle late initialization of the controller
listerWatcher ListerWatcher listerWatcher ListerWatcher
@ -222,7 +223,7 @@ func (v *dummyController) HasSynced() bool {
return v.informer.HasSynced() return v.informer.HasSynced()
} }
func (c *dummyController) LastSyncResourceVersion() string { func (v *dummyController) LastSyncResourceVersion() string {
return "" return ""
} }

View File

@ -302,6 +302,7 @@ func (c *threadSafeMap) Resync() error {
return nil return nil
} }
// NewThreadSafeStore creates a new instance of ThreadSafeStore.
func NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore { func NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore {
return &threadSafeMap{ return &threadSafeMap{
items: map[string]interface{}{}, items: map[string]interface{}{},

View File

@ -31,6 +31,7 @@ type UndeltaStore struct {
// Assert that it implements the Store interface. // Assert that it implements the Store interface.
var _ Store = &UndeltaStore{} var _ Store = &UndeltaStore{}
// Add inserts an object into the store and sends complete state by calling PushFunc.
// Note about thread safety. The Store implementation (cache.cache) uses a lock for all methods. // Note about thread safety. The Store implementation (cache.cache) uses a lock for all methods.
// In the functions below, the lock gets released and reacquired betweend the {Add,Delete,etc} // In the functions below, the lock gets released and reacquired betweend the {Add,Delete,etc}
// and the List. So, the following can happen, resulting in two identical calls to PushFunc. // and the List. So, the following can happen, resulting in two identical calls to PushFunc.
@ -41,7 +42,6 @@ var _ Store = &UndeltaStore{}
// 3 Store.Add(b) // 3 Store.Add(b)
// 4 Store.List() -> [a,b] // 4 Store.List() -> [a,b]
// 5 Store.List() -> [a,b] // 5 Store.List() -> [a,b]
func (u *UndeltaStore) Add(obj interface{}) error { func (u *UndeltaStore) Add(obj interface{}) error {
if err := u.Store.Add(obj); err != nil { if err := u.Store.Add(obj); err != nil {
return err return err
@ -50,6 +50,7 @@ func (u *UndeltaStore) Add(obj interface{}) error {
return nil return nil
} }
// Update sets an item in the cache to its updated state and sends complete state by calling PushFunc.
func (u *UndeltaStore) Update(obj interface{}) error { func (u *UndeltaStore) Update(obj interface{}) error {
if err := u.Store.Update(obj); err != nil { if err := u.Store.Update(obj); err != nil {
return err return err
@ -58,6 +59,7 @@ func (u *UndeltaStore) Update(obj interface{}) error {
return nil return nil
} }
// Delete removes an item from the cache and sends complete state by calling PushFunc.
func (u *UndeltaStore) Delete(obj interface{}) error { func (u *UndeltaStore) Delete(obj interface{}) error {
if err := u.Store.Delete(obj); err != nil { if err := u.Store.Delete(obj); err != nil {
return err return err
@ -66,6 +68,10 @@ func (u *UndeltaStore) Delete(obj interface{}) error {
return nil return nil
} }
// Replace will delete the contents of current store, using instead the given list.
// 'u' takes ownership of the list, you should not reference the list again
// after calling this function.
// The new contents complete state will be sent by calling PushFunc after replacement.
func (u *UndeltaStore) Replace(list []interface{}, resourceVersion string) error { func (u *UndeltaStore) Replace(list []interface{}, resourceVersion string) error {
if err := u.Store.Replace(list, resourceVersion); err != nil { if err := u.Store.Replace(list, resourceVersion); err != nil {
return err return err

View File

@ -47,7 +47,7 @@ func TestUpdateCallsPush(t *testing.T) {
} }
var got []interface{} var got []interface{}
var callcount int = 0 var callcount = 0
push := func(m []interface{}) { push := func(m []interface{}) {
callcount++ callcount++
got = m got = m
@ -73,7 +73,7 @@ func TestDeleteCallsPush(t *testing.T) {
} }
var got []interface{} var got []interface{}
var callcount int = 0 var callcount = 0
push := func(m []interface{}) { push := func(m []interface{}) {
callcount++ callcount++
got = m got = m
@ -110,7 +110,7 @@ func TestReplaceCallsPush(t *testing.T) {
} }
var got []interface{} var got []interface{}
var callcount int = 0 var callcount = 0
push := func(m []interface{}) { push := func(m []interface{}) {
callcount++ callcount++
got = m got = m