2019-12-08 12:17:24 +08:00
|
|
|
package provider
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
defaultURLTestTimeout = time.Second * 5
|
|
|
|
)
|
|
|
|
|
|
|
|
type HealthCheckOption struct {
|
|
|
|
URL string
|
|
|
|
Interval uint
|
|
|
|
}
|
|
|
|
|
2019-12-26 18:41:06 +08:00
|
|
|
type HealthCheck struct {
|
|
|
|
url string
|
|
|
|
proxies []C.Proxy
|
|
|
|
interval uint
|
|
|
|
done chan struct{}
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
|
2019-12-26 18:41:06 +08:00
|
|
|
func (hc *HealthCheck) process() {
|
|
|
|
ticker := time.NewTicker(time.Duration(hc.interval) * time.Second)
|
|
|
|
|
2019-12-08 12:17:24 +08:00
|
|
|
go hc.check()
|
2019-12-26 18:41:06 +08:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
hc.check()
|
|
|
|
case <-hc.done:
|
|
|
|
ticker.Stop()
|
|
|
|
return
|
|
|
|
}
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-26 18:41:06 +08:00
|
|
|
func (hc *HealthCheck) setProxy(proxies []C.Proxy) {
|
|
|
|
hc.proxies = proxies
|
|
|
|
}
|
|
|
|
|
|
|
|
func (hc *HealthCheck) auto() bool {
|
|
|
|
return hc.interval != 0
|
|
|
|
}
|
|
|
|
|
|
|
|
func (hc *HealthCheck) check() {
|
2019-12-08 12:17:24 +08:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
|
|
|
|
for _, proxy := range hc.proxies {
|
|
|
|
go proxy.URLTest(ctx, hc.url)
|
|
|
|
}
|
|
|
|
|
|
|
|
<-ctx.Done()
|
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
|
2019-12-26 18:41:06 +08:00
|
|
|
func (hc *HealthCheck) close() {
|
|
|
|
hc.done <- struct{}{}
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
|
2019-12-26 18:41:06 +08:00
|
|
|
func NewHealthCheck(proxies []C.Proxy, url string, interval uint) *HealthCheck {
|
|
|
|
return &HealthCheck{
|
|
|
|
proxies: proxies,
|
|
|
|
url: url,
|
|
|
|
interval: interval,
|
|
|
|
done: make(chan struct{}, 1),
|
2019-12-08 12:17:24 +08:00
|
|
|
}
|
|
|
|
}
|