From b8b35d99fa18f5839bc411ad09635c027596e4e4 Mon Sep 17 00:00:00 2001 From: Sudarsan Reddy Date: Wed, 7 Dec 2022 17:46:15 +0000 Subject: [PATCH] TUN-7002: Randomise first region selection We previously always preferred region2 as the first region to connect to if both the regions cloudflared connects to have the same number of availabe addresses. This change randomises that choice. The first connection, conn index: 0, can now either connect to region 1 or region 2. More importantly, conn 0 and 2 and 1 and 3 need not belong to the same region. --- edgediscovery/allregions/regions.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/edgediscovery/allregions/regions.go b/edgediscovery/allregions/regions.go index 4b2a841b..b9b7d3ea 100644 --- a/edgediscovery/allregions/regions.go +++ b/edgediscovery/allregions/regions.go @@ -2,6 +2,7 @@ package allregions import ( "fmt" + "math/rand" "github.com/rs/zerolog" ) @@ -85,6 +86,15 @@ func (rs *Regions) AddrUsedBy(connID int) *EdgeAddr { // GetUnusedAddr gets an unused addr from the edge, excluding the given addr. Prefer to use addresses // evenly across both regions. func (rs *Regions) GetUnusedAddr(excluding *EdgeAddr, connID int) *EdgeAddr { + // If both regions have the same number of available addrs, lets randomise which one + // we pick. The rest of this algorithm will continue to make sure we always use addresses + // evenly across both regions. + if rs.region1.AvailableAddrs() == rs.region2.AvailableAddrs() { + regions := []Region{rs.region1, rs.region2} + firstChoice := rand.Intn(2) + return getAddrs(excluding, connID, ®ions[firstChoice], ®ions[1-firstChoice]) + } + if rs.region1.AvailableAddrs() > rs.region2.AvailableAddrs() { return getAddrs(excluding, connID, &rs.region1, &rs.region2) }