plugin_ins_manager.go 9.6 KB

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