connection.go 5.2 KB

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