Skip to content

prefect_kubernetes.utilities

Utilities for working with the Python Kubernetes API.

KeepAliveClientRequest

Bases: ClientRequest

aiohttp only directly implements socket keepalive for incoming connections in its RequestHandler. For client connections, we need to set the keepalive ourselves.

Refer to https://github.com/aio-libs/aiohttp/issues/3904#issuecomment-759205696

Source code in prefect_kubernetes/utilities.py
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
class KeepAliveClientRequest(ClientRequest):
    """
    aiohttp only directly implements socket keepalive for incoming connections
    in its RequestHandler. For client connections, we need to set the keepalive
    ourselves.

    Refer to https://github.com/aio-libs/aiohttp/issues/3904#issuecomment-759205696
    """

    async def send(self, conn: Connection) -> ClientResponse:
        sock = conn.protocol.transport.get_extra_info("socket")
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 30)

        if hasattr(socket, "TCP_KEEPINTVL"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 6)

        if hasattr(socket, "TCP_KEEPCNT"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 6)

        if sys.platform == "darwin":
            # TCP_KEEP_ALIVE not available on socket module in macOS, but defined in
            # https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/netinet/tcp.h#L215
            TCP_KEEP_ALIVE = 0x10
            sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEP_ALIVE, 30)

        return await super().send(conn)