tcp_socket_opts.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # pylint: disable=C0111
  2. import logging
  3. import socket
  4. import pika.compat
  5. LOGGER = logging.getLogger(__name__)
  6. _SUPPORTED_TCP_OPTIONS = {}
  7. try:
  8. _SUPPORTED_TCP_OPTIONS['TCP_USER_TIMEOUT'] = socket.TCP_USER_TIMEOUT
  9. except AttributeError:
  10. if pika.compat.LINUX_VERSION and pika.compat.LINUX_VERSION >= (2, 6, 37):
  11. # this is not the timeout value, but the number corresponding
  12. # to the constant in tcp.h
  13. # https://github.com/torvalds/linux/blob/master/include/uapi/linux/tcp.h#
  14. # #define TCP_USER_TIMEOUT 18 /* How long for loss retry before timeout */
  15. _SUPPORTED_TCP_OPTIONS['TCP_USER_TIMEOUT'] = 18
  16. try:
  17. _SUPPORTED_TCP_OPTIONS['TCP_KEEPIDLE'] = socket.TCP_KEEPIDLE
  18. _SUPPORTED_TCP_OPTIONS['TCP_KEEPCNT'] = socket.TCP_KEEPCNT
  19. _SUPPORTED_TCP_OPTIONS['TCP_KEEPINTVL'] = socket.TCP_KEEPINTVL
  20. except AttributeError:
  21. pass
  22. def socket_requires_keepalive(tcp_options):
  23. return ('TCP_KEEPIDLE' in tcp_options or
  24. 'TCP_KEEPCNT' in tcp_options or
  25. 'TCP_KEEPINTVL' in tcp_options)
  26. def set_sock_opts(tcp_options, sock):
  27. if not tcp_options:
  28. return
  29. if socket_requires_keepalive(tcp_options):
  30. sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  31. for key, value in tcp_options.items():
  32. option = _SUPPORTED_TCP_OPTIONS.get(key)
  33. if option:
  34. sock.setsockopt(pika.compat.SOL_TCP, option, value)
  35. else:
  36. LOGGER.warning('Unsupported TCP option %s:%s', key, value)