connection.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Copyright 2021-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 runtime
  15. import (
  16. "fmt"
  17. "github.com/lf-edge/ekuiper/internal/conf"
  18. "github.com/lf-edge/ekuiper/pkg/api"
  19. "go.nanomsg.org/mangos/v3"
  20. "go.nanomsg.org/mangos/v3/protocol/pull"
  21. "go.nanomsg.org/mangos/v3/protocol/push"
  22. "go.nanomsg.org/mangos/v3/protocol/rep"
  23. _ "go.nanomsg.org/mangos/v3/transport/ipc"
  24. "sync"
  25. "time"
  26. )
  27. // TODO to design timeout strategy
  28. // sockOptions Initialized in config
  29. var (
  30. dialOptions = map[string]interface{}{
  31. mangos.OptionDialAsynch: false,
  32. mangos.OptionMaxReconnectTime: 5 * time.Second,
  33. mangos.OptionReconnectTime: 100 * time.Millisecond,
  34. }
  35. )
  36. type Closable interface {
  37. Close() error
  38. }
  39. type ControlChannel interface {
  40. Handshake() error
  41. SendCmd(arg []byte) error
  42. Closable
  43. }
  44. // NanomsgReqChannel shared by symbols
  45. type NanomsgReqChannel struct {
  46. sync.Mutex
  47. sock mangos.Socket
  48. }
  49. func (r *NanomsgReqChannel) Close() error {
  50. return r.sock.Close()
  51. }
  52. func (r *NanomsgReqChannel) SendCmd(arg []byte) error {
  53. r.Lock()
  54. defer r.Unlock()
  55. if err := r.sock.Send(arg); err != nil {
  56. return fmt.Errorf("can't send message on control rep socket: %s", err.Error())
  57. }
  58. if msg, err := r.sock.Recv(); err != nil {
  59. return fmt.Errorf("can't receive: %s", err.Error())
  60. } else {
  61. if string(msg) != "ok" {
  62. return fmt.Errorf("receive error: %s", string(msg))
  63. }
  64. }
  65. return nil
  66. }
  67. // Handshake should only be called once
  68. func (r *NanomsgReqChannel) Handshake() error {
  69. t, err := r.sock.GetOption(mangos.OptionRecvDeadline)
  70. if err != nil {
  71. return err
  72. }
  73. err = r.sock.SetOption(mangos.OptionRecvDeadline, 5*time.Second)
  74. if err != nil {
  75. return err
  76. }
  77. _, err = r.sock.Recv()
  78. if err != nil {
  79. return err
  80. }
  81. err = r.sock.SetOption(mangos.OptionRecvDeadline, t)
  82. if err != nil {
  83. return err
  84. }
  85. return nil
  86. }
  87. type DataInChannel interface {
  88. Recv() ([]byte, error)
  89. Closable
  90. }
  91. type DataOutChannel interface {
  92. Send([]byte) error
  93. Closable
  94. }
  95. type DataReqChannel interface {
  96. Handshake() error
  97. Req([]byte) ([]byte, error)
  98. Closable
  99. }
  100. type NanomsgReqRepChannel struct {
  101. sync.Mutex
  102. sock mangos.Socket
  103. }
  104. func (r *NanomsgReqRepChannel) Close() error {
  105. return r.sock.Close()
  106. }
  107. func (r *NanomsgReqRepChannel) Req(arg []byte) ([]byte, error) {
  108. r.Lock()
  109. defer r.Unlock()
  110. if err := r.sock.Send(arg); err != nil {
  111. return nil, fmt.Errorf("can't send message on function rep socket: %s", err.Error())
  112. }
  113. return r.sock.Recv()
  114. }
  115. // Handshake should only be called once
  116. func (r *NanomsgReqRepChannel) Handshake() error {
  117. _, err := r.sock.Recv()
  118. return err
  119. }
  120. func CreateSourceChannel(ctx api.StreamContext) (DataInChannel, error) {
  121. var (
  122. sock mangos.Socket
  123. err error
  124. )
  125. if sock, err = pull.NewSocket(); err != nil {
  126. return nil, fmt.Errorf("can't get new pull socket: %s", err)
  127. }
  128. setSockOptions(sock, map[string]interface{}{
  129. mangos.OptionRecvDeadline: 500 * time.Millisecond,
  130. })
  131. url := fmt.Sprintf("ipc:///tmp/%s_%s_%d.ipc", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId())
  132. if err = listenWithRetry(sock, url); err != nil {
  133. return nil, fmt.Errorf("can't listen on pull socket for %s: %s", url, err.Error())
  134. }
  135. conf.Log.Infof("source channel created: %s", url)
  136. return sock, nil
  137. }
  138. func CreateFunctionChannel(symbolName string) (DataReqChannel, error) {
  139. var (
  140. sock mangos.Socket
  141. err error
  142. )
  143. if sock, err = rep.NewSocket(); err != nil {
  144. return nil, fmt.Errorf("can't get new rep socket: %s", err)
  145. }
  146. // Function must send out data quickly and wait for the response with some buffer
  147. setSockOptions(sock, map[string]interface{}{
  148. mangos.OptionRecvDeadline: 5000 * time.Millisecond,
  149. mangos.OptionSendDeadline: 1000 * time.Millisecond,
  150. mangos.OptionRetryTime: 0,
  151. })
  152. url := fmt.Sprintf("ipc:///tmp/func_%s.ipc", symbolName)
  153. if err = listenWithRetry(sock, url); err != nil {
  154. return nil, fmt.Errorf("can't listen on rep socket for %s: %s", url, err.Error())
  155. }
  156. conf.Log.Infof("function channel created: %s", url)
  157. return &NanomsgReqRepChannel{sock: sock}, nil
  158. }
  159. func CreateSinkChannel(ctx api.StreamContext) (DataOutChannel, error) {
  160. var (
  161. sock mangos.Socket
  162. err error
  163. )
  164. if sock, err = push.NewSocket(); err != nil {
  165. return nil, fmt.Errorf("can't get new push socket: %s", err)
  166. }
  167. setSockOptions(sock, map[string]interface{}{
  168. mangos.OptionSendDeadline: 1000 * time.Millisecond,
  169. })
  170. url := fmt.Sprintf("ipc:///tmp/%s_%s_%d.ipc", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId())
  171. if err = sock.DialOptions(url, dialOptions); err != nil {
  172. return nil, fmt.Errorf("can't dial on push socket: %s", err.Error())
  173. }
  174. conf.Log.Infof("sink channel created: %s", url)
  175. return sock, nil
  176. }
  177. func CreateControlChannel(pluginName string) (ControlChannel, error) {
  178. var (
  179. sock mangos.Socket
  180. err error
  181. )
  182. if sock, err = rep.NewSocket(); err != nil {
  183. return nil, fmt.Errorf("can't get new rep socket: %s", err)
  184. }
  185. // NO time out now for control channel
  186. // because the plugin instance liveness can be detected
  187. // thus, if the plugin exit, the control channel will be closed
  188. setSockOptions(sock, map[string]interface{}{
  189. mangos.OptionRecvDeadline: 1 * time.Hour,
  190. })
  191. url := fmt.Sprintf("ipc:///tmp/plugin_%s.ipc", pluginName)
  192. if err = listenWithRetry(sock, url); err != nil {
  193. return nil, fmt.Errorf("can't listen on rep socket: %s", err.Error())
  194. }
  195. conf.Log.Infof("control channel created: %s", url)
  196. return &NanomsgReqChannel{sock: sock}, nil
  197. }
  198. func setSockOptions(sock mangos.Socket, sockOptions map[string]interface{}) {
  199. for k, v := range sockOptions {
  200. err := sock.SetOption(k, v)
  201. if err != nil && err != mangos.ErrBadOption {
  202. conf.Log.Errorf("can't set socket option %s: %s", k, err.Error())
  203. }
  204. }
  205. }
  206. func listenWithRetry(sock mangos.Socket, url string) error {
  207. var (
  208. retryCount = 300
  209. retryInterval = 100
  210. )
  211. for {
  212. err := sock.Listen(url)
  213. if err == nil {
  214. conf.Log.Infof("start to listen at %s after %d tries", url, 301-retryCount)
  215. return err
  216. }
  217. retryCount--
  218. if retryCount < 0 {
  219. return err
  220. }
  221. time.Sleep(time.Duration(retryInterval) * time.Millisecond)
  222. }
  223. }