2015-05-03 00:20:36 -05:00
|
|
|
package proxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2015-05-04 12:04:17 -05:00
|
|
|
type StaticUpstream struct {
|
|
|
|
From string
|
2015-05-03 00:20:36 -05:00
|
|
|
Hosts HostPool
|
|
|
|
Policy Policy
|
|
|
|
|
|
|
|
FailTimeout time.Duration
|
|
|
|
MaxFails int32
|
|
|
|
HealthCheck struct {
|
|
|
|
Path string
|
|
|
|
Interval time.Duration
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-04 12:04:17 -05:00
|
|
|
func (u *StaticUpstream) from() string {
|
|
|
|
return u.From
|
2015-05-03 00:20:36 -05:00
|
|
|
}
|
|
|
|
|
2015-05-04 12:04:17 -05:00
|
|
|
func (u *StaticUpstream) healthCheck() {
|
2015-05-03 00:20:36 -05:00
|
|
|
for _, host := range u.Hosts {
|
|
|
|
hostUrl := host.Name + u.HealthCheck.Path
|
|
|
|
if r, err := http.Get(hostUrl); err == nil {
|
|
|
|
io.Copy(ioutil.Discard, r.Body)
|
|
|
|
r.Body.Close()
|
|
|
|
host.Unhealthy = r.StatusCode < 200 || r.StatusCode >= 400
|
|
|
|
} else {
|
|
|
|
host.Unhealthy = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-04 12:04:17 -05:00
|
|
|
func (u *StaticUpstream) HealthCheckWorker(stop chan struct{}) {
|
2015-05-03 00:20:36 -05:00
|
|
|
ticker := time.NewTicker(u.HealthCheck.Interval)
|
|
|
|
u.healthCheck()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
u.healthCheck()
|
|
|
|
case <-stop:
|
|
|
|
// TODO: the library should provide a stop channel and global
|
|
|
|
// waitgroup to allow goroutines started by plugins a chance
|
|
|
|
// to clean themselves up.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-04 12:04:17 -05:00
|
|
|
func (u *StaticUpstream) Select() *UpstreamHost {
|
2015-05-03 00:20:36 -05:00
|
|
|
pool := u.Hosts
|
|
|
|
if len(pool) == 1 {
|
|
|
|
if pool[0].Down() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return pool[0]
|
|
|
|
}
|
|
|
|
allDown := true
|
|
|
|
for _, host := range pool {
|
|
|
|
if !host.Down() {
|
|
|
|
allDown = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if allDown {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if u.Policy == nil {
|
|
|
|
return (&Random{}).Select(pool)
|
|
|
|
} else {
|
|
|
|
return u.Policy.Select(pool)
|
|
|
|
}
|
|
|
|
}
|