proxy-loadbalancer/src/proxy/proxy.go

68 lines
1.8 KiB
Go
Raw Normal View History

2024-04-12 01:26:45 -06:00
package proxy
import (
2024-04-12 18:23:18 -06:00
"github.com/sirupsen/logrus"
"main/logging"
"slices"
2024-04-12 01:26:45 -06:00
"sync"
"sync/atomic"
)
type ForwardProxyCluster struct {
2024-04-12 18:23:18 -06:00
mu sync.RWMutex
ourOnlineProxies []string
thirdpartyOnlineProxies []string
thirdpartyBrokenProxies []string
ipAddresses []string
BalancerOnline WaitGroupCountable
currentProxyAll int32
currentProxyOurs int32
currentProxyAllWithBroken int32
2024-04-12 01:26:45 -06:00
}
2024-04-12 18:23:18 -06:00
var log *logrus.Logger
func init() {
log = logging.GetLogger()
}
2024-04-12 01:26:45 -06:00
func NewForwardProxyCluster() *ForwardProxyCluster {
p := &ForwardProxyCluster{}
2024-04-12 18:23:18 -06:00
atomic.StoreInt32(&p.currentProxyAll, 0)
atomic.StoreInt32(&p.currentProxyOurs, 0)
atomic.StoreInt32(&p.currentProxyAllWithBroken, 0)
2024-04-12 01:26:45 -06:00
p.BalancerOnline.Add(1)
return p
}
2024-04-12 18:23:18 -06:00
func (p *ForwardProxyCluster) cycleProxy(validProxies []string, currentProxy *int32) string {
2024-04-12 01:26:45 -06:00
// Just round robin
2024-04-12 18:23:18 -06:00
currProxy := atomic.LoadInt32(currentProxy)
downstreamProxy := validProxies[currProxy]
newCurrentProxy := (currProxy + 1) % int32(len(validProxies))
atomic.StoreInt32(currentProxy, newCurrentProxy)
2024-04-12 01:26:45 -06:00
return downstreamProxy
}
2024-04-12 18:23:18 -06:00
func (p *ForwardProxyCluster) getProxyFromAll() string {
p.mu.RLock()
defer p.mu.RUnlock()
validProxies := removeDuplicates(append(p.ourOnlineProxies, p.thirdpartyOnlineProxies...))
return p.cycleProxy(validProxies, &p.currentProxyAll)
}
func (p *ForwardProxyCluster) getProxyFromOurs() string {
p.mu.RLock()
defer p.mu.RUnlock()
validProxies := p.ourOnlineProxies
return p.cycleProxy(validProxies, &p.currentProxyOurs)
}
func (p *ForwardProxyCluster) getProxyFromAllWithBroken() string {
p.mu.RLock()
defer p.mu.RUnlock()
validProxies := removeDuplicates(slices.Concat(p.ourOnlineProxies, p.thirdpartyBrokenProxies, p.thirdpartyOnlineProxies))
return p.cycleProxy(validProxies, &p.currentProxyAllWithBroken)
}