PageRenderTime 28ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/channel/SenderChannel.py

https://bitbucket.org/selfStabilizingAtomicStorage/datx05-code
Python | 156 lines | 104 code | 8 blank | 44 comment | 26 complexity | 87c5004c0ef49adad4d10ace0f346563 MD5 | raw file
Possible License(s): MIT
  1. #!/bin/python3.6
  2. # -*- coding: utf-8 -*-
  3. #
  4. # MIT License
  5. #
  6. # Copyright (c) 2018 Robert Gustafsson
  7. # Copyright (c) 2018 Andreas Lindhé
  8. #
  9. # Permission is hereby granted, free of charge, to any person obtaining a copy
  10. # of this software and associated documentation files (the "Software"), to deal
  11. # in the Software without restriction, including without limitation the rights
  12. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. # copies of the Software, and to permit persons to whom the Software is
  14. # furnished to do so, subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included in all
  17. # copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. # SOFTWARE.
  26. import asyncio
  27. import struct
  28. import socket
  29. import io
  30. from .UdpSender import UdpSender
  31. class SenderChannel:
  32. """ Creates an instance of a sender channel"""
  33. def __init__(self, sid, uid, channel_type, callback_obj,
  34. ip, port, timeout = 2, init_tx = None, chunks_size = 1024):
  35. """
  36. Define all parameters that is specific to this channel
  37. """
  38. self.sid = sid
  39. self.uid = uid.encode()
  40. self.ch_type = channel_type
  41. self.cb_obj = callback_obj
  42. self.ip = ip
  43. self.port = int(port)
  44. self.udp_timeout = timeout
  45. self.tcp_timeout = timeout*5
  46. self.tx = init_tx
  47. self.chunks_size = chunks_size
  48. self.cap = 2**31
  49. self.loop = asyncio.get_event_loop()
  50. self.udp = True
  51. self.token_size = 2*struct.calcsize("i")+struct.calcsize("17s")
  52. self.addr = (ip, int(port))
  53. self.udp_sock = UdpSender(self.loop)
  54. self.tc_sock = None
  55. async def receive(self, token):
  56. """
  57. Waits for data on either tcp or udp port to be received and then return the data.
  58. If no data is received in self.timeout seconds, assume msg is lost and
  59. resend it.
  60. """
  61. while True:
  62. try:
  63. if self.udp:
  64. res, addr = await asyncio.wait_for(self.udp_sock.recvfrom(self.chunks_size), self.udp_timeout)
  65. else:
  66. res = await self.tcp_recv()
  67. token = res[:self.token_size]
  68. msg_type, msg_cntr, sender = struct.unpack("ii17s", token)
  69. msg_data = res[self.token_size:]
  70. break
  71. except Exception as e:
  72. msg = token+self.tx if self.tx else token
  73. if self.udp:
  74. if __debug__:
  75. print("Sending udp to %s" % str(self.addr))
  76. await self.udp_sock.sendto(msg, self.addr)
  77. else:
  78. await self.tcp_send(msg)
  79. if __debug__:
  80. print("TIMEOUT: no response within {}s".format(self.udp_timeout))
  81. return (sender, msg_type, msg_cntr, msg_data)
  82. async def start(self):
  83. """
  84. main loop for a sender channel. Receive data and if it is a token
  85. arrival construct a new message and send it.
  86. """
  87. counter = 1
  88. token = struct.pack("ii17s", self.ch_type, counter, self.uid)
  89. await asyncio.sleep(2)
  90. await self.udp_sock.sendto(token, self.addr)
  91. while True:
  92. token = struct.pack("ii17s", self.ch_type, counter, self.uid)
  93. sender, msg_type, msg_cntr, msg_data = await self.receive(token)
  94. if __debug__:
  95. print("Token arrival: cntr is {}".format(msg_cntr))
  96. if(msg_cntr >= counter):
  97. if self.ch_type:
  98. self.tx, self.udp = await self.cb_obj.departure(sender, msg_data)
  99. else:
  100. self.tx, self.udp = await self.cb_obj.departure(self.sid, msg_data)
  101. counter = (msg_cntr+1) % self.cap
  102. token = struct.pack("ii17s", self.ch_type, counter, self.uid)
  103. msg = token+self.tx if self.tx else token
  104. if self.udp:
  105. await self.udp_sock.sendto(msg, self.addr)
  106. else:
  107. await self.tcp_send(msg)
  108. async def tcp_connect(self):
  109. """
  110. Create a new tcp socket and wait until there is a connection
  111. """
  112. if self.tc_sock:
  113. self.tc_sock.close()
  114. self.tc_sock = socket.socket()
  115. self.tc_sock.setblocking(False)
  116. while True:
  117. try:
  118. await self.loop.sock_connect(self.tc_sock, (self.ip, self.port))
  119. except OSError as e:
  120. if __debug__:
  121. print("Trying to connect to ({}, {})".format(self.ip, self.port))
  122. await asyncio.sleep(1)
  123. else:
  124. break
  125. async def tcp_recv(self):
  126. """
  127. Read a stream of tcp messages until the server closes the socket
  128. """
  129. msg = b''
  130. while True:
  131. res_part = await asyncio.wait_for(self.loop.sock_recv(self.tc_sock, self.chunks_size), self.tcp_timeout)
  132. if not res_part:
  133. break
  134. else:
  135. msg += res_part
  136. return msg
  137. async def tcp_send(self, msg):
  138. """
  139. Send tcp stream in chunks defined by chunk_size
  140. """
  141. await self.tcp_connect()
  142. msg_size = struct.pack("i", len(msg))
  143. response_stream = io.BytesIO(msg_size+msg)
  144. stream = True
  145. while stream:
  146. stream = response_stream.read(self.chunks_size)
  147. await self.loop.sock_sendall(self.tc_sock, stream)