package ownerref import ( "context" "fmt" "reflect" appsv1 "k8s.io/api/apps/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "edge-infra.dev/pkg/edge/apis/meta" ) var ( deployment = metav1.TypeMeta{ APIVersion: appsv1.SchemeGroupVersion.String(), Kind: reflect.TypeOf(appsv1.Deployment{}).Name(), } daemonSet = metav1.TypeMeta{ APIVersion: appsv1.SchemeGroupVersion.String(), Kind: reflect.TypeOf(appsv1.DaemonSet{}).Name(), } statefulSet = metav1.TypeMeta{ APIVersion: appsv1.SchemeGroupVersion.String(), Kind: reflect.TypeOf(appsv1.StatefulSet{}).Name(), } validOwnerRefs = []metav1.TypeMeta{deployment, daemonSet, statefulSet} // has valid parent replicaSet = metav1.TypeMeta{ APIVersion: appsv1.SchemeGroupVersion.String(), Kind: reflect.TypeOf(appsv1.ReplicaSet{}).Name(), } ) func GetOwnerRef(ctx context.Context, cl client.Client, pod client.Object) (*metav1.OwnerReference, error) { for _, ref := range pod.GetOwnerReferences() { if isValidOwnerRef(ref) { return &ref, nil } if isSameResource(replicaSet, ref) { set := &appsv1.ReplicaSet{} nn := types.NamespacedName{Namespace: pod.GetNamespace(), Name: ref.Name} if err := cl.Get(ctx, nn, set); err != nil { return nil, err } return GetOwnerRef(ctx, cl, set) } } return nil, fmt.Errorf("invalid owner reference for pod") } func isValidOwnerRef(ref metav1.OwnerReference) bool { for _, resource := range validOwnerRefs { if isSameResource(resource, ref) { return true } } return false } func isSameResource(resource metav1.TypeMeta, ref metav1.OwnerReference) bool { return resource.APIVersion == ref.APIVersion && resource.Kind == ref.Kind } // ResourceName hash for a resource created based on owner ref and node name if needed func ResourceName(resource string, ref metav1.OwnerReference, ns string, nodeName string, isTouchPoint bool) string { var hash string if isTouchPoint { hash = meta.Hash(fmt.Sprintf("%s-%s-%s", ns, ref.Name, nodeName)) } else { hash = meta.Hash(fmt.Sprintf("%s-%s", ns, ref.Name)) } return fmt.Sprintf("%s-%s", resource, hash) }