Browse Source

[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
Gabriel de Souza Seibel 2 years ago
parent
commit
7e8b66e03d
3 changed files with 11 additions and 1 deletions
  1. 3 0
      logic/extpeers.go
  2. 4 1
      logic/networks.go
  3. 4 0
      logic/nodes.go

+ 3 - 0
logic/extpeers.go

@@ -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()

+ 4 - 1
logic/networks.go

@@ -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{}

+ 4 - 0
logic/nodes.go

@@ -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