Skip to content

Commit

Permalink
remove unused network policy as well
Browse files Browse the repository at this point in the history
  • Loading branch information
aasifkhan7 authored Dec 29, 2024
1 parent 94cd3f5 commit a287bed
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
25 changes: 24 additions & 1 deletion pkg/determiner/determiner.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,35 @@ func (d *determiner) DetermineDeletion(ctx context.Context, info *cliresource.In

case resource.KindHorizontalPodAutoscaler:
return d.determineDeletionHorizontalPodAutoscaler(ctx, info)

case resource.KindNetworkPolicy:
return d.determineDeletionNetworkPolicy(info)
default:
return false, fmt.Errorf("unsupported kind: %s/%s", kind, info.Name)
}
}

func (d *determiner) determineDeletionNetworkPolicy(info *cliresource.Info) (bool, error) {
np, err := resource.ObjectToNetworkPolicy(info.Object)
if err != nil {
return false, err
}

// Get the selector from the Network Policy
selector, err := metav1.LabelSelectorAsSelector(&np.Spec.PodSelector)
if err != nil {
return false, fmt.Errorf("invalid label selector (%s): %w", np.Name, err)
}

// Iterate over pods to check if any match the selector
for _, pod := range d.pods {
if selector.Matches(labels.Set(pod.Labels)) {
return false, nil // Pod matches the selector, so the Network Policy is used
}
}

return true, nil // No pods match the selector, so the Network Policy is unused
}

func (d *determiner) determineDeletionPod(info *cliresource.Info) (bool, error) {
pod, err := resource.ObjectToPod(info.Object)
if err != nil {
Expand Down
16 changes: 16 additions & 0 deletions pkg/resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
corev1 "k8s.io/api/core/v1"
policyv1beta1 "k8s.io/api/policy/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
networkingv1 "k8s.io/api/networking/v1"
)

const (
Expand All @@ -20,6 +21,7 @@ const (
KindJob = "Job"
KindPodDisruptionBudget = "PodDisruptionBudget"
KindHorizontalPodAutoscaler = "HorizontalPodAutoscaler"
KindNetworkPolicy = "NetworkPolicy"
)

var unstructuredConverter = runtime.DefaultUnstructuredConverter
Expand Down Expand Up @@ -108,6 +110,20 @@ func ObjectToHorizontalPodAutoscaler(obj runtime.Object) (*autoscalingv1.Horizon
return &hpa, nil
}

func ObjectToNetworkPolicy(obj runtime.Object) (*networkingv1.NetworkPolicy, error) {
u, err := toUnstructured(obj)
if err != nil {
return nil, err
}

var np networkingv1.NetworkPolicy
if err := fromUnstructured(u, &np); err != nil {
return nil, err
}

return &np, nil
}

func toUnstructured(obj runtime.Object) (map[string]interface{}, error) {
return unstructuredConverter.ToUnstructured(obj)
}
Expand Down

0 comments on commit a287bed

Please sign in to comment.