Skip to content

Commit

Permalink
core: fix datarace in MergeLabels (#7537)
Browse files Browse the repository at this point in the history
close #7535

Signed-off-by: lhy1024 <[email protected]>
  • Loading branch information
lhy1024 committed Feb 20, 2024
1 parent e264a61 commit 1772ad0
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions pkg/core/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -600,22 +600,36 @@ func DistinctScore(labels []string, stores []*StoreInfo, other *StoreInfo) float
return score
}

// MergeLabels merges the passed in labels with origins, overriding duplicated
// ones.
// MergeLabels merges the passed in labels with origins, overriding duplicated ones.
// Note: To prevent potential data races, it is advisable to refrain from directly modifying the 'origin' variable.
func MergeLabels(origin []*metapb.StoreLabel, labels []*metapb.StoreLabel) []*metapb.StoreLabel {
storeLabels := origin
L:
results := make([]*metapb.StoreLabel, 0, len(origin))
for _, label := range origin {
results = append(results, &metapb.StoreLabel{
Key: label.Key,
Value: label.Value,
})
}

for _, newLabel := range labels {
for _, label := range storeLabels {
found := false
for _, label := range results {
if strings.EqualFold(label.Key, newLabel.Key) {
// Update the value for an existing key.
label.Value = newLabel.Value
continue L
found = true
break
}
}
storeLabels = append(storeLabels, newLabel)
// Add a new label if the key doesn't exist in the original slice.
if !found {
results = append(results, newLabel)
}
}
res := storeLabels[:0]
for _, l := range storeLabels {

// Filter out labels with an empty value.
res := results[:0]
for _, l := range results {
if l.Value != "" {
res = append(res, l)
}
Expand Down

0 comments on commit 1772ad0

Please sign in to comment.