|
| 1 | + |
| 2 | +# Using Generated Informers |
| 3 | + |
| 4 | +This chapter describes how to use the client-go generated Informers with controller-runtime Watches. |
| 5 | + |
| 6 | +[Link to reference documentation](https://godoc.org/sigs.k8s.io/controller-runtime/pkg/source#Informer) |
| 7 | + |
| 8 | +**Note:** The `source.Informers` and `source.Kind` sources create different caches. Using both |
| 9 | +`source.Informers` and `source.Kind` sources in the same project will result in duplicate caches. |
| 10 | +This will not impact correctness, but will double the cache memory. |
| 11 | + |
| 12 | +{% method %} |
| 13 | +## Creating client-go generated Informers and Adding them to the Manager |
| 14 | + |
| 15 | +Instantiate the generated InformerFactory and add it to the Manager so it is started automatically. |
| 16 | + |
| 17 | +**Note:** The generated Informer should be used with the generated client. |
| 18 | + |
| 19 | +{% sample lang="go" %} |
| 20 | +```go |
| 21 | +// Create the InformerFactory |
| 22 | +generatedClient := kubernetes.NewForConfigOrDie(mgr.GetConfig()) |
| 23 | +generatedInformers := kubeinformers.NewSharedInformerFactory(generatedClient, time.Minute*30) |
| 24 | + |
| 25 | +err := mgr.Add(manager.RunnableFunc(func(s <-chan struct{}) error { |
| 26 | + generatedInformers.Start(s) |
| 27 | + return nil |
| 28 | +})) |
| 29 | +if err != nil { |
| 30 | + glog.Fatalf("error Adding InformerFactory to the Manager: %v", err) |
| 31 | +} |
| 32 | +``` |
| 33 | +{% endmethod %} |
| 34 | + |
| 35 | + |
| 36 | +{% method %} |
| 37 | +## Watching Resources using the client-go generated Informer |
| 38 | + |
| 39 | +Controllers may watch Resources using client-go generated Informers though the`source.Informers` struct. |
| 40 | + |
| 41 | +This example configures a Controller to watch for Services events, and to call Reconcile with |
| 42 | +the Service key. |
| 43 | + |
| 44 | +If Service *default/foo* is created, updated or deleted, then Reconcile will be called with |
| 45 | +*namespace: default, name: foo*. |
| 46 | + |
| 47 | +The generated InformerFactory must be manually wired into the Controller creation code. |
| 48 | + |
| 49 | +{% sample lang="go" %} |
| 50 | +```go |
| 51 | +// Setup Watch using the client-go generated Informer |
| 52 | +err := ctrl.Watch( |
| 53 | + &source.Informer{InformerProvider: generatedInformers.Core().V1().Services()}, |
| 54 | + &handler.EnqueueRequestForObject{}, |
| 55 | +) |
| 56 | +if err != nil { |
| 57 | + glog.Fatalf("error Watching Services: %v", err) |
| 58 | +} |
| 59 | +``` |
| 60 | +{% endmethod %} |
| 61 | + |
| 62 | +{% method %} |
| 63 | +## Starting the Manager |
| 64 | + |
| 65 | +The InformerFactory will be started through the Manager. |
| 66 | + |
| 67 | +{% sample lang="go" %} |
| 68 | +```go |
| 69 | +mgr.Start(signals.SetupSignalHandler()) |
| 70 | +``` |
| 71 | +{% endmethod %} |
0 commit comments