plugin_ins_manager.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. // Copyright 2021-2023 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package runtime
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/internal/conf"
  19. "github.com/lf-edge/ekuiper/pkg/api"
  20. "github.com/lf-edge/ekuiper/pkg/infra"
  21. "os"
  22. "os/exec"
  23. "sync"
  24. )
  25. var (
  26. once sync.Once
  27. pm *pluginInsManager
  28. )
  29. // TODO setting configuration
  30. var PortbleConf = &PortableConfig{
  31. SendTimeout: 1000,
  32. }
  33. // PluginIns created at two scenarios
  34. // 1. At runtime, plugin is created/updated: in order to be able to reload rules that already uses previous ins
  35. // 2. At system start/restart, when plugin is used by a rule
  36. // Once created, never deleted until delete plugin command or system shutdown
  37. type PluginIns struct {
  38. sync.RWMutex
  39. name string
  40. ctrlChan ControlChannel // the same lifecycle as pluginIns, once created keep listening
  41. // audit the commands, so that when restarting the plugin, we can replay the commands
  42. commands map[Meta][]byte
  43. process *os.Process // created when used by rule and deleted when no rule uses it
  44. }
  45. func NewPluginIns(name string, ctrlChan ControlChannel, process *os.Process) *PluginIns {
  46. return &PluginIns{
  47. process: process,
  48. ctrlChan: ctrlChan,
  49. name: name,
  50. commands: make(map[Meta][]byte),
  51. }
  52. }
  53. func NewPluginInsForTest(name string, ctrlChan ControlChannel) *PluginIns {
  54. commands := make(map[Meta][]byte)
  55. commands[Meta{
  56. RuleId: "test",
  57. OpId: "test",
  58. InstanceId: 0,
  59. }] = []byte{}
  60. return &PluginIns{
  61. process: nil,
  62. ctrlChan: ctrlChan,
  63. name: name,
  64. commands: commands,
  65. }
  66. }
  67. func (i *PluginIns) sendCmd(jsonArg []byte) error {
  68. err := i.ctrlChan.SendCmd(jsonArg)
  69. if err != nil && i.process == nil {
  70. return fmt.Errorf("plugin %s is not running sucessfully, please make sure it is valid", i.name)
  71. }
  72. return err
  73. }
  74. func (i *PluginIns) StartSymbol(ctx api.StreamContext, ctrl *Control) error {
  75. arg, err := json.Marshal(ctrl)
  76. if err != nil {
  77. return err
  78. }
  79. c := Command{
  80. Cmd: CMD_START,
  81. Arg: string(arg),
  82. }
  83. jsonArg, err := json.Marshal(c)
  84. if err != nil {
  85. return err
  86. }
  87. err = i.sendCmd(jsonArg)
  88. if err == nil {
  89. i.Lock()
  90. i.commands[ctrl.Meta] = jsonArg
  91. i.Unlock()
  92. ctx.GetLogger().Infof("started symbol %s", ctrl.SymbolName)
  93. }
  94. return err
  95. }
  96. func (i *PluginIns) StopSymbol(ctx api.StreamContext, ctrl *Control) error {
  97. arg, err := json.Marshal(ctrl)
  98. if err != nil {
  99. return err
  100. }
  101. c := Command{
  102. Cmd: CMD_STOP,
  103. Arg: string(arg),
  104. }
  105. jsonArg, err := json.Marshal(c)
  106. if err != nil {
  107. return err
  108. }
  109. err = i.sendCmd(jsonArg)
  110. if err == nil {
  111. referred := false
  112. i.Lock()
  113. delete(i.commands, ctrl.Meta)
  114. referred = len(i.commands) > 0
  115. i.Unlock()
  116. ctx.GetLogger().Infof("stopped symbol %s", ctrl.SymbolName)
  117. if !referred {
  118. err := GetPluginInsManager().Kill(i.name)
  119. if err != nil {
  120. ctx.GetLogger().Infof("fail to stop plugin %s: %v", i.name, err)
  121. return err
  122. }
  123. ctx.GetLogger().Infof("stop plugin %s", i.name)
  124. }
  125. }
  126. return err
  127. }
  128. // Stop intentionally
  129. func (i *PluginIns) Stop() error {
  130. var err error
  131. i.RLock()
  132. defer i.RUnlock()
  133. if i.process != nil { // will also trigger process exit clean up
  134. err = i.process.Kill()
  135. }
  136. return err
  137. }
  138. // Manager plugin process and control socket
  139. type pluginInsManager struct {
  140. instances map[string]*PluginIns
  141. sync.RWMutex
  142. }
  143. func GetPluginInsManager() *pluginInsManager {
  144. once.Do(func() {
  145. pm = &pluginInsManager{
  146. instances: make(map[string]*PluginIns),
  147. }
  148. })
  149. return pm
  150. }
  151. func (p *pluginInsManager) getPluginIns(name string) (*PluginIns, bool) {
  152. p.RLock()
  153. defer p.RUnlock()
  154. ins, ok := p.instances[name]
  155. return ins, ok
  156. }
  157. // deletePluginIns should only run when there is no state aka. commands
  158. func (p *pluginInsManager) deletePluginIns(name string) {
  159. p.Lock()
  160. defer p.Unlock()
  161. delete(p.instances, name)
  162. }
  163. // AddPluginIns For mock only
  164. func (p *pluginInsManager) AddPluginIns(name string, ins *PluginIns) {
  165. p.Lock()
  166. defer p.Unlock()
  167. p.instances[name] = ins
  168. }
  169. // CreateIns Run when plugin is created/updated
  170. func (p *pluginInsManager) CreateIns(pluginMeta *PluginMeta) {
  171. p.Lock()
  172. defer p.Unlock()
  173. if ins, ok := p.instances[pluginMeta.Name]; ok {
  174. if len(ins.commands) != 0 {
  175. go p.getOrStartProcess(pluginMeta, PortbleConf)
  176. }
  177. }
  178. }
  179. // getOrStartProcess Control the plugin process lifecycle.
  180. // Need to manage the resources: instances map, control socket, plugin process
  181. // May be called at plugin creation or restart with previous state(ctrlCh, commands)
  182. // PluginIns is created by plugin manager but started by rule/funcop.
  183. // During plugin delete/update, if the commands is not empty, keep the ins for next creation and restore
  184. // 1. During creation, clean up those resources for any errors in defer immediately after the resource is created.
  185. // 2. During plugin running, when detecting plugin process exit, clean up those resources for the current ins.
  186. func (p *pluginInsManager) getOrStartProcess(pluginMeta *PluginMeta, pconf *PortableConfig) (_ *PluginIns, e error) {
  187. p.Lock()
  188. defer p.Unlock()
  189. var (
  190. ins *PluginIns
  191. ok bool
  192. )
  193. // run initialization for firstly creating plugin instance
  194. ins, ok = p.instances[pluginMeta.Name]
  195. if !ok {
  196. ins = NewPluginIns(pluginMeta.Name, nil, nil)
  197. p.instances[pluginMeta.Name] = ins
  198. }
  199. // ins process has not run yet
  200. if ins.process != nil && ins.ctrlChan != nil {
  201. return ins, nil
  202. }
  203. // should only happen for first start, then the ctrl channel will keep running
  204. if ins.ctrlChan == nil {
  205. conf.Log.Infof("create control channel")
  206. ctrlChan, err := CreateControlChannel(pluginMeta.Name)
  207. if err != nil {
  208. return nil, fmt.Errorf("can't create new control channel: %s", err.Error())
  209. }
  210. ins.ctrlChan = ctrlChan
  211. }
  212. // init or restart all need to run the process
  213. conf.Log.Infof("executing plugin")
  214. jsonArg, err := json.Marshal(pconf)
  215. if err != nil {
  216. return nil, fmt.Errorf("invalid conf: %v", pconf)
  217. }
  218. var cmd *exec.Cmd
  219. err = infra.SafeRun(func() error {
  220. switch pluginMeta.Language {
  221. case "go":
  222. conf.Log.Printf("starting go plugin executable %s", pluginMeta.Executable)
  223. cmd = exec.Command(pluginMeta.Executable, string(jsonArg))
  224. case "python":
  225. conf.Log.Printf("starting python plugin executable %s with script %s\n", conf.Config.Portable.PythonBin, pluginMeta.Executable)
  226. cmd = exec.Command(conf.Config.Portable.PythonBin, pluginMeta.Executable, string(jsonArg))
  227. default:
  228. return fmt.Errorf("unsupported language: %s", pluginMeta.Language)
  229. }
  230. return nil
  231. })
  232. if err != nil {
  233. return nil, fmt.Errorf("fail to start plugin %s: %v", pluginMeta.Name, err)
  234. }
  235. cmd.Stdout = conf.Log.Out
  236. cmd.Stderr = conf.Log.Out
  237. conf.Log.Println("plugin starting")
  238. err = cmd.Start()
  239. if err != nil {
  240. return nil, fmt.Errorf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  241. }
  242. process := cmd.Process
  243. conf.Log.Printf("plugin started pid: %d\n", process.Pid)
  244. defer func() {
  245. if e != nil {
  246. _ = process.Kill()
  247. }
  248. }()
  249. go infra.SafeRun(func() error { // just print out error inside
  250. err = cmd.Wait()
  251. if err != nil {
  252. conf.Log.Printf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  253. }
  254. // must make sure the plugin ins is not cleaned up yet by checking the process identity
  255. // clean up for stop unintentionally
  256. if ins, ok := p.getPluginIns(pluginMeta.Name); ok && ins.process == cmd.Process {
  257. ins.Lock()
  258. if len(ins.commands) == 0 {
  259. if ins.ctrlChan != nil {
  260. _ = ins.ctrlChan.Close()
  261. }
  262. p.deletePluginIns(pluginMeta.Name)
  263. }
  264. ins.process = nil
  265. ins.Unlock()
  266. }
  267. return nil
  268. })
  269. conf.Log.Println("waiting handshake")
  270. err = ins.ctrlChan.Handshake()
  271. if err != nil {
  272. return nil, fmt.Errorf("plugin %s control handshake error: %v", pluginMeta.Executable, err)
  273. }
  274. ins.process = process
  275. p.instances[pluginMeta.Name] = ins
  276. conf.Log.Println("plugin start running")
  277. // restore symbols by sending commands when restarting plugin
  278. conf.Log.Info("restore plugin symbols")
  279. for m, c := range ins.commands {
  280. go func(key Meta, jsonArg []byte) {
  281. e := ins.sendCmd(jsonArg)
  282. if e != nil {
  283. conf.Log.Errorf("send command to %v error: %v", key, e)
  284. }
  285. }(m, c)
  286. }
  287. return ins, nil
  288. }
  289. func (p *pluginInsManager) Kill(name string) error {
  290. p.Lock()
  291. defer p.Unlock()
  292. var err error
  293. if ins, ok := p.instances[name]; ok {
  294. err = ins.Stop()
  295. } else {
  296. conf.Log.Warnf("instance %s not found when deleting", name)
  297. return nil
  298. }
  299. return err
  300. }
  301. func (p *pluginInsManager) KillAll() error {
  302. p.Lock()
  303. defer p.Unlock()
  304. for _, ins := range p.instances {
  305. _ = ins.Stop()
  306. }
  307. return nil
  308. }
  309. type PluginMeta struct {
  310. Name string `json:"name"`
  311. Version string `json:"version"`
  312. Language string `json:"language"`
  313. Executable string `json:"executable"`
  314. }