Skip to content

Commit

Permalink
Fix the potential race condition of InitializeSubnetService
Browse files Browse the repository at this point in the history
It is possible that an error occurs when trying to send to the already closed `fatalErrors` channel, resulting in a panic.
  • Loading branch information
zhengxiexie committed Nov 11, 2024
1 parent bf1880a commit 076af3a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
bin/
.DS_Store
go.work
go.work.sum
go.work.sum
.tool-versions
24 changes: 20 additions & 4 deletions pkg/nsx/services/subnet/subnet.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 076af3a

Please sign in to comment.