connection.go 5.5 KB

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