plugin.go 5.7 KB

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