plugin_ins_manager.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. // Copyright 2021-2022 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) StartSymbol(ctx api.StreamContext, ctrl *Control) error {
  68. arg, err := json.Marshal(ctrl)
  69. if err != nil {
  70. return err
  71. }
  72. c := Command{
  73. Cmd: CMD_START,
  74. Arg: string(arg),
  75. }
  76. jsonArg, err := json.Marshal(c)
  77. if err != nil {
  78. return err
  79. }
  80. err = i.ctrlChan.SendCmd(jsonArg)
  81. if err == nil {
  82. i.Lock()
  83. i.commands[ctrl.Meta] = jsonArg
  84. i.Unlock()
  85. ctx.GetLogger().Infof("started symbol %s", ctrl.SymbolName)
  86. }
  87. return err
  88. }
  89. func (i *PluginIns) StopSymbol(ctx api.StreamContext, ctrl *Control) error {
  90. arg, err := json.Marshal(ctrl)
  91. if err != nil {
  92. return err
  93. }
  94. c := Command{
  95. Cmd: CMD_STOP,
  96. Arg: string(arg),
  97. }
  98. jsonArg, err := json.Marshal(c)
  99. if err != nil {
  100. return err
  101. }
  102. err = i.ctrlChan.SendCmd(jsonArg)
  103. if err == nil {
  104. referred := false
  105. i.Lock()
  106. delete(i.commands, ctrl.Meta)
  107. referred = len(i.commands) > 0
  108. i.Unlock()
  109. ctx.GetLogger().Infof("stopped symbol %s", ctrl.SymbolName)
  110. if !referred {
  111. err := GetPluginInsManager().Kill(i.name)
  112. if err != nil {
  113. ctx.GetLogger().Infof("fail to stop plugin %s: %v", i.name, err)
  114. return err
  115. }
  116. ctx.GetLogger().Infof("stop plugin %s", i.name)
  117. }
  118. }
  119. return err
  120. }
  121. // Stop intentionally
  122. func (i *PluginIns) Stop() error {
  123. var err error
  124. i.RLock()
  125. defer i.RUnlock()
  126. if i.process != nil { // will also trigger process exit clean up
  127. err = i.process.Kill()
  128. }
  129. return err
  130. }
  131. // Manager plugin process and control socket
  132. type pluginInsManager struct {
  133. instances map[string]*PluginIns
  134. sync.RWMutex
  135. }
  136. func GetPluginInsManager() *pluginInsManager {
  137. once.Do(func() {
  138. pm = &pluginInsManager{
  139. instances: make(map[string]*PluginIns),
  140. }
  141. })
  142. return pm
  143. }
  144. func (p *pluginInsManager) getPluginIns(name string) (*PluginIns, bool) {
  145. p.RLock()
  146. defer p.RUnlock()
  147. ins, ok := p.instances[name]
  148. return ins, ok
  149. }
  150. // deletePluginIns should only run when there is no state aka. commands
  151. func (p *pluginInsManager) deletePluginIns(name string) {
  152. p.Lock()
  153. defer p.Unlock()
  154. delete(p.instances, name)
  155. }
  156. // AddPluginIns For mock only
  157. func (p *pluginInsManager) AddPluginIns(name string, ins *PluginIns) {
  158. p.Lock()
  159. defer p.Unlock()
  160. p.instances[name] = ins
  161. }
  162. // CreateIns Run when plugin is created/updated
  163. func (p *pluginInsManager) CreateIns(pluginMeta *PluginMeta) {
  164. p.Lock()
  165. defer p.Unlock()
  166. if ins, ok := p.instances[pluginMeta.Name]; ok {
  167. if len(ins.commands) != 0 {
  168. go p.getOrStartProcess(pluginMeta, PortbleConf, true)
  169. }
  170. }
  171. }
  172. // getOrStartProcess Control the plugin process lifecycle.
  173. // Need to manage the resources: instances map, control socket, plugin process
  174. // May be called at plugin creation or restart with previous state(ctrlCh, commands)
  175. // PluginIns is created by plugin manager but started by rule/funcop.
  176. // During plugin delete/update, if the commands is not empty, keep the ins for next creation and restore
  177. // 1. During creation, clean up those resources for any errors in defer immediately after the resource is created.
  178. // 2. During plugin running, when detecting plugin process exit, clean up those resources for the current ins.
  179. func (p *pluginInsManager) getOrStartProcess(pluginMeta *PluginMeta, pconf *PortableConfig, pluginCreation bool) (*PluginIns, error) {
  180. p.Lock()
  181. defer p.Unlock()
  182. var (
  183. ins *PluginIns
  184. ok bool
  185. )
  186. // run initialization for firstly creating plugin instance
  187. ins, ok = p.instances[pluginMeta.Name]
  188. if !ok {
  189. ins = NewPluginIns(pluginMeta.Name, nil, nil)
  190. p.instances[pluginMeta.Name] = ins
  191. }
  192. // ins process has not run yet
  193. if !pluginCreation && ins.ctrlChan != nil {
  194. return ins, nil
  195. }
  196. // should only happen for first start, then the ctrl channel will keep running
  197. if ins.ctrlChan == nil {
  198. conf.Log.Infof("create control channel")
  199. ctrlChan, err := CreateControlChannel(pluginMeta.Name)
  200. if err != nil {
  201. return nil, fmt.Errorf("can't create new control channel: %s", err.Error())
  202. }
  203. defer func() {
  204. if err != nil {
  205. _ = ctrlChan.Close()
  206. }
  207. }()
  208. ins.ctrlChan = ctrlChan
  209. }
  210. // init or restart all need to run the process
  211. conf.Log.Infof("executing plugin")
  212. jsonArg, err := json.Marshal(pconf)
  213. if err != nil {
  214. return nil, fmt.Errorf("invalid conf: %v", pconf)
  215. }
  216. var cmd *exec.Cmd
  217. err = infra.SafeRun(func() error {
  218. switch pluginMeta.Language {
  219. case "go":
  220. conf.Log.Printf("starting go plugin executable %s", pluginMeta.Executable)
  221. cmd = exec.Command(pluginMeta.Executable, string(jsonArg))
  222. case "python":
  223. conf.Log.Printf("starting python plugin executable %s with script %s\n", conf.Config.Portable.PythonBin, pluginMeta.Executable)
  224. cmd = exec.Command(conf.Config.Portable.PythonBin, pluginMeta.Executable, string(jsonArg))
  225. default:
  226. return fmt.Errorf("unsupported language: %s", pluginMeta.Language)
  227. }
  228. return nil
  229. })
  230. if err != nil {
  231. return nil, fmt.Errorf("fail to start plugin %s: %v", pluginMeta.Name, err)
  232. }
  233. cmd.Stdout = conf.Log.Out
  234. cmd.Stderr = conf.Log.Out
  235. conf.Log.Println("plugin starting")
  236. err = cmd.Start()
  237. if err != nil {
  238. return nil, fmt.Errorf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  239. }
  240. process := cmd.Process
  241. conf.Log.Printf("plugin started pid: %d\n", process.Pid)
  242. defer func() {
  243. if err != nil {
  244. _ = process.Kill()
  245. }
  246. }()
  247. go infra.SafeRun(func() error { // just print out error inside
  248. err = cmd.Wait()
  249. if err != nil {
  250. conf.Log.Printf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  251. }
  252. // must make sure the plugin ins is not cleaned up yet by checking the process identity
  253. // clean up for stop unintentionally
  254. if ins, ok := p.getPluginIns(pluginMeta.Name); ok && ins.process == cmd.Process {
  255. ins.Lock()
  256. if len(ins.commands) == 0 {
  257. if ins.ctrlChan != nil {
  258. _ = ins.ctrlChan.Close()
  259. }
  260. p.deletePluginIns(pluginMeta.Name)
  261. }
  262. ins.process = nil
  263. ins.Unlock()
  264. }
  265. return nil
  266. })
  267. conf.Log.Println("waiting handshake")
  268. err = ins.ctrlChan.Handshake()
  269. if err != nil {
  270. return nil, fmt.Errorf("plugin %s control handshake error: %v", pluginMeta.Executable, err)
  271. }
  272. ins.process = process
  273. p.instances[pluginMeta.Name] = ins
  274. conf.Log.Println("plugin start running")
  275. // restore symbols by sending commands when restarting plugin
  276. conf.Log.Info("restore plugin symbols")
  277. for m, c := range ins.commands {
  278. go func(key Meta, jsonArg []byte) {
  279. e := ins.ctrlChan.SendCmd(jsonArg)
  280. if e != nil {
  281. conf.Log.Errorf("send command to %v error: %v", key, e)
  282. }
  283. }(m, c)
  284. }
  285. return ins, nil
  286. }
  287. func (p *pluginInsManager) Kill(name string) error {
  288. p.Lock()
  289. defer p.Unlock()
  290. var err error
  291. if ins, ok := p.instances[name]; ok {
  292. err = ins.Stop()
  293. } else {
  294. conf.Log.Warnf("instance %s not found when deleting", name)
  295. return nil
  296. }
  297. return err
  298. }
  299. func (p *pluginInsManager) KillAll() error {
  300. p.Lock()
  301. defer p.Unlock()
  302. for _, ins := range p.instances {
  303. _ = ins.Stop()
  304. }
  305. return nil
  306. }
  307. type PluginMeta struct {
  308. Name string `json:"name"`
  309. Version string `json:"version"`
  310. Language string `json:"language"`
  311. Executable string `json:"executable"`
  312. }