Skip to content

Commit

Permalink
remove duplicates from resources list
Browse files Browse the repository at this point in the history
  • Loading branch information
murphd40 committed May 14, 2023
1 parent 3b95dd1 commit 6f7be35
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
17 changes: 9 additions & 8 deletions pkg/app/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import (
"k8s.io/kube-state-metrics/v2/pkg/metricshandler"
"k8s.io/kube-state-metrics/v2/pkg/optin"
"k8s.io/kube-state-metrics/v2/pkg/options"
"k8s.io/kube-state-metrics/v2/pkg/util/collections"
"k8s.io/kube-state-metrics/v2/pkg/util/proc"
)

Expand Down Expand Up @@ -173,25 +174,25 @@ func RunKubeStateMetrics(ctx context.Context, opts *options.Options) error {

}

resources := make([]string, len(factories))
resources := collections.NewSet[string]()

for i, factory := range factories {
resources[i] = factory.Name()
for _, factory := range factories {
resources.Add(factory.Name())
}

switch {
case len(opts.Resources) == 0 && !opts.CustomResourcesOnly:
resources = append(resources, options.DefaultResources.AsSlice()...)
resources.Add(options.DefaultResources.AsSlice()...)
klog.InfoS("Used default resources")
case opts.CustomResourcesOnly:
// enable custom resource only
klog.InfoS("Used CRD resources only", "resources", resources)
klog.InfoS("Used CRD resources only", "resources", resources.String())
default:
resources = append(resources, opts.Resources.AsSlice()...)
klog.InfoS("Used resources", "resources", resources)
resources.Add(opts.Resources.AsSlice()...)
klog.InfoS("Used resources", "resources", resources.String())
}

if err := storeBuilder.WithEnabledResources(resources); err != nil {
if err := storeBuilder.WithEnabledResources(resources.AsSlice()); err != nil {
return fmt.Errorf("failed to set up resources: %v", err)
}

Expand Down
37 changes: 37 additions & 0 deletions pkg/util/collections/set.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package collections

import (
"fmt"
"sort"
"strings"
)

type Set[T comparable] map[T]struct{}

func NewSet[T comparable](values ...T) Set[T] {
s := make(Set[T], len(values))
return s
}

func (s Set[T]) Add(values ...T) {
for _, val := range values {
s[val] = struct{}{}
}
}

func (s Set[T]) AsSlice() []T {
slice := make([]T, 0, len(s))
for val := range s {
slice = append(slice, val)
}
return slice
}

func (s *Set[T]) String() string {
ss := make([]string, 0, len(*s))
for val := range *s {
ss = append(ss, fmt.Sprint(val))
}
sort.Strings(ss)
return strings.Join(ss, ",")
}

0 comments on commit 6f7be35

Please sign in to comment.