Skip to content

Commit 77fdfc7

Browse files
committed
Add more examples in documentation
1 parent f1c940e commit 77fdfc7

File tree

4 files changed

+103
-8
lines changed

4 files changed

+103
-8
lines changed

example_test.go

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,14 @@ import (
2424

2525
appsv1 "k8s.io/api/apps/v1"
2626
corev1 "k8s.io/api/core/v1"
27+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28+
"k8s.io/apimachinery/pkg/runtime"
29+
"k8s.io/apimachinery/pkg/types"
30+
2731
ctrl "sigs.k8s.io/controller-runtime"
2832
"sigs.k8s.io/controller-runtime/pkg/client"
33+
"sigs.k8s.io/controller-runtime/pkg/handler"
34+
"sigs.k8s.io/controller-runtime/pkg/reconcile"
2935

3036
// since we invoke tests with -ginkgo.junit-report we need to import ginkgo.
3137
_ "github.com/onsi/ginkgo/v2"
@@ -38,7 +44,7 @@ import (
3844
//
3945
// * Start the application.
4046
func Example() {
41-
var log = ctrl.Log.WithName("builder-examples")
47+
log := ctrl.Log.WithName("builder-examples")
4248

4349
manager, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
4450
if err != nil {
@@ -62,6 +68,80 @@ func Example() {
6268
}
6369
}
6470

71+
type ExampleCRDWithConfigMapRef struct {
72+
metav1.TypeMeta `json:",inline"`
73+
metav1.ObjectMeta `json:"metadata,omitempty"`
74+
ConfigMapRef corev1.LocalObjectReference `json:"configMapRef"`
75+
}
76+
77+
// DeepCopyObject implements client.Object.
78+
func (*ExampleCRDWithConfigMapRef) DeepCopyObject() runtime.Object {
79+
panic("unimplemented")
80+
}
81+
82+
type ExampleCRDWithConfigMapRefList struct {
83+
metav1.TypeMeta `json:",inline"`
84+
metav1.ListMeta `json:"metadata,omitempty"`
85+
Items []ExampleCRDWithConfigMapRef `json:"items"`
86+
}
87+
88+
// DeepCopyObject implements client.ObjectList.
89+
func (*ExampleCRDWithConfigMapRefList) DeepCopyObject() runtime.Object {
90+
panic("unimplemented")
91+
}
92+
93+
// This example creates a simple application Controller that is configured for ExampleCRDWithConfigMapRef CRD.
94+
// Any change in the configMap referenced in this Custom Resource will cause the re-reconcile of the parent ExampleCRDWithConfigMapRef
95+
// due to the implementation of the .Watches method of "sigs.k8s.io/controller-runtime/pkg/builder".Builder.
96+
func Example_watches() {
97+
log := ctrl.Log.WithName("builder-examples")
98+
99+
manager, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
100+
if err != nil {
101+
log.Error(err, "could not create manager")
102+
os.Exit(1)
103+
}
104+
105+
err = ctrl.
106+
NewControllerManagedBy(manager).
107+
For(&ExampleCRDWithConfigMapRef{}).
108+
Watches(&corev1.ConfigMap{}, handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, cm client.Object) []ctrl.Request {
109+
// map a change to referenced configMap to ExampleCRDWithConfigMapRef, which causes its re-reconcile
110+
crList := &ExampleCRDWithConfigMapRefList{}
111+
if err := manager.GetClient().List(ctx, crList); err != nil {
112+
manager.GetLogger().Error(err, "while listing ExampleCRDWithConfigMapRefs")
113+
return nil
114+
}
115+
116+
reqs := make([]ctrl.Request, 0, len(crList.Items))
117+
for _, item := range crList.Items {
118+
if item.ConfigMapRef.Name == cm.GetName() {
119+
reqs = append(reqs, ctrl.Request{
120+
NamespacedName: types.NamespacedName{
121+
Namespace: item.GetNamespace(),
122+
Name: item.GetName(),
123+
},
124+
})
125+
}
126+
}
127+
128+
return reqs
129+
})).
130+
Complete(reconcile.Func(func(ctx context.Context, r reconcile.Request) (reconcile.Result, error) {
131+
// Your business logic to implement the API by creating, updating, deleting objects goes here.
132+
return reconcile.Result{}, nil
133+
}))
134+
if err != nil {
135+
log.Error(err, "could not create controller")
136+
os.Exit(1)
137+
}
138+
139+
if err := manager.Start(ctrl.SetupSignalHandler()); err != nil {
140+
log.Error(err, "could not start manager")
141+
os.Exit(1)
142+
}
143+
}
144+
65145
// This example creates a simple application Controller that is configured for ReplicaSets and Pods.
66146
// This application controller will be running leader election with the provided configuration in the manager options.
67147
// If leader election configuration is not provided, controller runs leader election with default values.
@@ -75,7 +155,7 @@ func Example() {
75155
//
76156
// * Start the application.
77157
func Example_updateLeaderElectionDurations() {
78-
var log = ctrl.Log.WithName("builder-examples")
158+
log := ctrl.Log.WithName("builder-examples")
79159
leaseDuration := 100 * time.Second
80160
renewDeadline := 80 * time.Second
81161
retryPeriod := 20 * time.Second

pkg/builder/example_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import (
3838
func ExampleBuilder_metadata_only() {
3939
logf.SetLogger(zap.New())
4040

41-
var log = logf.Log.WithName("builder-examples")
41+
log := logf.Log.WithName("builder-examples")
4242

4343
mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{})
4444
if err != nil {
@@ -95,7 +95,7 @@ func ExampleBuilder_metadata_only() {
9595
func ExampleBuilder() {
9696
logf.SetLogger(zap.New())
9797

98-
var log = logf.Log.WithName("builder-examples")
98+
log := logf.Log.WithName("builder-examples")
9999

100100
mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{})
101101
if err != nil {

pkg/client/example_test.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,14 @@ import (
2525
corev1 "k8s.io/api/core/v1"
2626
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2727
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
28+
"k8s.io/apimachinery/pkg/runtime"
2829
"k8s.io/apimachinery/pkg/runtime/schema"
2930
"k8s.io/apimachinery/pkg/types"
31+
corev1ac "k8s.io/client-go/applyconfigurations/core/v1"
3032

3133
"sigs.k8s.io/controller-runtime/pkg/client"
3234
"sigs.k8s.io/controller-runtime/pkg/client/config"
35+
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
3336
)
3437

3538
var (
@@ -159,7 +162,7 @@ func ExampleClient_update() {
159162
Namespace: "namespace",
160163
Name: "name",
161164
}, pod)
162-
pod.SetFinalizers(append(pod.GetFinalizers(), "new-finalizer"))
165+
controllerutil.AddFinalizer(pod, "new-finalizer")
163166
_ = c.Update(context.Background(), pod)
164167

165168
// Using a unstructured object.
@@ -173,7 +176,7 @@ func ExampleClient_update() {
173176
Namespace: "namespace",
174177
Name: "name",
175178
}, u)
176-
u.SetFinalizers(append(u.GetFinalizers(), "new-finalizer"))
179+
controllerutil.AddFinalizer(u, "new-finalizer")
177180
_ = c.Update(context.Background(), u)
178181
}
179182

@@ -188,6 +191,16 @@ func ExampleClient_patch() {
188191
}, client.RawPatch(types.StrategicMergePatchType, patch))
189192
}
190193

194+
// This example shows how to use the client with unstructured objects to create/patch objects using Server Side Apply,
195+
func ExampleClient_apply() {
196+
// Using a typed object.
197+
configMap := corev1ac.ConfigMap("name", "namespace").WithData(map[string]string{"key": "value"})
198+
// c is a created client.
199+
u := &unstructured.Unstructured{}
200+
u.Object, _ = runtime.DefaultUnstructuredConverter.ToUnstructured(configMap)
201+
_ = c.Patch(context.Background(), u, client.Apply, client.ForceOwnership, client.FieldOwner("field-owner"))
202+
}
203+
191204
// This example shows how to use the client with typed and unstructured objects to patch objects' status.
192205
func ExampleClient_patchStatus() {
193206
u := &unstructured.Unstructured{}

pkg/handler/example_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ import (
3232
"sigs.k8s.io/controller-runtime/pkg/source"
3333
)
3434

35-
var mgr manager.Manager
36-
var c controller.Controller
35+
var (
36+
mgr manager.Manager
37+
c controller.Controller
38+
)
3739

3840
// This example watches Pods and enqueues Requests with the Name and Namespace of the Pod from
3941
// the Event (i.e. change caused by a Create, Update, Delete).

0 commit comments

Comments
 (0)