plugin_ins_manager.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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) 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. conf.Log.Warnf("plugin %s is not run yet", pluginMeta.Name)
  195. return ins, nil
  196. }
  197. // should only happen for first start, then the ctrl channel will keep running
  198. if ins.ctrlChan == nil {
  199. conf.Log.Infof("create control channel")
  200. ctrlChan, err := CreateControlChannel(pluginMeta.Name)
  201. if err != nil {
  202. return nil, fmt.Errorf("can't create new control channel: %s", err.Error())
  203. }
  204. defer func() {
  205. if err != nil {
  206. _ = ctrlChan.Close()
  207. }
  208. }()
  209. ins.ctrlChan = ctrlChan
  210. }
  211. // init or restart all need to run the process
  212. conf.Log.Infof("executing plugin")
  213. jsonArg, err := json.Marshal(pconf)
  214. if err != nil {
  215. return nil, fmt.Errorf("invalid conf: %v", pconf)
  216. }
  217. var cmd *exec.Cmd
  218. err = infra.SafeRun(func() error {
  219. switch pluginMeta.Language {
  220. case "go":
  221. conf.Log.Printf("starting go plugin executable %s", pluginMeta.Executable)
  222. cmd = exec.Command(pluginMeta.Executable, string(jsonArg))
  223. case "python":
  224. if pluginMeta.VirtualType != nil {
  225. switch *pluginMeta.VirtualType {
  226. case "conda":
  227. cmd = exec.Command("conda", "run", "-n", *pluginMeta.Env, conf.Config.Portable.PythonBin, pluginMeta.Executable, string(jsonArg))
  228. default:
  229. return fmt.Errorf("unsupported virtual type: %s", *pluginMeta.VirtualType)
  230. }
  231. }
  232. if cmd == nil {
  233. cmd = exec.Command(conf.Config.Portable.PythonBin, pluginMeta.Executable, string(jsonArg))
  234. }
  235. conf.Log.Infof("starting python plugin: %s", cmd)
  236. default:
  237. return fmt.Errorf("unsupported language: %s", pluginMeta.Language)
  238. }
  239. return nil
  240. })
  241. if err != nil {
  242. return nil, fmt.Errorf("fail to start plugin %s: %v", pluginMeta.Name, err)
  243. }
  244. cmd.Stdout = conf.Log.Out
  245. cmd.Stderr = conf.Log.Out
  246. conf.Log.Println("plugin starting")
  247. err = cmd.Start()
  248. if err != nil {
  249. return nil, fmt.Errorf("plugin executable %s starts with error %v", pluginMeta.Executable, err)
  250. }
  251. process := cmd.Process
  252. conf.Log.Printf("plugin started pid: %d\n", process.Pid)
  253. defer func() {
  254. if err != nil {
  255. _ = process.Kill()
  256. }
  257. }()
  258. go infra.SafeRun(func() error { // just print out error inside
  259. err = cmd.Wait()
  260. if err != nil {
  261. conf.Log.Printf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  262. }
  263. // must make sure the plugin ins is not cleaned up yet by checking the process identity
  264. // clean up for stop unintentionally
  265. if ins, ok := p.getPluginIns(pluginMeta.Name); ok && ins.process == cmd.Process {
  266. ins.Lock()
  267. if len(ins.commands) == 0 {
  268. if ins.ctrlChan != nil {
  269. _ = ins.ctrlChan.Close()
  270. }
  271. p.deletePluginIns(pluginMeta.Name)
  272. }
  273. ins.process = nil
  274. ins.Unlock()
  275. }
  276. return nil
  277. })
  278. conf.Log.Println("waiting handshake")
  279. err = ins.ctrlChan.Handshake()
  280. if err != nil {
  281. return nil, fmt.Errorf("plugin %s control handshake error: %v", pluginMeta.Executable, err)
  282. }
  283. ins.process = process
  284. p.instances[pluginMeta.Name] = ins
  285. conf.Log.Println("plugin start running")
  286. // restore symbols by sending commands when restarting plugin
  287. conf.Log.Info("restore plugin symbols")
  288. for m, c := range ins.commands {
  289. go func(key Meta, jsonArg []byte) {
  290. e := ins.ctrlChan.SendCmd(jsonArg)
  291. if e != nil {
  292. conf.Log.Errorf("send command to %v error: %v", key, e)
  293. }
  294. }(m, c)
  295. }
  296. return ins, nil
  297. }
  298. func (p *pluginInsManager) Kill(name string) error {
  299. p.Lock()
  300. defer p.Unlock()
  301. var err error
  302. if ins, ok := p.instances[name]; ok {
  303. err = ins.Stop()
  304. } else {
  305. conf.Log.Warnf("instance %s not found when deleting", name)
  306. return nil
  307. }
  308. return err
  309. }
  310. func (p *pluginInsManager) KillAll() error {
  311. p.Lock()
  312. defer p.Unlock()
  313. for _, ins := range p.instances {
  314. _ = ins.Stop()
  315. }
  316. return nil
  317. }
  318. type PluginMeta struct {
  319. Name string `json:"name"`
  320. Version string `json:"version"`
  321. Language string `json:"language"`
  322. Executable string `json:"executable"`
  323. VirtualType *string `json:"virtualEnvType,omitempty"`
  324. Env *string `json:"env,omitempty"`
  325. }