What is the index struct and why is that in the k8s Indices?

Hi there, I’m trying to deepen my understanding of K8s Indexer, but I’m finding myself a bit confused about how index is stored in Indices.

Let’s say I’m creating a new pod called pod1 in the default namespace, and the key/index function is the namespace key/index function. So, we start with the function func (c *cache) Add(obj interface{}) error, and finally, we arrive at func (c *threadSafeMap) Update(key string, obj interface{}). At this point, we know that our pod pod1 will be stored in the items map[string]interface{} as items[“default/pod1”] = &v1.Pod{} ← our pod1.


// Add inserts an item into the cache.
func (c *cache) Add(obj interface{}) error {
	key, err := c.keyFunc(obj)
	if err != nil {
		return KeyError{obj, err}
	}
	c.cacheStorage.Add(key, obj)
	return nil
}

***All the way to***

func (c *threadSafeMap) Update(key string, obj interface{}) {
	c.lock.Lock()
	defer c.lock.Unlock()
	oldObject := c.items[key]
	c.items[key] = obj
	c.index.updateIndices(oldObject, obj, key)
}

After updating the items , the next step involves updating the indices. In the function c.index.updateIndices(oldObject, obj, key) , we can locate the following code block:

func (i *storeIndex) updateIndices(oldObj interface{}, newObj interface{}, key string) {
	for name := range i.indexers {
		i.updateSingleIndex(name, oldObj, newObj, key)
	}
}

Say we only have to deal with MetaNamespaceKeyFunc. And we could get all the params that are:

  • name = “namespace”
  • oldObj = nil
  • newObj = &v1.Pod{} ← our pod1
  • key = “default/pod1”

With updateSingleIndex func, we could reach to this code block:


	index := i.indices[name]
	if index == nil {
		index = Index{}
		i.indices[name] = index
	}

	for _, value := range indexValues {
		i.addKeyToIndex(key, value, index)
	}

------------
We can get indexValue = ["default"]
------------
func (i *storeIndex) addKeyToIndex(key, indexValue string, index Index) {
	set := index[indexValue]
	if set == nil {
		set = sets.String{}
		index[indexValue] = set
	}
	set.Insert(key)
}

As for now, we can get an index like this? Am I right? if so why does it store an index like this and what is the benefit?



"namespace": {
  "default": {
    "default/pod1": {}
  }
}


Please feel free to share any links or tutorials that might help me better understand indices in any form.

BR
Roger