sink.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. context2 "context"
  17. "fmt"
  18. "github.com/lf-edge/ekuiper/sdk/go/api"
  19. "github.com/lf-edge/ekuiper/sdk/go/connection"
  20. )
  21. type sinkRuntime struct {
  22. s api.Sink
  23. ch connection.DataInChannel
  24. ctx api.StreamContext
  25. cancel context2.CancelFunc
  26. key string
  27. }
  28. func setupSinkRuntime(con *Control, s api.Sink) (*sinkRuntime, error) {
  29. ctx, err := parseContext(con)
  30. if err != nil {
  31. return nil, err
  32. }
  33. err = s.Configure(con.Config)
  34. if err != nil {
  35. return nil, err
  36. }
  37. ch, err := connection.CreateSinkChannel(ctx)
  38. if err != nil {
  39. return nil, err
  40. }
  41. ctx.GetLogger().Info("Setup message pipeline, start listening")
  42. ctx, cancel := ctx.WithCancel()
  43. return &sinkRuntime{
  44. s: s,
  45. ch: ch,
  46. ctx: ctx,
  47. cancel: cancel,
  48. key: fmt.Sprintf("%s_%s_%d_%s", con.Meta.RuleId, con.Meta.OpId, con.Meta.InstanceId, con.SymbolName),
  49. }, nil
  50. }
  51. func (s *sinkRuntime) run() {
  52. err := s.s.Open(s.ctx)
  53. if err != nil {
  54. s.stop()
  55. return
  56. }
  57. for {
  58. var msg []byte
  59. msg, err = s.ch.Recv()
  60. if err != nil {
  61. s.ctx.GetLogger().Errorf("cannot receive from mangos Socket: %s", err.Error())
  62. s.stop()
  63. return
  64. }
  65. err = s.s.Collect(s.ctx, msg)
  66. if err != nil {
  67. s.ctx.GetLogger().Errorf("collect error: %s", err.Error())
  68. s.stop()
  69. return
  70. }
  71. }
  72. }
  73. func (s *sinkRuntime) stop() error {
  74. s.cancel()
  75. s.s.Close(s.ctx)
  76. err := s.ch.Close()
  77. if err != nil {
  78. s.ctx.GetLogger().Info(err)
  79. }
  80. s.ctx.GetLogger().Info("closed sink data channel")
  81. reg.Delete(s.key)
  82. return nil
  83. }
  84. func (s *sinkRuntime) isRunning() bool {
  85. return s.ctx.Err() == nil
  86. }