connection.go 6.9 KB

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