connection.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // Copyright 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 neuron
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "sync"
  19. "sync/atomic"
  20. "time"
  21. "go.nanomsg.org/mangos/v3"
  22. "go.nanomsg.org/mangos/v3/protocol/pair"
  23. // introduce ipc/tpc
  24. _ "go.nanomsg.org/mangos/v3/transport/ipc"
  25. _ "go.nanomsg.org/mangos/v3/transport/tcp"
  26. "github.com/lf-edge/ekuiper/internal/conf"
  27. "github.com/lf-edge/ekuiper/internal/io/memory/pubsub"
  28. kctx "github.com/lf-edge/ekuiper/internal/topo/context"
  29. "github.com/lf-edge/ekuiper/internal/topo/state"
  30. "github.com/lf-edge/ekuiper/pkg/api"
  31. "github.com/lf-edge/ekuiper/pkg/errorx"
  32. )
  33. const (
  34. TopicPrefix = "$$neuron_"
  35. DefaultNeuronUrl = "ipc:///tmp/neuron-ekuiper.ipc"
  36. )
  37. type conninfo struct {
  38. count int
  39. sock mangos.Socket
  40. opened int32
  41. }
  42. var (
  43. m sync.RWMutex
  44. connectionReg = make(map[string]*conninfo)
  45. sendTimeout = 100
  46. )
  47. // createOrGetNeuronConnection creates a new neuron connection or returns an existing one
  48. // This is the entry function for creating a neuron connection singleton
  49. // The context is from a rule, but the singleton will server for multiple rules
  50. func createOrGetConnection(sc api.StreamContext, url string) (*conninfo, error) {
  51. m.Lock()
  52. defer m.Unlock()
  53. sc.GetLogger().Infof("createOrGetConnection for %s", url)
  54. info, ok := connectionReg[url]
  55. if !ok || info.count <= 0 {
  56. sc.GetLogger().Infof("Creating neuron connection for %s", url)
  57. contextLogger := conf.Log.WithField("neuron_connection_url", url)
  58. ctx := kctx.WithValue(kctx.Background(), kctx.LoggerKey, contextLogger)
  59. ruleId := "$$neuron_connection_" + url
  60. opId := "$$neuron_connection_" + url
  61. store, err := state.CreateStore(ruleId, 0)
  62. if err != nil {
  63. ctx.GetLogger().Errorf("neuron connection create store error %v", err)
  64. return nil, err
  65. }
  66. sctx := ctx.WithMeta(ruleId, opId, store)
  67. info = &conninfo{count: 0}
  68. connectionReg[url] = info
  69. err = connect(sctx, url, info)
  70. if err != nil {
  71. return nil, err
  72. }
  73. sc.GetLogger().Infof("Neuron %s connected", url)
  74. pubsub.CreatePub(TopicPrefix + url)
  75. go run(sctx, info, url)
  76. }
  77. info.count++
  78. return info, nil
  79. }
  80. func closeConnection(ctx api.StreamContext, url string) error {
  81. m.Lock()
  82. defer m.Unlock()
  83. ctx.GetLogger().Infof("closeConnection %s", url)
  84. info, ok := connectionReg[url]
  85. if !ok {
  86. return fmt.Errorf("no connection for %s", url)
  87. }
  88. pubsub.RemovePub(TopicPrefix + url)
  89. if info.count == 1 {
  90. if info.sock != nil {
  91. err := info.sock.Close()
  92. if err != nil {
  93. return err
  94. }
  95. }
  96. }
  97. info.count--
  98. return nil
  99. }
  100. // nng connections
  101. // connect to nng
  102. func connect(ctx api.StreamContext, url string, info *conninfo) error {
  103. var err error
  104. info.sock, err = pair.NewSocket()
  105. if err != nil {
  106. return err
  107. }
  108. // options consider to export
  109. err = info.sock.SetOption(mangos.OptionSendDeadline, time.Duration(sendTimeout)*time.Millisecond)
  110. if err != nil {
  111. return err
  112. }
  113. info.sock.SetPipeEventHook(func(ev mangos.PipeEvent, p mangos.Pipe) {
  114. switch ev {
  115. case mangos.PipeEventAttached:
  116. atomic.StoreInt32(&info.opened, 1)
  117. conf.Log.Infof("neuron connection attached")
  118. case mangos.PipeEventAttaching:
  119. conf.Log.Infof("neuron connection is attaching")
  120. case mangos.PipeEventDetached:
  121. atomic.StoreInt32(&info.opened, 0)
  122. conf.Log.Warnf("neuron connection detached")
  123. pubsub.ProduceError(ctx, TopicPrefix+url, fmt.Errorf("neuron connection detached"))
  124. }
  125. })
  126. // sock.SetOption(mangos.OptionWriteQLen, 100)
  127. // sock.SetOption(mangos.OptionReadQLen, 100)
  128. // sock.SetOption(mangos.OptionBestEffort, false)
  129. if err = info.sock.DialOptions(url, map[string]interface{}{
  130. mangos.OptionDialAsynch: true, // will not report error and keep connecting
  131. mangos.OptionMaxReconnectTime: 5 * time.Second,
  132. mangos.OptionReconnectTime: 100 * time.Millisecond,
  133. }); err != nil {
  134. return fmt.Errorf("please make sure neuron has started and configured, can't dial to neuron: %s", err.Error())
  135. }
  136. return nil
  137. }
  138. // run the loop to receive message from the nng connection singleton
  139. // exit when connection is closed
  140. func run(ctx api.StreamContext, info *conninfo, url string) {
  141. ctx.GetLogger().Infof("neuron source receiving loop started")
  142. for {
  143. // no receiving deadline, will wait until the socket closed
  144. if msg, err := info.sock.Recv(); err == nil {
  145. ctx.GetLogger().Debugf("neuron received message %s", string(msg))
  146. result := make(map[string]interface{})
  147. err := json.Unmarshal(msg, &result)
  148. if err != nil {
  149. ctx.GetLogger().Errorf("neuron decode message error %v", err)
  150. continue
  151. }
  152. pubsub.Produce(ctx, TopicPrefix+url, result)
  153. } else if err == mangos.ErrClosed {
  154. ctx.GetLogger().Infof("neuron connection closed, exit receiving loop")
  155. return
  156. } else {
  157. ctx.GetLogger().Errorf("neuron receiving error %v", err)
  158. }
  159. }
  160. }
  161. func publish(ctx api.StreamContext, data []byte, info *conninfo) error {
  162. ctx.GetLogger().Debugf("publish to neuron: %s", string(data))
  163. if info.sock != nil && atomic.LoadInt32(&info.opened) == 1 {
  164. return info.sock.Send(data)
  165. }
  166. return fmt.Errorf("%s: neuron connection is not established", errorx.IOErr)
  167. }