Skip to content

✨ add EnqueueRequestForAnnotation enqueues Requests based on the presence of an annotation to watch resources #892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions examples/annotationbasedwatch/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"context"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/handler"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"

"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)

// reconcileReplicaSet reconciles ReplicaSets
type reconcileReplicaSet struct {
// client can be used to retrieve objects from the APIServer.
client client.Client
log logr.Logger
}

// Implement reconcile.Reconciler so the controller can reconcile objects
var _ reconcile.Reconciler = &reconcileReplicaSet{}

func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
// set up a convenient log object so we don't have to type request over and over again
log := r.log.WithValues("request", request)

// Fetch the ReplicaSet from the cache
rs := &appsv1.ReplicaSet{}
err := r.client.Get(context.TODO(), request.NamespacedName, rs)
if errors.IsNotFound(err) {
log.Error(nil, "Could not find ReplicaSet")
return reconcile.Result{}, nil
}

if err != nil {
log.Error(err, "Could not fetch ReplicaSet")
return reconcile.Result{}, err
}

// Print the ReplicaSet
log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name)

// Check if the Pod already exists, if not create a new one
podRs := &corev1.Pod{}
err = r.client.Get(context.TODO(), types.NamespacedName{Name: rs.Name, Namespace: rs.Namespace}, podRs)
if err != nil && errors.IsNotFound(err) {
// Define a new Deployment
pod := r.podForReplicasetWithWatchAnnotations(rs)
err = r.client.Create(context.TODO(), pod)
if err != nil {
log.Error(err, "Failed to create new Pod.", "Pod.Namespace", pod.Namespace, "Pod.Name", pod.Name)
return reconcile.Result{}, err
}
return reconcile.Result{Requeue: true}, nil
} else if err != nil {
log.Error(err, "Failed to get Pod.")
return reconcile.Result{}, err
}

// Set the label if it is missing
if rs.Labels == nil {
rs.Labels = map[string]string{}
}

if rs.Labels["hello"] == "world" {
return reconcile.Result{}, nil
}

// Update the ReplicaSet
rs.Labels["hello"] = "world"
err = r.client.Update(context.TODO(), rs)
if err != nil {
log.Error(err, "Could not write ReplicaSet")
return reconcile.Result{}, err
}

return reconcile.Result{}, nil
}

// podForReplicasetWithWatchAnnotations returns a pod object with the annotations required to be watched with.
func (r *reconcileReplicaSet) podForReplicasetWithWatchAnnotations(rs *appsv1.ReplicaSet) *corev1.Pod {
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: rs.Name,
Namespace: rs.Namespace,
},
}
annotation := schema.GroupKind{Group: "ReplicaSet", Kind: "apps"}
handler.SetWatchOwnerAnnotation(rs,pod, annotation)
return pod
}
98 changes: 98 additions & 0 deletions examples/annotationbasedwatch/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
"k8s.io/apimachinery/pkg/runtime/schema"
"os"

corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
"sigs.k8s.io/controller-runtime/pkg/source"
)

var log = logf.Log.WithName("example-annotationbasedwatch")

func main() {
logf.SetLogger(zap.Logger(false))
entryLog := log.WithName("entrypoint")

// Setup a Manager
entryLog.Info("setting up manager")
mgr, err := manager.New(config.GetConfigOrDie(), manager.Options{})
if err != nil {
entryLog.Error(err, "unable to set up overall controller manager")
os.Exit(1)
}

// Setup a new controller to reconcile ReplicaSets
entryLog.Info("Setting up controller")
c, err := controller.New("foo-controller", mgr, controller.Options{
Reconciler: &reconcileReplicaSet{client: mgr.GetClient(), log: log.WithName("reconciler")},
})
if err != nil {
entryLog.Error(err, "unable to set up individual controller")
os.Exit(1)
}

// Watch Pods that has the following annotations:
// ...
// annotations:
// watch.kubebuilder.io/owner-namespaced-name:my-namespace/my-replicaset
// watch.kubebuilder.io/owner-type:apps.ReplicaSet
// ...
// It will enqueue a Request to the primary-resource-namespace when some change occurs in a Pod resource with these
// annotations
annotation := schema.GroupKind{Group: "ReplicaSet", Kind: "apps"}
if err := c.Watch(&source.Kind{Type: &corev1.Pod{}}, &handler.EnqueueRequestForAnnotation{annotation}); err != nil {
entryLog.Error(err, "unable to watch Pods")
os.Exit(1)
}

// Watch ClusterRoles that has the following annotations:
// ...
// annotations:
// watch.kubebuilder.io/owner-namespaced-name:my-namespace/my-replicaset
// watch.kubebuilder.io/owner-type:apps.ReplicaSet
// ...
// It will enqueue a Request to the primary-resource-namespace when some change occurs in a ClusterRole resource with these
// annotations
if err := c.Watch(&source.Kind{
// Watch cluster roles
Type: &rbacv1.ClusterRole{}},

// Enqueue ReplicaSet reconcile requests using the
// namespacedName annotation value in the request.
&handler.EnqueueRequestForAnnotation{schema.GroupKind{Group:"ReplicaSet", Kind:"apps"}}); err != nil {
entryLog.Error(err, "unable to watch Cluster Role")
os.Exit(1)
}

entryLog.Info("starting manager")
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
entryLog.Error(err, "unable to run manager")
os.Exit(1)
}
}
Loading