Skip to content

Commit 717293d

Browse files
committed
examples-builtin: Refactor controller setup to use builder pattern
Signed-off-by: suzi1037 <[email protected]>
1 parent c024d17 commit 717293d

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

examples/builtins/main.go

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,10 @@ import (
2222
appsv1 "k8s.io/api/apps/v1"
2323
corev1 "k8s.io/api/core/v1"
2424
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
25+
26+
ctrl "sigs.k8s.io/controller-runtime"
2527
"sigs.k8s.io/controller-runtime/pkg/builder"
2628
"sigs.k8s.io/controller-runtime/pkg/client/config"
27-
"sigs.k8s.io/controller-runtime/pkg/controller"
2829
"sigs.k8s.io/controller-runtime/pkg/handler"
2930
"sigs.k8s.io/controller-runtime/pkg/log"
3031
"sigs.k8s.io/controller-runtime/pkg/log/zap"
@@ -38,7 +39,7 @@ func init() {
3839
}
3940

4041
func main() {
41-
entryLog := log.Log.WithName("entrypoint")
42+
entryLog := ctrl.Log.WithName("entrypoint")
4243

4344
// Setup a Manager
4445
entryLog.Info("setting up manager")
@@ -50,24 +51,17 @@ func main() {
5051

5152
// Setup a new controller to reconcile ReplicaSets
5253
entryLog.Info("Setting up controller")
53-
c, err := controller.New("foo-controller", mgr, controller.Options{
54-
Reconciler: &reconcileReplicaSet{client: mgr.GetClient()},
55-
})
56-
if err != nil {
57-
entryLog.Error(err, "unable to set up individual controller")
58-
os.Exit(1)
59-
}
6054

61-
// Watch ReplicaSets and enqueue ReplicaSet object key
62-
if err := c.Watch(source.Kind(mgr.GetCache(), &appsv1.ReplicaSet{}, &handler.TypedEnqueueRequestForObject[*appsv1.ReplicaSet]{})); err != nil {
63-
entryLog.Error(err, "unable to watch ReplicaSets")
64-
os.Exit(1)
65-
}
66-
67-
// Watch Pods and enqueue owning ReplicaSet key
68-
if err := c.Watch(source.Kind(mgr.GetCache(), &corev1.Pod{},
69-
handler.TypedEnqueueRequestForOwner[*corev1.Pod](mgr.GetScheme(), mgr.GetRESTMapper(), &appsv1.ReplicaSet{}, handler.OnlyControllerOwner()))); err != nil {
70-
entryLog.Error(err, "unable to watch Pods")
55+
err = ctrl.
56+
NewControllerManagedBy(mgr).
57+
Named("foo-controller").
58+
WatchesRawSource(source.Kind(mgr.GetCache(), &appsv1.ReplicaSet{},
59+
&handler.TypedEnqueueRequestForObject[*appsv1.ReplicaSet]{})).
60+
WatchesRawSource(source.Kind(mgr.GetCache(), &corev1.Pod{},
61+
handler.TypedEnqueueRequestForOwner[*corev1.Pod](mgr.GetScheme(), mgr.GetRESTMapper(), &appsv1.ReplicaSet{}, handler.OnlyControllerOwner()))).
62+
Complete(&reconcileReplicaSet{client: mgr.GetClient()})
63+
if err != nil {
64+
entryLog.Error(err, "could not create controller")
7165
os.Exit(1)
7266
}
7367

0 commit comments

Comments
 (0)