Skip to content

Commit

Permalink
provider: fix store race (#1589)
Browse files Browse the repository at this point in the history
* add race test

Signed-off-by: hejianpeng <hejianpeng2@huawei.com>

* fix race

Signed-off-by: hejianpeng <hejianpeng2@huawei.com>
  • Loading branch information
zirain authored Jun 26, 2023
1 parent 4d20828 commit 4e6786a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
9 changes: 9 additions & 0 deletions internal/provider/kubernetes/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
package kubernetes

import (
"sync"

corev1 "k8s.io/api/core/v1"
)

Expand All @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions internal/provider/kubernetes/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
2 changes: 1 addition & 1 deletion tools/make/golang.mk
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 4e6786a

Please sign in to comment.