Skip to content

Commit

Permalink
bug: [sc-103753] Host analysers are not deduplicating during multiple…
Browse files Browse the repository at this point in the history
… spec merges #1485 (#1542)

* dedupe host collector and analyzer

* dedup analyzer

* add unit test

* use generic
  • Loading branch information
nvanthao authored May 16, 2024
1 parent 78bbea1 commit fb0f81d
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cmd/troubleshoot/cli/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,12 @@ func loadSpecs(ctx context.Context, args []string, client kubernetes.Interface)
additionalRedactors.Spec.Redactors = util.Append(additionalRedactors.Spec.Redactors, r.Spec.Redactors)
}

// dedupe specs
mainBundle.Spec.Collectors = util.Dedup(mainBundle.Spec.Collectors)
mainBundle.Spec.Analyzers = util.Dedup(mainBundle.Spec.Analyzers)
mainBundle.Spec.HostCollectors = util.Dedup(mainBundle.Spec.HostCollectors)
mainBundle.Spec.HostAnalyzers = util.Dedup(mainBundle.Spec.HostAnalyzers)

return mainBundle, additionalRedactors, nil
}

Expand Down
28 changes: 28 additions & 0 deletions cmd/troubleshoot/cli/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,3 +343,31 @@ spec:
})
}
}

func Test_loadDuplicatedBundleSpecs(t *testing.T) {
spec := testutils.ServeFromFilePath(t, `
apiVersion: troubleshoot.sh/v1beta2
kind: SupportBundle
metadata:
name: sb
spec:
collectors:
- helm: {}
analyzers:
- clusterVersion: {}
hostCollectors:
- cpu: {}
hostAnalyzers:
- cpu: {}
`)
args := []string{spec, spec}

ctx := context.Background()
client := testclient.NewSimpleClientset()
sb, _, err := loadSpecs(ctx, args, client)
require.NoError(t, err)
assert.Len(t, sb.Spec.Collectors, 1+2) // default clusterInfo + clusterResources
assert.Len(t, sb.Spec.Analyzers, 1)
assert.Len(t, sb.Spec.HostCollectors, 1)
assert.Len(t, sb.Spec.HostAnalyzers, 1)
}
24 changes: 24 additions & 0 deletions internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package util
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
Expand Down Expand Up @@ -145,3 +146,26 @@ func PromptYesNo(question string) bool {
}
}
}

func Dedup[T any](objs []T) []T {
seen := make(map[string]bool)
out := []T{}

if len(objs) == 0 {
return objs
}

for _, o := range objs {
data, err := json.Marshal(o)
if err != nil {
out = append(out, o)
continue
}
key := string(data)
if _, ok := seen[key]; !ok {
out = append(out, o)
seen[key] = true
}
}
return out
}

0 comments on commit fb0f81d

Please sign in to comment.