plugin.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. // Plugin runtime to control the whole plugin with control channel: Distribute symbol data connection, stop symbol and stop plugin
  15. package runtime
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. "github.com/lf-edge/ekuiper/sdk/go/api"
  20. "github.com/lf-edge/ekuiper/sdk/go/connection"
  21. "github.com/lf-edge/ekuiper/sdk/go/context"
  22. "os"
  23. "os/signal"
  24. "sync"
  25. "syscall"
  26. )
  27. var (
  28. logger api.Logger
  29. reg runtimes
  30. )
  31. func initVars(args []string, conf *PluginConfig) {
  32. logger = context.LogEntry("plugin", conf.Name)
  33. reg = runtimes{
  34. content: make(map[string]RuntimeInstance),
  35. RWMutex: sync.RWMutex{},
  36. }
  37. // parse Args
  38. if len(args) == 2 {
  39. pc := &PortableConfig{}
  40. err := json.Unmarshal([]byte(args[1]), pc)
  41. if err != nil {
  42. panic(fmt.Sprintf("fail to parse args %v", args))
  43. }
  44. logger.Infof("config parsed to %v", pc)
  45. }
  46. }
  47. type NewSourceFunc func() api.Source
  48. type NewFunctionFunc func() api.Function
  49. type NewSinkFunc func() api.Sink
  50. // PluginConfig construct once and then read only
  51. type PluginConfig struct {
  52. Name string
  53. Sources map[string]NewSourceFunc
  54. Functions map[string]NewFunctionFunc
  55. Sinks map[string]NewSinkFunc
  56. }
  57. func (conf *PluginConfig) Get(pluginType string, symbolName string) (builderFunc interface{}) {
  58. switch pluginType {
  59. case TYPE_SOURCE:
  60. if f, ok := conf.Sources[symbolName]; ok {
  61. return f
  62. }
  63. case TYPE_FUNC:
  64. if f, ok := conf.Functions[symbolName]; ok {
  65. return f
  66. }
  67. case TYPE_SINK:
  68. if f, ok := conf.Sinks[symbolName]; ok {
  69. return f
  70. }
  71. }
  72. return nil
  73. }
  74. // Start Connect to control plane
  75. // Only run once at process startup
  76. func Start(args []string, conf *PluginConfig) {
  77. initVars(args, conf)
  78. logger.Info("starting plugin")
  79. ch, err := connection.CreateControlChannel(conf.Name)
  80. if err != nil {
  81. panic(err)
  82. }
  83. defer ch.Close()
  84. go func() {
  85. logger.Info("running control channel")
  86. err = ch.Run(func(req []byte) []byte { // not parallel run now
  87. c := &Command{}
  88. err := json.Unmarshal(req, c)
  89. if err != nil {
  90. return []byte(err.Error())
  91. }
  92. logger.Infof("received command %s with arg:'%s'", c.Cmd, c.Arg)
  93. ctrl := &Control{}
  94. err = json.Unmarshal([]byte(c.Arg), ctrl)
  95. if err != nil {
  96. return []byte(err.Error())
  97. }
  98. switch c.Cmd {
  99. case CMD_START:
  100. f := conf.Get(ctrl.PluginType, ctrl.SymbolName)
  101. if f == nil {
  102. return []byte("symbol not found")
  103. }
  104. switch ctrl.PluginType {
  105. case TYPE_SOURCE:
  106. sf := f.(NewSourceFunc)
  107. sr, err := setupSourceRuntime(ctrl, sf())
  108. if err != nil {
  109. return []byte(err.Error())
  110. }
  111. go sr.run()
  112. regKey := fmt.Sprintf("%s_%s_%d_%s", ctrl.Meta.RuleId, ctrl.Meta.OpId, ctrl.Meta.InstanceId, ctrl.SymbolName)
  113. reg.Set(regKey, sr)
  114. logger.Infof("running source %s", ctrl.SymbolName)
  115. case TYPE_SINK:
  116. sf := f.(NewSinkFunc)
  117. sr, err := setupSinkRuntime(ctrl, sf())
  118. if err != nil {
  119. return []byte(err.Error())
  120. }
  121. go sr.run()
  122. regKey := fmt.Sprintf("%s_%s_%d_%s", ctrl.Meta.RuleId, ctrl.Meta.OpId, ctrl.Meta.InstanceId, ctrl.SymbolName)
  123. reg.Set(regKey, sr)
  124. logger.Infof("running sink %s", ctrl.SymbolName)
  125. case TYPE_FUNC:
  126. regKey := fmt.Sprintf("func_%s", ctrl.SymbolName)
  127. _, ok := reg.Get(regKey)
  128. if ok {
  129. logger.Infof("got running function instance %s, do nothing", ctrl.SymbolName)
  130. } else {
  131. ff := f.(NewFunctionFunc)
  132. fr, err := setupFuncRuntime(ctrl, ff())
  133. if err != nil {
  134. return []byte(err.Error())
  135. }
  136. go fr.run()
  137. reg.Set(regKey, fr)
  138. logger.Infof("running function %s", ctrl.SymbolName)
  139. }
  140. default:
  141. return []byte(fmt.Sprintf("invalid plugin type %s", ctrl.PluginType))
  142. }
  143. return []byte(REPLY_OK)
  144. case CMD_STOP:
  145. // never stop a function symbol here.
  146. regKey := fmt.Sprintf("%s_%s_%d_%s", ctrl.Meta.RuleId, ctrl.Meta.OpId, ctrl.Meta.InstanceId, ctrl.SymbolName)
  147. logger.Infof("stopping %s", regKey)
  148. runtime, ok := reg.Get(regKey)
  149. if !ok {
  150. return []byte(fmt.Sprintf("symbol %s not found", regKey))
  151. }
  152. if runtime.isRunning() {
  153. err = runtime.stop()
  154. if err != nil {
  155. return []byte(err.Error())
  156. }
  157. }
  158. return []byte(REPLY_OK)
  159. default:
  160. return []byte(fmt.Sprintf("invalid command received: %s", c.Cmd))
  161. }
  162. })
  163. if err != nil {
  164. logger.Error(err)
  165. }
  166. os.Exit(1)
  167. }()
  168. //Stop the whole plugin
  169. sigint := make(chan os.Signal, 1)
  170. signal.Notify(sigint, os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
  171. <-sigint
  172. logger.Infof("stopping plugin %s", conf.Name)
  173. os.Exit(0)
  174. }
  175. // key is rule_op_ins_symbol
  176. type runtimes struct {
  177. content map[string]RuntimeInstance
  178. sync.RWMutex
  179. }
  180. func (r *runtimes) Set(name string, instance RuntimeInstance) {
  181. r.Lock()
  182. defer r.Unlock()
  183. r.content[name] = instance
  184. }
  185. func (r *runtimes) Get(name string) (RuntimeInstance, bool) {
  186. r.RLock()
  187. defer r.RUnlock()
  188. result, ok := r.content[name]
  189. return result, ok
  190. }
  191. func (r *runtimes) Delete(name string) {
  192. r.Lock()
  193. defer r.Unlock()
  194. delete(r.content, name)
  195. }