From 635e79e642f81b23c608ccd3d13ec7c38e455c74 Mon Sep 17 00:00:00 2001 From: Ti Chi Robot Date: Sat, 14 Sep 2024 12:27:42 +0800 Subject: [PATCH] core: fix datarace in MergeLabels (#7537) (#7827) close tikv/pd#7535 Co-authored-by: lhy1024 Co-authored-by: Ryan Leung Co-authored-by: Hu# Co-authored-by: ti-chi-bot[bot] <108142056+ti-chi-bot[bot]@users.noreply.github.com> --- server/core/store.go | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/server/core/store.go b/server/core/store.go index ff77b7f9ac0..b1f630523d0 100644 --- a/server/core/store.go +++ b/server/core/store.go @@ -562,22 +562,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) }