nginx $upstream_response_time start/stop 具体什么时候做

When does nginx $upstream_response_time start/stop specifically

有谁知道 $upstream_response_time 的时钟具体何时开始和结束?

文档似乎有点含糊:

keeps time spent on receiving the response from the upstream server; the time is kept in seconds with millisecond resolution. Times of several responses are separated by commas and colons like addresses in the $upstream_addr variable.

还有一个 $upstream_header_time 值,这增加了更多的混乱。

  1. 我假设$upstream_connect_time一旦连接建立就停止,但是它被上游接受之前?

  2. 这之后$upstream_response_time包括什么?

    • 等待上游接受所花费的时间?
    • 发送请求花费的时间?
    • 发送响应所花费的时间 header?

他们的 blog.

中有更具体的定义

$request_time – Full request time, starting when NGINX reads the first byte from the client and ending when NGINX sends the last byte of the response body

$upstream_connect_time – Time spent establishing a connection with an upstream server

$upstream_header_time – Time between establishing a connection to an upstream server and receiving the first byte of the response header

$upstream_response_time – Time between establishing a connection to an upstream server and receiving the last byte of the response body

所以

  • $upstream_header_time 包含在 $upstream_response_time.
  • 两者都不包括连接到上游的时间。
  • 两者都不包括向客户端发送响应所花费的时间。

我调查并调试了这方面的行为,结果如下:

start time end time
$upstream_connect_time before Nginx establishes TCP connection with upstream server before Nginx sends HTTP request to upstream server
$upstream_header_time before Nginx establishes TCP connection with upstream server after Nginx receives and processes headers in HTTP response from upstream server
$upstream_response_time before Nginx establishes TCP connection with upstream server after Nginx receives and processes HTTP response from upstream server

源代码

我将解释 $upstream_connect_time 和 $upstream_response_time 之间的值有何不同,因为这是我最感兴趣的。

u->state->connect_time 的值,以毫秒表示 $upstream_connect_time,在以下部分中提取:https://github.com/nginx/nginx/blob/3334585539168947650a37d74dd32973ab451d70/src/http/ngx_http_upstream.c#L2073

    if (u->state->connect_time == (ngx_msec_t) -1) {
        u->state->connect_time = ngx_current_msec - u->start_time;
    }

u->state->repponse_time 的值表示 $upstream_response_time 毫秒,在以下部分中设置:https://github.com/nginx/nginx/blob/3334585539168947650a37d74dd32973ab451d70/src/http/ngx_http_upstream.c#L4432

    if (u->state && u->state->response_time == (ngx_msec_t) -1) {
        u->state->response_time = ngx_current_msec - u->start_time;

你可以注意到这两个值都是根据 u->start_time 计算的,这是连接建立之前的时间,定义在 https://github.com/nginx/nginx/blob/3334585539168947650a37d74dd32973ab451d70/src/http/ngx_http_upstream.c#L1533 (注意 ngx_event_connect_peer 是在 nginx 工作进程和上游服务器之间建立 TCP 连接的函数。

因此,这两个值都包括建立TCP连接所花费的时间。您可以通过使用例如 gdbserver 进行实时调试来检查这一点。