File: tcp_socket_opts.py

package info (click to toggle)
python-pika 1.3.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,068 kB
  • sloc: python: 20,886; makefile: 136
file content (47 lines) | stat: -rw-r--r-- 1,513 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# pylint: disable=C0111

import logging
import socket
import pika.compat

LOGGER = logging.getLogger(__name__)

_SUPPORTED_TCP_OPTIONS = {}

try:
    _SUPPORTED_TCP_OPTIONS['TCP_USER_TIMEOUT'] = socket.TCP_USER_TIMEOUT
except AttributeError:
    if pika.compat.LINUX_VERSION and pika.compat.LINUX_VERSION >= (2, 6, 37):
        # this is not the timeout value, but the number corresponding
        # to the constant in tcp.h
        # https://github.com/torvalds/linux/blob/master/include/uapi/linux/tcp.h#
        # #define TCP_USER_TIMEOUT	18	/* How long for loss retry before timeout */
        _SUPPORTED_TCP_OPTIONS['TCP_USER_TIMEOUT'] = 18

try:
    _SUPPORTED_TCP_OPTIONS['TCP_KEEPIDLE'] = socket.TCP_KEEPIDLE
    _SUPPORTED_TCP_OPTIONS['TCP_KEEPCNT'] = socket.TCP_KEEPCNT
    _SUPPORTED_TCP_OPTIONS['TCP_KEEPINTVL'] = socket.TCP_KEEPINTVL
except AttributeError:
    pass


def socket_requires_keepalive(tcp_options):
    return ('TCP_KEEPIDLE' in tcp_options or
            'TCP_KEEPCNT' in tcp_options or
            'TCP_KEEPINTVL' in tcp_options)


def set_sock_opts(tcp_options, sock):
    if not tcp_options:
        return

    if socket_requires_keepalive(tcp_options):
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

    for key, value in tcp_options.items():
        option = _SUPPORTED_TCP_OPTIONS.get(key)
        if option:
            sock.setsockopt(pika.compat.SOL_TCP, option, value)
        else:
            LOGGER.warning('Unsupported TCP option %s:%s', key, value)