iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😽

Verifying that TCP keepalive does not start while packets are being retransmitted

に公開

This is a functional confirmation of the TCP keepalive feature discussed in the following article.

https://blog.cybozu.io/entry/2015/11/26/170019

I had seen the article in the past and thought, "I see," but about five years later, I suddenly decided to check it myself because "it's not good to feel like you understand without actually seeing it!" What I wanted to confirm is, as the title suggests, that "TCP keepalive does not start operation when there are packets being retransmitted." For details on why this behavior is problematic, please refer to the original article.

Experimental Environment

I used the following two machines.

  • coffee (Server machine): OS is Ubuntu 22.04, kernel is v5.15.0-117-generic.
  • tea (Client machine): OS is Ubuntu 22.04, kernel is v5.15.0-107-generic.

On the server and client machines, I ran server.py and client.py, which communicate via TCP.

server.py waits for a connection from client.py, outputs the received data, sends the same data back, and then terminates.

server.py
import socket
from datetime import datetime

HOST = "0.0.0.0"
PORT = 10000

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print(f"{datetime.now()}: listening {HOST}:{PORT}.")

    conn, addr = s.accept()
    with conn:
        print(f"{datetime.now()}: connected from {addr}.")
        try:
            data = conn.recv(1024)
            print(f"{datetime.now()}: received `{data.decode()}`.")
            conn.sendall(data)
        except (socket.error, OSError) as e:
            print(f"{datetime.now()}: {e}.")

client.py connects to server.py, waits for the user to press the ENTER key, sends a message to server.py 5 seconds after the input, outputs the returned message, and terminates. I have configured TCP keepalive on the socket to automatically close the connection if communication between the client and server machines is impossible for more than 10 seconds for some reason.

client.py
import socket
import time
from datetime import datetime

HOST = "192.168.1.100" # IP address of the server (coffee)
PORT = 10000

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5) # ★1
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 5) # ★2
    s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 2) # ★3
    s.connect((HOST, PORT))
    print(f"{datetime.now()}: connected to the server. The timeout for this TCP connection is 10 seconds.")
    print(f"{datetime.now()}: press enter.")
    input()
    for i in range(5):
        print(f"{datetime.now()}: send a message to the server after {5-i} seconds.")
        time.sleep(1)
    print(f"{datetime.now()}: send a message now.")
    try:
        s.sendall(b"hello!")
        data = s.recv(1024)
        print(f"{datetime.now()}: received `{data.decode()}`")
    except (socket.error, OSError) as e:
        print(f"{datetime.now()}: {e}")

To be more precise, if 5 seconds (★1) pass without any communication between client.py and server.py, the client machine's kernel automatically sends a TCP keepalive packet to the server machine's kernel. If there is still no response after another 5 seconds (★2), or if there is no response for 2 consecutive times (★3), it closes the connection. Simply not communicating for 10 seconds won't close it because kernel-level communication would still succeed. It only closes the connection when the two machines cannot communicate at the kernel level, such as when the server machine goes down or there's a network failure.

Confirming Normal Operation

First, let's confirm the normal behavior without considering TCP keepalive at all.

Start server.py on the server machine first.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 22:48:16.024905: listening 0.0.0.0:10000. ★ Waiting for connection from client.py

After this, if you start client.py on the client machine and press ENTER immediately, the message you sent will be returned 5 seconds later and the process will finish.

sat@tea:~/src/pysock$ python3 client.py
2024-08-17 22:48:22.343592: connected to the server. The timeout for this TCP connection is 10 seconds.
2024-08-17 22:48:22.343687: press enter. ★ Press ENTER here

2024-08-17 22:48:23.907758: send a message to the server after 5 seconds.
2024-08-17 22:48:24.908998: send a message to the server after 4 seconds.
2024-08-17 22:48:25.910346: send a message to the server after 3 seconds.
2024-08-17 22:48:26.911842: send a message to the server after 2 seconds.
2024-08-17 22:48:27.913317: send a message to the server after 1 seconds.
2024-08-17 22:48:28.914752: send a message now. ★ Sending message to server.py
2024-08-17 22:48:28.917909: received `hello!` ★ Confirmed that the message sent by itself was returned immediately from server.py

From the output of server.py, you can also see that it received a message after being connected from client.py.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 22:48:16.024905: listening 0.0.0.0:10000.
2024-08-17 22:48:22.345484: connected from ('192.168.1.101', 64450). ★ Connected from client.py
2024-08-17 22:48:28.917482: received `hello!`. ★ Received message from client.py

It's a common, unremarkable program.

How to Trigger TCP Keepalive Timeout

Now, to confirm the operation of TCP keepalive, we need to create a state where "for some reason, communication between the client machine and the server machine is impossible for more than 10 seconds." There are various ways to do this, but in this article, I will use stop-machine, a kernel module I created in the past that stops Linux's time for a specified period. Using stop-machine, I will make the server machine unable to do anything, including TCP/IP communication, for 30 seconds.

How stop-machine is built is outside the scope of this article, so I'll skip the explanation. If you're interested, please check out the following article, which discusses an older version.

https://zenn.dev/satoru_takeuchi/articles/f068e979dad99cc5230b

If you prefer a video, watch the following YouTube video.

https://youtu.be/OYvhXQLfBmw

Triggering TCP Keepalive

Confirm the operation using the following steps:

  1. Start server.py on the server machine.
  2. Start client.py on the client machine.
  3. Load stop-machine from another terminal on the server machine. After this, the server machine will be unable to do anything, including TCP/IP communication, for 30 seconds.
  4. After the communication failure state caused by stop-machine is resolved, press ENTER on the client machine to send a message to server.py.

Below are the execution results.

1. Start server.py on the server machine.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 22:51:22.606357: listening 0.0.0.0:10000.

2. Start client.py on the client machine.

sat@tea:~/src/pysock$ python3 client.py
2024-08-17 22:51:24.447714: connected to the server. The timeout for this TCP connection is 10 seconds.
2024-08-17 22:51:24.447788: press enter.

You can see from the ★ part below that server.py on the server machine has been connected to by client.py.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 22:51:22.606357: listening 0.0.0.0:10000.
2024-08-17 22:51:24.452076: connected from ('192.168.1.101', 64486). ★

3. Load stop-machine from another terminal on the server machine. After this, the server machine will be in a state where it cannot do anything, including TCP/IP communication, for 30 seconds.

sat@coffee:~/src/youtube-sample/0079-stop-machine$ date; sudo insmod stop-machine.ko ; date; sudo rmmod stop-machine
Sat Aug 17 22:51:28 JST 2024
Sat Aug 17 22:51:58 JST 2024 ★
sat@coffee:~/src/youtube-sample/0079-stop-machine$ 

From ★, you can see that the server machine became operational again 30 seconds after the module was loaded, and the date command was executed. The communication failure state has also been resolved here.

4. After the communication failure state caused by stop-machine is resolved, press ENTER on the client machine to send a message to server.py.

sat@tea:~/src/pysock$ python3 client.py
2024-08-17 22:51:24.447714: connected to the server. The timeout for this TCP connection is 10 seconds.
2024-08-17 22:51:24.447788: press enter.
  ★1 
2024-08-17 22:52:01.371441: send a message to the server after 5 seconds.
2024-08-17 22:52:02.372816: send a message to the server after 4 seconds.
2024-08-17 22:52:03.374325: send a message to the server after 3 seconds.
2024-08-17 22:52:04.375704: send a message to the server after 2 seconds.
2024-08-17 22:52:05.376974: send a message to the server after 1 seconds.
2024-08-17 22:52:06.378544: send a message now.
2024-08-17 22:52:06.378748: [Errno 110] Connection timed out ★2

You can see from ★1 that ENTER was pressed after 22:51:58, when the communication interruption was resolved. Subsequently, when trying to send a message, it was detected at ★2 that the connection had timed out and was closed.

The connection should have been closed by the TCP keepalive feature following this flow:

  1. On the client machine, client.py prompted the user to press the ENTER key at 22:51:24.
  2. From 22:51:28 to 22:51:58, the server machine was in a state where it could not communicate.
  3. Around 22:51:29, 5 seconds after starting to wait for ENTER key input on the client machine, the first packet for TCP keepalive was sent to the server machine, but there was no response.
  4. Around 22:51:34, another 5 seconds later, a second packet for TCP keepalive was sent to the server machine, but there was no response. The connection was closed.
  5. At 22:52:06, client.py tried to send a message to server.py, but since the connection was already closed, an error occurred.

server.py on the server machine detected that the connection was closed by the client at the moment the communication failure period caused by stop-machine ended, as shown in the ★ part below.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 22:51:22.606357: listening 0.0.0.0:10000.
2024-08-17 22:51:24.452076: connected from ('192.168.1.101', 64486).
2024-08-17 22:51:58.095116: [Errno 104] Connection reset by peer. ★

To be precise, it would be better to confirm that an RST was sent from the client using something like tcpdump, but I took a shortcut. I might add that later if I feel like it.

Confirming that TCP keepalive does not start operation when there are packets being retransmitted

Confirm the operation using the following steps:

  1. Start server.py on the server machine.
  2. Start client.py on the client machine.
  3. Load stop-machine on the server machine. After this, the server machine will be in a state where it cannot do anything, including TCP/IP communication, for 30 seconds.
  4. Within a few seconds after the communication failure state caused by stop-machine begins, press ENTER on the client machine to send a message to server.py.

Below are the execution results.

1. Start server.py on the server machine.

sat@coffee:~/src/pysock$ python3 server.py
2024-08-17 23:13:00.823749: listening 0.0.0.0:10000.

2. Start client.py on the client machine.

sat@tea:~/src/pysock$ python3 client.py
2024-08-17 23:13:03.747984: connected to the server. The timeout for this TCP connection is 10 seconds.
2024-08-17 23:13:03.748049: press enter.

3. Load stop-machine on the server machine. After this, the server machine will be in a state where it cannot do anything, including TCP/IP communication, for 30 seconds.

sat@coffee:~/src/youtube-sample/0079-stop-machine$ date; sudo insmod stop-machine.ko ; date; sudo rmmod stop-machine
Sat Aug 17 23:13:10 JST 2024
Sat Aug 17 23:13:39 JST 2024

4. Within a few seconds after the communication failure state caused by stop-machine begins, press ENTER on the client machine to send a message to server.py.

Below is the output on the client side.

sat@tea:~/src/pysock$ python3 client.py
2024-08-17 23:13:03.747984: connected to the server. The timeout for this TCP connection is 10 seconds.
2024-08-17 23:13:03.748049: press enter.
 ★1 
2024-08-17 23:13:11.778472: send a message to the server after 5 seconds.
2024-08-17 23:13:12.779654: send a message to the server after 4 seconds.
2024-08-17 23:13:13.781161: send a message to the server after 3 seconds.
2024-08-17 23:13:14.782496: send a message to the server after 2 seconds.
2024-08-17 23:13:15.783985: send a message to the server after 1 seconds.
2024-08-17 23:13:16.785534: send a message now.
2024-08-17 23:13:39.820123: received `hello!` ★2

You can see from ★1 that ENTER was pressed around 23:13:11, which is during the period between 23:13:10 and 23:13:39 when communication with the server machine was impossible. After that, looking at ★2, you can see that the message exchange with server.py was completed approximately 28 seconds later, which far exceeds the TCP keepalive timeout of 10 seconds.

Again, it would actually be better to confirm using something like tcpdump that packets were continuously retransmitted from the client while communication with the server was impossible, but I took a shortcut.

Conclusion

When I started to perform the above functional confirmation, I thought, "A check like this should be over in about 20 minutes." However, once I got into it, I struggled with basic things like what settings to use and in what order to run things to confirm the behavior, and in the end, it took me 2 or 3 hours. I suppose I didn't understand it as well as I thought I did. By actually trying it out, my understanding became clearer, so I'm glad I did it. I'll probably forget it a month from now, but in that case, I can just look back at this article. So, that's all.

Discussion