sink.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. package runtime
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/pkg/api"
  18. )
  19. type PortableSink struct {
  20. symbolName string
  21. reg *PluginMeta
  22. props map[string]interface{}
  23. dataCh DataOutChannel
  24. clean func() error
  25. }
  26. func NewPortableSink(symbolName string, reg *PluginMeta) *PortableSink {
  27. return &PortableSink{
  28. symbolName: symbolName,
  29. reg: reg,
  30. }
  31. }
  32. func (ps *PortableSink) Configure(props map[string]interface{}) error {
  33. ps.props = props
  34. return nil
  35. }
  36. func (ps *PortableSink) Open(ctx api.StreamContext) error {
  37. ctx.GetLogger().Infof("Start running portable sink %s with conf %+v", ps.symbolName, ps.props)
  38. pm := GetPluginInsManager()
  39. ins, err := pm.getOrStartProcess(ps.reg, PortbleConf)
  40. if err != nil {
  41. return err
  42. }
  43. ctx.GetLogger().Infof("Plugin started successfully")
  44. // Control: send message to plugin to ask starting symbol
  45. c := &Control{
  46. Meta: &Meta{
  47. RuleId: ctx.GetRuleId(),
  48. OpId: ctx.GetOpId(),
  49. InstanceId: ctx.GetInstanceId(),
  50. },
  51. SymbolName: ps.symbolName,
  52. PluginType: TYPE_SINK,
  53. Config: ps.props,
  54. }
  55. err = ins.StartSymbol(ctx, c)
  56. if err != nil {
  57. return err
  58. }
  59. // must start symbol firstly
  60. dataCh, err := CreateSinkChannel(ctx)
  61. if err != nil {
  62. return err
  63. }
  64. ps.clean = func() error {
  65. ctx.GetLogger().Info("closing sink data channe")
  66. dataCh.Close()
  67. return ins.StopSymbol(ctx, c)
  68. }
  69. ps.dataCh = dataCh
  70. return nil
  71. }
  72. func (ps *PortableSink) Collect(ctx api.StreamContext, item interface{}) error {
  73. ctx.GetLogger().Debugf("Receive %+v", item)
  74. // TODO item type
  75. switch input := item.(type) {
  76. case []byte:
  77. return ps.dataCh.Send(input)
  78. default:
  79. return ps.dataCh.Send([]byte(fmt.Sprintf("%v", input)))
  80. }
  81. }
  82. func (ps *PortableSink) Close(ctx api.StreamContext) error {
  83. return ps.clean()
  84. }