add reload and plugin support for hop

This commit is contained in:
ginuerzh
2023-09-28 21:04:15 +08:00
parent ddc3c9392e
commit ea585fc25d
88 changed files with 2208 additions and 1538 deletions

307
hop/hop.go Normal file
View File

@ -0,0 +1,307 @@
package hop
import (
"bytes"
"context"
"encoding/json"
"io"
"net"
"strings"
"sync"
"time"
"github.com/go-gost/core/bypass"
"github.com/go-gost/core/chain"
"github.com/go-gost/core/hop"
"github.com/go-gost/core/logger"
"github.com/go-gost/core/selector"
"github.com/go-gost/x/config"
node_parser "github.com/go-gost/x/config/parsing/node"
"github.com/go-gost/x/internal/loader"
)
type options struct {
name string
nodes []*chain.Node
bypass bypass.Bypass
selector selector.Selector[*chain.Node]
fileLoader loader.Loader
redisLoader loader.Loader
httpLoader loader.Loader
period time.Duration
logger logger.Logger
}
type Option func(*options)
func NameOption(name string) Option {
return func(o *options) {
o.name = name
}
}
func NodeOption(nodes ...*chain.Node) Option {
return func(o *options) {
o.nodes = nodes
}
}
func BypassOption(bp bypass.Bypass) Option {
return func(o *options) {
o.bypass = bp
}
}
func SelectorOption(s selector.Selector[*chain.Node]) Option {
return func(o *options) {
o.selector = s
}
}
func ReloadPeriodOption(period time.Duration) Option {
return func(opts *options) {
opts.period = period
}
}
func FileLoaderOption(fileLoader loader.Loader) Option {
return func(opts *options) {
opts.fileLoader = fileLoader
}
}
func RedisLoaderOption(redisLoader loader.Loader) Option {
return func(opts *options) {
opts.redisLoader = redisLoader
}
}
func HTTPLoaderOption(httpLoader loader.Loader) Option {
return func(opts *options) {
opts.httpLoader = httpLoader
}
}
func LoggerOption(logger logger.Logger) Option {
return func(opts *options) {
opts.logger = logger
}
}
type chainHop struct {
nodes []*chain.Node
mu sync.RWMutex
cancelFunc context.CancelFunc
options options
}
func NewHop(opts ...Option) hop.Hop {
var options options
for _, opt := range opts {
if opt != nil {
opt(&options)
}
}
ctx, cancel := context.WithCancel(context.TODO())
p := &chainHop{
cancelFunc: cancel,
options: options,
}
if err := p.reload(ctx); err != nil {
options.logger.Warnf("reload: %v", err)
}
if p.options.period > 0 {
go p.periodReload(ctx)
}
return p
}
func (p *chainHop) Nodes() []*chain.Node {
if p == nil {
return nil
}
p.mu.RLock()
defer p.mu.RUnlock()
return p.nodes
}
func (p *chainHop) Select(ctx context.Context, opts ...hop.SelectOption) *chain.Node {
var options hop.SelectOptions
for _, opt := range opts {
opt(&options)
}
ns := p.Nodes()
if len(ns) == 0 {
return nil
}
// hop level bypass
if p.options.bypass != nil &&
p.options.bypass.Contains(ctx, options.Addr) {
return nil
}
filters := ns
if host := options.Host; host != "" {
filters = nil
if v, _, _ := net.SplitHostPort(host); v != "" {
host = v
}
var nodes []*chain.Node
for _, node := range ns {
if node == nil {
continue
}
vhost := node.Options().Host
if vhost == "" {
nodes = append(nodes, node)
continue
}
if vhost == host ||
vhost[0] == '.' && strings.HasSuffix(host, vhost[1:]) {
filters = append(filters, node)
}
}
if len(filters) == 0 {
filters = nodes
}
} else if protocol := options.Protocol; protocol != "" {
filters = nil
for _, node := range ns {
if node == nil {
continue
}
if node.Options().Protocol == protocol {
filters = append(filters, node)
}
}
}
var nodes []*chain.Node
for _, node := range filters {
if node == nil {
continue
}
// node level bypass
if node.Options().Bypass != nil &&
node.Options().Bypass.Contains(ctx, options.Addr) {
continue
}
nodes = append(nodes, node)
}
if len(nodes) == 0 {
return nil
}
if s := p.options.selector; s != nil {
return s.Select(ctx, nodes...)
}
return nodes[0]
}
func (p *chainHop) periodReload(ctx context.Context) error {
period := p.options.period
if period < time.Second {
period = time.Second
}
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-ticker.C:
if err := p.reload(ctx); err != nil {
p.options.logger.Warnf("reload: %v", err)
// return err
}
p.options.logger.Debug("hop reload done")
case <-ctx.Done():
return ctx.Err()
}
}
}
func (p *chainHop) reload(ctx context.Context) (err error) {
nodes := p.options.nodes
nl, err := p.load(ctx)
nodes = append(nodes, nl...)
p.mu.Lock()
defer p.mu.Unlock()
p.nodes = nodes
return
}
func (p *chainHop) load(ctx context.Context) (nodes []*chain.Node, err error) {
if p.options.fileLoader != nil {
r, er := p.options.fileLoader.Load(ctx)
if er != nil {
p.options.logger.Warnf("file loader: %v", er)
}
nodes, _ = p.parseNode(r)
}
if p.options.redisLoader != nil {
if lister, ok := p.options.redisLoader.(loader.Lister); ok {
list, er := lister.List(ctx)
if er != nil {
p.options.logger.Warnf("redis loader: %v", er)
}
for _, s := range list {
nl, _ := p.parseNode(bytes.NewReader([]byte(s)))
nodes = append(nodes, nl...)
}
}
}
if p.options.httpLoader != nil {
r, er := p.options.httpLoader.Load(ctx)
if er != nil {
p.options.logger.Warnf("http loader: %v", er)
}
if node, _ := p.parseNode(r); node != nil {
nodes = append(nodes, node...)
}
}
p.options.logger.Debugf("load items %d", len(nodes))
return
}
func (p *chainHop) parseNode(r io.Reader) ([]*chain.Node, error) {
var ncs []*config.NodeConfig
if err := json.NewDecoder(r).Decode(&ncs); err != nil {
return nil, err
}
var nodes []*chain.Node
for _, nc := range ncs {
if nc == nil {
continue
}
node, err := node_parser.ParseNode(p.options.name, nc)
if err != nil {
return nodes, err
}
nodes = append(nodes, node)
}
return nodes, nil
}
func (p *chainHop) Close() error {
p.cancelFunc()
if p.options.fileLoader != nil {
p.options.fileLoader.Close()
}
if p.options.redisLoader != nil {
p.options.redisLoader.Close()
}
return nil
}

204
hop/plugin.go Normal file
View File

@ -0,0 +1,204 @@
package hop
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"github.com/go-gost/core/chain"
"github.com/go-gost/core/hop"
"github.com/go-gost/core/logger"
"github.com/go-gost/plugin/hop/proto"
"github.com/go-gost/x/config"
node_parser "github.com/go-gost/x/config/parsing/node"
"github.com/go-gost/x/internal/plugin"
auth_util "github.com/go-gost/x/internal/util/auth"
"google.golang.org/grpc"
)
type grpcPlugin struct {
name string
conn grpc.ClientConnInterface
client proto.HopClient
log logger.Logger
}
// NewGRPCPlugin creates a Hop plugin based on gRPC.
func NewGRPCPlugin(name string, addr string, opts ...plugin.Option) hop.Hop{
var options plugin.Options
for _, opt := range opts {
opt(&options)
}
log := logger.Default().WithFields(map[string]any{
"kind": "hop",
"hop": name,
})
conn, err := plugin.NewGRPCConn(addr, &options)
if err != nil {
log.Error(err)
}
p := &grpcPlugin{
name: name,
conn: conn,
log: log,
}
if conn != nil {
p.client = proto.NewHopClient(conn)
}
return p
}
func (p *grpcPlugin) Select(ctx context.Context, opts ...hop.SelectOption) *chain.Node {
if p.client == nil {
return nil
}
var options hop.SelectOptions
for _, opt := range opts {
opt(&options)
}
r, err := p.client.Select(ctx,
&proto.SelectRequest{
Addr: options.Addr,
Host: options.Host,
Client: string(auth_util.IDFromContext(ctx)),
})
if err != nil {
p.log.Error(err)
return nil
}
if r.Node == nil {
return nil
}
var cfg config.NodeConfig
if err := json.NewDecoder(bytes.NewReader(r.Node)).Decode(&cfg); err != nil {
p.log.Error(err)
return nil
}
node, err := node_parser.ParseNode(p.name, &cfg)
if err != nil {
p.log.Error(err)
return nil
}
return node
}
func (p *grpcPlugin) Close() error {
if closer, ok := p.conn.(io.Closer); ok {
return closer.Close()
}
return nil
}
type httpPluginRequest struct {
Network string `json:"network"`
Addr string `json:"addr"`
Host string `json:"host"`
Client string `json:"client"`
}
type httpPluginResponse struct {
Node string `json:"node"`
}
type httpPlugin struct {
name string
url string
client *http.Client
header http.Header
log logger.Logger
}
// NewHTTPPlugin creates an Hop plugin based on HTTP.
func NewHTTPPlugin(name string, url string, opts ...plugin.Option) hop.Hop{
var options plugin.Options
for _, opt := range opts {
opt(&options)
}
return &httpPlugin{
name: name,
url: url,
client: plugin.NewHTTPClient(&options),
header: options.Header,
log: logger.Default().WithFields(map[string]any{
"kind": "hop",
"hop": name,
}),
}
}
func (p *httpPlugin) Select(ctx context.Context, opts ...hop.SelectOption) *chain.Node {
if p.client == nil {
return nil
}
var options hop.SelectOptions
for _, opt := range opts {
opt(&options)
}
rb := httpPluginRequest{
Addr: options.Addr,
Host: options.Host,
Client: string(auth_util.IDFromContext(ctx)),
}
v, err := json.Marshal(&rb)
if err != nil {
p.log.Error(err)
return nil
}
req, err := http.NewRequest(http.MethodPost, p.url, bytes.NewReader(v))
if err != nil {
p.log.Error(err)
return nil
}
if p.header != nil {
req.Header = p.header.Clone()
}
req.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(req)
if err != nil {
p.log.Error(err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
p.log.Error(resp.Status)
return nil
}
res := httpPluginResponse{}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
p.log.Error(resp.Status)
return nil
}
if res.Node == "" {
return nil
}
var cfg config.NodeConfig
if err := json.NewDecoder(bytes.NewReader([]byte(res.Node))).Decode(&cfg); err != nil {
p.log.Error(err)
return nil
}
node, err := node_parser.ParseNode(p.name, &cfg)
if err != nil {
p.log.Error(err)
return nil
}
return node
}