Skip to content

Commit 15460ae

Browse files
committed
Add an example of an unmanaged controller
Signed-off-by: Nic Cope <[email protected]>
1 parent 9ce25c3 commit 15460ae

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

pkg/controller/example_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,48 @@ func ExampleController_unstructured() {
119119
os.Exit(1)
120120
}
121121
}
122+
123+
// This example creates a new controller named "pod-controller" to watch Pods
124+
// and call a no-op reconciler. The controller is not added to the provided
125+
// manager, and must thus be started and stopped by the caller.
126+
func ExampleNewUnmanaged() {
127+
// mgr is a manager.Manager
128+
129+
// Configure creates a new controller but does not add it to the supplied
130+
// manager.
131+
c, err := controller.NewUnmanaged("pod-controller", mgr, controller.Options{
132+
Reconciler: reconcile.Func(func(_ reconcile.Request) (reconcile.Result, error) {
133+
return reconcile.Result{}, nil
134+
}),
135+
})
136+
if err != nil {
137+
log.Error(err, "unable to create pod-controller")
138+
os.Exit(1)
139+
}
140+
141+
if err := c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForObject{}); err != nil {
142+
log.Error(err, "unable to watch pods")
143+
os.Exit(1)
144+
}
145+
146+
// Create a stop channel for our controller. The controller will stop when
147+
// this channel is closed.
148+
stop := make(chan struct{})
149+
150+
// Start our controller in a goroutine so that we do not block.
151+
go func() {
152+
// Block until our controller manager is elected leader. We presume our
153+
// entire process will terminate if we lose leadership, so we don't need
154+
// to handle that.
155+
<-mgr.Leading()
156+
157+
// Start our controller. This will block until the stop channel is
158+
// closed, or the controller returns an error.
159+
if err := c.Start(stop); err != nil {
160+
log.Error(err, "cannot run experiment controller")
161+
}
162+
}()
163+
164+
// Stop our controller.
165+
close(stop)
166+
}

0 commit comments

Comments
 (0)