1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-15 16:56:08 -05:00
v2fly/common/protocol/server_picker.go

91 lines
1.4 KiB
Go
Raw Normal View History

2016-07-24 17:22:46 -04:00
package protocol
import (
"sync"
)
type ServerList struct {
sync.RWMutex
servers []*ServerSpec
}
func NewServerList() *ServerList {
return &ServerList{}
}
2016-11-27 15:39:09 -05:00
func (v *ServerList) AddServer(server *ServerSpec) {
v.Lock()
defer v.Unlock()
2016-07-24 17:22:46 -04:00
2016-11-27 15:39:09 -05:00
v.servers = append(v.servers, server)
2016-07-24 17:22:46 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *ServerList) Size() uint32 {
v.RLock()
defer v.RUnlock()
2016-07-24 17:22:46 -04:00
2016-11-27 15:39:09 -05:00
return uint32(len(v.servers))
2016-07-24 17:22:46 -04:00
}
2016-11-27 15:39:09 -05:00
func (v *ServerList) GetServer(idx uint32) *ServerSpec {
v.RLock()
defer v.RUnlock()
2016-07-24 17:22:46 -04:00
for {
2016-11-27 15:39:09 -05:00
if idx >= uint32(len(v.servers)) {
2016-07-24 17:22:46 -04:00
return nil
}
2016-11-27 15:39:09 -05:00
server := v.servers[idx]
2016-07-24 17:22:46 -04:00
if !server.IsValid() {
2016-11-27 15:39:09 -05:00
v.RemoveServer(idx)
2016-07-24 17:22:46 -04:00
continue
}
return server
}
}
2016-08-24 05:17:42 -04:00
// Private: Visible for testing.
2016-11-27 15:39:09 -05:00
func (v *ServerList) RemoveServer(idx uint32) {
n := len(v.servers)
v.servers[idx] = v.servers[n-1]
v.servers = v.servers[:n-1]
2016-07-24 17:22:46 -04:00
}
type ServerPicker interface {
PickServer() *ServerSpec
}
type RoundRobinServerPicker struct {
sync.Mutex
serverlist *ServerList
nextIndex uint32
}
func NewRoundRobinServerPicker(serverlist *ServerList) *RoundRobinServerPicker {
return &RoundRobinServerPicker{
serverlist: serverlist,
nextIndex: 0,
}
}
2016-11-27 15:39:09 -05:00
func (v *RoundRobinServerPicker) PickServer() *ServerSpec {
v.Lock()
defer v.Unlock()
2016-07-24 17:22:46 -04:00
2016-11-27 15:39:09 -05:00
next := v.nextIndex
server := v.serverlist.GetServer(next)
2016-07-24 17:22:46 -04:00
if server == nil {
next = 0
2016-11-27 15:39:09 -05:00
server = v.serverlist.GetServer(0)
2016-07-24 17:22:46 -04:00
}
next++
2016-11-27 15:39:09 -05:00
if next >= v.serverlist.Size() {
2016-07-24 17:22:46 -04:00
next = 0
}
2016-11-27 15:39:09 -05:00
v.nextIndex = next
2016-07-24 17:22:46 -04:00
return server
}