From 076af3acdaa9c6cac3ed2048fb3e122fe9f45771 Mon Sep 17 00:00:00 2001 From: Xie Zheng Date: Mon, 11 Nov 2024 12:26:02 +0800 Subject: [PATCH] Fix the potential race condition of InitializeSubnetService It is possible that an error occurs when trying to send to the already closed `fatalErrors` channel, resulting in a panic. --- .gitignore | 3 ++- pkg/nsx/services/subnet/subnet.go | 24 ++++++++++++++++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 59402d8ae..2adb3be24 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ bin/ .DS_Store go.work -go.work.sum \ No newline at end of file +go.work.sum +.tool-versions \ No newline at end of file diff --git a/pkg/nsx/services/subnet/subnet.go b/pkg/nsx/services/subnet/subnet.go index f53c91ab0..8fb585bea 100644 --- a/pkg/nsx/services/subnet/subnet.go +++ b/pkg/nsx/services/subnet/subnet.go @@ -65,20 +65,36 @@ func InitializeSubnetService(service common.Service) (*SubnetService, error) { }, } + // Use sync.Once to ensure channel is closed only once + var closeOnce sync.Once + wg.Add(1) go subnetService.InitializeResourceStore(&wg, fatalErrors, ResourceTypeSubnet, nil, subnetService.SubnetStore) go func() { wg.Wait() - close(wgDone) + closeOnce.Do(func() { + close(wgDone) + }) }() select { case <-wgDone: - break + closeOnce.Do(func() { + close(fatalErrors) + }) + return subnetService, nil case err := <-fatalErrors: - close(fatalErrors) + // Wait for any pending operations to complete + go func() { + wg.Wait() // Ensure all goroutines complete + closeOnce.Do(func() { + close(wgDone) + }) + }() + closeOnce.Do(func() { + close(fatalErrors) + }) return subnetService, err } - return subnetService, nil } func (service *SubnetService) CreateOrUpdateSubnet(obj client.Object, vpcInfo common.VPCResourceInfo, tags []model.Tag) (string, error) {