/images/logo.svg

NTOHL

TCP Flow Collision Over Multiple LoadBalancers

What happens

In typical high-traffic scenarios, server clusters (e.g. game servers or chat platforms) must handle billions of concurrent TCP connections. To achieve this, they require deployment of distributed infrastructure components including Kubernetes pods and virtual machines. For traffic aggregation, a gateway layer - typically implemented as multiple load balancers - is essential to establish an efficient framework.

graph LR A([users]) --> B1(gateway1) A --> B2(gateway2) B1 --> C1[VM1] B2 --> C1 B1 --> C2[VM2] B2 --> C2 B1 --> C3[VM3] B2 --> C3

To understand load balancers (LBs), refer to resources like Wikipedia. Two common LB implementations are reverse proxy and DNAT (Destination Network Address Translation). The TCP flow collision problem occurs specifically in DNAT-based load balancers.

A case of vscode key-based login failing

Background

After some system update, vscode’s ssh server started asking for a password. The machine sleeps a lot, and re-entering the password for every open project was not acceptable.

Diagnosis

The vscode output panel showed only the password prompt and nothing that explained why:

[16:36:47.687] Remote-SSH version: remote-ssh@0.102.0
[16:36:47.688] SSH Resolver called for “ssh-remote+x.x.x.x”, attempt 1
[16:36:49.196] Found password prompt in other window
[16:36:49.197] Showing password prompt

So I ran ssh root@x.x.x.x -v in a terminal and read the debug output:

When a grub change silently does nothing

I was setting up PCI passthrough for a KVM guest and the detach failed with:

error: Operation not supported: neither VFIO nor KVM device assignment is currently supported on this system

So I went to check VT-d (already enabled in BIOS) and IOMMU, which needs a grub parameter.

I copied the commands off the internet without thinking, and nothing happened. After a closer look, the problem was that grub’s config had been written to the wrong file: legacy and EFI boots keep their config in different places, so regenerating the wrong one leaves your change unapplied.

Measuring the epoll thundering herd

The thundering herd

The thundering herd problem is simple to describe: several processes or threads wait on the same event, and when it arrives the kernel wakes all of them. Usually only one gets the event; the rest find nothing, go back to sleep, and the wakeup was wasted.

There are two common variants:

  • accept herd: many processes block in accept, and every one of them wakes when a connection arrives. Fixed in Linux 2.6, so not discussed here.
  • epoll herd: accept() no longer suffers from it, but when the same listen fd is registered in several epoll instances, the fd becoming readable still wakes every waiter.

The experiment

Plan

  • The parent process creates the listen socket;
  • Each child registers that socket with its own epoll. The epoll must be created after fork — otherwise the children share one epoll instance and cannot tell each other’s fds apart;
  • Register readability on the listen fd and call accept when it fires;
  • Watch what each process prints.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>

const int MAX_PROC_NUM = 4;
const int MAX_EVENTS = 128;
const int PORT = 8081;
const int BUF_SIZE = 1024;
const int CLIENT_SIZE = 128;
int g_pids[MAX_PROC_NUM] = {0};

void sig_handler(int signo) {
    int i;
    for (i = 0; i < MAX_PROC_NUM; i++) {
        kill(g_pids[i], SIGKILL);
    }
}

int child_procedure(int listenfd) {
    struct epoll_event ev;
    struct epoll_event events[MAX_EVENTS];
    int epfd = 0;
    int pid = 0;
    char buf[BUF_SIZE];
    int cnt = 0;
    int i = 0;

    pid = getpid();

    epfd = epoll_create(CLIENT_SIZE + 1);
    if (epfd < 0) {
        printf("Create epoll failed\n");
        return -1;
    }

    ev.events = EPOLLIN | EPOLLET;
    ev.data.fd = listenfd;

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev) < 0) {
        printf("Add ev failed\n");
        return -1;
    }

    printf("Epoll init finished, process pid: %d\n", pid);

    while (1) {
        cnt = epoll_wait(epfd, events, MAX_EVENTS, 0);
        if (cnt <= 0) {
            continue;
        }

        for (i = 0; i < cnt; i++) {
            if (events[i].data.fd == listenfd) {
                // 新连接请求
                int newfd;
                printf("Process %d receive a connection request\n", pid);
                newfd = accept(listenfd, NULL, 0);
                if (newfd <= 0) {
                    printf("Process %d accept failed\n", pid);
                    continue;
                }
                fcntl(newfd, F_SETFL, fcntl(newfd, F_GETFL, 0) | O_NONBLOCK);
                ev.events = EPOLLIN | EPOLLET;
                ev.data.fd = newfd;
                epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev);
            } else {
                int n = read(events[i].data.fd, buf, BUF_SIZE);
                printf("Process %d receive a msg, length %d\n", pid, n);
                if (n != 0) {
                    write(events[i].data.fd, buf, n);
                }
                close(events[i].data.fd);
                epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
            }
        }
    }

    return 0;
}

int main() {
    int listenfd = 0;
    int i = 0;
    struct sockaddr_in servaddr;

    // signal(SIGINT, sig_handler);
    // signal(SIGTERM, sig_handler);

    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(PORT);

    fcntl(listenfd, F_SETFL, fcntl(listenfd, F_GETFL, 0) | O_NONBLOCK);

    if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr)) == -1) {
        printf("bind error\n");
        return -1;
    }

    if (listen(listenfd, CLIENT_SIZE) == -1) {
        printf("Listen failed\n");
        return -1;
    }

    for (i = 0; i < MAX_PROC_NUM; i++) {
        g_pids[i] = fork();
        if (0 == g_pids[i]) {
            // 子进程跳出循环
            break;
        }
    }

    if (i == MAX_PROC_NUM) {
        // 父进程:注册信号,退出时把子进程一起 kill 掉
        signal(SIGINT, sig_handler);
        signal(SIGTERM, sig_handler);

        while (1) {
            sleep(100);
        }
    } else {
        // 子进程,进入子进程流程
        return child_procedure(listenfd);
    }

    return 0;
}

The epoll_wait timeout of 0 is a busy loop. It is there only to make the effect easy to observe; don’t write it this way for real.

Profiling C/C++ with google-perftools

Install libunwind

wget https://github.com/libunwind/libunwind/releases/download/v1.3.0/libunwind-1.3.0.tar.gz --no-check-certificate
tar -xvf libunwind-1.3.0.tar.gz
cd libunwind-1.3.0
./configure
make && make install

Install gperftools

git clone https://github.com/gperftools/gperftools
cd gperftools/
sh autogen.sh
./configure
make && make install
ln -s /usr/local/lib/libprofiler.so.0 /usr/lib64/libprofiler.so.0

For the symlink, 64-bit systems use /usr/lib64/, 32-bit systems /usr/lib/.

Why recover() Does Nothing for a panic in Go

We had an intermittent panic we couldn’t pin down, so the quick move was to wrap it in recover(), log the context, and keep the service running. Except the branch that was supposed to run never got there.

The rule for recover is: once a panic happens, the program jumps to the deferred function that contains recover(); recover() catches the panic and it stops propagating. The important part — execution does not resume at the point of the panic. It continues from wherever recover() sits.