plugin_ins_manager.go 9.6 KB

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