// AddPodControllerUIDIndexer adds an indexer for Pod's controllerRef.UID to the given PodInformer.
// This indexer is used to efficiently look up pods by their ControllerRef.UID
func AddPodControllerUIDIndexer(podInformer cache.SharedIndexInformer) error {
if _, exists := podInformer.GetIndexer().GetIndexers()[PodControllerUIDIndex]; exists {
// indexer already exists, do nothing
return podInformer.AddIndexers(cache.Indexers{
PodControllerUIDIndex: func(obj interface{}) ([]string, error) {
pod, ok := obj.(*v1.Pod)
// Get the ControllerRef of the Pod to check if it's managed by a controller
if ref := metav1.GetControllerOf(pod); ref != nil {
return []string{string(ref.UID)}, nil
// If the Pod has no controller (i.e., it's orphaned), index it with the OrphanPodIndexKey
// This helps identify orphan pods for reconciliation and adoption by controllers
return []string{OrphanPodIndexKey}, nil
// getRSPods returns the Pods that a given RS should manage.
func (rsc *ReplicaSetController) getRSPods(rs *apps.ReplicaSet) ([]*v1.Pod, error) {
// Iterate over two keys:
// The UID of the RS, which identifies Pods that are controlled by the RS.
// The OrphanPodIndexKey, which helps identify orphaned Pods that are not currently managed by any controller,
// but may be adopted later on if they have matching labels with the ReplicaSet.
podsForRS := []*v1.Pod{}
for _, key := range []string{string(rs.UID), controller.OrphanPodIndexKey} {
podObjs, err := rsc.podIndexer.ByIndex(controller.PodControllerUIDIndex, key)
for _, obj := range podObjs {
pod, ok := obj.(*v1.Pod)
utilruntime.HandleError(fmt.Errorf("unexpected object type in pod indexer: %v", obj))
podsForRS = append(podsForRS, pod)