Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Consistent Hashing Load Balancing Strategy #592

Merged
merged 6 commits into from
Aug 19, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
replace RWMutex to Mutex and added test case for concurency access
sinadarbouy committed Aug 19, 2024
commit 10e947f7cb11124cb44d23492eb0e629c7068e98
9 changes: 4 additions & 5 deletions network/consistenthash.go
Original file line number Diff line number Diff line change
@@ -15,7 +15,7 @@ type ConsistentHash struct {
originalStrategy LoadBalancerStrategy
useSourceIP bool
hashMap map[uint64]IProxy
hashMapMutex sync.RWMutex
mu sync.Mutex
}

// NewConsistentHash creates a new ConsistentHash instance. It requires a server configuration and an original
@@ -33,6 +33,9 @@ func NewConsistentHash(server *Server, originalStrategy LoadBalancerStrategy) *C
// proxy in the hash map based on the hashed key (either the source IP or the full address). If no match is found,
// it falls back to the original load balancing strategy, adds the selected proxy to the hash map, and returns it.
func (ch *ConsistentHash) NextProxy(conn IConnWrapper) (IProxy, *gerr.GatewayDError) {
ch.mu.Lock()
defer ch.mu.Unlock()

var key string

if ch.useSourceIP {
@@ -47,9 +50,7 @@ func (ch *ConsistentHash) NextProxy(conn IConnWrapper) (IProxy, *gerr.GatewayDEr

hash := hashKey(key)

ch.hashMapMutex.RLock()
proxy, exists := ch.hashMap[hash]
ch.hashMapMutex.RUnlock()

if exists {
return proxy, nil
@@ -62,9 +63,7 @@ func (ch *ConsistentHash) NextProxy(conn IConnWrapper) (IProxy, *gerr.GatewayDEr
}

// Add the selected proxy to the hash map for future requests
ch.hashMapMutex.Lock()
ch.hashMap[hash] = proxy
ch.hashMapMutex.Unlock()

return proxy, nil
}
57 changes: 55 additions & 2 deletions network/consistenthash_test.go
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ package network

import (
"net"
"sync"
"testing"

"github.com/gatewayd-io/gatewayd/config"
@@ -89,13 +90,65 @@ func TestConsistentHashNextProxyUseFullAddress(t *testing.T) {

// Hash should be calculated using the full address and cached in hashMap
hash := hashKey("192.168.1.1:1234")
consistentHash.hashMapMutex.RLock()
cachedProxy, exists := consistentHash.hashMap[hash]
consistentHash.hashMapMutex.RUnlock()

assert.True(t, exists)
assert.Equal(t, proxies[1], cachedProxy)

// Clean up
mockConn.AssertExpectations(t)
}

// TestConsistentHashNextProxyConcurrency tests the concurrency safety of the NextProxy method
// in the ConsistentHash struct. It ensures that multiple goroutines can concurrently call
// NextProxy without causing race conditions or inconsistent behavior.
func TestConsistentHashNextProxyConcurrency(t *testing.T) {
// Setup mocks
conn1 := new(MockConnWrapper)
conn2 := new(MockConnWrapper)
proxies := []IProxy{
MockProxy{name: "proxy1"},
MockProxy{name: "proxy2"},
MockProxy{name: "proxy3"},
}
server := &Server{
Proxies: proxies,
LoadbalancerConsistentHash: &config.ConsistentHash{UseSourceIP: true},
}
originalStrategy := NewRoundRobin(server)

// Mock IP addresses
mockAddr1 := &net.TCPAddr{IP: net.ParseIP("192.168.1.1"), Port: 1234}
mockAddr2 := &net.TCPAddr{IP: net.ParseIP("192.168.1.2"), Port: 1234}
conn1.On("LocalAddr").Return(mockAddr1)
conn2.On("LocalAddr").Return(mockAddr2)

// Initialize the ConsistentHash
consistentHash := NewConsistentHash(server, originalStrategy)

// Run the test concurrently
var waitGroup sync.WaitGroup
const numGoroutines = 100

for range numGoroutines {
waitGroup.Add(1)
go func() {
defer waitGroup.Done()
p, err := consistentHash.NextProxy(conn1)
assert.Nil(t, err)
assert.Equal(t, proxies[1], p)
}()
}

waitGroup.Wait()

// Ensure that the proxy is consistently the same
proxy, err := consistentHash.NextProxy(conn1)
assert.Nil(t, err)
assert.Equal(t, proxies[1], proxy)

// Ensure that connecting from a different address returns a different proxy
proxy, err = consistentHash.NextProxy(conn2)
assert.Nil(t, err)
assert.Equal(t, proxies[2], proxy)
}