nginx upstream使用及源码解析

来源:互联网 发布:淘宝上开网店要钱吗 编辑:程序博客网 时间:2024/06/06 00:41

nginx upstream机制使得nginx可以成为一个反向代理服务器,nginx一方面从下游客户端接收http请求,处理请求,并根据请求发送tcp报文到上游服务器,根据上游服务器的返回报文,来向下游客户端发送请求响应报文。
upstream机制也提供了负载分担的功能,可以将请求负载分担到集群服务器的某个服务器上面。

2.1upstream的流程介绍

1分析客户端请求报文,构建发往上游服务器的请求报文。
2调用ngx_http_upstream_init开始与上游服务器建立tcp连接。
  3发送在第一步中组建的请求报文。
4接收来自上游服务器的响应头并进行解析,往下游转发。
5接收来自上游服务器的相应体,进行转发。

在这5个阶段中,upstream机制允许开发人员自己设定相应的处理方式,来达到自己的目的,这也是开发人员使用upstream的方式。


2.2upstream的使用
开发人员使用upstream机制时,主要就是设置上面五个阶段的处理回调函数。
以http反向代理为例:

[cpp] view plain copy
  1. ngx_http_proxy_handler(ngx_http_request_t *r)  
  2. {  
  3.     :  
  4.     :  
  5.     :  
  6.     //设置http proxy使用到的upstream机制的各种方法  
  7.     //设置创建请求报文的回调函数  
  8.     u->create_request = ngx_http_proxy_create_request;  
  9.     //设置当链接失败时,需要执行的动作  
  10.     u->reinit_request = ngx_http_proxy_reinit_request;  
  11.     //设置处理上游服务器的响应头回调函数  
  12.     u->process_header = ngx_http_proxy_process_status_line;  
  13.     //当前无意义  
  14.     u->abort_request = ngx_http_proxy_abort_request;  
  15.     //请求结束后会调用该方法  
  16.     u->finalize_request = ngx_http_proxy_finalize_request;  
  17.   
  18.     //设置upstream的buffer标志位,为0时,以下游网速优先,  
  19.     //不会使用文件缓存响应包体,为1时,有多个buffer,并且  
  20.     //可以使用文件来缓存响应包体  
  21.     u->buffering = plcf->upstream.buffering;  
  22.   
  23.     //当buffering为1时会使用到该pipe结构,即下游网速优先,需要使用更多的buffer和临时文件缓存响应  
  24.     u->pipe = ngx_pcalloc(r->pool, sizeof(ngx_event_pipe_t));  
  25.     if (u->pipe == NULL) {  
  26.         return NGX_HTTP_INTERNAL_SERVER_ERROR;  
  27.     }  
  28.   
  29.     u->pipe->input_filter = ngx_event_pipe_copy_input_filter;  
  30.   
  31.     u->accel = 1;  
  32.     //开始读取请求包体,读取结束后,开始调用ngx_http_upstream_init,  
  33.     //开始upstream的流程  
  34.     rc = ngx_http_read_client_request_body(r, ngx_http_upstream_init);  
  35.     :  
  36.     :  
  37.     return NGX_DONE;  
  38. }  

2.3upstream源码解析(1.0.15版本)
2.3.1构建发往上游服务器的请求,建立与上游服务器的连接

主要函数是ngx_http_upstream_init_request,该函数会调用用户注册的请求构建函数去构建发往上游服务器的请求,同时将建立与上游服务器的连接。首先介绍两个辅助函数:

ngx_http_upstream_rd_check_broken_connection:该函数用来检查nginx与客户端之间的链路是否可用,

ngx_http_upstream_connect:该函数用来与上游服务器之间建立连接。


[cpp] view plain copy
  1. static void  
  2. ngx_http_upstream_check_broken_connection(ngx_http_request_t *r,  
  3.     ngx_event_t *ev)  
  4. {  
  5.     int                  n;  
  6.     char                 buf[1];  
  7.     ngx_err_t            err;  
  8.     ngx_int_t            event;  
  9.     ngx_connection_t     *c;  
  10.     ngx_http_upstream_t  *u;  
  11.   
  12.     c = r->connection;  
  13.     u = r->upstream;  
  14.   
  15.     //若连接已终止的话,该recv返回值会为0,MSG_PEEK表示会去  
  16.     //读取数据,但不会减少接收缓存中的数据,在这里读取1  
  17.     //个字节,来判断读方向能否正常工作  
  18.     n = recv(c->fd, buf, 1, MSG_PEEK);  
  19.   
  20.     err = ngx_socket_errno;  
  21.   
  22.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, ev->log, err,  
  23.                    "http upstream recv(): %d", n);  
  24.     //ev->write表明是写方向触发的事件,读方向能读到数据,  
  25.     //或者返回码为NGX_eagain,表明应该没有问题  
  26.     if (ev->write && (n >= 0 || err == NGX_EAGAIN)) {  
  27.         return;  
  28.     }  
  29.   
  30.     if ((ngx_event_flags & NGX_USE_LEVEL_EVENT) && ev->active) {  
  31.   
  32.         event = ev->write ? NGX_WRITE_EVENT : NGX_READ_EVENT;  
  33.   
  34.         if (ngx_del_event(ev, event, 0) != NGX_OK) {  
  35.             ngx_http_upstream_finalize_request(r, u,  
  36.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  37.             return;  
  38.         }  
  39.     }  
  40.     //能用该socket读出数据,说明连接没有问题  
  41.     if (n > 0) {  
  42.         return;  
  43.     }  
  44.   
  45.     //返回值为-1,但错误为NGX_EAGAIN,表明recv超时时间到了  
  46.     if (n == -1) {  
  47.         if (err == NGX_EAGAIN) {  
  48.             return;  
  49.         }  
  50.         //其他情况表明发生错误  
  51.         ev->error = 1;  
  52.   
  53.     } else { //n=0,一般表示连接已经结束  
  54.         err = 0;  
  55.     }  
  56.     //设置事件的标记位,标记已经结束了  
  57.     ev->eof = 1;  
  58.     c->error = 1;  
  59.   
  60.     if (!u->cacheable && u->peer.connection) {  
  61.         ngx_log_error(NGX_LOG_INFO, ev->log, err,  
  62.                       "client prematurely closed connection, "  
  63.                       "so upstream connection is closed too");  
  64.         ngx_http_upstream_finalize_request(r, u,  
  65.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);  
  66.         return;  
  67.     }  
  68.   
  69.     ngx_log_error(NGX_LOG_INFO, ev->log, err,  
  70.                   "client prematurely closed connection");  
  71.   
  72.     if (u->peer.connection == NULL) {  
  73.         ngx_http_upstream_finalize_request(r, u,  
  74.                                            NGX_HTTP_CLIENT_CLOSED_REQUEST);  
  75.     }  
  76. }  
  77. 2 ngx_http_upstream_connect  
  78.   
  79. static void  
  80. ngx_http_upstream_connect(ngx_http_request_t *r, ngx_http_upstream_t *u)  
  81. {  
  82.     ngx_int_t          rc;  
  83.     ngx_time_t        *tp;  
  84.     ngx_connection_t  *c;  
  85.   
  86.     r->connection->log->action = "connecting to upstream";  
  87.   
  88.     r->connection->single_connection = 0;  
  89.     //记录下当前的响应秒数和毫秒数  
  90.     if (u->state && u->state->response_sec) {  
  91.         tp = ngx_timeofday();  
  92.         u->state->response_sec = tp->sec - u->state->response_sec;  
  93.         u->state->response_msec = tp->msec - u->state->response_msec;  
  94.     }  
  95.   
  96.     u->state = ngx_array_push(r->upstream_states);  
  97.     if (u->state == NULL) {  
  98.         ngx_http_upstream_finalize_request(r, u,  
  99.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  100.         return;  
  101.     }  
  102.   
  103.     ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));  
  104.       
  105.     //记录下当前的响应秒数和毫秒数  
  106.     tp = ngx_timeofday();  
  107.     u->state->response_sec = tp->sec;  
  108.     u->state->response_msec = tp->msec;  
  109.   
  110.     //开始连接上游服务器  
  111.     rc = ngx_event_connect_peer(&u->peer);  
  112.     //printf("@@@@####rc is %d\n", (int)rc);  
  113.     ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,  
  114.                    "http upstream connect: %i", rc);  
  115.   
  116.     if (rc == NGX_ERROR) {  
  117.         ngx_http_upstream_finalize_request(r, u,  
  118.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  119.         return;  
  120.     }  
  121.   
  122.     u->state->peer = u->peer.name;  
  123.     //在busy或者declined的情况下,会调用ngx_http_upstream_next,该函数会  
  124.     //多次尝试调用connect试图与上游服务器连接,多次连接失败后,  
  125.     //才会调用ngx_http_upstream_finalize_request  
  126.     if (rc == NGX_BUSY) {  
  127.         ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "no live upstreams");  
  128.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_NOLIVE);  
  129.         return;  
  130.     }  
  131.   
  132.     if (rc == NGX_DECLINED) {  
  133.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);  
  134.         return;  
  135.     }  
  136.   
  137.     /* rc == NGX_OK || rc == NGX_AGAIN */  
  138.   
  139.     c = u->peer.connection;  
  140.   
  141.     c->data = r;  
  142.     //将客户端与上游服务器的连接的读写事件的处理回调设置为  
  143.     //ngx_http_upstream_handler  
  144.     c->write->handler = ngx_http_upstream_handler;  
  145.     c->read->handler = ngx_http_upstream_handler;  
  146.     //ngx_http_upstream_handler最后会调用u->write_event_handler或者read_event_handler  
  147.     u->write_event_handler = ngx_http_upstream_send_request_handler;  
  148.     u->read_event_handler = ngx_http_upstream_process_header;  
  149.   
  150.     c->sendfile &= r->connection->sendfile;  
  151.     u->output.sendfile = c->sendfile;  
  152.   
  153.     c->pool = r->pool;  
  154.     c->log = r->connection->log;  
  155.     c->read->log = c->log;  
  156.     c->write->log = c->log;  
  157.   
  158.     /* init or reinit the ngx_output_chain() and ngx_chain_writer() contexts */  
  159.   
  160.     u->writer.out = NULL;  
  161.     u->writer.last = &u->writer.out;  
  162.     u->writer.connection = c;  
  163.     u->writer.limit = 0;  
  164.       
  165.     if (u->request_sent) {  
  166.         if (ngx_http_upstream_reinit(r, u) != NGX_OK) {  
  167.             ngx_http_upstream_finalize_request(r, u,  
  168.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  169.             return;  
  170.         }  
  171.     }  
  172.   
  173.     if (r->request_body  
  174.         && r->request_body->buf  
  175.         && r->request_body->temp_file  
  176.         && r == r->main)  
  177.     {  
  178.         /* 
  179.          * the r->request_body->buf can be reused for one request only, 
  180.          * the subrequests should allocate their own temporay bufs 
  181.          */  
  182.   
  183.         u->output.free = ngx_alloc_chain_link(r->pool);  
  184.         if (u->output.free == NULL) {  
  185.             ngx_http_upstream_finalize_request(r, u,  
  186.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  187.             return;  
  188.         }  
  189.   
  190.         u->output.free->buf = r->request_body->buf;  
  191.         u->output.free->next = NULL;  
  192.         u->output.allocated = 1;  
  193.   
  194.         r->request_body->buf->pos = r->request_body->buf->start;  
  195.         r->request_body->buf->last = r->request_body->buf->start;  
  196.         r->request_body->buf->tag = u->output.tag;  
  197.     }  
  198.   
  199.     u->request_sent = 0;  
  200.     //与上游连接尚未建立起来,加入定时器,返回  
  201.     //当与上游服务器连接建立成功会调用相关的处理函数  
  202.     if (rc == NGX_AGAIN) {  
  203.         ngx_add_timer(c->write, u->conf->connect_timeout);  
  204.         return;  
  205.     }  
  206.   
  207. #if (NGX_HTTP_SSL)  
  208.   
  209.     if (u->ssl && c->ssl == NULL) {  
  210.         ngx_http_upstream_ssl_init_connection(r, u, c);  
  211.         return;  
  212.     }  
  213.   
  214. #endif  
  215.     //已经建立连接,向上游服务器发送请求内容  
  216.     ngx_http_upstream_send_request(r, u);  
  217. }  
  218. 3 ngx_http_upstream_init_request  
  219. static void  
  220. ngx_http_upstream_init_request(ngx_http_request_t *r)  
  221. {  
  222.     ngx_str_t                      *host;  
  223.     ngx_uint_t                      i;  
  224.     ngx_resolver_ctx_t             *ctx, temp;  
  225.     ngx_http_cleanup_t             *cln;  
  226.     ngx_http_upstream_t            *u;  
  227.     ngx_http_core_loc_conf_t       *clcf;  
  228.     ngx_http_upstream_srv_conf_t   *uscf, **uscfp;  
  229.     ngx_http_upstream_main_conf_t  *umcf;  
  230.   
  231.     if (r->aio) {  
  232.         return;  
  233.     }  
  234.   
  235.     u = r->upstream;  
  236.   
  237.     u->store = (u->conf->store || u->conf->store_lengths);  
  238.     //ignore_client_abort为0标志着需要关注nginx和客户端的连接是否稳定  
  239.     if (!u->store && !r->post_action && !u->conf->ignore_client_abort) {  
  240.         r->read_event_handler = ngx_http_upstream_rd_check_broken_connection;  
  241.         r->write_event_handler = ngx_http_upstream_wr_check_broken_connection;  
  242.     }  
  243.     //从代码来看,request_bufs貌似是在create_request中设置的  
  244.     if (r->request_body) {  
  245.         u->request_bufs = r->request_body->bufs;  
  246.     }  
  247.     //调用用户设置的create_request函数  
  248.     if (u->create_request(r) != NGX_OK) {  
  249.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);  
  250.         return;  
  251.     }  
  252.     //u->conf->local中保存的是与上游服务建立连接的本地地址  
  253.     u->peer.local = u->conf->local;  
  254.     //得到http core模块在该loc下的配置  
  255.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);  
  256.   
  257.     //设置upstream向下游客户端转发数据的各种参数,主要和  
  258.     //buf相关  
  259.     u->output.alignment = clcf->directio_alignment;  
  260.     u->output.pool = r->pool;  
  261.     u->output.bufs.num = 1;  
  262.     u->output.bufs.size = clcf->client_body_buffer_size;  
  263.     //往下游客户端写数据的接口  
  264.     u->output.output_filter = ngx_chain_writer;  
  265.     u->output.filter_ctx = &u->writer;  
  266.   
  267.     u->writer.pool = r->pool;  
  268.   
  269.     if (r->upstream_states == NULL) {  
  270.   
  271.         r->upstream_states = ngx_array_create(r->pool, 1,  
  272.                                           sizeof(ngx_http_upstream_state_t));  
  273.         if (r->upstream_states == NULL) {  
  274.             ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);  
  275.             return;  
  276.         }  
  277.   
  278.     } else {  
  279.   
  280.         u->state = ngx_array_push(r->upstream_states);  
  281.         if (u->state == NULL) {  
  282.             ngx_http_upstream_finalize_request(r, u,  
  283.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  284.             return;  
  285.         }  
  286.   
  287.         ngx_memzero(u->state, sizeof(ngx_http_upstream_state_t));  
  288.     }  
  289.     //将ngx_http_upstream_cleanup函数加入到request的cleanup链表中,  
  290.     //当request被删除时,会调用该函数  
  291.     cln = ngx_http_cleanup_add(r, 0);  
  292.     if (cln == NULL) {  
  293.         ngx_http_finalize_request(r, NGX_HTTP_INTERNAL_SERVER_ERROR);  
  294.         return;  
  295.     }  
  296.     //ngx_http_upstream_cleanup主要释放resolve数据结构,执行ngx_http_upstream_finalize  
  297.     cln->handler = ngx_http_upstream_cleanup;  
  298.     cln->data = r;  
  299.     u->cleanup = &cln->handler;  
  300.     //u->resolved中保存了用于与上游服务器建立连接的信息,  
  301.     //可以由开发人员在代码中设置,不设置的话,从配置文件中  
  302.     //去获取  
  303.     if (u->resolved == NULL) {  
  304.   
  305.         uscf = u->conf->upstream;  
  306.   
  307.     } else {  
  308.         //upstream中直接指定了相关的服务器地址,建立连接就ok了  
  309.         if (u->resolved->sockaddr) {  
  310.   
  311.             if (ngx_http_upstream_create_round_robin_peer(r, u->resolved)  
  312.                 != NGX_OK)  
  313.             {  
  314.                 ngx_http_upstream_finalize_request(r, u,  
  315.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  316.                 return;  
  317.             }  
  318.   
  319.             ngx_http_upstream_connect(r, u);  
  320.   
  321.             return;  
  322.         }  
  323.         //在这里host应该为一个upstream组的名字  
  324.         host = &u->resolved->host;  
  325.   
  326.         umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module);  
  327.   
  328.         uscfp = umcf->upstreams.elts;  
  329.         //遍历系统中的upstream数组,找到匹配的upstream  
  330.         for (i = 0; i < umcf->upstreams.nelts; i++) {  
  331.   
  332.             uscf = uscfp[i];  
  333.   
  334.             if (uscf->host.len == host->len  
  335.                 && ((uscf->port == 0 && u->resolved->no_port)  
  336.                      || uscf->port == u->resolved->port)  
  337.                 && ngx_memcmp(uscf->host.data, host->data, host->len) == 0)  
  338.             {  
  339.                 goto found;  
  340.             }  
  341.         }  
  342.   
  343.         if (u->resolved->port == 0) {  
  344.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,  
  345.                           "no port in upstream \"%V\"", host);  
  346.             ngx_http_upstream_finalize_request(r, u,  
  347.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  348.             return;  
  349.         }  
  350.   
  351.         temp.name = *host;  
  352.         //下面这部分需要进行域名解析  
  353.         ctx = ngx_resolve_start(clcf->resolver, &temp);  
  354.         if (ctx == NULL) {  
  355.             ngx_http_upstream_finalize_request(r, u,  
  356.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  357.             return;  
  358.         }  
  359.   
  360.         if (ctx == NGX_NO_RESOLVER) {  
  361.             ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,  
  362.                           "no resolver defined to resolve %V", host);  
  363.   
  364.             ngx_http_upstream_finalize_request(r, u, NGX_HTTP_BAD_GATEWAY);  
  365.             return;  
  366.         }  
  367.         //ngx_http_upstream_resolve_handler是域名解析后的回调函数  
  368.         ctx->name = *host;  
  369.         ctx->type = NGX_RESOLVE_A;  
  370.         ctx->handler = ngx_http_upstream_resolve_handler;  
  371.         ctx->data = r;  
  372.         ctx->timeout = clcf->resolver_timeout;  
  373.   
  374.         u->resolved->ctx = ctx;  
  375.   
  376.         if (ngx_resolve_name(ctx) != NGX_OK) {  
  377.             u->resolved->ctx = NULL;  
  378.             ngx_http_upstream_finalize_request(r, u,  
  379.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  380.             return;  
  381.         }  
  382.   
  383.         return;  
  384.     }  
  385.   
  386. found:  
  387.     //peer.init()方法中会根据upstream的算法去选择一个服务器,来进行发送  
  388.     //for example:us->peer.init = ngx_http_upstream_init_ip_hash_peer;  
  389.     if (uscf->peer.init(r, uscf) != NGX_OK) {  
  390.         ngx_http_upstream_finalize_request(r, u,  
  391.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  392.         return;  
  393.     }  
  394.     //与上游服务器建立连接  
  395.     ngx_http_upstream_connect(r, u);  
  396. }  
2.3.2往上游发送请求 

   当建立了与上游服务器的连接后,就会向上游服务器发送请求,主要函数是ngx_http_upstream_send_request。

[cpp] view plain copy
  1. static void  
  2. ngx_http_upstream_send_request(ngx_http_request_t *r, ngx_http_upstream_t *u)  
  3. {  
  4.     ngx_int_t          rc;  
  5.     ngx_connection_t  *c;  
  6.   
  7.     //peer.connection中是nginx与上游服务器建立的connection  
  8.     c = u->peer.connection;  
  9.   
  10.     ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0,  
  11.                    "http upstream send request");  
  12.       
  13.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {  
  14.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);  
  15.         return;  
  16.     }  
  17.   
  18.     c->log->action = "sending request to upstream";  
  19.     //通过ngx_output_chain向上游服务器发送请求报文,request_sent  
  20.     //用来表示是否已经发送请求头了,发送了的话,继续发送  
  21.     //剩余未发的就OK了,剩余未发送的数据保存在了u->output里面  
  22.     rc = ngx_output_chain(&u->output, u->request_sent ? NULL : u->request_bufs);  
  23.     //设置request_sent标志,表明已经发送过请求  
  24.     u->request_sent = 1;  
  25.   
  26.     if (rc == NGX_ERROR) {  
  27.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);  
  28.         return;  
  29.     }  
  30.     //若写事件已经被加入到了定时器中,删除它,为后面的  
  31.     //添加做准备  
  32.     if (c->write->timer_set) {  
  33.         ngx_del_timer(c->write);  
  34.     }  
  35.     //NGX_AGAIN表明数据尚未发送完毕,需要将其加入到定时器中  
  36.     //当发送事件触发时,会继续调用该函数。  
  37.     if (rc == NGX_AGAIN) {  
  38.         ngx_add_timer(c->write, u->conf->send_timeout);  
  39.         //主要是设置发送缓存的事件唤醒下限  
  40.         if (ngx_handle_write_event(c->write, u->conf->send_lowat) != NGX_OK) {  
  41.             ngx_http_upstream_finalize_request(r, u,  
  42.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  43.             return;  
  44.         }  
  45.   
  46.         return;  
  47.     }  
  48.   
  49.     /* rc == NGX_OK */  
  50.   
  51.     if (c->tcp_nopush == NGX_TCP_NOPUSH_SET) {  
  52.         if (ngx_tcp_push(c->fd) == NGX_ERROR) {  
  53.             ngx_log_error(NGX_LOG_CRIT, c->log, ngx_socket_errno,  
  54.                           ngx_tcp_push_n " failed");  
  55.             ngx_http_upstream_finalize_request(r, u,  
  56.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  57.             return;  
  58.         }  
  59.   
  60.         c->tcp_nopush = NGX_TCP_NOPUSH_UNSET;  
  61.     }  
  62.     //数据发送成功,添加一个读事件定时器  
  63.     ngx_add_timer(c->read, u->conf->read_timeout);  
  64.   
  65. #if 1  
  66.     //写事件已经发出,判断读事件是否ready  
  67.     if (c->read->ready) {  
  68.   
  69.         /* post aio operation */  
  70.   
  71.         /* 
  72.          * TODO comment 
  73.          * although we can post aio operation just in the end 
  74.          * of ngx_http_upstream_connect() CHECK IT !!! 
  75.          * it's better to do here because we postpone header buffer allocation 
  76.          */  
  77.         //读事件已经ready了,处理返回的报文头  
  78.         ngx_http_upstream_process_header(r, u);  
  79.         return;  
  80.     }  
  81. #endif  
  82.     //将写事件处理函数置为dummy的话,表明在读完相应之前,不允许  
  83.     //接着写了  
  84.     u->write_event_handler = ngx_http_upstream_dummy_handler;  
  85.   
  86.     if (ngx_handle_write_event(c->write, 0) != NGX_OK) {  
  87.         ngx_http_upstream_finalize_request(r, u,  
  88.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  89.         return;  
  90.     }  
  91. }  

2.3.3处理上游服务器返回的回应头部
往上游服务器发送完请求后,就要等待着处理服务器的回应了,首先会去处理服务器发回的响应头。处理函数是ngx_http_upstream_process_header.

[cpp] view plain copy
  1. static void  
  2. ngx_http_upstream_process_header(ngx_http_request_t *r, ngx_http_upstream_t *u)  
  3. {  
  4.     ssize_t            n;  
  5.     ngx_int_t          rc;  
  6.     ngx_connection_t  *c;  
  7.   
  8.     c = u->peer.connection;  
  9.     c->log->action = "reading response header from upstream";  
  10.     //读事件超时  
  11.     if (c->read->timedout) {  
  12.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_TIMEOUT);  
  13.         return;  
  14.     }  
  15.     //测试与upstream服务器的连通性  
  16.     if (!u->request_sent && ngx_http_upstream_test_connect(c) != NGX_OK) {  
  17.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);  
  18.         return;  
  19.     }  
  20.     //尚未实质分配数据缓冲区  
  21.     if (u->buffer.start == NULL) {  
  22.         //分配数据缓冲区  
  23.         u->buffer.start = ngx_palloc(r->pool, u->conf->buffer_size);  
  24.         if (u->buffer.start == NULL) {  
  25.             ngx_http_upstream_finalize_request(r, u,  
  26.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  27.             return;  
  28.         }  
  29.         //对缓冲区描述符进行初始化  
  30.         u->buffer.pos = u->buffer.start;  
  31.         u->buffer.last = u->buffer.start;  
  32.         u->buffer.end = u->buffer.start + u->conf->buffer_size;  
  33.         u->buffer.temporary = 1;  
  34.   
  35.         u->buffer.tag = u->output.tag;  
  36.         //为收到的请求头们创建ngx_list结构,用来存贮解析到的  
  37.         //请求头的名值对  
  38.         if (ngx_list_init(&u->headers_in.headers, r->pool, 8,  
  39.                           sizeof(ngx_table_elt_t))  
  40.             != NGX_OK)  
  41.         {  
  42.             ngx_http_upstream_finalize_request(r, u,  
  43.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  44.             return;  
  45.         }  
  46.   
  47.     }  
  48.   
  49.     //准备接受数据吧!!!狂奔的小怪兽  
  50.     for ( ;; ) {  
  51.   
  52.         n = c->recv(c, u->buffer.last, u->buffer.end - u->buffer.last);  
  53.         //数据尚未接收完毕  
  54.         if (n == NGX_AGAIN) {  
  55.   
  56.             if (ngx_handle_read_event(c->read, 0) != NGX_OK) {  
  57.                 ngx_http_upstream_finalize_request(r, u,  
  58.                                                NGX_HTTP_INTERNAL_SERVER_ERROR);  
  59.                 return;  
  60.             }  
  61.   
  62.             return;  
  63.         }  
  64.         //返回值为0,标志upstream服务器关闭了连接  
  65.         if (n == 0) {  
  66.             ngx_log_error(NGX_LOG_ERR, c->log, 0,  
  67.                           "upstream prematurely closed connection");  
  68.         }  
  69.       
  70.         if (n == NGX_ERROR || n == 0) {  
  71.             ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_ERROR);  
  72.             return;  
  73.         }  
  74.   
  75.         u->buffer.last += n;  
  76.   
  77.         //处理接收到响应头数据  
  78.         rc = u->process_header(r);  
  79.         //响应头尚未接收完毕   
  80.         if (rc == NGX_AGAIN) {  
  81.             //buffer已经满了,无法容纳更多的响应头部  
  82.             if (u->buffer.last == u->buffer.end) {  
  83.                 ngx_log_error(NGX_LOG_ERR, c->log, 0,  
  84.                               "upstream sent too big header");  
  85.   
  86.                 ngx_http_upstream_next(r, u,  
  87.                                        NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);  
  88.                 return;  
  89.             }  
  90.   
  91.             continue;  
  92.         }  
  93.   
  94.         break;  
  95.     }  
  96.     //解析到了无效错误头,真真苦逼啊  
  97.     if (rc == NGX_HTTP_UPSTREAM_INVALID_HEADER) {  
  98.         ngx_http_upstream_next(r, u, NGX_HTTP_UPSTREAM_FT_INVALID_HEADER);  
  99.         return;  
  100.     }  
  101.   
  102.     if (rc == NGX_ERROR) {  
  103.         ngx_http_upstream_finalize_request(r, u,  
  104.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  105.         return;  
  106.     }  
  107.   
  108.     /* rc == NGX_OK */  
  109.     //头部处理完毕,头部返回码大于300  
  110.     if (u->headers_in.status_n > NGX_HTTP_SPECIAL_RESPONSE) {  
  111.         if (r->subrequest_in_memory) {  
  112.             u->buffer.last = u->buffer.pos;  
  113.         }  
  114.   
  115.         if (ngx_http_upstream_test_next(r, u) == NGX_OK) {  
  116.             return;  
  117.         }  
  118.         //处理错误码大于300的错误情况,比如404错误,  
  119.         //页面没找到  
  120.         if (ngx_http_upstream_intercept_errors(r, u) == NGX_OK) {  
  121.             return;  
  122.         }  
  123.           
  124.     }  
  125.     //对u->headers_in中的头部进行处理过滤,把u->headers_in中的  
  126.     //各个头部信息挪到r->headers_out里面,以便于发送  
  127.     if (ngx_http_upstream_process_headers(r, u) != NGX_OK) {  
  128.         return;  
  129.     }  
  130.     //不是子请求,需要转发响应体  
  131.     if (!r->subrequest_in_memory) {  
  132.         //调用该函数,先转发响应头,再转发响应体  
  133.         ngx_http_upstream_send_response(r, u);  
  134.         return;  
  135.     }  
  136.   
  137.     /* subrequest content in memory */  
  138.     //以下为子请求的处理流程,当子请求的input_filter未设置时,  
  139.     //其默认的input_filter方法为ngx_http_upstream_non_buffered_filter,  
  140.     //即不转发收到的响应  
  141.     if (u->input_filter == NULL) {  
  142.         u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;  
  143.         u->input_filter = ngx_http_upstream_non_buffered_filter;  
  144.         u->input_filter_ctx = r;  
  145.     }  
  146.   
  147.     if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {  
  148.         ngx_http_upstream_finalize_request(r, u,  
  149.                                            NGX_HTTP_INTERNAL_SERVER_ERROR);  
  150.         return;  
  151.     }  
  152.     //buffer.last和buffer.pos之间是多余的包体  
  153.     n = u->buffer.last - u->buffer.pos;  
  154.     //下面对这段头部以外的包体进行处理  
  155.     if (n) {  
  156.         u->buffer.last -= n;  
  157.   
  158.         u->state->response_length += n;  
  159.   
  160.         if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {  
  161.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);  
  162.             return;  
  163.         }  
  164.   
  165.         //表明包体已经全部处理完毕,可以结束请求类  
  166.         if (u->length == 0) {  
  167.             ngx_http_upstream_finalize_request(r, u, 0);  
  168.             return;  
  169.         }  
  170.     }  
  171.     //设置接收事件的处理函数  
  172.     u->read_event_handler = ngx_http_upstream_process_body_in_memory;  
  173.     //在该函数中调用u->input_filter对后续包体进行处理,  
  174.     //该函数是针对子请求来说的,不转发包体,在内存中  
  175.     //对包体进行处理  
  176.     ngx_http_upstream_process_body_in_memory(r, u);  

2.3.4处理响应包体
处理完返回的响应头就要处理响应包体了,处理响应包体比较复杂,在子请求的情况下,不用转发响应包体,处理一下就可以了,在upstream模式下,需要转发接收到的请求,这时有下游网速优先和上游网速优先两种,下游网速优先,假设下游网速比上游快,因此分配了一块固定大小的buffer缓冲区去接收数据,同时进行转发,上游网速优先,假设上游网速比下游快,因此需要使用多块buffer缓冲区去缓存数据,同时必要时,使用临时文件来缓存接收到的数据。
ngx_http_upstream_process_body_in_memory:该函数用来处理子请求的情形,不转发响应包体。
ngx_http_upstream_send_response:该函数用来处理转发响应包体的情形,该函数会转发响应头和响应体,转发响应体时同时考虑了上游网速优先和下游网速优先两种情况。

[cpp] view plain copy
  1. 1ngx_http_upstream_process_body_in_memory  
  2. static void  
  3. ngx_http_upstream_process_body_in_memory(ngx_http_request_t *r,  
  4.     ngx_http_upstream_t *u)  
  5. {  
  6.     size_t             size;  
  7.     ssize_t            n;  
  8.     ngx_buf_t         *b;  
  9.     ngx_event_t       *rev;  
  10.     ngx_connection_t  *c;  
  11.     //c是nginx与upstream上游服务器之间建立的连接  
  12.     c = u->peer.connection;  
  13.     rev = c->read;  
  14.   
  15.     //读事件超时,结束upstream  
  16.     if (rev->timedout) {  
  17.         return;  
  18.     }  
  19.     //u->buffer用来保存读取的数据  
  20.     b = &u->buffer;  
  21.     for ( ;; ) {  
  22.         size = b->end - b->last;  
  23.         if (size == 0) {  
  24.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);  
  25.             return;  
  26.         }  
  27.         //读取相关数据到u->buffer中  
  28.         n = c->recv(c, b->last, size);  
  29.         //没有数据可读了,等待下一次处理  
  30.         if (n == NGX_AGAIN) {  
  31.             break;  
  32.         }  
  33.         //对端已经结束了该连接或者发生了错误  
  34.         if (n == 0 || n == NGX_ERROR) {  
  35.             ngx_http_upstream_finalize_request(r, u, n);  
  36.             return;  
  37.         }  
  38.         //response_length记录了已接收相应的长度  
  39.         u->state->response_length += n;  
  40.         //对接收到的数据进行处理,一般子请求会重置该方法,  
  41.         //未设置的话,则会默认为ngx_http_upstream_non_buffered_filter,该  
  42.         //方法仅仅是设置下该buffer以便继续接收数据  
  43.         if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {  
  44.             ngx_http_upstream_finalize_request(r, u, NGX_ERROR);  
  45.             return;  
  46.         }  
  47.         //接收方向未ready退出  
  48.         if (!rev->ready) {  
  49.             break;  
  50.         }  
  51.     }  
  52.     //设置读事件  
  53.     if (ngx_handle_read_event(rev, 0) != NGX_OK) {  
  54.         ngx_http_upstream_finalize_request(r, u, NGX_ERROR);  
  55.         return;  
  56.     }  
  57.   
  58.     if (rev->active) {  
  59.         ngx_add_timer(rev, u->conf->read_timeout);  
  60.   
  61.     } else if (rev->timer_set) {  
  62.         ngx_del_timer(rev);  
  63.     }  
  64. }  
  65.   
  66. 2 ngx_http_upstream_send_response  
  67.     该函数会往客户端发送响应头及转发响应体,根据不同的设置来调用不同的包体转发。  
  68. static void  
  69. ngx_http_upstream_send_response(ngx_http_request_t *r, ngx_http_upstream_t *u)  
  70. {  
  71.     int                        tcp_nodelay;  
  72.     ssize_t                    n;  
  73.     ngx_int_t                  rc;  
  74.     ngx_event_pipe_t          *p;  
  75.     ngx_connection_t          *c;  
  76.     ngx_http_core_loc_conf_t  *clcf;  
  77.   
  78.     //发送回应头部,回应头部存放在request的headers_in里面,  
  79.     //在这里,有可能头部没有发送完毕,没关系,未发送  
  80.     //完的数据在request的out链表里面放着呢,接着处理下面的  
  81.     //响应包体即可  
  82.     rc = ngx_http_send_header(r);  
  83.   
  84.     if (rc == NGX_ERROR || rc > NGX_OK || r->post_action) {  
  85.         ngx_http_upstream_finalize_request(r, u, rc);  
  86.         return;  
  87.     }  
  88.     //c是客户端与nginx之间建立的连接  
  89.     c = r->connection;  
  90.   
  91.     if (r->header_only) {  
  92.   
  93.         if (u->cacheable || u->store) {  
  94.   
  95.             if (ngx_shutdown_socket(c->fd, NGX_WRITE_SHUTDOWN) == -1) {  
  96.                 ngx_connection_error(c, ngx_socket_errno,  
  97.                                      ngx_shutdown_socket_n " failed");  
  98.             }  
  99.   
  100.             r->read_event_handler = ngx_http_request_empty_handler;  
  101.             r->write_event_handler = ngx_http_request_empty_handler;  
  102.             c->error = 1;  
  103.   
  104.         } else {  
  105.             ngx_http_upstream_finalize_request(r, u, rc);  
  106.             return;  
  107.         }  
  108.     }  
  109.     //将header_sent置位,表示响应头部已经发送了  
  110.     u->header_sent = 1;  
  111.     //请求中带有包体,且包体被保存在了临时文件里面,  
  112.     //现在这些临时文件没有用了,可以清理掉了,OK,  
  113.     //毕竟,服务器的回应都来了,应该没问题了  
  114.     if (r->request_body && r->request_body->temp_file) {  
  115.         ngx_pool_run_cleanup_file(r->pool, r->request_body->temp_file->file.fd);  
  116.         r->request_body->temp_file->file.fd = NGX_INVALID_FILE;  
  117.     }  
  118.     //获得http core在该loc下的配置  
  119.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);  
  120.     //u->buffering为0表示下游网速优先,不需要开辟更多的缓存区  
  121.     //来存放相关回应报文  
  122.     if (!u->buffering) {  
  123.         //未设置input_filter的话,设置默认的处理函数,input_filter是对  
  124.         //在buffer中接收到的数据进行相应处理,感觉主要有两个功能  
  125.         //一是把相关buffer挂到out链表,一是对内容进行过滤  
  126.         if (u->input_filter == NULL) {  
  127.             //啥都不做  
  128.             u->input_filter_init = ngx_http_upstream_non_buffered_filter_init;  
  129.             //该函数试图在buffer中缓存所有的数据,会操作设置ngx_buf中的  
  130.             //各个字段  
  131.             u->input_filter = ngx_http_upstream_non_buffered_filter;  
  132.             u->input_filter_ctx = r;  
  133.         }  
  134.         //设置upstream读事件的处理回调函数  
  135.         u->read_event_handler = ngx_http_upstream_process_non_buffered_upstream;  
  136.         //设置request写事件的处理回调函数  
  137.         r->write_event_handler =  
  138.                              ngx_http_upstream_process_non_buffered_downstream;  
  139.   
  140.         r->limit_rate = 0;  
  141.         //调用input_filter之前进行初始化  
  142.         if (u->input_filter_init(u->input_filter_ctx) == NGX_ERROR) {  
  143.             ngx_http_upstream_finalize_request(r, u, 0);  
  144.             return;  
  145.         }  
  146.   
  147.         if (clcf->tcp_nodelay && c->tcp_nodelay == NGX_TCP_NODELAY_UNSET) {  
  148.             ngx_log_debug0(NGX_LOG_DEBUG_HTTP, c->log, 0, "tcp_nodelay");  
  149.   
  150.             tcp_nodelay = 1;  
  151.   
  152.             if (setsockopt(c->fd, IPPROTO_TCP, TCP_NODELAY,  
  153.                                (const void *) &tcp_nodelay, sizeof(int)) == -1)  
  154.             {  
  155.                 ngx_connection_error(c, ngx_socket_errno,  
  156.                                      "setsockopt(TCP_NODELAY) failed");  
  157.                 ngx_http_upstream_finalize_request(r, u, 0);  
  158.                 return;  
  159.             }  
  160.   
  161.             c->tcp_nodelay = NGX_TCP_NODELAY_SET;  
  162.         }  
  163.         //buffer.last与buffer.pos之间是剩余未被处理的数据  
  164.         n = u->buffer.last - u->buffer.pos;  
  165.         //n>0,说明buffer中有未被转发的响应包体  
  166.         if (n) {  
  167.             //在这里设置该last是为了在input_filter中处理时,对其  
  168.             //进行重置  
  169.             u->buffer.last = u->buffer.pos;  
  170.             //将响应包体的长度加上n  
  171.             u->state->response_length += n;  
  172.             //在input_filter中处理此次接收到的数据  
  173.             if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {  
  174.                 ngx_http_upstream_finalize_request(r, u, 0);  
  175.                 return;  
  176.             }  
  177.             //在该函数中,开始向下游客户端发送响应包体,  
  178.             //发送完数据还会从上游接收包体  
  179.             ngx_http_upstream_process_non_buffered_downstream(r);  
  180.   
  181.         } else {  
  182.             //该buffer中目前仅有头部,没有回应包体,那下次  
  183.             //从头部接收就可以了  
  184.             u->buffer.pos = u->buffer.start;  
  185.             u->buffer.last = u->buffer.start;  
  186.   
  187.             if (ngx_http_send_special(r, NGX_HTTP_FLUSH) == NGX_ERROR) {  
  188.                 ngx_http_upstream_finalize_request(r, u, 0);  
  189.                 return;  
  190.             }  
  191.             //有数据可以进行处理,处理上游数据,在该函数中  
  192.             //收完上游包体也会往下游发送相应。  
  193.             if (u->peer.connection->read->ready) {  
  194.                 ngx_http_upstream_process_non_buffered_upstream(r, u);  
  195.             }  
  196.         }  
  197.   
  198.         return;  
  199.     }  
  200.   
  201.     /* TODO: preallocate event_pipe bufs, look "Content-Length" */  
  202.   
  203.     //下面这部分是buffer为1的情况,该情况允许nginx使用更多的buffer  
  204.     //去缓存包体数据,或者使用文件来进行缓存  
  205.     p = u->pipe;  
  206.     //对pipe结构进行初始化,该结构专用于上游网速优先的情况  
  207.     //设置向下游发送响应的调用函数      
  208.     p->output_filter = (ngx_event_pipe_output_filter_pt) ngx_http_output_filter;  
  209.     p->output_ctx = r;  
  210.     p->tag = u->output.tag;  
  211.     //设置可以使用的缓冲区的个数  
  212.     p->bufs = u->conf->bufs;  
  213.     //设置busy缓冲区中待发送的响应长度触发值  
  214.     p->busy_size = u->conf->busy_buffers_size;  
  215.     p->upstream = u->peer.connection;  
  216.     p->downstream = c;  
  217.     p->pool = r->pool;  
  218.     p->log = c->log;  
  219.   
  220.     p->cacheable = u->cacheable || u->store;  
  221.   
  222.     p->temp_file = ngx_pcalloc(r->pool, sizeof(ngx_temp_file_t));  
  223.     if (p->temp_file == NULL) {  
  224.         ngx_http_upstream_finalize_request(r, u, 0);  
  225.         return;  
  226.     }  
  227.     //设置缓存数据的临时文件的路径,fd等  
  228.     p->temp_file->file.fd = NGX_INVALID_FILE;  
  229.     p->temp_file->file.log = c->log;  
  230.     p->temp_file->path = u->conf->temp_path;  
  231.     p->temp_file->pool = r->pool;  
  232.   
  233.     if (p->cacheable) {  
  234.         p->temp_file->persistent = 1;  
  235.   
  236.     } else {  
  237.         p->temp_file->log_level = NGX_LOG_WARN;  
  238.         p->temp_file->warn = "an upstream response is buffered "  
  239.                              "to a temporary file";  
  240.     }  
  241.     //设置缓冲数据的临时文件的最大大小  
  242.     p->max_temp_file_size = u->conf->max_temp_file_size;  
  243.     p->temp_file_write_size = u->conf->temp_file_write_size;  
  244.   
  245.     p->preread_bufs = ngx_alloc_chain_link(r->pool);  
  246.     if (p->preread_bufs == NULL) {  
  247.         ngx_http_upstream_finalize_request(r, u, 0);  
  248.         return;  
  249.     }  
  250.     //初始化预读缓冲区链表,预读缓冲区是在读响应头  
  251.     //时同时读到的响应体  
  252.     p->preread_bufs->buf = &u->buffer;  
  253.     p->preread_bufs->next = NULL;  
  254.     u->buffer.recycled = 1;  
  255.   
  256.     p->preread_size = u->buffer.last - u->buffer.pos;  
  257.   
  258.     if (u->cacheable) {  
  259.   
  260.         p->buf_to_file = ngx_calloc_buf(r->pool);  
  261.         if (p->buf_to_file == NULL) {  
  262.             ngx_http_upstream_finalize_request(r, u, 0);  
  263.             return;  
  264.         }  
  265.   
  266.         p->buf_to_file->pos = u->buffer.start;  
  267.         p->buf_to_file->last = u->buffer.pos;  
  268.         p->buf_to_file->temporary = 1;  
  269.     }  
  270.   
  271.     if (ngx_event_flags & NGX_USE_AIO_EVENT) {  
  272.         /* the posted aio operation may corrupt a shadow buffer */  
  273.         p->single_buf = 1;  
  274.     }  
  275.   
  276.     /* TODO: p->free_bufs = 0 if use ngx_create_chain_of_bufs() */  
  277.     p->free_bufs = 1;  
  278.     u->buffer.last = u->buffer.pos;  
  279.   
  280.     if (u->conf->cyclic_temp_file) {  
  281.         p->cyclic_temp_file = 1;  
  282.         c->sendfile = 0;  
  283.   
  284.     } else {  
  285.         p->cyclic_temp_file = 0;  
  286.     }  
  287.     //设置接收,发送的超时时间,设置发送的低水位  
  288.     p->read_timeout = u->conf->read_timeout;  
  289.     p->send_timeout = clcf->send_timeout;  
  290.     p->send_lowat = clcf->send_lowat;  
  291.     //设置upstreadm的读事件处理方法,设置request的写时间处理方法  
  292.     u->read_event_handler = ngx_http_upstream_process_upstream;  
  293.     r->write_event_handler = ngx_http_upstream_process_downstream;  
  294.     //处理上游数据,同时会往下游发送数据  
  295.     ngx_http_upstream_process_upstream(r, u);  
  296. }  

从上面可以看出ngx_http_upstream_send_response里面根据bufferring的标记对包体的转发进行了不同的处理:
1使用了固定buffer来接收包体报文:读取上游报文使用函数ngx_http_upstrea m_process_non_buffered_upstream,往下游写报文使用函数ngx_http_upstre am_process_non_buffered_downstream,实际上这两个函数最后都是调用了ngx_http_upstrea m_process_non_buffered_request,通过一个标记位来控制读写方向。

2使用了多个buffer及临时文件来接收包体报文:读取上游报文用ngx_http_upstream_pr ocess_upstream,往下游写报文使用ngx_http_upstream_process_downstream。两个函数最后都是调用ngx_event_pipe,通过一个参数标记来控制读写方向。

[cpp] view plain copy
  1. 3 ngx_http_upstream_process_non_buffered_request  
  2. static void  
  3. ngx_http_upstream_process_non_buffered_request(ngx_http_request_t *r,  
  4.     ngx_uint_t do_write)  
  5. {  
  6.     size_t                     size;  
  7.     ssize_t                    n;  
  8.     ngx_buf_t                 *b;  
  9.     ngx_int_t                  rc;  
  10.     ngx_connection_t          *downstream, *upstream;  
  11.     ngx_http_upstream_t       *u;  
  12.     ngx_http_core_loc_conf_t  *clcf;  
  13.   
  14.     u = r->upstream;  
  15.     //downstream是下游与nginx的连接,upstream是上游与nginx的连接  
  16.     downstream = r->connection;  
  17.     upstream = u->peer.connection;  
  18.     //buffer用来存放响应数据  
  19.     b = &u->buffer;  
  20.     //do_write为1,或者所有的数据都已经发送完毕  
  21.     do_write = do_write || u->length == 0;  
  22.   
  23.     for ( ;; ) {  
  24.         //do_write标志代表需要进行数据发送操作  
  25.         if (do_write) {  
  26.             //如果out_bufs或者busy_bufs中有数据,busy_bufs记录的是  
  27.             //未能发送完毕的数据  
  28.             if (u->out_bufs || u->busy_bufs) {  
  29.                 rc = ngx_http_output_filter(r, u->out_bufs);  
  30.   
  31.                 if (rc == NGX_ERROR) {  
  32.                     ngx_http_upstream_finalize_request(r, u, 0);  
  33.                     return;  
  34.                 }  
  35.                 //该函数主要是置u->out_bufs为0,清理busy_bufs上已经被  
  36.                 //发送完毕的数据buf,将不用的数据buf放入到free_bufs里面  
  37.                 ngx_chain_update_chains(&u->free_bufs, &u->busy_bufs,  
  38.                                         &u->out_bufs, u->output.tag);  
  39.             }  
  40.             //busy_bufs中没有buf了,说明已经没有未发送完的数据了  
  41.             if (u->busy_bufs == NULL) {  
  42.                 //数据已经发送完毕,或者出错  
  43.                 if (u->length == 0  
  44.                     || upstream->read->eof  
  45.                     || upstream->read->error)  
  46.                 {  
  47.                     ngx_http_upstream_finalize_request(r, u, 0);  
  48.                     return;  
  49.                 }  
  50.                 //重置数据buffer的pos,last以便下次进行数据接收  
  51.                 b->pos = b->start;  
  52.                 b->last = b->start;  
  53.             }  
  54.         }  
  55.         //last与end之间是可以用于接收数据的buffer大小  
  56.         size = b->end - b->last;  
  57.         //确定下次要接收的数据大小  
  58.         if (size > u->length) {  
  59.             size = u->length;  
  60.         }  
  61.         //read方向可读  
  62.         if (size && upstream->read->ready) {  
  63.             //从upstream方向读取数据,放入到buffer里面  
  64.             n = upstream->recv(upstream, b->last, size);  
  65.             //未能读取到数据,需要下次再读  
  66.             if (n == NGX_AGAIN) {  
  67.                 break;  
  68.             }  
  69.             //读取到了相关数据  
  70.             if (n > 0) {  
  71.                 u->state->response_length += n;  
  72.                 //调用input_filter进行处理  
  73.                 if (u->input_filter(u->input_filter_ctx, n) == NGX_ERROR) {  
  74.                     ngx_http_upstream_finalize_request(r, u, 0);  
  75.                     return;  
  76.                 }  
  77.             }  
  78.             //读取到了数据,开始往下游写  
  79.             do_write = 1;  
  80.   
  81.             continue;  
  82.         }  
  83.   
  84.         break;  
  85.     }  
  86.     //得到core module在loc下的配置  
  87.     clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module);  
  88.   
  89.     if (downstream->data == r) {  
  90.         //设置downstream的写事件,添加到epoll中  
  91.         if (ngx_handle_write_event(downstream->write, clcf->send_lowat)  
  92.             != NGX_OK)  
  93.         {  
  94.             ngx_http_upstream_finalize_request(r, u, 0);  
  95.             return;  
  96.         }  
  97.     }  
  98.     //downstream connection写方向未ready,设置写  
  99.     if (downstream->write->active && !downstream->write->ready) {  
  100.         ngx_add_timer(downstream->write, clcf->send_timeout);  
  101.   
  102.     } else if (downstream->write->timer_set) {  
  103.         ngx_del_timer(downstream->write);  
  104.     }  
  105.     //设置upstream的读事件到epoll中  
  106.     if (ngx_handle_read_event(upstream->read, 0) != NGX_OK) {  
  107.         ngx_http_upstream_finalize_request(r, u, 0);  
  108.         return;  
  109.     }  
  110.     //设置读超时  
  111.     if (upstream->read->active && !upstream->read->ready) {  
  112.         ngx_add_timer(upstream->read, u->conf->read_timeout);  
  113.   
  114.     } else if (upstream->read->timer_set) {  
  115.         ngx_del_timer(upstream->read);  
  116.     }  
  117. }  
  118.   
  119. 4 ngx_event_pipe  
  120. ngx_int_t  
  121. ngx_event_pipe(ngx_event_pipe_t *p, ngx_int_t do_write)  
  122. {  
  123.     u_int         flags;  
  124.     ngx_int_t     rc;  
  125.     ngx_event_t  *rev, *wev;  
  126.   
  127.     for ( ;; ) {  
  128.         //do_write标记表明此时是向下游客户端写响应  
  129.         if (do_write) {  
  130.             p->log->action = "sending to client";  
  131.             //调用pipe_write_to_downstream往下游写响应  
  132.             rc = ngx_event_pipe_write_to_downstream(p);  
  133.   
  134.             if (rc == NGX_ABORT) {  
  135.                 return NGX_ABORT;  
  136.             }  
  137.   
  138.             if (rc == NGX_BUSY) {  
  139.                 return NGX_OK;  
  140.             }  
  141.         }  
  142.         //p->read应该表明了有没有从上游读取到数据  
  143.         p->read = 0;  
  144.         //upstream_blocked表明了是否可以继续从上游接收数据,  
  145.         //因为有可能缓冲区和缓存文件都满了,无法继续接收了  
  146.         p->upstream_blocked = 0;  
  147.   
  148.         p->log->action = "reading upstream";  
  149.         //调用pipe_read_upstream从上游接收数据  
  150.         if (ngx_event_pipe_read_upstream(p) == NGX_ABORT) {  
  151.             return NGX_ABORT;  
  152.         }  
  153.         //在允许读取数据的情况下,没有从上游读取到数据  
  154.         if (!p->read && !p->upstream_blocked) {  
  155.             break;  
  156.         }  
  157.         //读取到数据,往下游写  
  158.         do_write = 1;  
  159.     }  
  160.   
  161.     //将上游的读事件插入到定时器,将上游的读事件  
  162.     //加入到epoll中,p->upstream是上游的connection.  
  163.     if (p->upstream->fd != -1) {  
  164.         rev = p->upstream->read;  
  165.   
  166.         flags = (rev->eof || rev->error) ? NGX_CLOSE_EVENT : 0;  
  167.   
  168.         if (ngx_handle_read_event(rev, flags) != NGX_OK) {  
  169.             return NGX_ABORT;  
  170.         }  
  171.         //receive方向处于active状态,但当前没有数据可读  
  172.         if (rev->active && !rev->ready) {  
  173.             ngx_add_timer(rev, p->read_timeout);  
  174.   
  175.         } else if (rev->timer_set) {  
  176.             ngx_del_timer(rev);  
  177.         }  
  178.     }  
  179.     //将下游的读事件插入到定时器,将下游的写事件  
  180.     //加入到epoll中,p->downstream是下游的connection  
  181.     if (p->downstream->fd != -1 && p->downstream->data == p->output_ctx) {  
  182.         wev = p->downstream->write;  
  183.         if (ngx_handle_write_event(wev, p->send_lowat) != NGX_OK) {  
  184.             return NGX_ABORT;  
  185.         }  
  186.         //当发送的响应数据包速率超过了限制,就会置delayed标记  
  187.         //,表明被延迟  
  188.         if (!wev->delayed) {  
  189.             if (wev->active && !wev->ready) {  
  190.                 ngx_add_timer(wev, p->send_timeout);  
  191.   
  192.             } else if (wev->timer_set) {  
  193.                 ngx_del_timer(wev);  
  194.             }  
  195.         }  
  196.     }  
  197.   
  198.     return NGX_OK;  
  199. }  
  200.   
  201.     从ngx_event_pipe的代码中可以看出,从上游接收及往下游发送分别调用了两个不同的函数:  
  202.     ngx_event_pipe_read_upstream:从上游读取报文的处理函数。  
  203.     ngx_event_pipe_write_downstream:往下游发送数据。  
  204.   
  205. 4ngx_event_pipe_read_upstream  
  206. static ngx_int_t  
  207.   ngx_event_pipe_read_upstream(ngx_event_pipe_t *p)   
  208.   {  
  209.     ssize_t       n, size;  
  210.     ngx_int_t     rc;  
  211.     ngx_buf_t    *b;  
  212.     ngx_chain_t  *chain, *cl, *ln;  
  213.       
  214.     if (p->upstream_eof || p->upstream_error || p->upstream_done) {  
  215.         return NGX_OK;  
  216.     }  
  217.   
  218.     ngx_log_debug1(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  219.                    "pipe read upstream: %d", p->upstream->read->ready);  
  220.   
  221.     for ( ;; ) {  
  222.   
  223.         if (p->upstream_eof || p->upstream_error || p->upstream_done) {  
  224.             break;  
  225.         }  
  226.         //upstream读事件没有数据可读,且预读buf不存在,  
  227.         //退出循环,预读buf中在读取响应头时可能会顺带着  
  228.         //读出一部分的响应包体  
  229.         if (p->preread_bufs == NULL && !p->upstream->read->ready) {  
  230.             break;  
  231.         }  
  232.         //预读的buf存在  
  233.         if (p->preread_bufs) {  
  234.             //有preread_bufs存在,那么已经读取了一些响应数据,需要把  
  235.             //这部分数据挂入到chain里面。  
  236.             chain = p->preread_bufs;  
  237.             p->preread_bufs = NULL;  
  238.             //n是已经预读出来的数据,预读buf中已经存在了部分读取数据  
  239.             n = p->preread_size;  
  240.   
  241.             ngx_log_debug1(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  242.                            "pipe preread: %z", n);  
  243.             //p->read表明读取出了响应,有preread_bufs,那么  
  244.             if (n) {  
  245.                 p->read = 1;  
  246.             }  
  247.   
  248.         } else {  
  249.             //preread_bufs使用之后,就被置空了,如上面的代码所示  
  250.             //下面就是找个buf去进行数据接收  
  251.             if (p->free_raw_bufs) {  
  252.   
  253.                 /* use the free bufs if they exist */  
  254.   
  255.                 chain = p->free_raw_bufs;  
  256.                 if (p->single_buf) {  
  257.                     p->free_raw_bufs = p->free_raw_bufs->next;  
  258.                     chain->next = NULL;  
  259.                 } else {  
  260.                     p->free_raw_bufs = NULL;  
  261.                 }  
  262.                     //free_raw_bufs不存在,需要分配一个新的buf用,不能超过  
  263.                     //buf的个数限制  
  264.             } else if (p->allocated < p->bufs.num) {  
  265.                   
  266.                 /* allocate a new buf if it's still allowed */  
  267.                 //分配新的buffer,包括实际的缓冲区和buf描述符  
  268.                 b = ngx_create_temp_buf(p->pool, p->bufs.size);  
  269.                 if (b == NULL) {  
  270.                     return NGX_ABORT;  
  271.                 }  
  272.   
  273.                 p->allocated++;  
  274.                 //分配一个ngx_chain,指向刚分配的buf  
  275.                 chain = ngx_alloc_chain_link(p->pool);  
  276.                 if (chain == NULL) {  
  277.                     return NGX_ABORT;  
  278.                 }  
  279.   
  280.                 chain->buf = b;  
  281.                 chain->next = NULL;  
  282.   
  283.             } else if (!p->cacheable  
  284.                        && p->downstream->data == p->output_ctx  
  285.                        && p->downstream->write->ready  
  286.                        && !p->downstream->write->delayed)  
  287.             {//该条件表明,downstream方向write已经准备好,可以发送数据,  
  288.             //且不存在发送速率超标的情况,那么将upstream_blocked置1,  
  289.             //阻止上游继续接收数据包,然后,尽快发送,以腾出buffer  
  290.                 p->upstream_blocked = 1;  
  291.                 break;  
  292.   
  293.             } else if (p->cacheable  
  294.                        || p->temp_file->offset < p->max_temp_file_size)  
  295.             {//到了这里,buffer都已经使用光了,且下游现在不能写,  
  296.             //那么只能缓存到临时文件里面去了,HOHO  
  297.   
  298.                 /* 
  299.                  * if it is allowed, then save some bufs from r->in 
  300.                  * to a temporary file, and add them to a r->out chain 
  301.                  */  
  302.   
  303.                 rc = ngx_event_pipe_write_chain_to_temp_file(p);  
  304.   
  305.                 ngx_log_debug1(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  306.                                "pipe temp offset: %O", p->temp_file->offset);  
  307.   
  308.                 if (rc == NGX_BUSY) {  
  309.                     break;  
  310.                 }  
  311.   
  312.                 if (rc == NGX_AGAIN) {  
  313.                     if (ngx_event_flags & NGX_USE_LEVEL_EVENT  
  314.                         && p->upstream->read->active  
  315.                         && p->upstream->read->ready)  
  316.                     {  
  317.                         if (ngx_del_event(p->upstream->read, NGX_READ_EVENT, 0)  
  318.                             == NGX_ERROR)  
  319.                         {  
  320.                             return NGX_ABORT;  
  321.                         }  
  322.                     }  
  323.                 }  
  324.   
  325.                 if (rc != NGX_OK) {  
  326.                     return rc;  
  327.                 }  
  328.                 //p->free_raw_bufs链表中的buf是p->in链表中把数据写入临时文件后  
  329.                 //空闲出来的buf  
  330.                 chain = p->free_raw_bufs;  
  331.                 if (p->single_buf) {  
  332.                     p->free_raw_bufs = p->free_raw_bufs->next;  
  333.                     chain->next = NULL;  
  334.                 } else {  
  335.                     p->free_raw_bufs = NULL;  
  336.                 }  
  337.   
  338.             } else {  
  339.   
  340.                 /* there are no bufs to read in */  
  341.   
  342.                 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  343.                                "no pipe bufs to read in");  
  344.   
  345.                 break;  
  346.             }  
  347.             //读取数据到buf  
  348.             n = p->upstream->recv_chain(p->upstream, chain);  
  349.   
  350.             ngx_log_debug1(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  351.                            "pipe recv chain: %z", n);  
  352.             //后面读取的数据居然在链表的前列,无语了。。。  
  353.             if (p->free_raw_bufs) {  
  354.                 chain->next = p->free_raw_bufs;  
  355.             }  
  356.             //重置free_raw_bufs  
  357.             p->free_raw_bufs = chain;  
  358.             //读取数据发生错误,置upstream_error  
  359.             if (n == NGX_ERROR) {  
  360.                 p->upstream_error = 1;  
  361.                 return NGX_ERROR;  
  362.             }  
  363.             //没有读取出数据,HOHO,退出就好了  
  364.             if (n == NGX_AGAIN) {  
  365.                 if (p->single_buf) {  
  366.                     ngx_event_pipe_remove_shadow_links(chain->buf);  
  367.                 }  
  368.   
  369.                 break;  
  370.             }  
  371.             //到这里,说明n>0,已经读取到了数据  
  372.             p->read = 1;  
  373.             //n==0,说明上游服务器已经关闭了该连接,置upstream_eof标记  
  374.             if (n == 0) {  
  375.                 p->upstream_eof = 1;  
  376.                 break;  
  377.             }  
  378.         }  
  379.         //read_length记录了从上游服务器读取的数据的长度  
  380.         p->read_length += n;  
  381.         //c1其实记录了以前和本次free_raw_bufs的数据的链表  
  382.         cl = chain;  
  383.         p->free_raw_bufs = NULL;  
  384.   
  385.         //该段代码中会不停的把读取到的数据buf挂入到p->in的链表中  
  386.         while (cl && n > 0) {  
  387.   
  388.             ngx_event_pipe_remove_shadow_links(cl->buf);  
  389.             //size是该buf能读取的数据的大小  
  390.             size = cl->buf->end - cl->buf->last;  
  391.             //该buf全部用来了读取数据,没有残余空间  
  392.             if (n >= size) {  
  393.                 cl->buf->last = cl->buf->end;  
  394.   
  395.                 /* STUB */ cl->buf->num = p->num++;  
  396.                 //调用input_filter对刚刚接收到的数据进行处理,默认为  
  397.                 //ngx_event_pipe_copy_input_filter  
  398.                 if (p->input_filter(p, cl->buf) == NGX_ERROR) {  
  399.                     return NGX_ABORT;  
  400.                 }  
  401.   
  402.                 n -= size;  
  403.                 ln = cl;  
  404.                 cl = cl->next;  
  405.                 //释放相关chain的数据结构  
  406.                 ngx_free_chain(p->pool, ln);  
  407.   
  408.             } else {  
  409.                 //该cl的buf上面尚有部分数据未被挂入到in链表中  
  410.                 cl->buf->last += n;  
  411.                 n = 0;  
  412.             }  
  413.         }  
  414.         //c1存在,应该说明其buf上尚有部分空间可以读入数据  
  415.         if (cl) {  
  416.             for (ln = cl; ln->next; ln = ln->next) { /* void */ }  
  417.   
  418.             ln->next = p->free_raw_bufs;  
  419.             p->free_raw_bufs = cl;  
  420.         }  
  421.     }  
  422.   
  423.     if ((p->upstream_eof || p->upstream_error) && p->free_raw_bufs) {  
  424.   
  425.         /* STUB */ p->free_raw_bufs->buf->num = p->num++;  
  426.   
  427.         if (p->input_filter(p, p->free_raw_bufs->buf) == NGX_ERROR) {  
  428.             return NGX_ABORT;  
  429.         }  
  430.   
  431.         p->free_raw_bufs = p->free_raw_bufs->next;  
  432.   
  433.         if (p->free_bufs && p->buf_to_file == NULL) {  
  434.             for (cl = p->free_raw_bufs; cl; cl = cl->next) {  
  435.                 if (cl->buf->shadow == NULL) {  
  436.                     ngx_pfree(p->pool, cl->buf->start);  
  437.                 }  
  438.             }  
  439.         }  
  440.     }  
  441.   
  442.     if (p->cacheable && p->in) {  
  443.         if (ngx_event_pipe_write_chain_to_temp_file(p) == NGX_ABORT) {  
  444.             return NGX_ABORT;  
  445.         }  
  446.     }  
  447.   
  448.     return NGX_OK;  
  449. }  
  450. 5 ngx_event_pipe_write_to_downstream  
  451. static ngx_int_t  
  452. ngx_event_pipe_write_to_downstream(ngx_event_pipe_t *p)  
  453. {  
  454.     u_char            *prev;  
  455.     size_t             bsize;  
  456.     ngx_int_t          rc;  
  457.     ngx_uint_t         flush, flushed, prev_last_shadow;  
  458.     ngx_chain_t       *out, **ll, *cl, file;  
  459.     ngx_connection_t  *downstream;  
  460.     //downstream表示nginx与下游客户端之间的连接  
  461.     downstream = p->downstream;  
  462.     flushed = 0;  
  463.   
  464.     for ( ;; ) {  
  465.         if (p->downstream_error) {  
  466.             return ngx_event_pipe_drain_chains(p);  
  467.         }  
  468.         //上游服务器关闭了连接,或者出错的情况  
  469.         if (p->upstream_eof || p->upstream_error || p->upstream_done) {  
  470.             for (cl = p->busy; cl; cl = cl->next) {  
  471.                 cl->buf->recycled = 0;  
  472.             }  
  473.             //要发送的话,先发送p->out链表上的,再发送p->in链表上的  
  474.             if (p->out) {  
  475.                 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  476.                                "pipe write downstream flush out");  
  477.   
  478.                 for (cl = p->out; cl; cl = cl->next) {  
  479.                     cl->buf->recycled = 0;  
  480.                 }  
  481.                 //将p->out链表上的buf发送出去  
  482.                 rc = p->output_filter(p->output_ctx, p->out);  
  483.                 if (rc == NGX_ERROR) {  
  484.                     p->downstream_error = 1;  
  485.                     return ngx_event_pipe_drain_chains(p);  
  486.                 }  
  487.                 p->out = NULL;  
  488.             }  
  489.             //后发送p->in链表上的buf,OK  
  490.             if (p->in) {  
  491.                 ngx_log_debug0(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  492.                                "pipe write downstream flush in");  
  493.                 for (cl = p->in; cl; cl = cl->next) {  
  494.                     cl->buf->recycled = 0;  
  495.                 }  
  496.                 //将p->in链表上的buf发送出去  
  497.                 rc = p->output_filter(p->output_ctx, p->in);  
  498.                 if (rc == NGX_ERROR) {  
  499.                     p->downstream_error = 1;  
  500.                     return ngx_event_pipe_drain_chains(p);  
  501.                 }  
  502.                 p->in = NULL;  
  503.             }  
  504.             if (p->cacheable && p->buf_to_file) {  
  505.   
  506.                 file.buf = p->buf_to_file;  
  507.                 file.next = NULL;  
  508.   
  509.                 if (ngx_write_chain_to_temp_file(p->temp_file, &file)  
  510.                     == NGX_ERROR)  
  511.                 {  
  512.                     return NGX_ABORT;  
  513.                 }  
  514.             }  
  515.   
  516.             ngx_log_debug0(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  517.                            "pipe write downstream done");  
  518.   
  519.             /* TODO: free unused bufs */  
  520.             //置downstream_done标记,表明downstream写操作处理完成  
  521.             p->downstream_done = 1;  
  522.             break;  
  523.         }  
  524.   
  525.         if (downstream->data != p->output_ctx  
  526.             || !downstream->write->ready  
  527.             || downstream->write->delayed)  
  528.         {  
  529.             break;  
  530.         }  
  531.         prev = NULL;  
  532.         bsize = 0;  
  533.         //计算已有busy buffer的大小  
  534.         for (cl = p->busy; cl; cl = cl->next) {  
  535.   
  536.             if (cl->buf->recycled) {  
  537.                 if (prev == cl->buf->start) {  
  538.                     continue;  
  539.                 }  
  540.   
  541.                 bsize += cl->buf->end - cl->buf->start;  
  542.                 prev = cl->buf->start;  
  543.             }  
  544.         }  
  545.         out = NULL;  
  546.         //已有的busy链表中数据长度已经超出了限制,需先  
  547.         //flush掉该部分数据,才能接着写入out与in链表的数据、  
  548.         if (bsize >= (size_t) p->busy_size) {  
  549.             flush = 1;  
  550.             goto flush;  
  551.         }  
  552.   
  553.         flush = 0;  
  554.         ll = NULL;  
  555.         prev_last_shadow = 1;  
  556.         //下面是遍历out链表和in链表,将out和in链表中不超过busy_size  
  557.         //的buf串起来组成一个临时的out链表,调用output_filter函数去发送  
  558.         for ( ;; ) {  
  559.             if (p->out) {  
  560.                 cl = p->out;  
  561.   
  562.                 if (cl->buf->recycled  
  563.                     && bsize + cl->buf->last - cl->buf->pos > p->busy_size)  
  564.                 {  
  565.                     flush = 1;  
  566.                     break;  
  567.                 }  
  568.   
  569.                 p->out = p->out->next;  
  570.   
  571.                 ngx_event_pipe_free_shadow_raw_buf(&p->free_raw_bufs, cl->buf);  
  572.   
  573.             } else if (!p->cacheable && p->in) {  
  574.                 cl = p->in;  
  575.   
  576.                 ngx_log_debug3(NGX_LOG_DEBUG_EVENT, p->log, 0,  
  577.                                "pipe write buf ls:%d %p %z",  
  578.                                cl->buf->last_shadow,  
  579.                                cl->buf->pos,  
  580.                                cl->buf->last - cl->buf->pos);  
  581.   
  582.                 if (cl->buf->recycled  
  583.                     && cl->buf->last_shadow  
  584.                     && bsize + cl->buf->last - cl->buf->pos > p->busy_size)  
  585.                 {  
  586.                     if (!prev_last_shadow) {  
  587.                         p->in = p->in->next;  
  588.   
  589.                         cl->next = NULL;  
  590.   
  591.                         if (out) {  
  592.                             *ll = cl;  
  593.                         } else {  
  594.                             out = cl;  
  595.                         }  
  596.                     }  
  597.   
  598.                     flush = 1;  
  599.                     break;  
  600.                 }  
  601.   
  602.                 prev_last_shadow = cl->buf->last_shadow;  
  603.   
  604.                 p->in = p->in->next;  
  605.   
  606.             } else {  
  607.                 break;  
  608.             }  
  609.   
  610.             if (cl->buf->recycled) {  
  611.                 bsize += cl->buf->last - cl->buf->pos;  
  612.             }  
  613.   
  614.             cl->next = NULL;  
  615.   
  616.             if (out) {  
  617.                 *ll = cl;  
  618.             } else {  
  619.                 out = cl;  
  620.             }  
  621.             ll = &cl->next;  
  622.         }  
  623.   
  624.     flush:  
  625.         if (out == NULL) {  
  626.             if (!flush) {  
  627.                 break;  
  628.             }  
  629.   
  630.             /* a workaround for AIO */  
  631.             if (flushed++ > 10) {  
  632.                 return NGX_BUSY;  
  633.             }  
  634.         }  
  635.         //将临时组成的包含了p->out,p->in中buf的链表,往下游发送  
  636.         rc = p->output_filter(p->output_ctx, out);  
  637.         //更新busy,free链表  
  638.         ngx_chain_update_chains(&p->free, &p->busy, &out, p->tag);  
  639.   
  640.         if (rc == NGX_ERROR) {  
  641.             p->downstream_error = 1;  
  642.             return ngx_event_pipe_drain_chains(p);  
  643.         }  
  644.         //释放free链表中的缓冲区  
  645.         for (cl = p->free; cl; cl = cl->next) {  
  646.   
  647.             if (cl->buf->temp_file) {  
  648.                 if (p->cacheable || !p->cyclic_temp_file) {  
  649.                     continue;  
  650.                 }  
  651.   
  652.                 /* reset p->temp_offset if all bufs had been sent */  
  653.   
  654.                 if (cl->buf->file_last == p->temp_file->offset) {  
  655.                     p->temp_file->offset = 0;  
  656.                 }  
  657.             }  
  658.             if (cl->buf->last_shadow) {  
  659.                 if (ngx_event_pipe_add_free_buf(p, cl->buf->shadow) != NGX_OK) {  
  660.                     return NGX_ABORT;  
  661.                 }  
  662.   
  663.                 cl->buf->last_shadow = 0;  
  664.             }  
  665.   
  666.             cl->buf->shadow = NULL;  
  667.         }  
  668.     }  
  669.   
  670.     return NGX_OK;  
  671. }  

0 0