Skip to content

Commit

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

Co-authored-by: lhy1024 <[email protected]>
Co-authored-by: Ryan Leung <[email protected]>
Co-authored-by: ti-chi-bot[bot] <108142056+ti-chi-bot[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored Sep 14, 2024
1 parent b7396e6 commit 69d2142
Showing 1 changed file with 24 additions and 9 deletions.
33 changes: 24 additions & 9 deletions server/core/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,22 +522,37 @@ 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 (s *StoreInfo) MergeLabels(labels []*metapb.StoreLabel) []*metapb.StoreLabel {
storeLabels := s.GetLabels()
L:
origin := s.GetLabels()
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 69d2142

Please sign in to comment.