sigs.k8s.io/controller-runtime@v0.18.2/examples/builtins/controller.go (about) 1 /* 2 Copyright 2018 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "context" 21 "fmt" 22 23 appsv1 "k8s.io/api/apps/v1" 24 "k8s.io/apimachinery/pkg/api/errors" 25 "sigs.k8s.io/controller-runtime/pkg/client" 26 "sigs.k8s.io/controller-runtime/pkg/log" 27 "sigs.k8s.io/controller-runtime/pkg/reconcile" 28 ) 29 30 // reconcileReplicaSet reconciles ReplicaSets 31 type reconcileReplicaSet struct { 32 // client can be used to retrieve objects from the APIServer. 33 client client.Client 34 } 35 36 // Implement reconcile.Reconciler so the controller can reconcile objects 37 var _ reconcile.Reconciler = &reconcileReplicaSet{} 38 39 func (r *reconcileReplicaSet) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { 40 // set up a convenient log object so we don't have to type request over and over again 41 log := log.FromContext(ctx) 42 43 // Fetch the ReplicaSet from the cache 44 rs := &appsv1.ReplicaSet{} 45 err := r.client.Get(ctx, request.NamespacedName, rs) 46 if errors.IsNotFound(err) { 47 log.Error(nil, "Could not find ReplicaSet") 48 return reconcile.Result{}, nil 49 } 50 51 if err != nil { 52 return reconcile.Result{}, fmt.Errorf("could not fetch ReplicaSet: %+v", err) 53 } 54 55 // Print the ReplicaSet 56 log.Info("Reconciling ReplicaSet", "container name", rs.Spec.Template.Spec.Containers[0].Name) 57 58 // Set the label if it is missing 59 if rs.Labels == nil { 60 rs.Labels = map[string]string{} 61 } 62 if rs.Labels["hello"] == "world" { 63 return reconcile.Result{}, nil 64 } 65 66 // Update the ReplicaSet 67 rs.Labels["hello"] = "world" 68 err = r.client.Update(ctx, rs) 69 if err != nil { 70 return reconcile.Result{}, fmt.Errorf("could not write ReplicaSet: %+v", err) 71 } 72 73 return reconcile.Result{}, nil 74 }