add weight for tunnel connector

This commit is contained in:
ginuerzh
2024-01-27 23:31:23 +08:00
parent 43d37d0a5f
commit b5b39de62c
7 changed files with 45 additions and 14 deletions

View File

@ -30,6 +30,8 @@ func (h *tunnelHandler) handleBind(ctx context.Context, conn net.Conn, network,
if network == "udp" {
connectorID = relay.NewUDPConnectorID(uuid[:])
}
// copy weight from tunnelID
connectorID = connectorID.SetWeight(tunnelID.Weight())
v := md5.Sum([]byte(tunnelID.String()))
endpoint := hex.EncodeToString(v[:8])

View File

@ -3,16 +3,20 @@ package tunnel
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/go-gost/core/logger"
"github.com/go-gost/core/sd"
"github.com/go-gost/relay"
"github.com/go-gost/x/internal/util/mux"
"github.com/go-gost/x/selector"
"github.com/google/uuid"
)
const (
MaxWeight uint8 = 0xff
)
type Connector struct {
id relay.ConnectorID
tid relay.TunnelID
@ -67,11 +71,11 @@ type Tunnel struct {
id relay.TunnelID
connectors []*Connector
t time.Time
n uint64
close chan struct{}
mu sync.RWMutex
sd sd.SD
ttl time.Duration
rw *selector.RandomWeighted[*Connector]
}
func NewTunnel(node string, tid relay.TunnelID, ttl time.Duration) *Tunnel {
@ -81,6 +85,7 @@ func NewTunnel(node string, tid relay.TunnelID, ttl time.Duration) *Tunnel {
t: time.Now(),
close: make(chan struct{}),
ttl: ttl,
rw: selector.NewRandomWeighted[*Connector](),
}
if t.ttl <= 0 {
t.ttl = defaultTTL
@ -112,21 +117,39 @@ func (t *Tunnel) GetConnector(network string) *Connector {
t.mu.RLock()
defer t.mu.RUnlock()
rw := t.rw
rw.Reset()
found := false
var connectors []*Connector
for _, c := range t.connectors {
if c.Session().IsClosed() {
continue
}
weight := c.ID().Weight()
if weight == 0 {
weight = 1
}
if network == "udp" && c.id.IsUDP() ||
network != "udp" && !c.id.IsUDP() {
connectors = append(connectors, c)
if weight == MaxWeight && !found {
connectors = nil
found = true
}
if weight == MaxWeight || !found {
connectors = append(connectors, c)
rw.Add(c, int(weight))
}
}
}
if len(connectors) == 0 {
return nil
}
n := atomic.AddUint64(&t.n, 1) - 1
return connectors[n%uint64(len(connectors))]
return rw.Next()
}
func (t *Tunnel) CloseOnIdle() bool {