function.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2022-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. kctx "github.com/lf-edge/ekuiper/internal/topo/context"
  20. "github.com/lf-edge/ekuiper/pkg/api"
  21. )
  22. // PortableFunc each function symbol only has a singleton
  23. // Each singleton are long-running go routine
  24. // Currently, it is cached and never ended once created
  25. // It is actually a wrapper of the data channel and can be fit to any plugin instance
  26. // Thus, it is possible to hot reload, which is simply attach a new nng client to the same channel
  27. // without changing the server(plugin runtime) side
  28. // TODO think about ending a portable func when needed.
  29. type PortableFunc struct {
  30. symbolName string
  31. reg *PluginMeta // initial plugin meta, only used for initialize the function instance
  32. dataCh DataReqChannel
  33. isAgg int // 0 - not calculate yet, 1 - no, 2 - yes
  34. }
  35. func NewPortableFunc(symbolName string, reg *PluginMeta) (_ *PortableFunc, e error) {
  36. // Setup channel and route the data
  37. conf.Log.Infof("Start running portable function meta %+v", reg)
  38. pm := GetPluginInsManager()
  39. ins, err := pm.getOrStartProcess(reg, PortbleConf)
  40. if err != nil {
  41. return nil, err
  42. }
  43. // Create function channel
  44. conf.Log.Infof("creating function channel for symbol %s", symbolName)
  45. dataCh, err := CreateFunctionChannel(symbolName)
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer func() {
  50. if e != nil {
  51. dataCh.Close()
  52. }
  53. }()
  54. // Start symbol
  55. c := &Control{
  56. SymbolName: symbolName,
  57. PluginType: TYPE_FUNC,
  58. }
  59. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, conf.Log)
  60. conf.Log.Infof("starting symbol %s", symbolName)
  61. err = ins.StartSymbol(ctx, c)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return &PortableFunc{
  66. symbolName: reg.Name,
  67. reg: reg,
  68. dataCh: dataCh,
  69. }, nil
  70. }
  71. func (f *PortableFunc) Validate(args []interface{}) error {
  72. // TODO function arg encoding
  73. jsonArg, err := encode("Validate", args)
  74. if err != nil {
  75. return err
  76. }
  77. res, err := f.dataCh.Req(jsonArg)
  78. if err != nil {
  79. return err
  80. }
  81. fr := &FuncReply{}
  82. err = json.Unmarshal(res, fr)
  83. if err != nil {
  84. return err
  85. }
  86. if fr.State {
  87. return nil
  88. } else {
  89. return fmt.Errorf("validate return state is false, got %+v", fr)
  90. }
  91. }
  92. func (f *PortableFunc) Exec(args []interface{}, ctx api.FunctionContext) (interface{}, bool) {
  93. ctx.GetLogger().Debugf("running portable func with args %+v", args)
  94. ctxRaw, err := encodeCtx(ctx)
  95. if err != nil {
  96. return err, false
  97. }
  98. jsonArg, err := encode("Exec", append(args, ctxRaw))
  99. if err != nil {
  100. return err, false
  101. }
  102. res, err := f.dataCh.Req(jsonArg)
  103. if err != nil {
  104. return err, false
  105. }
  106. fr := &FuncReply{}
  107. err = json.Unmarshal(res, fr)
  108. if err != nil {
  109. return fmt.Errorf("Failed to unmarshal function result %s", string(res)), false
  110. }
  111. if !fr.State {
  112. if fr.Result != nil {
  113. return fmt.Errorf("%s", fr.Result), false
  114. } else {
  115. return nil, false
  116. }
  117. }
  118. return fr.Result, fr.State
  119. }
  120. func (f *PortableFunc) IsAggregate() bool {
  121. if f.isAgg > 0 {
  122. return f.isAgg > 1
  123. }
  124. jsonArg, err := encode("IsAggregate", nil)
  125. if err != nil {
  126. conf.Log.Error(err)
  127. return false
  128. }
  129. res, err := f.dataCh.Req(jsonArg)
  130. if err != nil {
  131. conf.Log.Error(err)
  132. return false
  133. }
  134. fr := &FuncReply{}
  135. err = json.Unmarshal(res, fr)
  136. if err != nil {
  137. conf.Log.Error(err)
  138. return false
  139. }
  140. if fr.State {
  141. r, ok := fr.Result.(bool)
  142. if !ok {
  143. conf.Log.Errorf("IsAggregate result is not bool, got %s", string(res))
  144. return false
  145. } else {
  146. if r {
  147. f.isAgg = 2
  148. } else {
  149. f.isAgg = 1
  150. }
  151. return r
  152. }
  153. } else {
  154. conf.Log.Errorf("IsAggregate return state is false, got %+v", fr)
  155. return false
  156. }
  157. }
  158. func (f *PortableFunc) Close() error {
  159. return f.dataCh.Close()
  160. // Symbol must be closed by instance manager
  161. // ins.StopSymbol(ctx, c)
  162. }
  163. func encode(funcName string, arg interface{}) ([]byte, error) {
  164. c := FuncData{
  165. Func: funcName,
  166. Arg: arg,
  167. }
  168. return json.Marshal(c)
  169. }
  170. func encodeCtx(ctx api.FunctionContext) (string, error) {
  171. m := FuncMeta{
  172. Meta: Meta{
  173. RuleId: ctx.GetRuleId(),
  174. OpId: ctx.GetOpId(),
  175. InstanceId: ctx.GetInstanceId(),
  176. },
  177. FuncId: ctx.GetFuncId(),
  178. }
  179. bs, err := json.Marshal(m)
  180. return string(bs), err
  181. }