func serviceToEndpointSliceMapFunc()

in projects/k8s-hybrid-neg-controller/pkg/reconciler/reconciler.go [76:125]


func serviceToEndpointSliceMapFunc(k8sClient client.Client) handler.MapFunc {
	return func(ctx context.Context, o client.Object) []reconcile.Request {
		logger := log.FromContext(ctx).WithValues("namespace", o.GetNamespace(), "service", o.GetName())
		if o.GetDeletionTimestamp() != nil {
			logger.V(4).Info("Not triggering EndpointSlice reconciliation for Service, as Service is being deleted")
			return nil
		}
		if _, exists := o.GetAnnotations()[annotation.HybridNEGConfigKey]; !exists {
			logger.V(4).Info("Not triggering EndpointSlice reconciliation for Service," +
				" as Service does not have the hybrid NEG config annotation")
			return nil
		}
		labelSelector, err := labels.Parse(fmt.Sprintf("%s=%s", discoveryv1.LabelServiceName, o.GetName()))
		if err != nil {
			logger.Error(err, "Could not create label selector, must wait for next EndpointSlice event to reconcile NEG endpoints")
			return nil
		}

		// Query for metadata only to save memory.
		endpointSliceList := &metav1.PartialObjectMetadataList{
			TypeMeta: metav1.TypeMeta{
				APIVersion: "discovery.k8s.io/v1",
				Kind:       "EndpointSliceList",
			},
		}
		if err := k8sClient.List(ctx, endpointSliceList, &client.ListOptions{
			Namespace:     o.GetNamespace(),
			LabelSelector: labelSelector,
		}); err != nil {
			logger.Error(err, "Could not list EndpointSlices, must wait for next EndpointSlice event to reconcile NEG endpoints")
			return nil
		}
		if len(endpointSliceList.Items) == 0 || endpointSliceList.Items[0].GetName() == "" {
			logger.V(4).Info("Not triggering EndpointSlice reconciliation for Service, as no EndpointSlices found")
			return nil
		}
		logger.V(2).Info("Enqueueing EndpointSlice reconciliation for Service")

		// The EndpointSlice reconciler looks up all EndpointSlices for the Service, so we only
		// need to enqueue a reconcile request for one of the EndpointSlices.
		return []reconcile.Request{
			{
				NamespacedName: types.NamespacedName{
					Namespace: o.GetNamespace(),
					Name:      endpointSliceList.Items[0].GetName(),
				},
			},
		}
	}
}