plugin.go 5.62 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
2
3
package plugin

import (
4
5
6
	"agent/cmd/agent/config"
	"agent/pkg/file"
	"encoding/json"
Lei Li's avatar
Lei Li committed
7
	"fmt"
8
9
	"os"
	"path/filepath"
Lei Li's avatar
Lei Li committed
10
11
12
	"sync"
	"time"

13
	"agent/cmd/agent/global"
Lei Li's avatar
Lei Li committed
14
15
16
	"agent/cmd/agent/option"
	"linkfog.com/pluginx/pluginmgr"
	"linkfog.com/pluginx/pluginrpc"
17
	"linkfog.com/public/lib/common"
18
	pFile "linkfog.com/public/lib/file"
Lei Li's avatar
Lei Li committed
19
20
21
	"linkfog.com/public/lib/l"
)

22
var defaultPluginCliConf = make(map[string]string)
Lei Li's avatar
Lei Li committed
23
24

type Plugin struct {
Lei Li's avatar
Lei Li committed
25
	signal     chan *global.Message
Lei Li's avatar
Lei Li committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
	signalSize int
	isRunning  bool
	plgServer  *pluginServer
	plgConf    map[string]*pluginmgr.PluginProcessConf
	processMgr *pluginmgr.PluginProcessMgr
	grpcServer *pluginrpc.PluginGrpcServer
	grpcClient *pluginrpc.PluginGrpcClient
	sync.Mutex
}

type PluginOpt func(*Plugin)

func New(opts ...PluginOpt) *Plugin {
	p := Plugin{
Lei Li's avatar
Lei Li committed
40
		signalSize: 512,
Lei Li's avatar
Lei Li committed
41
42
43
44
	}
	for _, opt := range opts {
		opt(&p)
	}
45
	setPluginSocketPath()
Lei Li's avatar
Lei Li committed
46
	p.signal = make(chan *global.Message, p.signalSize)
Lei Li's avatar
Lei Li committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

	return &p
}

func (p *Plugin) Start() error {
	if p.IsRunning() {
		return nil
	}
	l.Info("init plugin module")

	//// 启动自身grpc服务
	//p.plgServer = newPluginServer()
	//var err error
	//p.grpcServer, err = pluginrpc.NewPluginGrpcServer(HadesPluginSocket, p.plgServer)
	//if err != nil {
	//	return fmt.Errorf("NewPluginGrpcServer err: %v", err)
	//}

	// 启动插件管理器,运行各插件进程
	pluginmgr.EnableValidatePluginMD5 = option.Opt.EnableValidatePluginMD5
	pluginmgr.InitDur = option.Opt.PluginStatusCheckDur
68
	plgCfgMap, err := pluginmgr.LoadPluginConfigWithFile(defaultPluginMgrConfFile)
Lei Li's avatar
Lei Li committed
69
	if err != nil {
70
71
		l.Warnf("load plugin config file failed, %v", err)
		plgCfgMap = make(map[string]*pluginmgr.PluginProcessConf)
Lei Li's avatar
Lei Li committed
72
	}
73

Lei Li's avatar
Lei Li committed
74
	for name, plg := range plgCfgMap {
75
76
77
78
79
80
		if name == PushStreamingPlugin {
			defaultPluginCliConf[name] = PushStreamingPluginSocket
		} else if name == ReportDCSInfoPlugin {
			defaultPluginCliConf[name] = ReportDCSInfoPluginSocket
		}

Lei Li's avatar
Lei Li committed
81
82
83
84
85
86
87
		l.Info("plugin config:", name, plg)
	}
	p.plgConf = plgCfgMap
	p.processMgr = pluginmgr.NewProcessMgr(p.plgConf)
	p.processMgr.Start()

	// 建立与各插件进程的grpc连接
88
	p.grpcClient, err = pluginrpc.New()
Lei Li's avatar
Lei Li committed
89
90
91
	if err != nil {
		return fmt.Errorf("NewGrpcClientHelper err: %v", err)
	}
92
93
94
95
96
97
98
	if len(defaultPluginCliConf) > 0 {
		err := p.grpcClient.NewPluginClient(defaultPluginCliConf)
		if err != nil {
			l.Error(err)
			return err
		}
	}
Lei Li's avatar
Lei Li committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

	// 等待所有插件运行正常
	allIsRunning := false
	for i := 0; i < option.Opt.PluginStatusCheckTimes; i++ {
		if p.processMgr.AllPluginProcessIsRunning() {
			allIsRunning = true
			break
		}
		l.Info("all plugin process are init ...")
		time.Sleep(option.Opt.PluginStatusCheckDur)
	}
	if !allIsRunning {
		return fmt.Errorf("plugin processes init failed")
	}

	go func() {
Lei Li's avatar
Lei Li committed
115
		var sig *global.Message
Lei Li's avatar
Lei Li committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
		var ok bool
		for {
			select {
			case sig, ok = <-p.signal:
				if !ok {
					p.Stop()
					l.Info("module resources exit")
					return
				} else {
					p.dealWithSig(sig)
				}
			}
		}
	}()
	p.isRunning = true
	l.Info("init plugin module success")
	return nil
}

func (p *Plugin) Name() string {
	return global.PluginModuleName
}

func (p *Plugin) IsRunning() bool {
	return p.isRunning
}

func (p *Plugin) Stop() {
	if p.IsRunning() {
		if p.processMgr != nil {
			p.processMgr.Stop()
		}
		if p.grpcClient != nil {
			p.grpcClient.Close()
		}
		if p.grpcServer != nil {
			p.grpcServer.Close()
		}
		close(p.signal)
		p.isRunning = false
	}
}

159
160
161
162
163
164
type pluginInfo struct {
	Name string
	URL  string
	MD5  string
}

Lei Li's avatar
Lei Li committed
165
func (p *Plugin) Receive(msg *global.Message) error {
Lei Li's avatar
Lei Li committed
166
	if len(p.signal) > (p.signalSize - 2) {
Lei Li's avatar
Lei Li committed
167
		return l.WrapError("plugin manager signal chan is full, drop msg:", msg.Key)
Lei Li's avatar
Lei Li committed
168
169
170
171
172
	}
	p.signal <- msg
	return nil
}

Lei Li's avatar
Lei Li committed
173
174
175
176
177
func (p *Plugin) dealWithSig(msg *global.Message) {
	defer common.TimeCost("deal sig finished, msgType:" + msg.Key)()

	switch msg.Key {
	case global.ConsumerTopicPluginUpgrade:
178
		// TODO: 更新插件版本
Lei Li's avatar
Lei Li committed
179
	case global.ConsumerTopicStartupPlugin:
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
		info := &pluginInfo{}
		err := json.Unmarshal([]byte(msg.Payload), &info)
		if err != nil {
			l.Error(err)
			return
		}
		// 首次启动,该不存在文件
		if _, err = os.Stat(filepath.Join(config.PluginDir, info.Name)); err != nil {
			downloadPlugin(info.URL, config.PluginDir, info.Name)
		} else {
			md5, err := pFile.GetFileMD5(filepath.Join(config.PluginDir, info.Name))
			if err != nil {
				l.Warn(err)
			}
			if md5 != info.MD5 {
				// TODO: 备份
				// 下载
				downloadPlugin(info.URL, config.PluginDir, info.Name)
			}
		}
		p.processMgr.ChangeSinglePluginConf(&pluginmgr.PluginProcessConf{
			Name:   info.Name,
			Path:   filepath.Join(config.PluginDir, info.Name),
			Enable: true,
		})

		// 等待一秒再建立连接
		time.Sleep(1 * time.Second)
		err = p.grpcClient.NewPluginClient(map[string]string{
			info.Name: filepath.Join(config.PluginDir, info.Name+".sock"),
		})
		if err != nil {
			l.Error(err)
			return
		}

		if info.Name == ReportDCSInfoPlugin {
			go chatWithPlugin(p.grpcClient, ReportDCSInfoPlugin, global.PublishTopicReportInfo)
		}

Lei Li's avatar
Lei Li committed
220
	case global.ConsumerTopicStopPlugin:
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
		info := &pluginInfo{}
		err := json.Unmarshal([]byte(msg.Payload), &info)
		if err != nil {
			l.Error(err)
			return
		}
		p.processMgr.ChangeSinglePluginConf(&pluginmgr.PluginProcessConf{
			Name:   info.Name,
			Path:   filepath.Join(config.PluginDir, info.Name),
			Enable: false,
		})
		// grpc连接,server被kill掉,连接自动断开,故客户端不用主动关闭
	}
}

func downloadPlugin(url, dir, name string) {
	err := global.DownloadFile(url, dir, name)
	if err != nil {
		l.Errorf("download file err:%v", err)
		return
	}

	// 增加执行权限
	err = file.SetFileExecPerm(filepath.Join(dir, name))
	if err != nil {
		l.Error(err)
Lei Li's avatar
Lei Li committed
247
	}
248
	// TODO md5校验
Lei Li's avatar
Lei Li committed
249
}