Hello World

    This chapter shows a simple Controller implementation using thecontroller-runtime builderlibraries to do most of the Controller configuration.

    For a more detailed look at creating Resources and Controllers that may be more complex,see the , Controller and examples.

    • On ReplicaSet create/update/delete events - Reconcile the ReplicaSet
    • On Pod create/update/delete events - Reconcile the ReplicaSet that created the Pod
    • Reconcile by calling ReplicaSetController.Reconcile with the Namespace and Name ofReplicaSet

    ReplicaSet Implementation

    ReplicaSetController implements reconcile.Reconciler. It takes the Namespace and Name fora ReplicaSet object and makes the state of the cluster match what is specified in the ReplicaSetat the time Reconcile is called. This typically means using a client.Client to readthe same of multiple objects, and perform create / update / delete as needed.

    • Implement InjectClient to get a client.Client from the application.Builder
    • Read the ReplicaSet object using the provided Namespace and Name
    • List the Pods matching the ReplicaSet selector
    • Set a Label on the ReplicaSet with the matching Pod countBecause the Controller watches for Pod events, the count will be updated any timea Pod is created or deleted.
    1. // InjectClient is called by the application.Builder
    2. // to provide a client.Client
    3. func (a *ReplicaSetController) InjectClient(
    4. c client.Client) error {
    5. a.Client = c
    6. return nil
    7. // Reconcile reads the Pods for a ReplicaSet and writes
    8. // the count back as an annotation
    9. func (a *ReplicaSetController) Reconcile(
    10. req reconcile.Request) (reconcile.Result, error) {
    11. // Read the ReplicaSet
    12. rs := &appsv1.ReplicaSet{}
    13. err := a.Get(context.TODO(), req.NamespacedName, rs)
    14. if err != nil {
    15. return reconcile.Result{}, err
    16. }
    17. // List the Pods matching the PodTemplate Labels
    18. pods := &corev1.PodList{}
    19. err = a.List(context.TODO(),
    20. MatchingLabels(rs.Spec.Template.Labels),
    21. pods)
    22. if err != nil {
    23. return reconcile.Result{}, err
    24. }
    25. // Update the ReplicaSet
    26. rs.Labels["selector-pod-count"] =
    27. fmt.Sprintf("%v", len(pods.Items))
    28. err = a.Update(context.TODO(), rs)
    29. if err != nil {
    30. return reconcile.Result{}, err
    31. }