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