跳到主内容
@wquguru
精选88Hacker News Best(web_list)技巧与观点

CDN77排查Linux内核TCP节流:cgroup内存压力导致nginx降速

Uncovering Hidden TCP Throttling in the Linux Kernel

原文
发到 X
推荐理由

这是一篇极具价值的工程复盘,详细展示了如何利用bpftrace和内核源码排查复杂的网络性能问题,对运维和后端开发同学很有借鉴意义。

Disclaimer: No AI was used for writing this blog. Enjoy a humanly engineered piece.

免责声明:撰写此博客未使用任何 AI。请享受这篇由人工精心打造的文章。

One day, a customer was complaining about slow download speeds from one of our edge servers. Since the internet is full of unpredictability, complaints like that occasionally happen, but this time, there were no error codes. We couldn't reproduce the issue. The only thing we could see was lower traffic on the network interface. The strangest part was that it happened randomly, recovered on its own, and it didn't affect all clients connected to that server.

有一天,一位客户抱怨从我们的一台边缘服务器下载速度缓慢。由于互联网充满不可预测性,此类投诉偶尔会发生,但这次并没有错误代码。我们无法复现该问题。唯一能观察到的是网络接口的流量较低。最奇怪的是,这种情况随机发生,会自动恢复,并且并未影响连接到该服务器的所有客户端。

CDNs are usually built in a multi-layer setup. When a client requests content, the closest edge node serves it from its cache. If the content isn't there, the edge fetches it from an upper layer. The request can travel further up until it reaches a shield node, which finally fetches the content from the customer's origin. At CDN77, all these layers run heavily modified nginx. As we would eventually discover, nginx was an important part of this story.

CDN 通常采用多层架构构建。当客户端请求内容时,最近的边缘节点会从缓存中提供该内容。如果缓存中没有该内容,边缘节点会向上层获取。请求可以继续向上传递,直到到达屏蔽节点(shield node),最后由屏蔽节点从客户的源站获取内容。在 CDN77,所有这些层级都运行着经过重度修改的 nginx。正如我们后来发现的,nginx 是这个故事的重要组成部分。

Here's what we could see internally about the complaint: The download speed would collapse for certain connections, stay low for hours, and then recover without anyone touching anything. In one instance, it dropped just before 3 a.m., stayed flat for five hours, and returned to normal around 8 a.m. Nothing told us why.

以下是我们内部关于该投诉的观察情况:某些连接的下载速度会骤降,持续数小时处于低位,然后在无人干预的情况下自行恢复。在一次实例中,速度在凌晨 3 点前突然下降,保持平稳五个小时,并在早上 8 点左右恢复正常。没有任何迹象告诉我们原因所在。

So we started with the usual suspects: Maybe it was an ISP, peering, or transit issue; some network problem outside our infrastructure. Maybe one of the kernel's TCP settings was misconfigured - the well-known tcp_rmem, tcp_wmem, or tcp_mem. Or perhaps something in the nginx configuration, like proxy buffering. We also considered disk I/O stalling the cache, CPU or memory saturation, something hidden in the kernel logs, or a particular kernel version.

于是我们从常见的嫌疑对象开始排查:也许是 ISP、对等互联或传输线路的问题;或者是我们基础设施之外的某个网络问题。也许是内核的 TCP 设置配置不当——比如众所周知的 tcp_rmem、tcp_wmem 或 tcp_mem。或者可能是 nginx 配置中的某些内容,例如代理缓冲。我们还考虑过磁盘 I/O 导致缓存停滞、CPU 或内存饱和、内核日志中的隐藏问题,或是特定的内核版本。

All reasonable possibilities. And every one of them led to a dead end. Over time, the issue appeared in multiple regions, ruling out a specific ISP or network path. The sysctl settings and nginx configuration were identical to those on healthy neighboring servers. So were the nginx and kernel versions. CPU utilization, memory usage, and kernel logs showed no discrepancies either.

这些都是合理的可能性。然而每一条线索都走向了死胡同。随着时间的推移,该问题出现在多个区域,排除了特定 ISP 或网络路径的原因。sysctl 设置和 nginx 配置与健康的相邻服务器完全相同。nginx 和内核版本也是如此。CPU 利用率、内存使用情况和内核日志也没有显示任何差异。

But we noticed something interesting: The issue only appeared on HTTP cache misses. So, when the bug was happening and actively throttling, we launched a curl command on that server to test the download speed. But it was working; only nginx downloaded it slowly. We also noticed that rebooting the server fixed the issue for quite some time. Until, of course, it happened again. At this point, we had a pretty strange combination of symptoms. The problem was:

但我们注意到一个有趣的现象:该问题仅出现在 HTTP 缓存未命中时。因此,当 bug 发生并主动进行限速时,我们在该服务器上执行了 curl 命令以测试下载速度。但 curl 工作正常;只有 nginx 下载缓慢。我们还注意到,重启服务器可以在相当长的一段时间内解决问题。当然,直到它再次出现。此时,我们面对着一组相当奇怪的症状组合。问题是:

  • Dynamic,
  • Self-healing,
  • Affected only nginx processes,
  • Appeared on cache-miss connections.
  • 动态的,
  • 自我修复的,
  • 仅影响 nginx 进程,
  • 仅在缓存未命中的连接中出现。

Static config reviews weren't getting us anywhere. We needed to see what was actually happening.

静态配置审查毫无进展。我们需要看到实际发生了什么。

Going further down the rabbit hole

进一步深入兔子洞

Since only nginx seemed to be affected, we were suspicious of userspace. Maybe nginx was delaying its read syscalls. Maybe it wasn't reading enough bytes per call. We were even desperate enough to suspect that epoll itself was broken. We hooked into the entry and exit points of the read and epoll related syscalls, capturing function arguments, return codes, and syscall durations. If nginx was spending too much time waiting, or doing something strange while reading data, we should have been able to see it. But the experiments showed no anomalies whatsoever. Nginx wasn't delaying its read syscalls. It was issuing them as fast as possible. Was it reading too few bytes? No. It was reading everything available until it hit EAGAIN, exactly as expected.

由于似乎只有 nginx 受到影响,我们对用户态空间产生了怀疑。也许是 nginx 延迟了其 read 系统调用。也许是每次调用读取的字节数不足。我们甚至绝望到怀疑 epoll 本身存在缺陷。我们挂钩了与 read 和 epoll 相关的系统调用的入口和出口点,捕获函数参数、返回码和系统调用持续时间。如果 nginx 花费了太多时间等待,或在读取数据时做了奇怪的事情,我们应该能够观察到。但实验结果显示没有任何异常。nginx 并没有延迟其 read 系统调用。它以尽可能快的速度发出这些调用。是读取的字节数太少吗?不是。它在遇到 EAGAIN 之前读取了所有可用数据,完全符合预期。

So userspace probably wasn't the culprit.

所以用户态空间可能不是罪魁祸首。

Time to look into the kernel.

是时候调查内核了。

What if... the bug was in the kernel?

如果……bug 在内核中呢?

We hooked a kprobe into tcp_rcv_established using bpftrace and started printing fields from struct tcp_sock that could plausibly explain a throughput collapse. Fields like rcv_ssthresh, the advertised maximum segment size, the send congestion window, app_limited, the receive window, etc. (Note: The receive window was our main suspect.)

我们使用 bpftrace 在 tcp_rcv_established 上挂载了一个 kprobe,并开始打印 struct tcp_sock 中可能解释吞吐量崩溃的字段。例如 rcv_ssthresh、通告的最大分段大小、发送拥塞窗口、app_limited、接收窗口等。(注:接收窗口是我们的主要嫌疑对象。)

代码 · 13 行
struct tcp_sock {
...
    u32    window_clamp;   /* Maximal window to advertise */
    u32    rcv_ssthresh;    /* Current window clamp */
...
    u16    advmss;          /* Advertised MSS */
    u32    snd_cwnd;        /* Sending congestion window */
...
    u32    app_limited;     /* limited until "delivered" reaches this val */
...
    u32    rcv_wnd;         /* Current receiver window */
...
};

And finally, we started seeing a pattern. The value of rcv_ssthresh was tiny. Exactly four times the advertised maximum segment size. And that value is only ever written by tcp_adjust_rcv_ssthresh(). In our case, the only viable path leading to that function was through tcp_grow_window(), but only when tcp_under_memory_pressure() returned true.

终于,我们开始看到一个模式。rcv_ssthresh 的值非常小。恰好是通告最大分段大小的四倍。而这个值只能由 tcp_adjust_rcv_ssthresh() 写入。在我们的案例中,导致该函数的唯一可行路径是通过 tcp_grow_window(),但前提是 tcp_under_memory_pressure() 返回 true。

代码 · 22 行
/* Check #1 */
if (!tcp_under_memory_pressure(sk)) {
    unsigned int truesize = truesize_adjust(adjust, skb);
    int incr;
    /* Check #2. Increase window, if skb with such overhead
     * will fit to rcvbuf in future.
     */
    if (tcp_win_from_space(sk, truesize) <= skb->len)
        incr = 2 * tp->advmss;
    else
        incr = __tcp_grow_window(sk, skb, truesize);
    if (incr) {
        incr = max_t(int, incr, 2 * skb->len);
        tp->rcv_ssthresh += min(room, incr);
        inet_csk(sk)->icsk_ack.quick |= 1;
    }
} else {
    /* Under pressure:
     * Adjust rcv_ssthresh according to reserved mem
     */
    tcp_adjust_rcv_ssthresh(sk);
}

But that was suspicious. Earlier in our debugging, we'd checked the SNMP counters and they reported zero memory pressure, none whatsoever. And yet, tcp_under_memory_pressure() was returning true. Something didn't add up.

但这很可疑。在我们早期的调试中,我们检查了 SNMP 计数器,它们报告内存压力为零,完全没有。然而,tcp_under_memory_pressure() 却返回了 true。有些不对劲。

代码 · 3 行
$ nstat -z | grep Pressure
TcpExtTCPMemoryPressures        0                  0.0
TcpExtTCPMemoryPressuresChrono  0                  0.0

Finding the hidden rabbit

寻找隐藏的兔子

It turns out that the TCP variant of the memory pressure check is implemented differently from others. Besides checking global TCP memory pressure, it also checks whether the socket's cgroup is under memory pressure. This additional check happens when the cgroup memory controller is loaded, which it is by default on most distributions.

事实证明,内存压力检查的 TCP 变体与其他变体的实现方式不同。除了检查全局 TCP 内存压力外,它还检查套接字的 cgroup 是否处于内存压力下。当加载 cgroup 内存控制器时(在大多数发行版中默认已加载),会进行这项额外的检查。

代码 · 8 行
/* optimized version of sk_under_memory_pressure() for TCP sockets */
static inline bool tcp_under_memory_pressure(const struct sock *sk)
{
    if (mem_cgroup_sockets_enabled && sk->sk_memcg &&
        mem_cgroup_under_socket_pressure(sk->sk_memcg))
        return true;
    return READ_ONCE(tcp_memory_pressure);
}

And then it clicked. It was the cgroup memory controller all along. We launch nginx as a systemd service, and systemd places each service into its own cgroup and sets default controllers, like the already mentioned memory controller. The memory controller helps you set limits for the maximum memory consumption of a service, which we are actually not using. It's the well-known memory.high, memory.max, etc. But the memory controller has an undocumented feature, which activates when the controller is only loaded.

然后我恍然大悟。罪魁祸首一直是 cgroup 内存控制器。我们将 nginx 作为 systemd 服务启动,systemd 将每个服务放入其独立的 cgroup 中,并设置默认控制器,比如前面提到的内存控制器。内存控制器可帮助设置服务的最大内存消耗限制,而我们实际上并未使用这一功能。即众所周知的 memory.high、memory.max 等参数。但内存控制器有一个未记录的特性,当仅加载该控制器时便会激活。

The next diagram summarises what was happening. There's a flag which is set per cgroup, not per socket. So one reclaim shortfall throttles every connection nginx owns. When there's memory pressure inside a cgroup, reclaim falls short, and it sets a pressure flag on the memcg, which is a cgroup-wide option that shrinks every socket buffer, basically collapsing all the throughput. Once the pressure clears, it gets back to the normal state.

下图总结了正在发生的情况。存在一个按 cgroup 设置的标志位,而非按套接字设置。因此,一次回收不足会导致 nginx 拥有的所有连接都被限速。当 cgroup 内部出现内存压力时,回收操作不足,从而在 memcg(cgroup 级别的选项)上设置压力标志,这会缩小每个套接字缓冲区,基本上导致吞吐量崩溃。一旦压力解除,系统便恢复正常状态。

The pressure is raised through the vmpressure() function, which returns immediately for the root cgroup. So it only does anything for non-root cgroups. If the level rises above low, it writes jiffies + HZ into the memcg socket pressure, and every socket in that cgroup is throttled for at least one second.

压力通过 vmpressure() 函数提升,该函数对根 cgroup 立即返回。因此,它仅对非根 cgroup 起作用。如果级别超过 low,它会将 jiffies + HZ 写入 memcg 套接字压力中,该 cgroup 中的每个套接字都将被限速至少一秒钟。

更进一步:量化金融体系

看懂新闻只是起点——沿量化金融路径,把它变成能交付的工程能力

进入量化体系 →

相似阅读

关联信息,但可能不是同一事件