code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func NewTransformingInformer(
lw ListerWatcher,
objType runtime.Object,
resyncPeriod time.Duration,
h ResourceEventHandler,
transformer TransformFunc,
) (Store, Controller) {
// This will hold the client state, as we know it.
clientState := NewStore(DeletionHandlingMetaNamespaceKeyFunc)
return clientState, newInformer(lw, objType, resyncPeriod, h, clientState, transformer)
} | NewTransformingInformer returns a Store and a controller for populating
the store while also providing event notifications. You should only used
the returned Store for Get/List operations; Add/Modify/Deletes will cause
the event notifications to be faulty.
The given transform function will be called on all objects before they will
put into the Store and corresponding Add/Modify/Delete handlers will
be invoked for them. | NewTransformingInformer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/controller.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/controller.go | Apache-2.0 |
func NewTransformingIndexerInformer(
lw ListerWatcher,
objType runtime.Object,
resyncPeriod time.Duration,
h ResourceEventHandler,
indexers Indexers,
transformer TransformFunc,
) (Indexer, Controller) {
// This will hold the client state, as we know it.
clientState := NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)
return clientState, newInformer(lw, objType, resyncPeriod, h, clientState, transformer)
} | NewTransformingIndexerInformer returns an Indexer and a controller for
populating the index while also providing event notifications. You should
only used the returned Index for Get/List operations; Add/Modify/Deletes
will cause the event notifications to be faulty.
The given transform function will be called on all objects before they will
be put into the Index and corresponding Add/Modify/Delete handlers will
be invoked for them. | NewTransformingIndexerInformer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/controller.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/controller.go | Apache-2.0 |
func processDeltas(
// Object which receives event notifications from the given deltas
handler ResourceEventHandler,
clientState Store,
deltas Deltas,
isInInitialList bool,
) error {
// from oldest to newest
for _, d := range deltas {
obj := d.Object
switch d.Type {
case Sync, Replaced, Added, Updated:
if old, exists, err := clientState.Get(obj); err == nil && exists {
if err := clientState.Update(obj); err != nil {
return err
}
handler.OnUpdate(old, obj)
} else {
if err := clientState.Add(obj); err != nil {
return err
}
handler.OnAdd(obj, isInInitialList)
}
case Deleted:
if err := clientState.Delete(obj); err != nil {
return err
}
handler.OnDelete(obj)
}
}
return nil
} | Multiplexes updates in the form of a list of Deltas into a Store, and informs
a given handler of events OnUpdate, OnAdd, OnDelete | processDeltas | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/controller.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/controller.go | Apache-2.0 |
func newInformer(
lw ListerWatcher,
objType runtime.Object,
resyncPeriod time.Duration,
h ResourceEventHandler,
clientState Store,
transformer TransformFunc,
) Controller {
// This will hold incoming changes. Note how we pass clientState in as a
// KeyLister, that way resync operations will result in the correct set
// of update/delete deltas.
fifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{
KnownObjects: clientState,
EmitDeltaTypeReplaced: true,
Transformer: transformer,
})
cfg := &Config{
Queue: fifo,
ListerWatcher: lw,
ObjectType: objType,
FullResyncPeriod: resyncPeriod,
RetryOnError: false,
Process: func(obj interface{}, isInInitialList bool) error {
if deltas, ok := obj.(Deltas); ok {
return processDeltas(h, clientState, deltas, isInInitialList)
}
return errors.New("object given as Process argument is not Deltas")
},
}
return New(cfg)
} | newInformer returns a controller for populating the store while also
providing event notifications.
Parameters
- lw is list and watch functions for the source of the resource you want to
be informed of.
- objType is an object of the type that you expect to receive.
- resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
calls, even if nothing changed). Otherwise, re-list will be delayed as
long as possible (until the upstream source closes the watch or times out,
or you stop the controller).
- h is the object you want notifications sent to.
- clientState is the store you want to populate | newInformer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/controller.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/controller.go | Apache-2.0 |
func NewCacheMutationDetector(name string) MutationDetector {
if !mutationDetectionEnabled {
return dummyMutationDetector{}
}
klog.Warningln("Mutation detector is enabled, this will result in memory leakage.")
return &defaultCacheMutationDetector{name: name, period: 1 * time.Second, retainDuration: 2 * time.Minute}
} | NewCacheMutationDetector creates a new instance for the defaultCacheMutationDetector. | NewCacheMutationDetector | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_detector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_detector.go | Apache-2.0 |
func (d *defaultCacheMutationDetector) AddObject(obj interface{}) {
if _, ok := obj.(DeletedFinalStateUnknown); ok {
return
}
if obj, ok := obj.(runtime.Object); ok {
copiedObj := obj.DeepCopyObject()
d.addedObjsLock.Lock()
defer d.addedObjsLock.Unlock()
d.addedObjs = append(d.addedObjs, cacheObj{cached: obj, copied: copiedObj})
}
} | AddObject makes a deep copy of the object for later comparison. It only works on runtime.Object
but that covers the vast majority of our cached objects | AddObject | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_detector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_detector.go | Apache-2.0 |
func (p *TTLPolicy) IsExpired(obj *TimestampedEntry) bool {
return p.TTL > 0 && p.Clock.Since(obj.Timestamp) > p.TTL
} | IsExpired returns true if the given object is older than the ttl, or it can't
determine its age. | IsExpired | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) getTimestampedEntry(key string) (*TimestampedEntry, bool) {
item, _ := c.cacheStorage.Get(key)
if tsEntry, ok := item.(*TimestampedEntry); ok {
return tsEntry, true
}
return nil, false
} | getTimestampedEntry returns the TimestampedEntry stored under the given key. | getTimestampedEntry | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) getOrExpire(key string) (interface{}, bool) {
// Prevent all inserts from the time we deem an item as "expired" to when we
// delete it, so an un-expired item doesn't sneak in under the same key, just
// before the Delete.
c.expirationLock.Lock()
defer c.expirationLock.Unlock()
timestampedItem, exists := c.getTimestampedEntry(key)
if !exists {
return nil, false
}
if c.expirationPolicy.IsExpired(timestampedItem) {
c.cacheStorage.Delete(key)
return nil, false
}
return timestampedItem.Obj, true
} | getOrExpire retrieves the object from the TimestampedEntry if and only if it hasn't
already expired. It holds a write lock across deletion. | getOrExpire | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) GetByKey(key string) (interface{}, bool, error) {
obj, exists := c.getOrExpire(key)
return obj, exists, nil
} | GetByKey returns the item stored under the key, or sets exists=false. | GetByKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Get(obj interface{}) (interface{}, bool, error) {
key, err := c.keyFunc(obj)
if err != nil {
return nil, false, KeyError{obj, err}
}
obj, exists := c.getOrExpire(key)
return obj, exists, nil
} | Get returns unexpired items. It purges the cache of expired items in the
process. | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) List() []interface{} {
items := c.cacheStorage.List()
list := make([]interface{}, 0, len(items))
for _, item := range items {
key := item.(*TimestampedEntry).key
if obj, exists := c.getOrExpire(key); exists {
list = append(list, obj)
}
}
return list
} | List retrieves a list of unexpired items. It purges the cache of expired
items in the process. | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) ListKeys() []string {
return c.cacheStorage.ListKeys()
} | ListKeys returns a list of all keys in the expiration cache. | ListKeys | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Add(obj interface{}) error {
key, err := c.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
c.expirationLock.Lock()
defer c.expirationLock.Unlock()
c.cacheStorage.Add(key, &TimestampedEntry{obj, c.clock.Now(), key})
return nil
} | Add timestamps an item and inserts it into the cache, overwriting entries
that might exist under the same key. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Update(obj interface{}) error {
return c.Add(obj)
} | Update has not been implemented yet for lack of a use case, so this method
simply calls `Add`. This effectively refreshes the timestamp. | Update | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Delete(obj interface{}) error {
key, err := c.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
c.expirationLock.Lock()
defer c.expirationLock.Unlock()
c.cacheStorage.Delete(key)
return nil
} | Delete removes an item from the cache. | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Replace(list []interface{}, resourceVersion string) error {
items := make(map[string]interface{}, len(list))
ts := c.clock.Now()
for _, item := range list {
key, err := c.keyFunc(item)
if err != nil {
return KeyError{item, err}
}
items[key] = &TimestampedEntry{item, ts, key}
}
c.expirationLock.Lock()
defer c.expirationLock.Unlock()
c.cacheStorage.Replace(items, resourceVersion)
return nil
} | Replace will convert all items in the given list to TimestampedEntries
before attempting the replace operation. The replace operation will
delete the contents of the ExpirationCache `c`. | Replace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func (c *ExpirationCache) Resync() error {
return nil
} | Resync is a no-op for one of these | Resync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func NewTTLStore(keyFunc KeyFunc, ttl time.Duration) Store {
return NewExpirationStore(keyFunc, &TTLPolicy{ttl, clock.RealClock{}})
} | NewTTLStore creates and returns a ExpirationCache with a TTLPolicy | NewTTLStore | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func NewExpirationStore(keyFunc KeyFunc, expirationPolicy ExpirationPolicy) Store {
return &ExpirationCache{
cacheStorage: NewThreadSafeStore(Indexers{}, Indices{}),
keyFunc: keyFunc,
clock: clock.RealClock{},
expirationPolicy: expirationPolicy,
}
} | NewExpirationStore creates and returns a ExpirationCache for a given policy | NewExpirationStore | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache.go | Apache-2.0 |
func IndexFuncToKeyFuncAdapter(indexFunc IndexFunc) KeyFunc {
return func(obj interface{}) (string, error) {
indexKeys, err := indexFunc(obj)
if err != nil {
return "", err
}
if len(indexKeys) > 1 {
return "", fmt.Errorf("too many keys: %v", indexKeys)
}
if len(indexKeys) == 0 {
return "", fmt.Errorf("unexpected empty indexKeys")
}
return indexKeys[0], nil
}
} | IndexFuncToKeyFuncAdapter adapts an indexFunc to a keyFunc. This is only useful if your index function returns
unique values for every object. This conversion can create errors when more than one key is found. You
should prefer to make proper key and index functions. | IndexFuncToKeyFuncAdapter | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/index.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/index.go | Apache-2.0 |
func MetaNamespaceIndexFunc(obj interface{}) ([]string, error) {
meta, err := meta.Accessor(obj)
if err != nil {
return []string{""}, fmt.Errorf("object has no meta: %v", err)
}
return []string{meta.GetNamespace()}, nil
} | MetaNamespaceIndexFunc is a default index function that indexes based on an object's namespace | MetaNamespaceIndexFunc | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/index.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/index.go | Apache-2.0 |
func NewListWatchFromClient(c Getter, resource string, namespace string, fieldSelector fields.Selector) *ListWatch {
optionsModifier := func(options *metav1.ListOptions) {
options.FieldSelector = fieldSelector.String()
}
return NewFilteredListWatchFromClient(c, resource, namespace, optionsModifier)
} | NewListWatchFromClient creates a new ListWatch from the specified client, resource, namespace and field selector. | NewListWatchFromClient | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listwatch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listwatch.go | Apache-2.0 |
func NewFilteredListWatchFromClient(c Getter, resource string, namespace string, optionsModifier func(options *metav1.ListOptions)) *ListWatch {
listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
optionsModifier(&options)
return c.Get().
Namespace(namespace).
Resource(resource).
VersionedParams(&options, metav1.ParameterCodec).
Do(context.TODO()).
Get()
}
watchFunc := func(options metav1.ListOptions) (watch.Interface, error) {
options.Watch = true
optionsModifier(&options)
return c.Get().
Namespace(namespace).
Resource(resource).
VersionedParams(&options, metav1.ParameterCodec).
Watch(context.TODO())
}
return &ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
} | NewFilteredListWatchFromClient creates a new ListWatch from the specified client, resource, namespace, and option modifier.
Option modifier is a function takes a ListOptions and modifies the consumed ListOptions. Provide customized modifier function
to apply modification to ListOptions with a field selector, a label selector, or any other desired options. | NewFilteredListWatchFromClient | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listwatch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listwatch.go | Apache-2.0 |
func (lw *ListWatch) List(options metav1.ListOptions) (runtime.Object, error) {
// ListWatch is used in Reflector, which already supports pagination.
// Don't paginate here to avoid duplication.
return lw.ListFunc(options)
} | List a set of apiserver resources | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listwatch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listwatch.go | Apache-2.0 |
func (lw *ListWatch) Watch(options metav1.ListOptions) (watch.Interface, error) {
return lw.WatchFunc(options)
} | Watch a set of apiserver resources | Watch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/listwatch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/listwatch.go | Apache-2.0 |
func NewIntegerResourceVersionMutationCache(backingCache Store, indexer Indexer, ttl time.Duration, includeAdds bool) MutationCache {
return &mutationCache{
backingCache: backingCache,
indexer: indexer,
mutationCache: utilcache.NewLRUExpireCache(100),
comparator: etcdObjectVersioner{},
ttl: ttl,
includeAdds: includeAdds,
}
} | NewIntegerResourceVersionMutationCache returns a MutationCache that understands how to
deal with objects that have a resource version that:
- is an integer
- increases when updated
- is comparable across the same resource in a namespace
Most backends will have these semantics. Indexer may be nil. ttl controls how long an item
remains in the mutation cache before it is removed.
If includeAdds is true, objects in the mutation cache will be returned even if they don't exist
in the underlying store. This is only safe if your use of the cache can handle mutation entries
remaining in the cache for up to ttl when mutations and deletes occur very closely in time. | NewIntegerResourceVersionMutationCache | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (c *mutationCache) GetByKey(key string) (interface{}, bool, error) {
c.lock.Lock()
defer c.lock.Unlock()
obj, exists, err := c.backingCache.GetByKey(key)
if err != nil {
return nil, false, err
}
if !exists {
if !c.includeAdds {
// we can't distinguish between, "didn't observe create" and "was deleted after create", so
// if the key is missing, we always return it as missing
return nil, false, nil
}
obj, exists = c.mutationCache.Get(key)
if !exists {
return nil, false, nil
}
}
objRuntime, ok := obj.(runtime.Object)
if !ok {
return obj, true, nil
}
return c.newerObject(key, objRuntime), true, nil
} | GetByKey is never guaranteed to return back the value set in Mutation. It could be paged out, it could
be older than another copy, the backingCache may be more recent or, you might have written twice into the same key.
You get a value that was valid at some snapshot of time and will always return the newer of backingCache and mutationCache. | GetByKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (c *mutationCache) ByIndex(name string, indexKey string) ([]interface{}, error) {
c.lock.Lock()
defer c.lock.Unlock()
if c.indexer == nil {
return nil, fmt.Errorf("no indexer has been provided to the mutation cache")
}
keys, err := c.indexer.IndexKeys(name, indexKey)
if err != nil {
return nil, err
}
var items []interface{}
keySet := sets.NewString()
for _, key := range keys {
keySet.Insert(key)
obj, exists, err := c.indexer.GetByKey(key)
if err != nil {
return nil, err
}
if !exists {
continue
}
if objRuntime, ok := obj.(runtime.Object); ok {
items = append(items, c.newerObject(key, objRuntime))
} else {
items = append(items, obj)
}
}
if c.includeAdds {
fn := c.indexer.GetIndexers()[name]
// Keys() is returned oldest to newest, so full traversal does not alter the LRU behavior
for _, key := range c.mutationCache.Keys() {
updated, ok := c.mutationCache.Get(key)
if !ok {
continue
}
if keySet.Has(key.(string)) {
continue
}
elements, err := fn(updated)
if err != nil {
klog.V(4).Infof("Unable to calculate an index entry for mutation cache entry %s: %v", key, err)
continue
}
for _, inIndex := range elements {
if inIndex != indexKey {
continue
}
items = append(items, updated)
break
}
}
}
return items, nil
} | ByIndex returns the newer objects that match the provided index and indexer key.
Will return an error if no indexer was provided. | ByIndex | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (c *mutationCache) newerObject(key string, backing runtime.Object) runtime.Object {
mutatedObj, exists := c.mutationCache.Get(key)
if !exists {
return backing
}
mutatedObjRuntime, ok := mutatedObj.(runtime.Object)
if !ok {
return backing
}
if c.comparator.CompareResourceVersion(backing, mutatedObjRuntime) >= 0 {
c.mutationCache.Remove(key)
return backing
}
return mutatedObjRuntime
} | newerObject checks the mutation cache for a newer object and returns one if found. If the
mutated object is older than the backing object, it is removed from the Must be
called while the lock is held. | newerObject | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (c *mutationCache) Mutation(obj interface{}) {
c.lock.Lock()
defer c.lock.Unlock()
key, err := DeletionHandlingMetaNamespaceKeyFunc(obj)
if err != nil {
// this is a "nice to have", so failures shouldn't do anything weird
utilruntime.HandleError(err)
return
}
if objRuntime, ok := obj.(runtime.Object); ok {
if mutatedObj, exists := c.mutationCache.Get(key); exists {
if mutatedObjRuntime, ok := mutatedObj.(runtime.Object); ok {
if c.comparator.CompareResourceVersion(objRuntime, mutatedObjRuntime) < 0 {
return
}
}
}
}
c.mutationCache.Add(key, obj, c.ttl)
} | Mutation adds a change to the cache that can be returned in GetByKey if it is newer than the backingCache
copy. If you call Mutation twice with the same object on different threads, one will win, but its not defined
which one. This doesn't affect correctness, since the GetByKey guaranteed of "later of these two caches" is
preserved, but you may not get the version of the object you want. The object you get is only guaranteed to
"one that was valid at some point in time", not "the one that I want". | Mutation | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (a etcdObjectVersioner) ObjectResourceVersion(obj runtime.Object) (uint64, error) {
accessor, err := meta.Accessor(obj)
if err != nil {
return 0, err
}
version := accessor.GetResourceVersion()
if len(version) == 0 {
return 0, nil
}
return strconv.ParseUint(version, 10, 64)
} | ObjectResourceVersion implements Versioner | ObjectResourceVersion | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func (a etcdObjectVersioner) CompareResourceVersion(lhs, rhs runtime.Object) int {
lhsVersion, err := a.ObjectResourceVersion(lhs)
if err != nil {
// coder error
panic(err)
}
rhsVersion, err := a.ObjectResourceVersion(rhs)
if err != nil {
// coder error
panic(err)
}
if lhsVersion == rhsVersion {
return 0
}
if lhsVersion < rhsVersion {
return -1
}
return 1
} | CompareResourceVersion compares etcd resource versions. Outside this API they are all strings,
but etcd resource versions are special, they're actually ints, so we can easily compare them. | CompareResourceVersion | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/mutation_cache.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/mutation_cache.go | Apache-2.0 |
func NewSharedInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration) SharedInformer {
return NewSharedIndexInformer(lw, exampleObject, defaultEventHandlerResyncPeriod, Indexers{})
} | NewSharedInformer creates a new instance for the ListerWatcher. See NewSharedIndexInformerWithOptions for full details. | NewSharedInformer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func NewSharedIndexInformer(lw ListerWatcher, exampleObject runtime.Object, defaultEventHandlerResyncPeriod time.Duration, indexers Indexers) SharedIndexInformer {
return NewSharedIndexInformerWithOptions(
lw,
exampleObject,
SharedIndexInformerOptions{
ResyncPeriod: defaultEventHandlerResyncPeriod,
Indexers: indexers,
},
)
} | NewSharedIndexInformer creates a new instance for the ListerWatcher and specified Indexers. See
NewSharedIndexInformerWithOptions for full details. | NewSharedIndexInformer | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func NewSharedIndexInformerWithOptions(lw ListerWatcher, exampleObject runtime.Object, options SharedIndexInformerOptions) SharedIndexInformer {
realClock := &clock.RealClock{}
return &sharedIndexInformer{
indexer: NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, options.Indexers),
processor: &sharedProcessor{clock: realClock},
listerWatcher: lw,
objectType: exampleObject,
objectDescription: options.ObjectDescription,
resyncCheckPeriod: options.ResyncPeriod,
defaultEventHandlerResyncPeriod: options.ResyncPeriod,
clock: realClock,
cacheMutationDetector: NewCacheMutationDetector(fmt.Sprintf("%T", exampleObject)),
}
} | NewSharedIndexInformerWithOptions creates a new instance for the ListerWatcher.
The created informer will not do resyncs if options.ResyncPeriod is zero. Otherwise: for each
handler that with a non-zero requested resync period, whether added
before or after the informer starts, the nominal resync period is
the requested resync period rounded up to a multiple of the
informer's resync checking period. Such an informer's resync
checking period is established when the informer starts running,
and is the maximum of (a) the minimum of the resync periods
requested before the informer starts and the
options.ResyncPeriod given here and (b) the constant
`minimumResyncPeriod` defined in this file. | NewSharedIndexInformerWithOptions | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func WaitForNamedCacheSync(controllerName string, stopCh <-chan struct{}, cacheSyncs ...InformerSynced) bool {
klog.Infof("Waiting for caches to sync for %s", controllerName)
if !WaitForCacheSync(stopCh, cacheSyncs...) {
utilruntime.HandleError(fmt.Errorf("unable to sync caches for %s", controllerName))
return false
}
klog.Infof("Caches are synced for %s", controllerName)
return true
} | WaitForNamedCacheSync is a wrapper around WaitForCacheSync that generates log messages
indicating that the caller identified by name is waiting for syncs, followed by
either a successful or failed sync. | WaitForNamedCacheSync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func WaitForCacheSync(stopCh <-chan struct{}, cacheSyncs ...InformerSynced) bool {
err := wait.PollImmediateUntil(syncedPollPeriod,
func() (bool, error) {
for _, syncFunc := range cacheSyncs {
if !syncFunc() {
return false, nil
}
}
return true, nil
},
stopCh)
if err != nil {
return false
}
return true
} | WaitForCacheSync waits for caches to populate. It returns true if it was successful, false
if the controller should shutdown
callers should prefer WaitForNamedCacheSync() | WaitForCacheSync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (s *sharedIndexInformer) OnAdd(obj interface{}, isInInitialList bool) {
// Invocation of this function is locked under s.blockDeltas, so it is
// save to distribute the notification
s.cacheMutationDetector.AddObject(obj)
s.processor.distribute(addNotification{newObj: obj, isInInitialList: isInInitialList}, false)
} | Conforms to ResourceEventHandler | OnAdd | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (s *sharedIndexInformer) OnUpdate(old, new interface{}) {
isSync := false
// If is a Sync event, isSync should be true
// If is a Replaced event, isSync is true if resource version is unchanged.
// If RV is unchanged: this is a Sync/Replaced event, so isSync is true
if accessor, err := meta.Accessor(new); err == nil {
if oldAccessor, err := meta.Accessor(old); err == nil {
// Events that didn't change resourceVersion are treated as resync events
// and only propagated to listeners that requested resync
isSync = accessor.GetResourceVersion() == oldAccessor.GetResourceVersion()
}
}
// Invocation of this function is locked under s.blockDeltas, so it is
// save to distribute the notification
s.cacheMutationDetector.AddObject(new)
s.processor.distribute(updateNotification{oldObj: old, newObj: new}, isSync)
} | Conforms to ResourceEventHandler | OnUpdate | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (s *sharedIndexInformer) OnDelete(old interface{}) {
// Invocation of this function is locked under s.blockDeltas, so it is
// save to distribute the notification
s.processor.distribute(deleteNotification{oldObj: old}, false)
} | Conforms to ResourceEventHandler | OnDelete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (s *sharedIndexInformer) IsStopped() bool {
s.startedLock.Lock()
defer s.startedLock.Unlock()
return s.stopped
} | IsStopped reports whether the informer has already been stopped | IsStopped | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (p *sharedProcessor) shouldResync() bool {
p.listenersLock.Lock()
defer p.listenersLock.Unlock()
resyncNeeded := false
now := p.clock.Now()
for listener := range p.listeners {
// need to loop through all the listeners to see if they need to resync so we can prepare any
// listeners that are going to be resyncing.
shouldResync := listener.shouldResync(now)
p.listeners[listener] = shouldResync
if shouldResync {
resyncNeeded = true
listener.determineNextResync(now)
}
}
return resyncNeeded
} | shouldResync queries every listener to determine if any of them need a resync, based on each
listener's resyncPeriod. | shouldResync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func (p *processorListener) HasSynced() bool {
return p.syncTracker.HasSynced()
} | HasSynced returns true if the source informer has synced, and all
corresponding events have been delivered. | HasSynced | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/shared_informer.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/shared_informer.go | Apache-2.0 |
func DefaultWatchErrorHandler(r *Reflector, err error) {
switch {
case isExpiredError(err):
// Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already
// has a semantic that it returns data at least as fresh as provided RV.
// So first try to LIST with setting RV to resource version of last observed object.
klog.V(4).Infof("%s: watch of %v closed with: %v", r.name, r.typeDescription, err)
case err == io.EOF:
// watch closed normally
case err == io.ErrUnexpectedEOF:
klog.V(1).Infof("%s: Watch for %v closed with unexpected EOF: %v", r.name, r.typeDescription, err)
default:
utilruntime.HandleError(fmt.Errorf("%s: Failed to watch %v: %v", r.name, r.typeDescription, err))
}
} | DefaultWatchErrorHandler is the default implementation of WatchErrorHandler | DefaultWatchErrorHandler | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func NewNamespaceKeyedIndexerAndReflector(lw ListerWatcher, expectedType interface{}, resyncPeriod time.Duration) (indexer Indexer, reflector *Reflector) {
indexer = NewIndexer(MetaNamespaceKeyFunc, Indexers{NamespaceIndex: MetaNamespaceIndexFunc})
reflector = NewReflector(lw, expectedType, indexer, resyncPeriod)
return indexer, reflector
} | NewNamespaceKeyedIndexerAndReflector creates an Indexer and a Reflector
The indexer is configured to key on namespace | NewNamespaceKeyedIndexerAndReflector | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func NewReflector(lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{ResyncPeriod: resyncPeriod})
} | NewReflector creates a new Reflector with its name defaulted to the closest source_file.go:line in the call stack
that is outside this package. See NewReflectorWithOptions for further information. | NewReflector | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func NewNamedReflector(name string, lw ListerWatcher, expectedType interface{}, store Store, resyncPeriod time.Duration) *Reflector {
return NewReflectorWithOptions(lw, expectedType, store, ReflectorOptions{Name: name, ResyncPeriod: resyncPeriod})
} | NewNamedReflector creates a new Reflector with the specified name. See NewReflectorWithOptions for further
information. | NewNamedReflector | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func NewReflectorWithOptions(lw ListerWatcher, expectedType interface{}, store Store, options ReflectorOptions) *Reflector {
reflectorClock := options.Clock
if reflectorClock == nil {
reflectorClock = clock.RealClock{}
}
r := &Reflector{
name: options.Name,
resyncPeriod: options.ResyncPeriod,
typeDescription: options.TypeDescription,
listerWatcher: lw,
store: store,
// We used to make the call every 1sec (1 QPS), the goal here is to achieve ~98% traffic reduction when
// API server is not healthy. With these parameters, backoff will stop at [30,60) sec interval which is
// 0.22 QPS. If we don't backoff for 2min, assume API server is healthy and we reset the backoff.
backoffManager: wait.NewExponentialBackoffManager(800*time.Millisecond, 30*time.Second, 2*time.Minute, 2.0, 1.0, reflectorClock),
clock: reflectorClock,
watchErrorHandler: WatchErrorHandler(DefaultWatchErrorHandler),
expectedType: reflect.TypeOf(expectedType),
}
if r.name == "" {
r.name = naming.GetNameFromCallsite(internalPackages...)
}
if r.typeDescription == "" {
r.typeDescription = getTypeDescriptionFromObject(expectedType)
}
if r.expectedGVK == nil {
r.expectedGVK = getExpectedGVKFromObject(expectedType)
}
if s := os.Getenv("ENABLE_CLIENT_GO_WATCH_LIST_ALPHA"); len(s) > 0 {
r.UseWatchList = true
}
return r
} | NewReflectorWithOptions creates a new Reflector object which will keep the
given store up to date with the server's contents for the given
resource. Reflector promises to only put things in the store that
have the type of expectedType, unless expectedType is nil. If
resyncPeriod is non-zero, then the reflector will periodically
consult its ShouldResync function to determine whether to invoke
the Store's Resync operation; `ShouldResync==nil` means always
"yes". This enables you to use reflectors to periodically process
everything as well as incrementally processing the things that
change. | NewReflectorWithOptions | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) Run(stopCh <-chan struct{}) {
klog.V(3).Infof("Starting reflector %s (%s) from %s", r.typeDescription, r.resyncPeriod, r.name)
wait.BackoffUntil(func() {
if err := r.ListAndWatch(stopCh); err != nil {
r.watchErrorHandler(r, err)
}
}, r.backoffManager, true, stopCh)
klog.V(3).Infof("Stopping reflector %s (%s) from %s", r.typeDescription, r.resyncPeriod, r.name)
} | Run repeatedly uses the reflector's ListAndWatch to fetch all the
objects and subsequent deltas.
Run will exit when stopCh is closed. | Run | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) {
if r.resyncPeriod == 0 {
return neverExitWatch, func() bool { return false }
}
// The cleanup function is required: imagine the scenario where watches
// always fail so we end up listing frequently. Then, if we don't
// manually stop the timer, we could end up with many timers active
// concurrently.
t := r.clock.NewTimer(r.resyncPeriod)
return t.C(), t.Stop
} | resyncChan returns a channel which will receive something when a resync is
required, and a cleanup function. | resyncChan | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error {
klog.V(3).Infof("Listing and watching %v from %s", r.typeDescription, r.name)
var err error
var w watch.Interface
fallbackToList := !r.UseWatchList
if r.UseWatchList {
w, err = r.watchList(stopCh)
if w == nil && err == nil {
// stopCh was closed
return nil
}
if err != nil {
klog.Warningf("The watchlist request ended with an error, falling back to the standard LIST/WATCH semantics because making progress is better than deadlocking, err = %v", err)
fallbackToList = true
// ensure that we won't accidentally pass some garbage down the watch.
w = nil
}
}
if fallbackToList {
err = r.list(stopCh)
if err != nil {
return err
}
}
klog.V(2).Infof("Caches populated for %v from %s", r.typeDescription, r.name)
resyncerrc := make(chan error, 1)
cancelCh := make(chan struct{})
defer close(cancelCh)
go r.startResync(stopCh, cancelCh, resyncerrc)
return r.watch(w, stopCh, resyncerrc)
} | ListAndWatch first lists all items and get the resource version at the moment of call,
and then use the resource version to watch.
It returns error if ListAndWatch didn't even try to initialize watch. | ListAndWatch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) startResync(stopCh <-chan struct{}, cancelCh <-chan struct{}, resyncerrc chan error) {
resyncCh, cleanup := r.resyncChan()
defer func() {
cleanup() // Call the last one written into cleanup
}()
for {
select {
case <-resyncCh:
case <-stopCh:
return
case <-cancelCh:
return
}
if r.ShouldResync == nil || r.ShouldResync() {
klog.V(4).Infof("%s: forcing resync", r.name)
if err := r.store.Resync(); err != nil {
resyncerrc <- err
return
}
}
cleanup()
resyncCh, cleanup = r.resyncChan()
}
} | startResync periodically calls r.store.Resync() method.
Note that this method is blocking and should be
called in a separate goroutine. | startResync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) watch(w watch.Interface, stopCh <-chan struct{}, resyncerrc chan error) error {
var err error
retry := NewRetryWithDeadline(r.MaxInternalErrorRetryDuration, time.Minute, apierrors.IsInternalError, r.clock)
for {
// give the stopCh a chance to stop the loop, even in case of continue statements further down on errors
select {
case <-stopCh:
// we can only end up here when the stopCh
// was closed after a successful watchlist or list request
if w != nil {
w.Stop()
}
return nil
default:
}
// start the clock before sending the request, since some proxies won't flush headers until after the first watch event is sent
start := r.clock.Now()
if w == nil {
timeoutSeconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0))
options := metav1.ListOptions{
ResourceVersion: r.LastSyncResourceVersion(),
// We want to avoid situations of hanging watchers. Stop any watchers that do not
// receive any events within the timeout window.
TimeoutSeconds: &timeoutSeconds,
// To reduce load on kube-apiserver on watch restarts, you may enable watch bookmarks.
// Reflector doesn't assume bookmarks are returned at all (if the server do not support
// watch bookmarks, it will ignore this field).
AllowWatchBookmarks: true,
}
w, err = r.listerWatcher.Watch(options)
if err != nil {
if canRetry := isWatchErrorRetriable(err); canRetry {
klog.V(4).Infof("%s: watch of %v returned %v - backing off", r.name, r.typeDescription, err)
select {
case <-stopCh:
return nil
case <-r.backoffManager.Backoff().C():
continue
}
}
return err
}
}
err = watchHandler(start, w, r.store, r.expectedType, r.expectedGVK, r.name, r.typeDescription, r.setLastSyncResourceVersion, nil, r.clock, resyncerrc, stopCh)
// Ensure that watch will not be reused across iterations.
w.Stop()
w = nil
retry.After(err)
if err != nil {
if err != errorStopRequested {
switch {
case isExpiredError(err):
// Don't set LastSyncResourceVersionUnavailable - LIST call with ResourceVersion=RV already
// has a semantic that it returns data at least as fresh as provided RV.
// So first try to LIST with setting RV to resource version of last observed object.
klog.V(4).Infof("%s: watch of %v closed with: %v", r.name, r.typeDescription, err)
case apierrors.IsTooManyRequests(err):
klog.V(2).Infof("%s: watch of %v returned 429 - backing off", r.name, r.typeDescription)
select {
case <-stopCh:
return nil
case <-r.backoffManager.Backoff().C():
continue
}
case apierrors.IsInternalError(err) && retry.ShouldRetry():
klog.V(2).Infof("%s: retrying watch of %v internal error: %v", r.name, r.typeDescription, err)
continue
default:
klog.Warningf("%s: watch of %v ended with: %v", r.name, r.typeDescription, err)
}
}
return nil
}
}
} | watch simply starts a watch request with the server. | watch | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) list(stopCh <-chan struct{}) error {
var resourceVersion string
options := metav1.ListOptions{ResourceVersion: r.relistResourceVersion()}
initTrace := trace.New("Reflector ListAndWatch", trace.Field{Key: "name", Value: r.name})
defer initTrace.LogIfLong(10 * time.Second)
var list runtime.Object
var paginatedResult bool
var err error
listCh := make(chan struct{}, 1)
panicCh := make(chan interface{}, 1)
go func() {
defer func() {
if r := recover(); r != nil {
panicCh <- r
}
}()
// Attempt to gather list in chunks, if supported by listerWatcher, if not, the first
// list request will return the full response.
pager := pager.New(pager.SimplePageFunc(func(opts metav1.ListOptions) (runtime.Object, error) {
return r.listerWatcher.List(opts)
}))
switch {
case r.WatchListPageSize != 0:
pager.PageSize = r.WatchListPageSize
case r.paginatedResult:
// We got a paginated result initially. Assume this resource and server honor
// paging requests (i.e. watch cache is probably disabled) and leave the default
// pager size set.
case options.ResourceVersion != "" && options.ResourceVersion != "0":
// User didn't explicitly request pagination.
//
// With ResourceVersion != "", we have a possibility to list from watch cache,
// but we do that (for ResourceVersion != "0") only if Limit is unset.
// To avoid thundering herd on etcd (e.g. on master upgrades), we explicitly
// switch off pagination to force listing from watch cache (if enabled).
// With the existing semantic of RV (result is at least as fresh as provided RV),
// this is correct and doesn't lead to going back in time.
//
// We also don't turn off pagination for ResourceVersion="0", since watch cache
// is ignoring Limit in that case anyway, and if watch cache is not enabled
// we don't introduce regression.
pager.PageSize = 0
}
list, paginatedResult, err = pager.ListWithAlloc(context.Background(), options)
if isExpiredError(err) || isTooLargeResourceVersionError(err) {
r.setIsLastSyncResourceVersionUnavailable(true)
// Retry immediately if the resource version used to list is unavailable.
// The pager already falls back to full list if paginated list calls fail due to an "Expired" error on
// continuation pages, but the pager might not be enabled, the full list might fail because the
// resource version it is listing at is expired or the cache may not yet be synced to the provided
// resource version. So we need to fallback to resourceVersion="" in all to recover and ensure
// the reflector makes forward progress.
list, paginatedResult, err = pager.ListWithAlloc(context.Background(), metav1.ListOptions{ResourceVersion: r.relistResourceVersion()})
}
close(listCh)
}()
select {
case <-stopCh:
return nil
case r := <-panicCh:
panic(r)
case <-listCh:
}
initTrace.Step("Objects listed", trace.Field{Key: "error", Value: err})
if err != nil {
klog.Warningf("%s: failed to list %v: %v", r.name, r.typeDescription, err)
return fmt.Errorf("failed to list %v: %w", r.typeDescription, err)
}
// We check if the list was paginated and if so set the paginatedResult based on that.
// However, we want to do that only for the initial list (which is the only case
// when we set ResourceVersion="0"). The reasoning behind it is that later, in some
// situations we may force listing directly from etcd (by setting ResourceVersion="")
// which will return paginated result, even if watch cache is enabled. However, in
// that case, we still want to prefer sending requests to watch cache if possible.
//
// Paginated result returned for request with ResourceVersion="0" mean that watch
// cache is disabled and there are a lot of objects of a given type. In such case,
// there is no need to prefer listing from watch cache.
if options.ResourceVersion == "0" && paginatedResult {
r.paginatedResult = true
}
r.setIsLastSyncResourceVersionUnavailable(false) // list was successful
listMetaInterface, err := meta.ListAccessor(list)
if err != nil {
return fmt.Errorf("unable to understand list result %#v: %v", list, err)
}
resourceVersion = listMetaInterface.GetResourceVersion()
initTrace.Step("Resource version extracted")
items, err := meta.ExtractListWithAlloc(list)
if err != nil {
return fmt.Errorf("unable to understand list result %#v (%v)", list, err)
}
initTrace.Step("Objects extracted")
if err := r.syncWith(items, resourceVersion); err != nil {
return fmt.Errorf("unable to sync list result: %v", err)
}
initTrace.Step("SyncWith done")
r.setLastSyncResourceVersion(resourceVersion)
initTrace.Step("Resource version updated")
return nil
} | list simply lists all items and records a resource version obtained from the server at the moment of the call.
the resource version can be used for further progress notification (aka. watch). | list | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) watchList(stopCh <-chan struct{}) (watch.Interface, error) {
var w watch.Interface
var err error
var temporaryStore Store
var resourceVersion string
// TODO(#115478): see if this function could be turned
// into a method and see if error handling
// could be unified with the r.watch method
isErrorRetriableWithSideEffectsFn := func(err error) bool {
if canRetry := isWatchErrorRetriable(err); canRetry {
klog.V(2).Infof("%s: watch-list of %v returned %v - backing off", r.name, r.typeDescription, err)
<-r.backoffManager.Backoff().C()
return true
}
if isExpiredError(err) || isTooLargeResourceVersionError(err) {
// we tried to re-establish a watch request but the provided RV
// has either expired or it is greater than the server knows about.
// In that case we reset the RV and
// try to get a consistent snapshot from the watch cache (case 1)
r.setIsLastSyncResourceVersionUnavailable(true)
return true
}
return false
}
initTrace := trace.New("Reflector WatchList", trace.Field{Key: "name", Value: r.name})
defer initTrace.LogIfLong(10 * time.Second)
for {
select {
case <-stopCh:
return nil, nil
default:
}
resourceVersion = ""
lastKnownRV := r.rewatchResourceVersion()
temporaryStore = NewStore(DeletionHandlingMetaNamespaceKeyFunc)
// TODO(#115478): large "list", slow clients, slow network, p&f
// might slow down streaming and eventually fail.
// maybe in such a case we should retry with an increased timeout?
timeoutSeconds := int64(minWatchTimeout.Seconds() * (rand.Float64() + 1.0))
options := metav1.ListOptions{
ResourceVersion: lastKnownRV,
AllowWatchBookmarks: true,
SendInitialEvents: pointer.Bool(true),
ResourceVersionMatch: metav1.ResourceVersionMatchNotOlderThan,
TimeoutSeconds: &timeoutSeconds,
}
start := r.clock.Now()
w, err = r.listerWatcher.Watch(options)
if err != nil {
if isErrorRetriableWithSideEffectsFn(err) {
continue
}
return nil, err
}
bookmarkReceived := pointer.Bool(false)
err = watchHandler(start, w, temporaryStore, r.expectedType, r.expectedGVK, r.name, r.typeDescription,
func(rv string) { resourceVersion = rv },
bookmarkReceived,
r.clock, make(chan error), stopCh)
if err != nil {
w.Stop() // stop and retry with clean state
if err == errorStopRequested {
return nil, nil
}
if isErrorRetriableWithSideEffectsFn(err) {
continue
}
return nil, err
}
if *bookmarkReceived {
break
}
}
// We successfully got initial state from watch-list confirmed by the
// "k8s.io/initial-events-end" bookmark.
initTrace.Step("Objects streamed", trace.Field{Key: "count", Value: len(temporaryStore.List())})
r.setIsLastSyncResourceVersionUnavailable(false)
// we utilize the temporaryStore to ensure independence from the current store implementation.
// as of today, the store is implemented as a queue and will be drained by the higher-level
// component as soon as it finishes replacing the content.
checkWatchListConsistencyIfRequested(stopCh, r.name, resourceVersion, r.listerWatcher, temporaryStore)
if err = r.store.Replace(temporaryStore.List(), resourceVersion); err != nil {
return nil, fmt.Errorf("unable to sync watch-list result: %v", err)
}
initTrace.Step("SyncWith done")
r.setLastSyncResourceVersion(resourceVersion)
return w, nil
} | watchList establishes a stream to get a consistent snapshot of data
from the server as described in https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#proposal
case 1: start at Most Recent (RV="", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)
Establishes a consistent stream with the server.
That means the returned data is consistent, as if, served directly from etcd via a quorum read.
It begins with synthetic "Added" events of all resources up to the most recent ResourceVersion.
It ends with a synthetic "Bookmark" event containing the most recent ResourceVersion.
After receiving a "Bookmark" event the reflector is considered to be synchronized.
It replaces its internal store with the collected items and
reuses the current watch requests for getting further events.
case 2: start at Exact (RV>"0", ResourceVersionMatch=ResourceVersionMatchNotOlderThan)
Establishes a stream with the server at the provided resource version.
To establish the initial state the server begins with synthetic "Added" events.
It ends with a synthetic "Bookmark" event containing the provided or newer resource version.
After receiving a "Bookmark" event the reflector is considered to be synchronized.
It replaces its internal store with the collected items and
reuses the current watch requests for getting further events. | watchList | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) syncWith(items []runtime.Object, resourceVersion string) error {
found := make([]interface{}, 0, len(items))
for _, item := range items {
found = append(found, item)
}
return r.store.Replace(found, resourceVersion)
} | syncWith replaces the store's items with the given list. | syncWith | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func watchHandler(start time.Time,
w watch.Interface,
store Store,
expectedType reflect.Type,
expectedGVK *schema.GroupVersionKind,
name string,
expectedTypeName string,
setLastSyncResourceVersion func(string),
exitOnInitialEventsEndBookmark *bool,
clock clock.Clock,
errc chan error,
stopCh <-chan struct{},
) error {
eventCount := 0
if exitOnInitialEventsEndBookmark != nil {
// set it to false just in case somebody
// made it positive
*exitOnInitialEventsEndBookmark = false
}
loop:
for {
select {
case <-stopCh:
return errorStopRequested
case err := <-errc:
return err
case event, ok := <-w.ResultChan():
if !ok {
break loop
}
if event.Type == watch.Error {
return apierrors.FromObject(event.Object)
}
if expectedType != nil {
if e, a := expectedType, reflect.TypeOf(event.Object); e != a {
utilruntime.HandleError(fmt.Errorf("%s: expected type %v, but watch event object had type %v", name, e, a))
continue
}
}
if expectedGVK != nil {
if e, a := *expectedGVK, event.Object.GetObjectKind().GroupVersionKind(); e != a {
utilruntime.HandleError(fmt.Errorf("%s: expected gvk %v, but watch event object had gvk %v", name, e, a))
continue
}
}
meta, err := meta.Accessor(event.Object)
if err != nil {
utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", name, event))
continue
}
resourceVersion := meta.GetResourceVersion()
switch event.Type {
case watch.Added:
err := store.Add(event.Object)
if err != nil {
utilruntime.HandleError(fmt.Errorf("%s: unable to add watch event object (%#v) to store: %v", name, event.Object, err))
}
case watch.Modified:
err := store.Update(event.Object)
if err != nil {
utilruntime.HandleError(fmt.Errorf("%s: unable to update watch event object (%#v) to store: %v", name, event.Object, err))
}
case watch.Deleted:
// TODO: Will any consumers need access to the "last known
// state", which is passed in event.Object? If so, may need
// to change this.
err := store.Delete(event.Object)
if err != nil {
utilruntime.HandleError(fmt.Errorf("%s: unable to delete watch event object (%#v) from store: %v", name, event.Object, err))
}
case watch.Bookmark:
// A `Bookmark` means watch has synced here, just update the resourceVersion
if meta.GetAnnotations()["k8s.io/initial-events-end"] == "true" {
if exitOnInitialEventsEndBookmark != nil {
*exitOnInitialEventsEndBookmark = true
}
}
default:
utilruntime.HandleError(fmt.Errorf("%s: unable to understand watch event %#v", name, event))
}
setLastSyncResourceVersion(resourceVersion)
if rvu, ok := store.(ResourceVersionUpdater); ok {
rvu.UpdateResourceVersion(resourceVersion)
}
eventCount++
if exitOnInitialEventsEndBookmark != nil && *exitOnInitialEventsEndBookmark {
watchDuration := clock.Since(start)
klog.V(4).Infof("exiting %v Watch because received the bookmark that marks the end of initial events stream, total %v items received in %v", name, eventCount, watchDuration)
return nil
}
}
}
watchDuration := clock.Since(start)
if watchDuration < 1*time.Second && eventCount == 0 {
return fmt.Errorf("very short watch: %s: Unexpected watch close - watch lasted less than a second and no items received", name)
}
klog.V(4).Infof("%s: Watch close - %v total %v items received", name, expectedTypeName, eventCount)
return nil
} | watchHandler watches w and sets setLastSyncResourceVersion | watchHandler | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) LastSyncResourceVersion() string {
r.lastSyncResourceVersionMutex.RLock()
defer r.lastSyncResourceVersionMutex.RUnlock()
return r.lastSyncResourceVersion
} | LastSyncResourceVersion is the resource version observed when last sync with the underlying store
The value returned is not synchronized with access to the underlying store and is not thread-safe | LastSyncResourceVersion | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) relistResourceVersion() string {
r.lastSyncResourceVersionMutex.RLock()
defer r.lastSyncResourceVersionMutex.RUnlock()
if r.isLastSyncResourceVersionUnavailable {
// Since this reflector makes paginated list requests, and all paginated list requests skip the watch cache
// if the lastSyncResourceVersion is unavailable, we set ResourceVersion="" and list again to re-establish reflector
// to the latest available ResourceVersion, using a consistent read from etcd.
return ""
}
if r.lastSyncResourceVersion == "" {
// For performance reasons, initial list performed by reflector uses "0" as resource version to allow it to
// be served from the watch cache if it is enabled.
return "0"
}
return r.lastSyncResourceVersion
} | relistResourceVersion determines the resource version the reflector should list or relist from.
Returns either the lastSyncResourceVersion so that this reflector will relist with a resource
versions no older than has already been observed in relist results or watch events, or, if the last relist resulted
in an HTTP 410 (Gone) status code, returns "" so that the relist will use the latest resource version available in
etcd via a quorum read. | relistResourceVersion | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) rewatchResourceVersion() string {
r.lastSyncResourceVersionMutex.RLock()
defer r.lastSyncResourceVersionMutex.RUnlock()
if r.isLastSyncResourceVersionUnavailable {
// initial stream should return data at the most recent resource version.
// the returned data must be consistent i.e. as if served from etcd via a quorum read
return ""
}
return r.lastSyncResourceVersion
} | rewatchResourceVersion determines the resource version the reflector should start streaming from. | rewatchResourceVersion | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func (r *Reflector) setIsLastSyncResourceVersionUnavailable(isUnavailable bool) {
r.lastSyncResourceVersionMutex.Lock()
defer r.lastSyncResourceVersionMutex.Unlock()
r.isLastSyncResourceVersionUnavailable = isUnavailable
} | setIsLastSyncResourceVersionUnavailable sets if the last list or watch request with lastSyncResourceVersion returned
"expired" or "too large resource version" error. | setIsLastSyncResourceVersionUnavailable | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func isWatchErrorRetriable(err error) bool {
// If this is "connection refused" error, it means that most likely apiserver is not responsive.
// It doesn't make sense to re-list all objects because most likely we will be able to restart
// watch where we ended.
// If that's the case begin exponentially backing off and resend watch request.
// Do the same for "429" errors.
if utilnet.IsConnectionRefused(err) || apierrors.IsTooManyRequests(err) {
return true
}
return false
} | isWatchErrorRetriable determines if it is safe to retry
a watch error retrieved from the server. | isWatchErrorRetriable | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector.go | Apache-2.0 |
func NewDeltaFIFO(keyFunc KeyFunc, knownObjects KeyListerGetter) *DeltaFIFO {
return NewDeltaFIFOWithOptions(DeltaFIFOOptions{
KeyFunction: keyFunc,
KnownObjects: knownObjects,
})
} | NewDeltaFIFO returns a Queue which can be used to process changes to items.
keyFunc is used to figure out what key an object should have. (It is
exposed in the returned DeltaFIFO's KeyOf() method, with additional handling
around deleted objects and queue state).
'knownObjects' may be supplied to modify the behavior of Delete,
Replace, and Resync. It may be nil if you do not need those
modifications.
TODO: consider merging keyLister with this object, tracking a list of
"known" keys when Pop() is called. Have to think about how that
affects error retrying.
NOTE: It is possible to misuse this and cause a race when using an
external known object source.
Whether there is a potential race depends on how the consumer
modifies knownObjects. In Pop(), process function is called under
lock, so it is safe to update data structures in it that need to be
in sync with the queue (e.g. knownObjects).
Example:
In case of sharedIndexInformer being a consumer
(https://github.com/kubernetes/kubernetes/blob/0cdd940f/staging/src/k8s.io/client-go/tools/cache/shared_informer.go#L192),
there is no race as knownObjects (s.indexer) is modified safely
under DeltaFIFO's lock. The only exceptions are GetStore() and
GetIndexer() methods, which expose ways to modify the underlying
storage. Currently these two methods are used for creating Lister
and internal tests.
Also see the comment on DeltaFIFO.
Warning: This constructs a DeltaFIFO that does not differentiate between
events caused by a call to Replace (e.g., from a relist, which may
contain object updates), and synthetic events caused by a periodic resync
(which just emit the existing object). See https://issue.k8s.io/86015 for details.
Use `NewDeltaFIFOWithOptions(DeltaFIFOOptions{..., EmitDeltaTypeReplaced: true})`
instead to receive a `Replaced` event depending on the type.
Deprecated: Equivalent to NewDeltaFIFOWithOptions(DeltaFIFOOptions{KeyFunction: keyFunc, KnownObjects: knownObjects}) | NewDeltaFIFO | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func NewDeltaFIFOWithOptions(opts DeltaFIFOOptions) *DeltaFIFO {
if opts.KeyFunction == nil {
opts.KeyFunction = MetaNamespaceKeyFunc
}
f := &DeltaFIFO{
items: map[string]Deltas{},
queue: []string{},
keyFunc: opts.KeyFunction,
knownObjects: opts.KnownObjects,
emitDeltaTypeReplaced: opts.EmitDeltaTypeReplaced,
transformer: opts.Transformer,
}
f.cond.L = &f.lock
return f
} | NewDeltaFIFOWithOptions returns a Queue which can be used to process changes to
items. See also the comment on DeltaFIFO. | NewDeltaFIFOWithOptions | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) KeyOf(obj interface{}) (string, error) {
if d, ok := obj.(Deltas); ok {
if len(d) == 0 {
return "", KeyError{obj, ErrZeroLengthDeltasObject}
}
obj = d.Newest().Object
}
if d, ok := obj.(DeletedFinalStateUnknown); ok {
return d.Key, nil
}
return f.keyFunc(obj)
} | KeyOf exposes f's keyFunc, but also detects the key of a Deltas object or
DeletedFinalStateUnknown objects. | KeyOf | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) HasSynced() bool {
f.lock.Lock()
defer f.lock.Unlock()
return f.hasSynced_locked()
} | HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,
or the first batch of items inserted by Replace() has been popped. | HasSynced | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Add(obj interface{}) error {
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
return f.queueActionLocked(Added, obj)
} | Add inserts an item, and puts it in the queue. The item is only enqueued
if it doesn't already exist in the set. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Update(obj interface{}) error {
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
return f.queueActionLocked(Updated, obj)
} | Update is just like Add, but makes an Updated Delta. | Update | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Delete(obj interface{}) error {
id, err := f.KeyOf(obj)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
if f.knownObjects == nil {
if _, exists := f.items[id]; !exists {
// Presumably, this was deleted when a relist happened.
// Don't provide a second report of the same deletion.
return nil
}
} else {
// We only want to skip the "deletion" action if the object doesn't
// exist in knownObjects and it doesn't have corresponding item in items.
// Note that even if there is a "deletion" action in items, we can ignore it,
// because it will be deduped automatically in "queueActionLocked"
_, exists, err := f.knownObjects.GetByKey(id)
_, itemsExist := f.items[id]
if err == nil && !exists && !itemsExist {
// Presumably, this was deleted when a relist happened.
// Don't provide a second report of the same deletion.
return nil
}
}
// exist in items and/or KnownObjects
return f.queueActionLocked(Deleted, obj)
} | Delete is just like Add, but makes a Deleted Delta. If the given
object does not already exist, it will be ignored. (It may have
already been deleted by a Replace (re-list), for example.) In this
method `f.knownObjects`, if not nil, provides (via GetByKey)
_additional_ objects that are considered to already exist. | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) AddIfNotPresent(obj interface{}) error {
deltas, ok := obj.(Deltas)
if !ok {
return fmt.Errorf("object must be of type deltas, but got: %#v", obj)
}
id, err := f.KeyOf(deltas)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.addIfNotPresent(id, deltas)
return nil
} | AddIfNotPresent inserts an item, and puts it in the queue. If the item is already
present in the set, it is neither enqueued nor added to the set.
This is useful in a single producer/consumer scenario so that the consumer can
safely retry items without contending with the producer and potentially enqueueing
stale items.
Important: obj must be a Deltas (the output of the Pop() function). Yes, this is
different from the Add/Update/Delete functions. | AddIfNotPresent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) addIfNotPresent(id string, deltas Deltas) {
f.populated = true
if _, exists := f.items[id]; exists {
return
}
f.queue = append(f.queue, id)
f.items[id] = deltas
f.cond.Broadcast()
} | addIfNotPresent inserts deltas under id if it does not exist, and assumes the caller
already holds the fifo lock. | addIfNotPresent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func dedupDeltas(deltas Deltas) Deltas {
n := len(deltas)
if n < 2 {
return deltas
}
a := &deltas[n-1]
b := &deltas[n-2]
if out := isDup(a, b); out != nil {
deltas[n-2] = *out
return deltas[:n-1]
}
return deltas
} | re-listing and watching can deliver the same update multiple times in any
order. This will combine the most recent two deltas if they are the same. | dedupDeltas | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func isDup(a, b *Delta) *Delta {
if out := isDeletionDup(a, b); out != nil {
return out
}
// TODO: Detect other duplicate situations? Are there any?
return nil
} | If a & b represent the same event, returns the delta that ought to be kept.
Otherwise, returns nil.
TODO: is there anything other than deletions that need deduping? | isDup | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func isDeletionDup(a, b *Delta) *Delta {
if b.Type != Deleted || a.Type != Deleted {
return nil
}
// Do more sophisticated checks, or is this sufficient?
if _, ok := b.Object.(DeletedFinalStateUnknown); ok {
return a
}
return b
} | keep the one with the most information if both are deletions. | isDeletionDup | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) queueActionLocked(actionType DeltaType, obj interface{}) error {
id, err := f.KeyOf(obj)
if err != nil {
return KeyError{obj, err}
}
// Every object comes through this code path once, so this is a good
// place to call the transform func. If obj is a
// DeletedFinalStateUnknown tombstone, then the containted inner object
// will already have gone through the transformer, but we document that
// this can happen. In cases involving Replace(), such an object can
// come through multiple times.
if f.transformer != nil {
var err error
obj, err = f.transformer(obj)
if err != nil {
return err
}
}
oldDeltas := f.items[id]
newDeltas := append(oldDeltas, Delta{actionType, obj})
newDeltas = dedupDeltas(newDeltas)
if len(newDeltas) > 0 {
if _, exists := f.items[id]; !exists {
f.queue = append(f.queue, id)
}
f.items[id] = newDeltas
f.cond.Broadcast()
} else {
// This never happens, because dedupDeltas never returns an empty list
// when given a non-empty list (as it is here).
// If somehow it happens anyway, deal with it but complain.
if oldDeltas == nil {
klog.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; ignoring", id, oldDeltas, obj)
return nil
}
klog.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; breaking invariant by storing empty Deltas", id, oldDeltas, obj)
f.items[id] = newDeltas
return fmt.Errorf("Impossible dedupDeltas for id=%q: oldDeltas=%#+v, obj=%#+v; broke DeltaFIFO invariant by storing empty Deltas", id, oldDeltas, obj)
}
return nil
} | queueActionLocked appends to the delta list for the object.
Caller must lock first. | queueActionLocked | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) List() []interface{} {
f.lock.RLock()
defer f.lock.RUnlock()
return f.listLocked()
} | List returns a list of all the items; it returns the object
from the most recent Delta.
You should treat the items returned inside the deltas as immutable. | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) ListKeys() []string {
f.lock.RLock()
defer f.lock.RUnlock()
list := make([]string, 0, len(f.queue))
for _, key := range f.queue {
list = append(list, key)
}
return list
} | ListKeys returns a list of all the keys of the objects currently
in the FIFO. | ListKeys | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {
key, err := f.KeyOf(obj)
if err != nil {
return nil, false, KeyError{obj, err}
}
return f.GetByKey(key)
} | Get returns the complete list of deltas for the requested item,
or sets exists=false.
You should treat the items returned inside the deltas as immutable. | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) GetByKey(key string) (item interface{}, exists bool, err error) {
f.lock.RLock()
defer f.lock.RUnlock()
d, exists := f.items[key]
if exists {
// Copy item's slice so operations on this slice
// won't interfere with the object we return.
d = copyDeltas(d)
}
return d, exists, nil
} | GetByKey returns the complete list of deltas for the requested item,
setting exists=false if that list is empty.
You should treat the items returned inside the deltas as immutable. | GetByKey | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) IsClosed() bool {
f.lock.Lock()
defer f.lock.Unlock()
return f.closed
} | IsClosed checks if the queue is closed | IsClosed | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Pop(process PopProcessFunc) (interface{}, error) {
f.lock.Lock()
defer f.lock.Unlock()
for {
for len(f.queue) == 0 {
// When the queue is empty, invocation of Pop() is blocked until new item is enqueued.
// 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().
if f.closed {
return nil, ErrFIFOClosed
}
f.cond.Wait()
}
isInInitialList := !f.hasSynced_locked()
id := f.queue[0]
f.queue = f.queue[1:]
depth := len(f.queue)
if f.initialPopulationCount > 0 {
f.initialPopulationCount--
}
item, ok := f.items[id]
if !ok {
// This should never happen
klog.Errorf("Inconceivable! %q was in f.queue but not f.items; ignoring.", id)
continue
}
delete(f.items, id)
// Only log traces if the queue depth is greater than 10 and it takes more than
// 100 milliseconds to process one item from the queue.
// Queue depth never goes high because processing an item is locking the queue,
// and new items can't be added until processing finish.
// https://github.com/kubernetes/kubernetes/issues/103789
if depth > 10 {
trace := utiltrace.New("DeltaFIFO Pop Process",
utiltrace.Field{Key: "ID", Value: id},
utiltrace.Field{Key: "Depth", Value: depth},
utiltrace.Field{Key: "Reason", Value: "slow event handlers blocking the queue"})
defer trace.LogIfLong(100 * time.Millisecond)
}
err := process(item, isInInitialList)
if e, ok := err.(ErrRequeue); ok {
f.addIfNotPresent(id, item)
err = e.Err
}
// Don't need to copyDeltas here, because we're transferring
// ownership to the caller.
return item, err
}
} | Pop blocks until the queue has some items, and then returns one. If
multiple items are ready, they are returned in the order in which they were
added/updated. The item is removed from the queue (and the store) before it
is returned, so if you don't successfully process it, you need to add it back
with AddIfNotPresent().
process function is called under lock, so it is safe to update data structures
in it that need to be in sync with the queue (e.g. knownKeys). The PopProcessFunc
may return an instance of ErrRequeue with a nested error to indicate the current
item should be requeued (equivalent to calling AddIfNotPresent under the lock).
process should avoid expensive I/O operation so that other queue operations, i.e.
Add() and Get(), won't be blocked for too long.
Pop returns a 'Deltas', which has a complete list of all the things
that happened to the object (deltas) while it was sitting in the queue. | Pop | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Replace(list []interface{}, _ string) error {
f.lock.Lock()
defer f.lock.Unlock()
keys := make(sets.String, len(list))
// keep backwards compat for old clients
action := Sync
if f.emitDeltaTypeReplaced {
action = Replaced
}
// Add Sync/Replaced action for each new item.
for _, item := range list {
key, err := f.KeyOf(item)
if err != nil {
return KeyError{item, err}
}
keys.Insert(key)
if err := f.queueActionLocked(action, item); err != nil {
return fmt.Errorf("couldn't enqueue object: %v", err)
}
}
// Do deletion detection against objects in the queue
queuedDeletions := 0
for k, oldItem := range f.items {
if keys.Has(k) {
continue
}
// Delete pre-existing items not in the new list.
// This could happen if watch deletion event was missed while
// disconnected from apiserver.
var deletedObj interface{}
if n := oldItem.Newest(); n != nil {
deletedObj = n.Object
// if the previous object is a DeletedFinalStateUnknown, we have to extract the actual Object
if d, ok := deletedObj.(DeletedFinalStateUnknown); ok {
deletedObj = d.Obj
}
}
queuedDeletions++
if err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {
return err
}
}
if f.knownObjects != nil {
// Detect deletions for objects not present in the queue, but present in KnownObjects
knownKeys := f.knownObjects.ListKeys()
for _, k := range knownKeys {
if keys.Has(k) {
continue
}
if len(f.items[k]) > 0 {
continue
}
deletedObj, exists, err := f.knownObjects.GetByKey(k)
if err != nil {
deletedObj = nil
klog.Errorf("Unexpected error %v during lookup of key %v, placing DeleteFinalStateUnknown marker without object", err, k)
} else if !exists {
deletedObj = nil
klog.Infof("Key %v does not exist in known objects store, placing DeleteFinalStateUnknown marker without object", k)
}
queuedDeletions++
if err := f.queueActionLocked(Deleted, DeletedFinalStateUnknown{k, deletedObj}); err != nil {
return err
}
}
}
if !f.populated {
f.populated = true
f.initialPopulationCount = keys.Len() + queuedDeletions
}
return nil
} | Replace atomically does two things: (1) it adds the given objects
using the Sync or Replace DeltaType and then (2) it does some deletions.
In particular: for every pre-existing key K that is not the key of
an object in `list` there is the effect of
`Delete(DeletedFinalStateUnknown{K, O})` where O is the latest known
object of K. The pre-existing keys are those in the union set of the keys in
`f.items` and `f.knownObjects` (if not nil). The last known object for key K is
the one present in the last delta in `f.items`. If there is no delta for K
in `f.items`, it is the object in `f.knownObjects` | Replace | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (f *DeltaFIFO) Resync() error {
f.lock.Lock()
defer f.lock.Unlock()
if f.knownObjects == nil {
return nil
}
keys := f.knownObjects.ListKeys()
for _, k := range keys {
if err := f.syncKeyLocked(k); err != nil {
return err
}
}
return nil
} | Resync adds, with a Sync type of Delta, every object listed by
`f.knownObjects` whose key is not already queued for processing.
If `f.knownObjects` is `nil` then Resync does nothing. | Resync | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (d Deltas) Oldest() *Delta {
if len(d) > 0 {
return &d[0]
}
return nil
} | Oldest is a convenience function that returns the oldest delta, or
nil if there are no deltas. | Oldest | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (d Deltas) Newest() *Delta {
if n := len(d); n > 0 {
return &d[n-1]
}
return nil
} | Newest is a convenience function that returns the newest delta, or
nil if there are no deltas. | Newest | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func copyDeltas(d Deltas) Deltas {
d2 := make(Deltas, len(d))
copy(d2, d)
return d2
} | copyDeltas returns a shallow copy of d; that is, it copies the slice but not
the objects in the slice. This allows Get/List to return an object that we
know won't be clobbered by a subsequent modifications. | copyDeltas | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/delta_fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/delta_fifo.go | Apache-2.0 |
func (p *FakeExpirationPolicy) IsExpired(obj *TimestampedEntry) bool {
key, _ := p.RetrieveKeyFunc(obj)
return !p.NeverExpire.Has(key)
} | IsExpired used to check if object is expired. | IsExpired | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache_fakes.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache_fakes.go | Apache-2.0 |
func NewFakeExpirationStore(keyFunc KeyFunc, deletedKeys chan<- string, expirationPolicy ExpirationPolicy, cacheClock clock.Clock) Store {
cacheStorage := NewThreadSafeStore(Indexers{}, Indices{})
return &ExpirationCache{
cacheStorage: &fakeThreadSafeMap{cacheStorage, deletedKeys},
keyFunc: keyFunc,
clock: cacheClock,
expirationPolicy: expirationPolicy,
}
} | NewFakeExpirationStore creates a new instance for the ExpirationCache. | NewFakeExpirationStore | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/expiration_cache_fakes.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/expiration_cache_fakes.go | Apache-2.0 |
func SetReflectorMetricsProvider(metricsProvider MetricsProvider) {
metricsFactory.setProviders.Do(func() {
metricsFactory.metricsProvider = metricsProvider
})
} | SetReflectorMetricsProvider sets the metrics provider | SetReflectorMetricsProvider | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/reflector_metrics.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/reflector_metrics.go | Apache-2.0 |
func Pop(queue Queue) interface{} {
var result interface{}
queue.Pop(func(obj interface{}, isInInitialList bool) error {
result = obj
return nil
})
return result
} | Pop is helper function for popping from Queue.
WARNING: Do NOT use this function in non-test code to avoid races
unless you really really really really know what you are doing.
NOTE: This function is deprecated and may be removed in the future without
additional warning. | Pop | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) HasSynced() bool {
f.lock.Lock()
defer f.lock.Unlock()
return f.hasSynced_locked()
} | HasSynced returns true if an Add/Update/Delete/AddIfNotPresent are called first,
or the first batch of items inserted by Replace() has been popped. | HasSynced | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Add(obj interface{}) error {
id, err := f.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
if _, exists := f.items[id]; !exists {
f.queue = append(f.queue, id)
}
f.items[id] = obj
f.cond.Broadcast()
return nil
} | Add inserts an item, and puts it in the queue. The item is only enqueued
if it doesn't already exist in the set. | Add | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) AddIfNotPresent(obj interface{}) error {
id, err := f.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.addIfNotPresent(id, obj)
return nil
} | AddIfNotPresent inserts an item, and puts it in the queue. If the item is already
present in the set, it is neither enqueued nor added to the set.
This is useful in a single producer/consumer scenario so that the consumer can
safely retry items without contending with the producer and potentially enqueueing
stale items. | AddIfNotPresent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) addIfNotPresent(id string, obj interface{}) {
f.populated = true
if _, exists := f.items[id]; exists {
return
}
f.queue = append(f.queue, id)
f.items[id] = obj
f.cond.Broadcast()
} | addIfNotPresent assumes the fifo lock is already held and adds the provided
item to the queue under id if it does not already exist. | addIfNotPresent | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Update(obj interface{}) error {
return f.Add(obj)
} | Update is the same as Add in this implementation. | Update | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Delete(obj interface{}) error {
id, err := f.keyFunc(obj)
if err != nil {
return KeyError{obj, err}
}
f.lock.Lock()
defer f.lock.Unlock()
f.populated = true
delete(f.items, id)
return err
} | Delete removes an item. It doesn't add it to the queue, because
this implementation assumes the consumer only cares about the objects,
not the order in which they were created/added. | Delete | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) List() []interface{} {
f.lock.RLock()
defer f.lock.RUnlock()
list := make([]interface{}, 0, len(f.items))
for _, item := range f.items {
list = append(list, item)
}
return list
} | List returns a list of all the items. | List | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) ListKeys() []string {
f.lock.RLock()
defer f.lock.RUnlock()
list := make([]string, 0, len(f.items))
for key := range f.items {
list = append(list, key)
}
return list
} | ListKeys returns a list of all the keys of the objects currently
in the FIFO. | ListKeys | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
func (f *FIFO) Get(obj interface{}) (item interface{}, exists bool, err error) {
key, err := f.keyFunc(obj)
if err != nil {
return nil, false, KeyError{obj, err}
}
return f.GetByKey(key)
} | Get returns the requested item, or sets exists=false. | Get | go | k8snetworkplumbingwg/multus-cni | vendor/k8s.io/client-go/tools/cache/fifo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/k8s.io/client-go/tools/cache/fifo.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.