66 lines
1.9 KiB
Go
66 lines
1.9 KiB
Go
|
package manage
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"gitea.cdlsxd.cn/BaseSystem/plugin/shared"
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
"github.com/hashicorp/go-plugin"
|
||
|
"github.com/pkg/errors"
|
||
|
"os/exec"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type Config struct {
|
||
|
Cmd string `validate:"required"` // 插件的执行路径
|
||
|
Tag string `validate:"required"` // 插件的tag,对应插件
|
||
|
Version uint `validate:"required"` // 插件的版本
|
||
|
CookieKey string `validate:"required"` // 插件通信的cookie key
|
||
|
CookieValue string `validate:"required"` // 插件通信的cookie value
|
||
|
Timeout time.Duration // 插件超时时间
|
||
|
|
||
|
// 供应商配置
|
||
|
// Config json.RawMessage
|
||
|
}
|
||
|
|
||
|
func (c *Config) Validate() error {
|
||
|
err := validator.New().Struct(c)
|
||
|
if err == nil {
|
||
|
return nil
|
||
|
}
|
||
|
var combinedErr error
|
||
|
for index, err2 := range err.(validator.ValidationErrors) {
|
||
|
combinedErr = errors.Wrap(err2, fmt.Sprintf("index:%d,field:%s \n", index, err2.Field()))
|
||
|
}
|
||
|
return combinedErr
|
||
|
}
|
||
|
|
||
|
func newClient(c *Config) (shared.PluginService, func(), error) {
|
||
|
pluginClientConfig := &plugin.ClientConfig{
|
||
|
HandshakeConfig: shared.HandshakeConfig(c.Version, c.CookieKey, c.CookieValue),
|
||
|
Cmd: exec.Command(c.Cmd),
|
||
|
Plugins: map[string]plugin.Plugin{c.Tag: &shared.GRPCPlugin{}},
|
||
|
AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},
|
||
|
}
|
||
|
if c.Timeout != 0 {
|
||
|
pluginClientConfig.StartTimeout = c.Timeout
|
||
|
}
|
||
|
client := plugin.NewClient(pluginClientConfig)
|
||
|
protocol, err := client.Client()
|
||
|
if err != nil {
|
||
|
return nil, func() {}, fmt.Errorf("pluginClient.Client err:%v", err)
|
||
|
}
|
||
|
cleanup := func() {
|
||
|
_ = protocol.Close()
|
||
|
client.Kill()
|
||
|
}
|
||
|
raw, err := protocol.Dispense(c.Tag)
|
||
|
if err != nil {
|
||
|
return nil, cleanup, fmt.Errorf("protocol.Dispense err:%v", err)
|
||
|
}
|
||
|
pluginService, ok := raw.(shared.PluginService)
|
||
|
if !ok {
|
||
|
return nil, cleanup, fmt.Errorf("unexpected plugin type: %T", raw)
|
||
|
}
|
||
|
return pluginService, cleanup, nil
|
||
|
}
|