function.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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, 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, false)
  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. // Start symbol
  50. c := &Control{
  51. SymbolName: symbolName,
  52. PluginType: TYPE_FUNC,
  53. }
  54. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, conf.Log)
  55. conf.Log.Infof("starting symbol %s", symbolName)
  56. err = ins.StartSymbol(ctx, c)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return &PortableFunc{
  61. symbolName: reg.Name,
  62. reg: reg,
  63. dataCh: dataCh,
  64. }, nil
  65. }
  66. func (f *PortableFunc) Validate(args []interface{}) error {
  67. // TODO function arg encoding
  68. jsonArg, err := encode("Validate", args)
  69. if err != nil {
  70. return err
  71. }
  72. res, err := f.dataCh.Req(jsonArg)
  73. if err != nil {
  74. return err
  75. }
  76. fr := &FuncReply{}
  77. err = json.Unmarshal(res, fr)
  78. if err != nil {
  79. return err
  80. }
  81. if fr.State {
  82. return nil
  83. } else {
  84. return fmt.Errorf("validate return state is false, got %+v", fr)
  85. }
  86. }
  87. func (f *PortableFunc) Exec(args []interface{}, ctx api.FunctionContext) (interface{}, bool) {
  88. ctx.GetLogger().Debugf("running portable func with args %+v", args)
  89. ctxRaw, err := encodeCtx(ctx)
  90. if err != nil {
  91. return err, false
  92. }
  93. jsonArg, err := encode("Exec", append(args, ctxRaw))
  94. if err != nil {
  95. return err, false
  96. }
  97. res, err := f.dataCh.Req(jsonArg)
  98. if err != nil {
  99. return err, false
  100. }
  101. fr := &FuncReply{}
  102. err = json.Unmarshal(res, fr)
  103. if err != nil {
  104. return fmt.Errorf("Failed to unmarshal function result %s", string(res)), false
  105. }
  106. if !fr.State {
  107. if fr.Result != nil {
  108. return fmt.Errorf("%s", fr.Result), false
  109. } else {
  110. return nil, false
  111. }
  112. }
  113. return fr.Result, fr.State
  114. }
  115. func (f *PortableFunc) IsAggregate() bool {
  116. if f.isAgg > 0 {
  117. return f.isAgg > 1
  118. }
  119. jsonArg, err := encode("IsAggregate", nil)
  120. if err != nil {
  121. conf.Log.Error(err)
  122. return false
  123. }
  124. res, err := f.dataCh.Req(jsonArg)
  125. if err != nil {
  126. conf.Log.Error(err)
  127. return false
  128. }
  129. fr := &FuncReply{}
  130. err = json.Unmarshal(res, fr)
  131. if err != nil {
  132. conf.Log.Error(err)
  133. return false
  134. }
  135. if fr.State {
  136. r, ok := fr.Result.(bool)
  137. if !ok {
  138. conf.Log.Errorf("IsAggregate result is not bool, got %s", string(res))
  139. return false
  140. } else {
  141. if r {
  142. f.isAgg = 2
  143. } else {
  144. f.isAgg = 1
  145. }
  146. return r
  147. }
  148. } else {
  149. conf.Log.Errorf("IsAggregate return state is false, got %+v", fr)
  150. return false
  151. }
  152. }
  153. func (f *PortableFunc) Close() error {
  154. return f.dataCh.Close()
  155. // Symbol must be closed by instance manager
  156. // ins.StopSymbol(ctx, c)
  157. }
  158. func encode(funcName string, arg interface{}) ([]byte, error) {
  159. c := FuncData{
  160. Func: funcName,
  161. Arg: arg,
  162. }
  163. return json.Marshal(c)
  164. }
  165. func encodeCtx(ctx api.FunctionContext) (string, error) {
  166. m := FuncMeta{
  167. Meta: Meta{
  168. RuleId: ctx.GetRuleId(),
  169. OpId: ctx.GetOpId(),
  170. InstanceId: ctx.GetInstanceId(),
  171. },
  172. FuncId: ctx.GetFuncId(),
  173. }
  174. bs, err := json.Marshal(m)
  175. return string(bs), err
  176. }