Feature: add experimental provider

This commit is contained in:
Dreamacro
2019-12-08 12:17:24 +08:00
parent 4d7096f451
commit c427bc89ef
33 changed files with 1247 additions and 620 deletions

View File

@ -0,0 +1,53 @@
package provider
import (
"context"
"time"
C "github.com/Dreamacro/clash/constant"
)
const (
defaultURLTestTimeout = time.Second * 5
)
type HealthCheckOption struct {
URL string
Interval uint
}
type healthCheck struct {
url string
proxies []C.Proxy
ticker *time.Ticker
}
func (hc *healthCheck) process() {
go hc.check()
for range hc.ticker.C {
hc.check()
}
}
func (hc *healthCheck) check() {
ctx, cancel := context.WithTimeout(context.Background(), defaultURLTestTimeout)
for _, proxy := range hc.proxies {
go proxy.URLTest(ctx, hc.url)
}
<-ctx.Done()
cancel()
}
func (hc *healthCheck) close() {
hc.ticker.Stop()
}
func newHealthCheck(proxies []C.Proxy, url string, interval uint) *healthCheck {
ticker := time.NewTicker(time.Duration(interval) * time.Second)
return &healthCheck{
proxies: proxies,
url: url,
ticker: ticker,
}
}

View File

@ -0,0 +1,60 @@
package provider
import (
"errors"
"fmt"
"time"
"github.com/Dreamacro/clash/common/structure"
C "github.com/Dreamacro/clash/constant"
)
var (
errVehicleType = errors.New("unsupport vehicle type")
)
type healthCheckSchema struct {
Enable bool `provider:"enable"`
URL string `provider:"url"`
Interval int `provider:"interval"`
}
type proxyProviderSchema struct {
Type string `provider:"type"`
Path string `provider:"path"`
URL string `provider:"url,omitempty"`
Interval int `provider:"interval,omitempty"`
HealthCheck healthCheckSchema `provider:"health-check,omitempty"`
}
func ParseProxyProvider(name string, mapping map[string]interface{}) (ProxyProvider, error) {
decoder := structure.NewDecoder(structure.Option{TagName: "provider", WeaklyTypedInput: true})
schema := &proxyProviderSchema{}
if err := decoder.Decode(mapping, schema); err != nil {
return nil, err
}
var healthCheckOption *HealthCheckOption
if schema.HealthCheck.Enable {
healthCheckOption = &HealthCheckOption{
URL: schema.HealthCheck.URL,
Interval: uint(schema.HealthCheck.Interval),
}
}
path := C.Path.Reslove(schema.Path)
var vehicle Vehicle
switch schema.Type {
case "file":
vehicle = NewFileVehicle(path)
case "http":
vehicle = NewHTTPVehicle(schema.URL, path)
default:
return nil, fmt.Errorf("%w: %s", errVehicleType, schema.Type)
}
interval := time.Duration(uint(schema.Interval)) * time.Second
return NewProxySetProvider(name, interval, vehicle, healthCheckOption), nil
}

View File

@ -0,0 +1,293 @@
package provider
import (
"bytes"
"crypto/md5"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"sync"
"time"
"github.com/Dreamacro/clash/adapters/outbound"
C "github.com/Dreamacro/clash/constant"
"github.com/Dreamacro/clash/log"
"gopkg.in/yaml.v2"
)
const (
ReservedName = "default"
fileMode = 0666
)
// Provider Type
const (
Proxy ProviderType = iota
Rule
)
// ProviderType defined
type ProviderType int
func (pt ProviderType) String() string {
switch pt {
case Proxy:
return "Proxy"
case Rule:
return "Rule"
default:
return "Unknown"
}
}
// Provider interface
type Provider interface {
Name() string
VehicleType() VehicleType
Type() ProviderType
Initial() error
Reload() error
Destroy() error
}
// ProxyProvider interface
type ProxyProvider interface {
Provider
Proxies() []C.Proxy
}
type ProxySchema struct {
Proxies []map[string]interface{} `yaml:"proxies"`
}
type ProxySetProvider struct {
name string
vehicle Vehicle
hash [16]byte
proxies []C.Proxy
healthCheck *healthCheck
healthCheckOption *HealthCheckOption
ticker *time.Ticker
// mux for avoiding creating new goroutines when pulling
mux sync.Mutex
}
func (pp *ProxySetProvider) Name() string {
return pp.name
}
func (pp *ProxySetProvider) Reload() error {
return nil
}
func (pp *ProxySetProvider) Destroy() error {
pp.mux.Lock()
defer pp.mux.Unlock()
if pp.healthCheck != nil {
pp.healthCheck.close()
pp.healthCheck = nil
}
if pp.ticker != nil {
pp.ticker.Stop()
}
return nil
}
func (pp *ProxySetProvider) Initial() error {
var buf []byte
var err error
if _, err := os.Stat(pp.vehicle.Path()); err == nil {
buf, err = ioutil.ReadFile(pp.vehicle.Path())
} else {
buf, err = pp.vehicle.Read()
}
if err != nil {
return err
}
proxies, err := pp.parse(buf)
if err != nil {
return err
}
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
return err
}
pp.hash = md5.Sum(buf)
pp.setProxies(proxies)
// pull proxies automatically
if pp.ticker != nil {
go pp.pullLoop()
}
return nil
}
func (pp *ProxySetProvider) VehicleType() VehicleType {
return pp.vehicle.Type()
}
func (pp *ProxySetProvider) Type() ProviderType {
return Proxy
}
func (pp *ProxySetProvider) Proxies() []C.Proxy {
return pp.proxies
}
func (pp *ProxySetProvider) pullLoop() {
for range pp.ticker.C {
if err := pp.pull(); err != nil {
log.Warnln("[Provider] %s pull error: %s", pp.Name(), err.Error())
}
}
}
func (pp *ProxySetProvider) pull() error {
buf, err := pp.vehicle.Read()
if err != nil {
return err
}
hash := md5.Sum(buf)
if bytes.Equal(pp.hash[:], hash[:]) {
log.Debugln("[Provider] %s's proxies doesn't change", pp.Name())
return nil
}
proxies, err := pp.parse(buf)
if err != nil {
return err
}
log.Infoln("[Provider] %s's proxies update", pp.Name())
if err := ioutil.WriteFile(pp.vehicle.Path(), buf, fileMode); err != nil {
return err
}
pp.hash = hash
pp.setProxies(proxies)
return nil
}
func (pp *ProxySetProvider) parse(buf []byte) ([]C.Proxy, error) {
schema := &ProxySchema{}
if err := yaml.Unmarshal(buf, schema); err != nil {
return nil, err
}
if schema.Proxies == nil {
return nil, errors.New("File must have a `proxies` field")
}
proxies := []C.Proxy{}
for idx, mapping := range schema.Proxies {
proxy, err := outbound.ParseProxy(mapping)
if err != nil {
return nil, fmt.Errorf("Proxy %d error: %w", idx, err)
}
proxies = append(proxies, proxy)
}
return proxies, nil
}
func (pp *ProxySetProvider) setProxies(proxies []C.Proxy) {
pp.proxies = proxies
if pp.healthCheckOption != nil {
pp.mux.Lock()
if pp.healthCheck != nil {
pp.healthCheck.close()
pp.healthCheck = newHealthCheck(proxies, pp.healthCheckOption.URL, pp.healthCheckOption.Interval)
go pp.healthCheck.process()
}
pp.mux.Unlock()
}
}
func NewProxySetProvider(name string, interval time.Duration, vehicle Vehicle, option *HealthCheckOption) *ProxySetProvider {
var ticker *time.Ticker
if interval != 0 {
ticker = time.NewTicker(interval)
}
return &ProxySetProvider{
name: name,
vehicle: vehicle,
proxies: []C.Proxy{},
healthCheckOption: option,
ticker: ticker,
}
}
type CompatibleProvier struct {
name string
healthCheck *healthCheck
proxies []C.Proxy
}
func (cp *CompatibleProvier) Name() string {
return cp.name
}
func (cp *CompatibleProvier) Reload() error {
return nil
}
func (cp *CompatibleProvier) Destroy() error {
if cp.healthCheck != nil {
cp.healthCheck.close()
}
return nil
}
func (cp *CompatibleProvier) Initial() error {
if cp.healthCheck != nil {
go cp.healthCheck.process()
}
return nil
}
func (cp *CompatibleProvier) VehicleType() VehicleType {
return Compatible
}
func (cp *CompatibleProvier) Type() ProviderType {
return Proxy
}
func (cp *CompatibleProvier) Proxies() []C.Proxy {
return cp.proxies
}
func NewCompatibleProvier(name string, proxies []C.Proxy, option *HealthCheckOption) (*CompatibleProvier, error) {
if len(proxies) == 0 {
return nil, errors.New("Provider need one proxy at least")
}
var hc *healthCheck
if option != nil {
if _, err := url.Parse(option.URL); err != nil {
return nil, fmt.Errorf("URL format error: %w", err)
}
hc = newHealthCheck(proxies, option.URL, option.Interval)
}
return &CompatibleProvier{
name: name,
proxies: proxies,
healthCheck: hc,
}, nil
}

View File

@ -0,0 +1,109 @@
package provider
import (
"context"
"io/ioutil"
"net/http"
"time"
)
// Vehicle Type
const (
File VehicleType = iota
HTTP
Compatible
)
// VehicleType defined
type VehicleType int
func (v VehicleType) String() string {
switch v {
case File:
return "File"
case HTTP:
return "HTTP"
case Compatible:
return "Compatible"
default:
return "Unknown"
}
}
type Vehicle interface {
Read() ([]byte, error)
Path() string
Type() VehicleType
}
type FileVehicle struct {
path string
}
func (f *FileVehicle) Type() VehicleType {
return File
}
func (f *FileVehicle) Path() string {
return f.path
}
func (f *FileVehicle) Read() ([]byte, error) {
return ioutil.ReadFile(f.path)
}
func NewFileVehicle(path string) *FileVehicle {
return &FileVehicle{path: path}
}
type HTTPVehicle struct {
url string
path string
}
func (h *HTTPVehicle) Type() VehicleType {
return HTTP
}
func (h *HTTPVehicle) Path() string {
return h.path
}
func (h *HTTPVehicle) Read() ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
req, err := http.NewRequest(http.MethodGet, h.url, nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
transport := &http.Transport{
// from http.DefaultTransport
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
client := http.Client{Transport: transport}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := ioutil.WriteFile(h.path, buf, fileMode); err != nil {
return nil, err
}
return buf, nil
}
func NewHTTPVehicle(url string, path string) *HTTPVehicle {
return &HTTPVehicle{url, path}
}