connection.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. if err == mangos.ErrProtoState {
  57. _, err = r.sock.Recv()
  58. if err == nil {
  59. err = r.sock.Send(arg)
  60. if err == nil {
  61. return nil
  62. }
  63. }
  64. }
  65. return fmt.Errorf("can't send message on control rep socket: %s", err.Error())
  66. }
  67. if msg, err := r.sock.Recv(); err != nil {
  68. return fmt.Errorf("can't receive: %s", err.Error())
  69. } else {
  70. if string(msg) != "ok" {
  71. return fmt.Errorf("receive error: %s", string(msg))
  72. }
  73. }
  74. return nil
  75. }
  76. // Handshake should only be called once
  77. func (r *NanomsgReqChannel) Handshake() error {
  78. t, err := r.sock.GetOption(mangos.OptionRecvDeadline)
  79. if err != nil {
  80. return err
  81. }
  82. err = r.sock.SetOption(mangos.OptionRecvDeadline, 5*time.Second)
  83. if err != nil {
  84. return err
  85. }
  86. _, err = r.sock.Recv()
  87. if err != nil && err != mangos.ErrProtoState {
  88. return err
  89. }
  90. err = r.sock.SetOption(mangos.OptionRecvDeadline, t)
  91. if err != nil {
  92. return err
  93. }
  94. return nil
  95. }
  96. type DataInChannel interface {
  97. Recv() ([]byte, error)
  98. Closable
  99. }
  100. type DataOutChannel interface {
  101. Send([]byte) error
  102. Closable
  103. }
  104. type DataReqChannel interface {
  105. Handshake() error
  106. Req([]byte) ([]byte, error)
  107. Closable
  108. }
  109. type NanomsgReqRepChannel struct {
  110. sync.Mutex
  111. sock mangos.Socket
  112. }
  113. func (r *NanomsgReqRepChannel) Close() error {
  114. return r.sock.Close()
  115. }
  116. func (r *NanomsgReqRepChannel) Req(arg []byte) ([]byte, error) {
  117. r.Lock()
  118. defer r.Unlock()
  119. if err := r.sock.Send(arg); err != nil {
  120. if err == mangos.ErrProtoState { // resend if protocol state wrong, because of plugin restart or other problems
  121. err = r.Handshake()
  122. if err == nil {
  123. err = r.sock.Send(arg)
  124. if err == nil {
  125. return r.sock.Recv()
  126. }
  127. }
  128. }
  129. return nil, fmt.Errorf("can't send message on function rep socket: %s", err.Error())
  130. }
  131. return r.sock.Recv()
  132. }
  133. // Handshake should only be called once
  134. func (r *NanomsgReqRepChannel) Handshake() error {
  135. _, err := r.sock.Recv()
  136. if err != nil && err != mangos.ErrProtoState {
  137. return err
  138. }
  139. return nil
  140. }
  141. func CreateSourceChannel(ctx api.StreamContext) (DataInChannel, error) {
  142. var (
  143. sock mangos.Socket
  144. err error
  145. )
  146. if sock, err = pull.NewSocket(); err != nil {
  147. return nil, fmt.Errorf("can't get new pull socket: %s", err)
  148. }
  149. setSockOptions(sock, map[string]interface{}{
  150. mangos.OptionRecvDeadline: 500 * time.Millisecond,
  151. })
  152. url := fmt.Sprintf("ipc:///tmp/%s_%s_%d.ipc", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId())
  153. if err = listenWithRetry(sock, url); err != nil {
  154. return nil, fmt.Errorf("can't listen on pull socket for %s: %s", url, err.Error())
  155. }
  156. conf.Log.Infof("source channel created: %s", url)
  157. return sock, nil
  158. }
  159. func CreateFunctionChannel(symbolName string) (DataReqChannel, error) {
  160. var (
  161. sock mangos.Socket
  162. err error
  163. )
  164. if sock, err = rep.NewSocket(); err != nil {
  165. return nil, fmt.Errorf("can't get new rep socket: %s", err)
  166. }
  167. // Function must send out data quickly and wait for the response with some buffer
  168. setSockOptions(sock, map[string]interface{}{
  169. mangos.OptionRecvDeadline: 5000 * time.Millisecond,
  170. mangos.OptionSendDeadline: 1000 * time.Millisecond,
  171. mangos.OptionRetryTime: 0,
  172. })
  173. url := fmt.Sprintf("ipc:///tmp/func_%s.ipc", symbolName)
  174. if err = listenWithRetry(sock, url); err != nil {
  175. return nil, fmt.Errorf("can't listen on rep socket for %s: %s", url, err.Error())
  176. }
  177. conf.Log.Infof("function channel created: %s", url)
  178. return &NanomsgReqRepChannel{sock: sock}, nil
  179. }
  180. func CreateSinkChannel(ctx api.StreamContext) (DataOutChannel, error) {
  181. var (
  182. sock mangos.Socket
  183. err error
  184. )
  185. if sock, err = push.NewSocket(); err != nil {
  186. return nil, fmt.Errorf("can't get new push socket: %s", err)
  187. }
  188. setSockOptions(sock, map[string]interface{}{
  189. mangos.OptionSendDeadline: 1000 * time.Millisecond,
  190. })
  191. url := fmt.Sprintf("ipc:///tmp/%s_%s_%d.ipc", ctx.GetRuleId(), ctx.GetOpId(), ctx.GetInstanceId())
  192. if err = sock.DialOptions(url, dialOptions); err != nil {
  193. return nil, fmt.Errorf("can't dial on push socket: %s", err.Error())
  194. }
  195. conf.Log.Infof("sink channel created: %s", url)
  196. return sock, nil
  197. }
  198. func CreateControlChannel(pluginName string) (ControlChannel, error) {
  199. var (
  200. sock mangos.Socket
  201. err error
  202. )
  203. if sock, err = rep.NewSocket(); err != nil {
  204. return nil, fmt.Errorf("can't get new rep socket: %s", err)
  205. }
  206. // NO time out now for control channel
  207. // because the plugin instance liveness can be detected
  208. // thus, if the plugin exit, the control channel will be closed
  209. setSockOptions(sock, map[string]interface{}{
  210. mangos.OptionRecvDeadline: 1 * time.Hour,
  211. })
  212. url := fmt.Sprintf("ipc:///tmp/plugin_%s.ipc", pluginName)
  213. if err = listenWithRetry(sock, url); err != nil {
  214. return nil, fmt.Errorf("can't listen on rep socket: %s", err.Error())
  215. }
  216. conf.Log.Infof("control channel created: %s", url)
  217. return &NanomsgReqChannel{sock: sock}, nil
  218. }
  219. func setSockOptions(sock mangos.Socket, sockOptions map[string]interface{}) {
  220. for k, v := range sockOptions {
  221. err := sock.SetOption(k, v)
  222. if err != nil && err != mangos.ErrBadOption {
  223. conf.Log.Errorf("can't set socket option %s: %s", k, err.Error())
  224. }
  225. }
  226. }
  227. func listenWithRetry(sock mangos.Socket, url string) error {
  228. var (
  229. retryCount = 300
  230. retryInterval = 100
  231. )
  232. for {
  233. err := sock.Listen(url)
  234. if err == nil {
  235. conf.Log.Infof("start to listen at %s after %d tries", url, 301-retryCount)
  236. return err
  237. }
  238. retryCount--
  239. if retryCount < 0 {
  240. return err
  241. }
  242. time.Sleep(time.Duration(retryInterval) * time.Millisecond)
  243. }
  244. }