func policyToTargetRefObj[T client.Object]()

in pkg/controllers/eventhandlers/mapper.go [91:148]


func policyToTargetRefObj[T client.Object](r *resourceMapper, ctx context.Context, policy policyhelper.Policy, retObj T) T {
	null := *new(T)
	if policy == nil {
		return null
	}
	policyNamespacedName := k8sutils.NamespacedName(policy)

	targetRef := policy.GetTargetRef()
	if targetRef == nil {
		r.log.Infow(ctx, "Policy does not have targetRef, skipping",
			"policyName", policyNamespacedName)
		return null
	}
	expectedGroup, expectedKind, err := k8sResourceTypeToGroupAndKind(retObj)
	if err != nil {
		r.log.Errorw(ctx, "Failed to get expected GroupKind for targetRefObj",
			"policyName", policyNamespacedName,
			"targetRef", targetRef,
			"reason", err.Error())
		return null
	}

	if targetRef.Group != expectedGroup || targetRef.Kind != expectedKind {
		r.log.Infow(ctx, "Detected targetRef GroupKind and expected retObj GroupKind are different, skipping",
			"policyName", policyNamespacedName,
			"targetRef", targetRef,
			"expectedGroup", expectedGroup,
			"expectedKind", expectedKind)
		return null
	}
	if targetRef.Namespace != nil && policyNamespacedName.Namespace != string(*targetRef.Namespace) {
		r.log.Infow(ctx, "Detected Policy and TargetRef namespace are different, skipping",
			"policyNamespacedName", policyNamespacedName, "targetRef", targetRef,
			"targetRef.Namespace", targetRef.Namespace,
			"policyNamespacedName.Namespace", policyNamespacedName.Namespace)
		return null
	}

	key := types.NamespacedName{
		Namespace: policyNamespacedName.Namespace,
		Name:      string(targetRef.Name),
	}
	if err := r.client.Get(ctx, key, retObj); err != nil {
		if errors.IsNotFound(err) {
			r.log.Debugw(ctx, "Policy is referring to a non-existent targetRefObj, skipping",
				"policyName", policyNamespacedName, "targetRef", targetRef)
		} else {
			// Still gracefully skipping the event but errors other than NotFound are bad sign.
			r.log.Errorw(ctx, "Failed to query targetRef of TargetGroupPolicy",
				"policyName", policyNamespacedName, "targetRef", targetRef, "reason", err.Error())
		}
		return null
	}
	r.log.Debugw(ctx, "Policy change on Service detected",
		"policyName", policyNamespacedName, "targetRef", targetRef)

	return retObj
}