connection.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright 2021 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. import logging
  15. import time
  16. from typing import Callable
  17. from pynng import Req0, Push0, Pull0
  18. class PairChannel:
  19. def __init__(self, name: str, typ: int):
  20. s = Req0()
  21. """TODO options"""
  22. if typ == 0:
  23. url = "ipc:///tmp/plugin_{}.ipc".format(name)
  24. else:
  25. url = "ipc:///tmp/func_{}.ipc".format(name)
  26. s.dial(url)
  27. self.sock = s
  28. """ run this in a new thread"""
  29. def run(self, reply_func: Callable[[bytes], bytes]):
  30. self.sock.send(b'handshake')
  31. while True:
  32. msg = self.sock.recv()
  33. reply = reply_func(msg)
  34. self.sock.send(reply)
  35. def close(self):
  36. self.sock.close()
  37. class SourceChannel:
  38. def __init__(self, meta: dict):
  39. s = Push0()
  40. url = "ipc:///tmp/{}_{}_{}.ipc".format(meta['ruleId'], meta['opId'], meta['instanceId'])
  41. logging.info(url)
  42. s.dial(url)
  43. self.sock = s
  44. def send(self, data: bytes):
  45. self.sock.send(data)
  46. def close(self):
  47. self.sock.close()
  48. class SinkChannel:
  49. def __init__(self, meta: dict):
  50. s = Pull0()
  51. url = "ipc:///tmp/{}_{}_{}.ipc".format(meta['ruleId'], meta['opId'], meta['instanceId'])
  52. logging.info(url)
  53. listen_with_retry(s, url)
  54. self.sock = s
  55. def recv(self) -> bytes:
  56. return self.sock.recv()
  57. def close(self):
  58. self.sock.close()
  59. def listen_with_retry(sock, url: str):
  60. retry_count = 10
  61. retry_interval = 0.05
  62. while True:
  63. # noinspection PyBroadException
  64. try:
  65. sock.listen(url)
  66. break
  67. except Exception:
  68. retry_count -= 1
  69. if retry_count < 0:
  70. raise
  71. time.sleep(retry_interval)