How to provide Owner Reference to the `ListOptions` of KubeBuilder's List method?

912 Views Asked by At

I want to list the pods that are owned by the resource X from the Kubernetes cluster using Kubuilder's List(ctx context.Context, list ObjectList, opts ...ListOption) method. ListOptions contains options for limiting or filtering results. Here is the the structure of the ListOptions

type ListOptions struct {
    // LabelSelector filters results by label. Use labels.Parse() to
    // set from raw string form.
    LabelSelector labels.Selector
    // FieldSelector filters results by a particular field.  In order
    // to use this with cache-based implementations, restrict usage to
    // a single field-value pair that's been added to the indexers.
    FieldSelector fields.Selector

    // Namespace represents the namespace to list for, or empty for
    // non-namespaced objects, or to list across all namespaces.
    Namespace string

    // Limit specifies the maximum number of results to return from the server. The server may
    // not support this field on all resource types, but if it does and more results remain it
    // will set the continue field on the returned list object. This field is not supported if watch
    // is true in the Raw ListOptions.
    Limit int64
    // Continue is a token returned by the server that lets a client retrieve chunks of results
    // from the server by specifying limit. The server may reject requests for continuation tokens
    // it does not recognize and will return a 410 error if the token can no longer be used because
    // it has expired. This field is not supported if watch is true in the Raw ListOptions.
    Continue string

    // Raw represents raw ListOptions, as passed to the API server.  Note
    // that these may not be respected by all implementations of interface,
    // and the LabelSelector, FieldSelector, Limit and Continue fields are ignored.
    Raw *metav1.ListOptions
}

Now, How can I provide the owner information to this ListOptions so the List method will only list the pods that are owned by X?

Here is an example from the KubeBuilder book that shows how to filter results by a particular field,

  listOps := &client.ListOptions{
        FieldSelector: fields.OneTermEqualSelector(configMapField, configMap.GetName()),
        Namespace:     configMap.GetNamespace(),
  }
  err := r.List(context.TODO(), attachedConfigDeployments, listOps)
1

There are 1 best solutions below

1
On

Unfortunately it's not possible to use field selector for every field of a resource. In your case for example, you can only use these fields as field selector. It's also stated in this thread.

Alternatively, you can put labels to pods that is owned by a custom resource and use label selectors. Or you can get all pods and apply programmatic filter to get necessary pods. (I recommend the first approach since metadata.ownerReferences is an array and the cost is O(n^2))