Using Generated Informers

This chapter describes how to use the client-go generated Informers with controller-runtime Watches.

Link to reference documentation

Note: The source.Informers and source.Kind sources create different caches. Using bothsource.Informers and source.Kind sources in the same project will result in duplicate caches.This will not impact correctness, but will double the cache memory.

Creating client-go generated Informers and Adding them to the Manager

Instantiate the generated InformerFactory and add it to the Manager so it is started automatically.

Note: The generated Informer should be used with the generated client.

  1. // Create the InformerFactory
  2. generatedClient := kubernetes.NewForConfigOrDie(mgr.GetConfig())
  3. generatedInformers := kubeinformers.NewSharedInformerFactory(generatedClient, time.Minute*30)
  4. err := mgr.Add(manager.RunnableFunc(func(s <-chan struct{}) error {
  5. generatedInformers.Start(s)
  6. <- s
  7. return nil
  8. }))
  9. if err != nil {
  10. glog.Fatalf("error Adding InformerFactory to the Manager: %v", err)
  11. }

Watching Resources using the client-go generated Informer

Controllers may watch Resources using client-go generated Informers though thesource.Informers struct.

This example configures a Controller to watch for Services events, and to call Reconcile withthe Service key.

If Service default/foo is created, updated or deleted, then Reconcile will be called withnamespace: default, name: foo.

The generated InformerFactory must be manually wired into the Controller creation code.

  1. // Setup Watch using the client-go generated Informer
  2. err := ctrl.Watch(
  3. &source.Informer{Informer: generatedInformers.Core().V1().Services()},
  4. &handler.EnqueueRequestForObject{},
  5. )
  6. if err != nil {
  7. glog.Fatalf("error Watching Services: %v", err)
  8. }

Starting the Manager

The InformerFactory will be started through the Manager.

  1. mgr.Start(signals.SetupSignalHandler())