Created
November 11, 2021 22:08
-
-
Save nakamasato/2c406312521864f8ba45d412ae626671 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
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" | |
"reflect" //added | |
"context" | |
cachev1alpha1 "github.com/example/memcached-operator/api/v1alpha1" | |
"github.com/go-logr/logr" | |
"k8s.io/apimachinery/pkg/runtime" | |
ctrl "sigs.k8s.io/controller-runtime" | |
"sigs.k8s.io/controller-runtime/pkg/client" | |
) | |
... | |
func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { | |
log := r.Log.WithValues("memcached", req.NamespacedName) | |
// 1. Fetch the Memcached instance | |
// implemented | |
// 2. Check if the deployment already exists, if not create a new one | |
// implemented | |
// 3. Ensure the deployment size is the same as the spec | |
// implemented | |
// 4. Update the Memcached status with the pod names | |
// List the pods for this memcached's deployment | |
podList := &corev1.PodList{} | |
listOpts := []client.ListOption{ | |
client.InNamespace(memcached.Namespace), | |
client.MatchingLabels(labelsForMemcached(memcached.Name)), | |
} | |
if err = r.List(ctx, podList, listOpts...); err != nil { | |
log.Error(err, "4. Update the Memcached status with the pod names. Failed to list pods", "Memcached.Namespace", memcached.Namespace, "Memcached.Name", memcached.Name) | |
return ctrl.Result{}, err | |
} | |
podNames := getPodNames(podList.Items) | |
log.Info("4. Update the Memcached status with the pod names. Pod list", "podNames", podNames) | |
// Update status.Nodes if needed | |
if !reflect.DeepEqual(podNames, memcached.Status.Nodes) { | |
memcached.Status.Nodes = podNames | |
err := r.Status().Update(ctx, memcached) | |
if err != nil { | |
log.Error(err, "4. Update the Memcached status with the pod names. Failed to update Memcached status") | |
return ctrl.Result{}, err | |
} | |
} | |
log.Info("4. Update the Memcached status with the pod names. Update memcached.Status", "memcached.Status.Nodes", memcached.Status.Nodes) | |
return ctrl.Result{}, nil | |
} | |
... | |
// getPodNames returns the pod names of the array of pods passed in | |
func getPodNames(pods []corev1.Pod) []string { | |
var podNames []string | |
for _, pod := range pods { | |
podNames = append(podNames, pod.Name) | |
} | |
return podNames | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment