feat: support customized plugin manager

This commit is contained in:
mzz2017 committed 2022-08-03 23:09:24 +08:00
1 parent 08ae5b6e33
commit c27ca4bf7c
16 files changed
+243 -44

No files matched your search

+9
View File
@@ -245,3 +245,12 @@ func HomeExpand(path string) (string, error) {
}
return filepath.Join(usr.HomeDir, path[1:]), nil
}
func HasAnyPrefix(s string, prefix []string) bool {
for _, p := range prefix {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
+1
View File
@@ -20,6 +20,7 @@ type Params struct {
V2rayAssetsDirectory string `id:"v2ray-assetsdir" desc:"v2ray-core assets directory for searching and downloading files like geoip.dat. This will override environment V2RAY_LOCATION_ASSET and XRAY_LOCATION_ASSET."`
TransparentHook string `id:"transparent-hook" desc:"the executable file to run in the transparent proxy life-cycle. v2rayA will pass in the --transparent-type (tproxy, redirect) and --stage (pre-start, post-start, pre-stop, post-stop) arguments."`
CoreHook string `id:"core-hook" desc:"the executable file to run in the v2ray-core life-cycle. v2rayA will pass in the --stage (pre-start, post-start, pre-stop, post-stop) argument."`
PluginManager string `id:"plugin-manager" desc:"the executable file to run in the v2ray-core life-cycle. v2rayA will pass in the --stage (pre-start, post-start, pre-stop, post-stop) argument."`
WebDir string `id:"webdir" desc:"v2rayA web files directory. use embedded files if not specify."`
VlessGrpcInboundCertKey []string `id:"vless-grpc-inbound-cert-key" desc:"Specify the certification path instead of automatically generating a self-signed certificate. Example: /etc/v2raya/grpc_certificate.crt,/etc/v2raya/grpc_private.key"`
IPV6Support string `id:"ipv6-support" default:"auto" desc:"Optional values: auto, on, off. Make sure your IPv6 network works fine before you turn it on."`
+1 -1
View File
@@ -126,7 +126,7 @@ func (h *HTTP) ExportToURL() string {
return u.String()
}
func (h *HTTP) NeedPlugin() bool {
func (h *HTTP) NeedPluginPort() bool {
return false
}
+1 -1
View File
@@ -112,7 +112,7 @@ func (p *PingTunnel) ExportToURL() string {
return U.String()
}
func (p *PingTunnel) NeedPlugin() bool {
func (p *PingTunnel) NeedPluginPort() bool {
return true
}
+125
View File
@@ -0,0 +1,125 @@
package serverObj
import (
"fmt"
jsoniter "github.com/json-iterator/go"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/coreObj"
"github.com/v2rayA/v2rayA/pkg/util/log"
"os/exec"
"strconv"
"strings"
)
var ErrUnsupportedPlugin = fmt.Errorf("unsupported plugin")
const PluginManagerScheme = "plugin-manager"
func init() {
FromLinkRegister(PluginManagerScheme, NewPlugin)
EmptyRegister(PluginManagerScheme, func() (ServerObj, error) {
return new(Plugin), nil
})
}
type Plugin struct {
Name string `json:"pm_name"`
Host string `json:"pm_add"`
Port string `json:"pm_port"`
ProtocolToShow string `json:"pm_protocol"`
Link string `json:"pm_link"`
Protocol string `json:"protocol"`
}
func NewPlugin(link string) (ServerObj, error) {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
b, err := exec.Command(pm,
"--stage=parse",
fmt.Sprintf("--link=%v", link),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
).CombinedOutput()
if err != nil {
log.Info("[PluginManager] failed to parse %v: %v", link, string(b))
return nil, err
}
nExpected := 4
fields := strings.SplitN(strings.TrimSpace(string(b)), ";", nExpected)
if len(fields) < nExpected {
return nil, fmt.Errorf("[PluginManager] insufficient return value: %v. Expected number: %v", fields, nExpected)
}
return &Plugin{
Name: fields[0],
Host: fields[1],
Port: fields[2],
ProtocolToShow: fields[3],
Link: link,
Protocol: PluginManagerScheme,
}, nil
}
return nil, ErrUnsupportedPlugin
}
func (v *Plugin) Configuration(info PriorInfo) (c Configuration, err error) {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
b, err := exec.Command(pm,
"--stage=configuration",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", info.PluginPort),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
).CombinedOutput()
sOut := strings.TrimSpace(string(b))
if err != nil {
return Configuration{}, fmt.Errorf("[PluginManager] Error when Configuration: %w: %v", err, sOut)
}
var core coreObj.OutboundObject
if err := jsoniter.UnmarshalFromString(sOut, &core); err != nil {
return Configuration{}, fmt.Errorf("[PluginManager] Error when Configuration: failed to parse json output")
}
core.Tag = info.Tag
return Configuration{
CoreOutbound: core,
PluginChain: "",
UDPSupport: true,
PluginManagerServerLink: v.Link,
}, nil
} else {
return Configuration{}, ErrUnsupportedPlugin
}
}
func (v *Plugin) ExportToURL() string {
if v.Link == "" {
log.Warn("You may need to re-import the node for PluginManager to take effect")
}
return v.Link
}
func (v *Plugin) NeedPluginPort() bool {
return true
}
func (v *Plugin) ProtoToShow() string {
return v.ProtocolToShow + "(plugin)"
}
func (v *Plugin) GetProtocol() string {
return v.ProtocolToShow
}
func (v *Plugin) GetHostname() string {
return v.Host
}
func (v *Plugin) GetPort() int {
p, _ := strconv.Atoi(v.Port)
return p
}
func (v *Plugin) GetName() string {
return v.Name
}
func (v *Plugin) SetName(name string) {
v.Name = name
}
+15 -5
View File
@@ -2,6 +2,7 @@ package serverObj
import (
"fmt"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/coreObj"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"net/url"
@@ -12,7 +13,7 @@ var InvalidParameterErr = fmt.Errorf("invalid parameters")
type ServerObj interface {
Configuration(info PriorInfo) (c Configuration, err error)
ExportToURL() string
NeedPlugin() bool
NeedPluginPort() bool
ProtoToShow() string
GetProtocol() string
GetHostname() string
@@ -22,10 +23,11 @@ type ServerObj interface {
}
type Configuration struct {
CoreOutbound coreObj.OutboundObject
ExtraOutbounds []coreObj.OutboundObject
PluginChain string // The first is a server plugin, and the others are client plugins. Split by ",".
UDPSupport bool
CoreOutbound coreObj.OutboundObject
ExtraOutbounds []coreObj.OutboundObject
PluginChain string // The first is a server plugin, and the others are client plugins. Split by ",".
UDPSupport bool
PluginManagerServerLink string
}
type PriorInfo struct {
@@ -64,6 +66,10 @@ func EmptyRegister(name string, creator EmptyCreator) {
func New(name string) (ServerObj, error) {
if creator, ok := emptyCreators[name]; ok {
return creator()
} else if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
// we do not support to override build-in protocols
creator := emptyCreators[PluginManagerScheme]
return creator()
} else {
return nil, fmt.Errorf("unsupported link type: %v", name)
}
@@ -71,6 +77,10 @@ func New(name string) (ServerObj, error) {
func NewFromLink(name string, link string) (ServerObj, error) {
if creator, ok := fromLinkCreators[name]; ok {
return creator(link)
} else if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
// we do not support to override build-in protocols
creator := fromLinkCreators[PluginManagerScheme]
return creator(link)
} else {
return nil, fmt.Errorf("unsupported link type: %v", name)
}
+1 -1
View File
@@ -229,7 +229,7 @@ func (s *Shadowsocks) ExportToURL() string {
return u.String()
}
func (s *Shadowsocks) NeedPlugin() bool {
func (s *Shadowsocks) NeedPluginPort() bool {
return len(s.Plugin.Name) > 0
}
+1 -1
View File
@@ -149,7 +149,7 @@ func (s *ShadowsocksR) ExportToURL() string {
)), "="))
}
func (s *ShadowsocksR) NeedPlugin() bool {
func (s *ShadowsocksR) NeedPluginPort() bool {
return true
}
+1 -1
View File
@@ -100,7 +100,7 @@ func (h *SOCKS) ExportToURL() string {
return u.String()
}
func (h *SOCKS) NeedPlugin() bool {
func (h *SOCKS) NeedPluginPort() bool {
return false
}
+1 -1
View File
@@ -186,7 +186,7 @@ func (t *Trojan) ExportToURL() string {
return u.String()
}
func (t *Trojan) NeedPlugin() bool {
func (t *Trojan) NeedPluginPort() bool {
return t.Protocol == "trojan-go"
}
+1 -1
View File
@@ -419,7 +419,7 @@ func (v *V2Ray) ExportToURL() string {
return ""
}
func (v *V2Ray) NeedPlugin() bool {
func (v *V2Ray) NeedPluginPort() bool {
return false
}
+33 -9
View File
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"github.com/shirou/gopsutil/v3/mem"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/serverObj"
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"github.com/v2rayA/v2rayA/core/v2ray/service"
@@ -28,7 +29,8 @@ type Process struct {
// mutex protect the proc
mutex sync.Mutex
proc *os.Process
procCancel func()
procCancel func() // cancel func for proc and pluginManagers
pluginManagers []*os.Process
template *Template
tag2WhichIndex map[string]int
}
@@ -54,6 +56,34 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
return nil, fmt.Errorf("%v", err)
}
go tmpl.ServePlugins()
pCtx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
// start PluginManagers
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
for _, v := range tmpl.PluginManagerInfoList {
arguments := []string{
pm,
"--stage=run",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", v.Port),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
}
proc, err := RunWithLog(pCtx, pm, arguments, "", os.Environ())
if err != nil {
// clean
for _, pm := range process.pluginManagers {
_ = pm.Kill()
}
process.pluginManagers = nil
return nil, fmt.Errorf("executing PluginManager [state: run, link: %v]: %w", v.Link, err)
}
process.pluginManagers = append(process.pluginManagers, proc)
}
}
defer func() {
if err != nil {
_ = tmpl.Close()
@@ -62,18 +92,15 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
if tmpl.API == nil {
log.Fatal("unexpected tmpl.API == nil")
}
ctx, cancel := context.WithCancel(context.Background())
process.procCancel = cancel
if err = prestart(); err != nil {
return nil, err
}
proc, err := StartCoreProcess(ctx)
proc, err := StartCoreProcess(pCtx)
if err != nil {
cancel()
return nil, err
}
if err = poststart(); err != nil {
cancel()
return nil, err
}
process.proc = proc
@@ -103,7 +130,6 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
for _, plu := range tmpl.Plugins {
_, port, err := net.SplitHostPort(plu.ListenAddr())
if err != nil {
cancel()
return nil, err
}
portList = append(portList, port)
@@ -117,14 +143,12 @@ func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (
continue
}
if unexpectedExiting {
cancel()
if log.Log.GetLevel() > log.ParseLevel("info") {
log.Error("some critical information may lost due to your log level")
}
return nil, fmt.Errorf("unexpected exiting: check the log for more information")
}
if time.Since(startTime) > 15*time.Second {
cancel()
return nil, fmt.Errorf("timeout: check the log for more information")
}
time.Sleep(200 * time.Millisecond)
@@ -237,7 +261,7 @@ func StartCoreProcess(ctx context.Context) (*os.Process, error) {
func findAvailablePluginPorts(vms []serverObj.ServerObj) (pluginPortMap map[int]int, err error) {
pluginPortMap = make(map[int]int)
for i, v := range vms {
if !v.NeedPlugin() {
if !v.NeedPluginPort() {
continue
}
//find a port that not be occupied
+6
View File
@@ -158,6 +158,12 @@ func (m *CoreProcessManager) Stop(saveRunning bool) {
m.mu.Lock()
defer m.mu.Unlock()
m.stop(saveRunning)
if m.p != nil {
for _, pm := range m.p.pluginManagers {
_ = pm.Kill()
}
m.p.pluginManagers = nil
}
}
func (m *CoreProcessManager) stop(saveRunning bool) {
+33 -10
View File
@@ -49,13 +49,19 @@ type Template struct {
Observatory *coreObj.Observatory `json:"observatory,omitempty"`
API *coreObj.APIObject `json:"api,omitempty"`
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
Plugins []plugin.Server `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
Variant where.Variant `json:"-"`
CoreVersion string `json:"-"`
Plugins []plugin.Server `json:"-"`
OutboundTags []string `json:"-"`
ApiCloses []func() `json:"-"`
ApiPort int `json:"-"`
Setting *configure.Setting `json:"-"`
PluginManagerInfoList []PluginManagerInfo `json:"-"`
}
type PluginManagerInfo struct {
Link string
Port int
}
func (t *Template) Close() error {
@@ -1261,9 +1267,9 @@ func (t *Template) resolveOutbounds(
usedByBalancer bool
balancerPluginPort int
)
// a vmessInfo(server template) may is used by multiple serverInfos(a connected server)
// an vmessInfo(server template) may be used by multiple serverInfos(a connected server)
// outbound name is not just v2ray outbound tag, it may is a balancer
// outbound name is not just v2ray outbound tag, it may be a balancer
type balancer struct {
name string
serverInfo *serverInfo
@@ -1296,6 +1302,12 @@ func (t *Template) resolveOutbounds(
return nil, nil, err
}
extraOutbounds = append(extraOutbounds, c.ExtraOutbounds...)
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: sInfo.PluginPort,
})
}
var s plugin.Server
if len(c.PluginChain) > 0 {
s, err = plugin.ServerFromChain(c.PluginChain)
@@ -1329,7 +1341,12 @@ func (t *Template) resolveOutbounds(
for _, v := range balancers {
c.CoreOutbound.Balancers = append(c.CoreOutbound.Balancers, v.name)
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: balancerPluginPort,
})
}
// we use the lowest serverInfo index as the order weight of the balancer outbound
weight := -1
for _, v := range balancers {
@@ -1775,6 +1792,12 @@ func (t *Template) InsertMappingOutbound(o serverObj.ServerObj, inboundPort stri
t.Plugins = append(t.Plugins, server)
}
}
if c.PluginManagerServerLink != "" {
t.PluginManagerInfoList = append(t.PluginManagerInfoList, PluginManagerInfo{
Link: c.PluginManagerServerLink,
Port: pluginPort,
})
}
var mark = 0x80
t.checkAndSetMark(&c.CoreOutbound, mark)
t.Outbounds = append(t.Outbounds, c.CoreOutbound)
+13 -12
View File
@@ -2,6 +2,7 @@ package service
import (
"fmt"
"github.com/v2rayA/v2rayA/conf"
url2 "net/url"
"strings"
"time"
@@ -15,6 +16,15 @@ import (
"github.com/v2rayA/v2rayA/db/configure"
)
func PluginManagerValidateLink(url string) bool {
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
_, err := serverObj.NewFromLink(serverObj.PluginManagerScheme, url)
return err == nil
} else {
return false
}
}
func Import(url string, which *configure.Which) (err error) {
//log.Trace(url)
resolv.CheckResolvConf()
@@ -29,18 +39,9 @@ func Import(url string, which *configure.Which) (err error) {
}
return err
}
if strings.HasPrefix(url, "vmess://") ||
strings.HasPrefix(url, "vless://") ||
strings.HasPrefix(url, "ss://") ||
strings.HasPrefix(url, "ssr://") ||
strings.HasPrefix(url, "pingtunnel://") ||
strings.HasPrefix(url, "ping-tunnel://") ||
strings.HasPrefix(url, "trojan://") ||
strings.HasPrefix(url, "trojan-go://") ||
strings.HasPrefix(url, "http-proxy://") ||
strings.HasPrefix(url, "https-proxy://") ||
strings.HasPrefix(url, "socks5://") ||
strings.HasPrefix(url, "http2://") {
supportedPrefix := []string{"vmess://", "vless://", "ss://", "ssr://", "pingtunnel://", "ping-tunnel://",
"trojan://", "trojan-go://", "http-proxy://", "https-proxy://", "socks5://", "http2://"}
if PluginManagerValidateLink(url) || common.HasAnyPrefix(url, supportedPrefix) {
var obj serverObj.ServerObj
obj, err = ResolveURL(url)
if err != nil {
+1 -1
View File
@@ -158,7 +158,7 @@ func TestHttpLatency(which []*configure.Which, timeout time.Duration, maxParalle
}
v2rayInboundPort := strconv.Itoa(port)
pluginPort := 0
if v.NeedPlugin() {
if v.NeedPluginPort() {
// find a port for the plugin
for {
l, err := net.Listen("tcp", "127.0.0.1:0")