From 4e6786a5dc9103fc155ad24b340ba43bc5fdb537 Mon Sep 17 00:00:00 2001 From: zirain Date: Tue, 27 Jun 2023 04:14:13 +0800 Subject: [PATCH] provider: fix store race (#1589) * add race test Signed-off-by: hejianpeng * fix race Signed-off-by: hejianpeng --- internal/provider/kubernetes/store.go | 9 +++++++++ internal/provider/kubernetes/store_test.go | 15 +++++++++++++++ tools/make/golang.mk | 2 +- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/internal/provider/kubernetes/store.go b/internal/provider/kubernetes/store.go index fd60ff1c79e..eeb63a1da4c 100644 --- a/internal/provider/kubernetes/store.go +++ b/internal/provider/kubernetes/store.go @@ -6,6 +6,8 @@ package kubernetes import ( + "sync" + corev1 "k8s.io/api/core/v1" ) @@ -20,6 +22,7 @@ type kubernetesProviderStore struct { // addresses, in case the Gateway is exposed on every Node of the cluster, using // Service of type NodePort. nodes map[string]nodeDetails + mu sync.Mutex } func newProviderStore() *kubernetesProviderStore { @@ -49,15 +52,21 @@ func (p *kubernetesProviderStore) addNode(n *corev1.Node) { } else if internalIP != "" { details.address = internalIP } + p.mu.Lock() + defer p.mu.Unlock() p.nodes[n.Name] = details } func (p *kubernetesProviderStore) removeNode(n *corev1.Node) { + p.mu.Lock() + defer p.mu.Unlock() delete(p.nodes, n.Name) } func (p *kubernetesProviderStore) listNodeAddresses() []string { addrs := []string{} + p.mu.Lock() + defer p.mu.Unlock() for _, n := range p.nodes { if n.address != "" { addrs = append(addrs, n.address) diff --git a/internal/provider/kubernetes/store_test.go b/internal/provider/kubernetes/store_test.go index ef461bf714b..d2082100083 100644 --- a/internal/provider/kubernetes/store_test.go +++ b/internal/provider/kubernetes/store_test.go @@ -77,3 +77,18 @@ func TestNodeDetailsAddressStore(t *testing.T) { }) } } + +func TestRace(t *testing.T) { + s := newProviderStore() + + go func() { + for { + s.addNode(&corev1.Node{ + ObjectMeta: v1.ObjectMeta{Name: "node1"}, + Status: corev1.NodeStatus{Addresses: []corev1.NodeAddress{{}}}, + }) + } + }() + + _ = s.listNodeAddresses() +} diff --git a/tools/make/golang.mk b/tools/make/golang.mk index 82d5d9c43f8..c5d5f8ac21e 100644 --- a/tools/make/golang.mk +++ b/tools/make/golang.mk @@ -42,7 +42,7 @@ go.build.multiarch: $(foreach p,$(PLATFORMS),$(addprefix go.build., $(addprefix .PHONY: go.test.unit go.test.unit: ## Run go unit tests - go test ./... + go test -race ./... .PHONY: go.testdata.complete go.testdata.complete: ## Override test ouputdata