Skip to content

Can't index and list by arbitrary field with Unstructured objects #1705

Closed
@mengqiy

Description

@mengqiy

I can't index and list by arbitrary field with Unstructured objects in controller-runtime v0.7.0+ (including the latest v0.10.2). It will complain with the following error:
{"reconciler group": "example.co", "reconciler kind": "Foo", "name": "hello", "namespace": "default", "error": "field label not supported: metadata.ownerReferences.example.co.foo"}

I can do that with Unstructured objects in controller-runtime v0.6.*.

Code not working
package main

import (
  "context"
  "flag"
  "fmt"
  "os"

  "k8s.io/apimachinery/pkg/runtime/schema"
  "sigs.k8s.io/controller-runtime/pkg/client"
  "sigs.k8s.io/controller-runtime/pkg/reconcile"

  _ "k8s.io/client-go/plugin/pkg/client/auth"

  "k8s.io/apimachinery/pkg/runtime"
  "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  clientgoscheme "k8s.io/client-go/kubernetes/scheme"
  ctrl "sigs.k8s.io/controller-runtime"
  "sigs.k8s.io/controller-runtime/pkg/log/zap"
)

var (
  sche   = runtime.NewScheme()
  setupLog = ctrl.Log.WithName("setup")
)

const indexName = "metadata.ownerReferences.example.co.foo"

func init() {
  utilruntime.Must(clientgoscheme.AddToScheme(sche))
}

func main() {
  var metricsAddr string
  var enableLeaderElection bool
  var probeAddr string
  flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
  flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
  flag.BoolVar(&enableLeaderElection, "leader-elect", false,
    "Enable leader election for controller manager. "+
      "Enabling this will ensure there is only one active controller manager.")
  opts := zap.Options{
    Development: true,
  }
  opts.BindFlags(flag.CommandLine)
  flag.Parse()

  ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

  mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
    Scheme:                 sche,
    MetricsBindAddress:     metricsAddr,
    Port:                   9443,
    HealthProbeBindAddress: probeAddr,
    LeaderElection:         enableLeaderElection,
    LeaderElectionID:       "dd1da13f.example.co",
  })
  if err != nil {
    setupLog.Error(err, "unable to start manager")
    os.Exit(1)
  }

  uo := &unstructured.Unstructured{}
  uo.SetAPIVersion("example.co/v1")
  uo.SetKind("Foo")

  upo := &unstructured.Unstructured{}
  upo.SetGroupVersionKind(schema.GroupVersionKind{
    Group:   "",
    Version: "v1",
    Kind:    "Pod",
  })

  cl := mgr.GetClient()
  indexer := mgr.GetFieldIndexer()

  ///////////////////////////////////////////////////////////////////////////////
  // Note: We call the IndexField function by passing in a Unstructured object
  ///////////////////////////////////////////////////////////////////////////////
  err = indexer.IndexField(context.Background(), upo, indexName, func(object client.Object) []string { // <==== upo is a Unstructured object.
    ownerRef := metav1.GetControllerOf(object)
    if ownerRef == nil {
      return nil
    }
    if ownerRef.APIVersion != "example.co/v1" || ownerRef.Kind != "Foo" {
      return nil
    }
    return []string{ownerRef.Name}
  })

  err = ctrl.NewControllerManagedBy(mgr).
    For(uo).
    Owns(upo).
    Complete(reconcile.Func(func(ctx context.Context, req reconcile.Request) (reconcile.Result, error){
      listOps := []client.ListOption{
        client.MatchingFields{indexName: req.Name},
        client.InNamespace(req.Namespace),
      }
    uout := &unstructured.UnstructuredList{}
    uout.SetGroupVersionKind(schema.GroupVersionKind{
      Group:   "",
      Version: "v1",
      Kind:    "PodList",
    })
  ///////////////////////////////////////////////////////////////////////////////
  // Note: We call cl.List with an UnstructuredList object
  ///////////////////////////////////////////////////////////////////////////////
      if err = cl.List(ctx, uout, listOps...); err != nil {
        return reconcile.Result{}, err
      }

      return reconcile.Result{}, nil
  }))
  if err != nil {
    setupLog.Error(err, "unable to create controller")
    os.Exit(1)
  }

  setupLog.Info("starting manager")
  if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
    setupLog.Error(err, "problem running manager")
    os.Exit(1)
  }
}

I have also verified that v0.10.2 works with typed objects and PartialObjectMetadata objects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/bugCategorizes issue or PR as related to a bug.kind/regressionCategorizes issue or PR as related to a regression from a prior release.lifecycle/rottenDenotes an issue or PR that has aged beyond stale and will be auto-closed.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions