diff --git a/go.mod b/go.mod index 1d3d3f9..b7b4a78 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( k8s.io/api v0.34.1 k8s.io/apimachinery v0.34.1 k8s.io/client-go v0.34.1 + k8s.io/utils v0.0.0-20250820121507-0af2bda4dd1d ) require ( @@ -78,7 +79,6 @@ require ( gopkg.in/inf.v0 v0.9.1 // indirect k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect - k8s.io/utils v0.0.0-20250820121507-0af2bda4dd1d // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect diff --git a/internal/kubernetes.go b/internal/kubernetes.go index 7be1245..5ac0c2c 100644 --- a/internal/kubernetes.go +++ b/internal/kubernetes.go @@ -6,6 +6,7 @@ import ( "iter" "log/slog" "math/rand" + "slices" "strings" "time" @@ -17,6 +18,7 @@ import ( "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/flowcontrol" + slicesutils "k8s.io/utils/strings/slices" ) // ConnectToKubernetesCluster : Try connect to a cluster from inside if path is empty, @@ -109,6 +111,14 @@ func (exporter *Exporter) parseAllKubeObjects() ([]*certificateRef, []error) { } func (exporter *Exporter) listNamespacesToWatch() ([]string, error) { + if len(exporter.KubeIncludeNamespaces) > 0 && + len(exporter.KubeIncludeNamespaceLabels) == 0 && + len(exporter.KubeExcludeNamespaceLabels) == 0 { + return slicesutils.Filter(nil, exporter.KubeIncludeNamespaces, func(namespace string) bool { + return !slicesutils.Contains(exporter.KubeExcludeNamespaces, namespace) + }), nil + } + _, includedLabelsWithValue := exporter.prepareLabelFilters(exporter.KubeIncludeNamespaceLabels) labelSelector := metav1.LabelSelector{MatchLabels: includedLabelsWithValue} namespaces, err := exporter.kubeClient.CoreV1().Namespaces().List(context.Background(), metav1.ListOptions{ @@ -124,27 +134,11 @@ func (exporter *Exporter) listNamespacesToWatch() ([]string, error) { func (exporter *Exporter) filterNamespaces(namespaces []v1.Namespace) []string { filteredNamespaces := []*v1.Namespace{} for _, namespace := range namespaces { - found := false - for _, includeNs := range exporter.KubeIncludeNamespaces { - if namespace.Name == includeNs { - found = true - break - } - } - - if len(exporter.KubeIncludeNamespaces) > 0 && !found { + if len(exporter.KubeIncludeNamespaces) > 0 && !slices.Contains(exporter.KubeIncludeNamespaces, namespace.Name) { continue } - found = false - for _, excludeNs := range exporter.KubeExcludeNamespaces { - if namespace.Name == excludeNs { - found = true - break - } - } - - if !found { + if !slices.Contains(exporter.KubeExcludeNamespaces, namespace.Name) { filteredNamespaces = append(filteredNamespaces, &namespace) } }