plugin_ins_manager.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. type PluginIns struct {
  34. process *os.Process
  35. ctrlChan ControlChannel
  36. runningCount int
  37. name string
  38. }
  39. func NewPluginIns(name string, ctrlChan ControlChannel, process *os.Process) *PluginIns {
  40. // if process is not passed, it is run in simulator mode. Then do not count running.
  41. // so that it won't be automatically close.
  42. rc := 0
  43. if process == nil {
  44. rc = 1
  45. }
  46. return &PluginIns{
  47. process: process,
  48. ctrlChan: ctrlChan,
  49. runningCount: rc,
  50. name: name,
  51. }
  52. }
  53. func (i *PluginIns) StartSymbol(ctx api.StreamContext, ctrl *Control) error {
  54. arg, err := json.Marshal(ctrl)
  55. if err != nil {
  56. return err
  57. }
  58. c := Command{
  59. Cmd: CMD_START,
  60. Arg: string(arg),
  61. }
  62. jsonArg, err := json.Marshal(c)
  63. if err != nil {
  64. return err
  65. }
  66. err = i.ctrlChan.SendCmd(jsonArg)
  67. if err == nil {
  68. i.runningCount++
  69. ctx.GetLogger().Infof("started symbol %s", ctrl.SymbolName)
  70. }
  71. return err
  72. }
  73. func (i *PluginIns) StopSymbol(ctx api.StreamContext, ctrl *Control) error {
  74. arg, err := json.Marshal(ctrl)
  75. if err != nil {
  76. return err
  77. }
  78. c := Command{
  79. Cmd: CMD_STOP,
  80. Arg: string(arg),
  81. }
  82. jsonArg, err := json.Marshal(c)
  83. if err != nil {
  84. return err
  85. }
  86. err = i.ctrlChan.SendCmd(jsonArg)
  87. i.runningCount--
  88. ctx.GetLogger().Infof("stopped symbol %s", ctrl.SymbolName)
  89. if i.runningCount == 0 {
  90. err := GetPluginInsManager().Kill(i.name)
  91. if err != nil {
  92. ctx.GetLogger().Infof("fail to stop plugin %s: %v", i.name, err)
  93. return err
  94. }
  95. ctx.GetLogger().Infof("stop plugin %s", i.name)
  96. }
  97. return err
  98. }
  99. func (i *PluginIns) Stop() error {
  100. var err error
  101. if i.ctrlChan != nil {
  102. err = i.ctrlChan.Close()
  103. }
  104. if i.process != nil { // will also trigger process exit clean up
  105. err = i.process.Kill()
  106. }
  107. return err
  108. }
  109. // Manager plugin process and control socket
  110. type pluginInsManager struct {
  111. instances map[string]*PluginIns
  112. sync.RWMutex
  113. }
  114. func GetPluginInsManager() *pluginInsManager {
  115. once.Do(func() {
  116. pm = &pluginInsManager{
  117. instances: make(map[string]*PluginIns),
  118. }
  119. })
  120. return pm
  121. }
  122. func (p *pluginInsManager) getPluginIns(name string) (*PluginIns, bool) {
  123. p.RLock()
  124. defer p.RUnlock()
  125. ins, ok := p.instances[name]
  126. return ins, ok
  127. }
  128. func (p *pluginInsManager) deletePluginIns(name string) {
  129. p.Lock()
  130. defer p.Unlock()
  131. delete(p.instances, name)
  132. }
  133. // AddPluginIns For mock only
  134. func (p *pluginInsManager) AddPluginIns(name string, ins *PluginIns) {
  135. p.Lock()
  136. defer p.Unlock()
  137. p.instances[name] = ins
  138. }
  139. // getOrStartProcess Control the plugin process lifecycle.
  140. // Need to manage the resources: instances map, control socket, plugin process
  141. // 1. During creation, clean up those resources for any errors in defer immediately after the resource is created.
  142. // 2. During plugin running, when detecting plugin process exit, clean up those resources for the current ins.
  143. func (p *pluginInsManager) getOrStartProcess(pluginMeta *PluginMeta, pconf *PortableConfig) (*PluginIns, error) {
  144. p.Lock()
  145. defer p.Unlock()
  146. if ins, ok := p.instances[pluginMeta.Name]; ok {
  147. return ins, nil
  148. }
  149. conf.Log.Infof("create control channel")
  150. ctrlChan, err := CreateControlChannel(pluginMeta.Name)
  151. if err != nil {
  152. return nil, fmt.Errorf("can't create new control channel: %s", err.Error())
  153. }
  154. defer func() {
  155. if err != nil {
  156. _ = ctrlChan.Close()
  157. }
  158. }()
  159. conf.Log.Infof("executing plugin")
  160. jsonArg, err := json.Marshal(pconf)
  161. if err != nil {
  162. return nil, fmt.Errorf("invalid conf: %v", pconf)
  163. }
  164. var cmd *exec.Cmd
  165. err = infra.SafeRun(func() error {
  166. switch pluginMeta.Language {
  167. case "go":
  168. conf.Log.Printf("starting go plugin executable %s", pluginMeta.Executable)
  169. cmd = exec.Command(pluginMeta.Executable, string(jsonArg))
  170. case "python":
  171. conf.Log.Printf("starting python plugin executable %s with script %s\n", conf.Config.Portable.PythonBin, pluginMeta.Executable)
  172. cmd = exec.Command(conf.Config.Portable.PythonBin, pluginMeta.Executable, string(jsonArg))
  173. default:
  174. return fmt.Errorf("unsupported language: %s", pluginMeta.Language)
  175. }
  176. return nil
  177. })
  178. if err != nil {
  179. return nil, fmt.Errorf("fail to start plugin %s: %v", pluginMeta.Name, err)
  180. }
  181. cmd.Stdout = conf.Log.Out
  182. cmd.Stderr = conf.Log.Out
  183. conf.Log.Println("plugin starting")
  184. err = cmd.Start()
  185. if err != nil {
  186. return nil, fmt.Errorf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  187. }
  188. process := cmd.Process
  189. conf.Log.Printf("plugin started pid: %d\n", process.Pid)
  190. defer func() {
  191. if err != nil {
  192. _ = process.Kill()
  193. }
  194. }()
  195. go infra.SafeRun(func() error { // just print out error inside
  196. err = cmd.Wait()
  197. if err != nil {
  198. conf.Log.Printf("plugin executable %s stops with error %v", pluginMeta.Executable, err)
  199. }
  200. // must make sure the plugin ins is not cleaned up yet by checking the process identity
  201. if ins, ok := p.getPluginIns(pluginMeta.Name); ok && ins.process == cmd.Process {
  202. if ins.ctrlChan != nil {
  203. _ = ins.ctrlChan.Close()
  204. }
  205. p.deletePluginIns(pluginMeta.Name)
  206. }
  207. return nil
  208. })
  209. conf.Log.Println("waiting handshake")
  210. err = ctrlChan.Handshake()
  211. if err != nil {
  212. return nil, fmt.Errorf("plugin %s control handshake error: %v", pluginMeta.Executable, err)
  213. }
  214. ins := NewPluginIns(pluginMeta.Name, ctrlChan, process)
  215. p.instances[pluginMeta.Name] = ins
  216. conf.Log.Println("plugin start running")
  217. return ins, nil
  218. }
  219. func (p *pluginInsManager) Kill(name string) error {
  220. p.Lock()
  221. defer p.Unlock()
  222. var err error
  223. if ins, ok := p.instances[name]; ok {
  224. err = ins.Stop()
  225. delete(p.instances, name)
  226. } else {
  227. return fmt.Errorf("instance %s not found", name)
  228. }
  229. return err
  230. }
  231. func (p *pluginInsManager) KillAll() error {
  232. p.Lock()
  233. defer p.Unlock()
  234. for _, ins := range p.instances {
  235. _ = ins.Stop()
  236. }
  237. p.instances = make(map[string]*PluginIns)
  238. return nil
  239. }
  240. type PluginMeta struct {
  241. Name string `json:"name"`
  242. Version string `json:"version"`
  243. Language string `json:"language"`
  244. Executable string `json:"executable"`
  245. }