yonahd / kor

A Golang Tool to discover unused Kubernetes Resources
MIT License
1.04k stars 96 forks source link

refactor: PDB label selection #366

Closed doronkg closed 3 weeks ago

doronkg commented 1 month ago

What this PR does / why we need it?

This PR changes the behavior of how kor maps unused PDBs. Currently, it validates the PDB label selector against Deployments/StatefulSets direct metadata labels, while it should validate the template labels, as PDBs select pods and through .metadata.ownerReferences field finds the respective workload controllers and not the other way around.

For example, the following Deployment is valid, but kor will map it as unused, as .metadata.labels field is not matched, even if the template labels match:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-name
spec:
  replicas: 2
  selector:
    matchLabels:
      app.kubernetes.io/name: app-name
      app.kubernetes.io/instance: app-instance
  template:
    metadata:
      labels:
        app.kubernetes.io/name: app-name
        app.kubernetes.io/instance: app-instance

In addition, added support for empty selectors & arbitrary pods.

PR Checklist

GitHub Issue

Closes #364

Notes for your reviewers

$ kor pdb --show-reason
Unused resources in namespace: "empty"
+---+---------------+----------------+--------------------------------------------------------------+
| # | RESOURCE TYPE | RESOURCE NAME  |                            REASON                            |
+---+---------------+----------------+--------------------------------------------------------------+
| 1 | Pdb           | app-name-empty | Pdb matches every pod (empty selector) but 0 pods run        |
| 2 | Pdb           | app-name2      | Pdb is not referencing any deployments, statefulsets or pods |
+---+---------------+----------------+--------------------------------------------------------------+

Based the feature on the official PDB docs.

codecov-commenter commented 1 month ago

:warning: Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

Attention: Patch coverage is 66.66667% with 26 lines in your changes missing coverage. Please review.

Project coverage is 43.38%. Comparing base (673c21e) to head (63f6aab). Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/kor/pdbs.go 61.76% 17 Missing and 9 partials :warning:

:exclamation: Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #366 +/- ## ========================================== - Coverage 44.48% 43.38% -1.11% ========================================== Files 63 63 Lines 3356 4020 +664 ========================================== + Hits 1493 1744 +251 - Misses 1622 2030 +408 - Partials 241 246 +5 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.