2018-08-11 11:46:10 +08:00
|
|
|
package strategy
|
2017-07-13 21:55:41 +08:00
|
|
|
|
2017-08-23 16:35:39 +08:00
|
|
|
import (
|
2018-06-26 16:15:48 +08:00
|
|
|
"github.com/nadoo/glider/common/log"
|
|
|
|
"github.com/nadoo/glider/proxy"
|
2017-08-23 16:35:39 +08:00
|
|
|
)
|
|
|
|
|
2018-08-23 00:01:31 +08:00
|
|
|
// Checker is an interface of forwarder checker
|
|
|
|
type Checker interface {
|
|
|
|
Check()
|
|
|
|
}
|
|
|
|
|
2018-08-11 11:46:10 +08:00
|
|
|
// Config of strategy
|
|
|
|
type Config struct {
|
2018-08-10 19:03:30 +08:00
|
|
|
Strategy string
|
|
|
|
CheckWebSite string
|
|
|
|
CheckInterval int
|
2018-08-12 21:40:22 +08:00
|
|
|
MaxFailures int
|
2018-08-20 22:23:00 +08:00
|
|
|
IntFace string
|
2018-08-10 19:03:30 +08:00
|
|
|
}
|
|
|
|
|
2018-08-11 11:46:10 +08:00
|
|
|
// NewDialer returns a new strategy dialer
|
|
|
|
func NewDialer(s []string, c *Config) proxy.Dialer {
|
2018-08-10 19:03:30 +08:00
|
|
|
var fwdrs []*proxy.Forwarder
|
|
|
|
for _, chain := range s {
|
2018-08-20 22:23:00 +08:00
|
|
|
fwdr, err := proxy.ForwarderFromURL(chain, c.IntFace)
|
2018-08-10 19:03:30 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
2018-08-23 00:01:31 +08:00
|
|
|
fwdr.SetMaxFailures(uint32(c.MaxFailures))
|
2018-08-10 19:03:30 +08:00
|
|
|
fwdrs = append(fwdrs, fwdr)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(fwdrs) == 0 {
|
2018-08-20 22:23:00 +08:00
|
|
|
d, err := proxy.NewDirect(c.IntFace)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
return d
|
2018-01-13 20:08:49 +08:00
|
|
|
}
|
|
|
|
|
2018-08-10 19:03:30 +08:00
|
|
|
if len(fwdrs) == 1 {
|
|
|
|
return fwdrs[0]
|
2018-01-13 20:08:49 +08:00
|
|
|
}
|
|
|
|
|
2018-06-26 16:15:48 +08:00
|
|
|
var dialer proxy.Dialer
|
2018-08-10 19:03:30 +08:00
|
|
|
switch c.Strategy {
|
2018-01-13 20:08:49 +08:00
|
|
|
case "rr":
|
2018-08-10 19:03:30 +08:00
|
|
|
dialer = newRRDialer(fwdrs, c.CheckWebSite, c.CheckInterval)
|
2018-06-26 16:15:48 +08:00
|
|
|
log.F("forward to remote servers in round robin mode.")
|
2018-01-13 20:08:49 +08:00
|
|
|
case "ha":
|
2018-08-10 19:03:30 +08:00
|
|
|
dialer = newHADialer(fwdrs, c.CheckWebSite, c.CheckInterval)
|
2018-06-26 16:15:48 +08:00
|
|
|
log.F("forward to remote servers in high availability mode.")
|
2018-08-14 19:33:18 +08:00
|
|
|
case "lha":
|
|
|
|
dialer = newLHADialer(fwdrs, c.CheckWebSite, c.CheckInterval)
|
|
|
|
log.F("forward to remote servers in latency based high availability mode.")
|
2018-08-24 18:45:57 +08:00
|
|
|
case "dh":
|
|
|
|
dialer = newDHDialer(fwdrs, c.CheckWebSite, c.CheckInterval)
|
|
|
|
log.F("forward to remote servers in destination hashing mode.")
|
2018-01-13 20:08:49 +08:00
|
|
|
default:
|
2018-08-10 19:03:30 +08:00
|
|
|
log.F("not supported forward mode '%s', just use the first forward server.", c.Strategy)
|
|
|
|
dialer = fwdrs[0]
|
2017-07-29 21:31:01 +08:00
|
|
|
}
|
|
|
|
|
2017-08-23 16:35:39 +08:00
|
|
|
return dialer
|
2017-07-29 21:31:01 +08:00
|
|
|
}
|