[NET-353] Solve race condition with "unique" ips (#2461)

* Use a lock for getting unique ips

* Make getting & setting unique ips atomic

* Remove some blank lines

* Set addressLock to &sync.Mutex on declaration
This commit is contained in:
Gabriel de Souza Seibel 2023-07-27 03:04:15 -03:00 committed by GitHub
parent 4bcb3d0196
commit 7e8b66e03d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 11 additions and 1 deletions

View file

@ -154,6 +154,9 @@ func GetExtClientByPubKey(publicKey string, network string) (*models.ExtClient,
// CreateExtClient - creates an extclient
func CreateExtClient(extclient *models.ExtClient) error {
// lock because we need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs
addressLock.Lock()
defer addressLock.Unlock()
if len(extclient.PublicKey) == 0 {
privateKey, err := wgtypes.GeneratePrivateKey()

View file

@ -7,6 +7,7 @@ import (
"net"
"sort"
"strings"
"sync"
"github.com/c-robinson/iplib"
validator "github.com/go-playground/validator/v10"
@ -147,7 +148,7 @@ func GetNetworkSettings(networkname string) (models.Network, error) {
return network, nil
}
// UniqueAddress - see if address is unique
// UniqueAddress - get a unique ipv4 address
func UniqueAddress(networkName string, reverse bool) (net.IP, error) {
add := net.IP{}
var network models.Network
@ -424,3 +425,5 @@ func SortNetworks(unsortedNetworks []models.Network) {
}
// == Private ==
var addressLock = &sync.Mutex{}

View file

@ -460,6 +460,10 @@ func updateProNodeACLS(node *models.Node) error {
// createNode - creates a node in database
func createNode(node *models.Node) error {
// lock because we need unique IPs and having it concurrent makes parallel calls result in same "unique" IPs
addressLock.Lock()
defer addressLock.Unlock()
host, err := GetHost(node.HostID.String())
if err != nil {
return err