Nginx之核心结构体ngx_cycle_t

1. ngx_listening_t 结构体

ngx_cycle_t 对象中有一个动态数组成员叫做 listening,它的每个数组元素都是 ngx_listening_t 结构体,而每个 ngx_listening_t 结构体又代表着 Nginx 服务器监听的一个端口。

typedef struct ngx_listening_s  ngx_listening_t;

struct ngx_listening_s {
    // socket 套接字句柄
    ngx_socket_t        fd;

    // 监听 sockaddr 地址
    struct sockaddr    *sockaddr;
    // sockaddr 地址长度
    socklen_t           socklen;    /* size of sockaddr */
    // 存储 IP 地址的字符串 addr_text 最大长度,即它指定了 addr_text 所分配的内存大小
    size_t              addr_text_max_len;
    // 以字符串形式存储IP地址
    ngx_str_t           addr_text;

    // 套接字类型
    int                 type;

    // TCP 实现监听时的 backlog 队列,它表示允许正在通过三次握手建立 TCP 
    // 连接但没有任何进程开始处理的连接最大个数
    int                 backlog;
    // 内核中对于这个套接字的接收缓存区大小
    int                 rcvbuf;
    // 内核中对于这个套接字的发送缓冲区大小
    int                 sndbuf;
#if (NGX_HAVE_KEEPALIVE_TUNABLE)
    int                 keepidle;
    int                 keepintvl;
    int                 keepcnt;
#endif

    // 当新的 TCP 连接建立成功后调用的回调处理函数
    /* handler of accepted connection */
    ngx_connection_handler_pt   handler;

    // 实际上框架并不使用 servers 指针,它更多的是作为一个保留指针,目前
    // 主要用于HTTP或mail等模块,用于保存当前监听端口对应着的所有主机名
    void               *servers;  /* array of ngx_http_in_addr_t, for example */

    ngx_log_t           log;
    ngx_log_t          *logp;

    // 如果为新的 TCP 连接创建内存池,则内存池的大小为 pool_size
    size_t              pool_size;
    /* should be here because of the AcceptEx() preread */
    size_t              post_accept_buffer_size;
    // TCP_DEFER_ACCEPT选项将在建立TCP连接成功且接收到用户的请求数据后,才向对监听套接字
    // 感兴趣的进程发送事件通知,而连接建立成功后,如果post_accept_timeout秒后仍然
    // 没有收到用户数据,则内核直接丢弃连接
    /* should be here because of the deferred accept */
    ngx_msec_t          post_accept_timeout;

    // 前一个ngx_listening_t结构,多个ngx_listening_t结构体之间由previous指针组成单链表
    ngx_listening_t    *previous;
    // 当前监听句柄对应着的ngx_connection_t结构体
    ngx_connection_t   *connection;

    ngx_uint_t          worker;

    // 标志位,为1则表示当前监听句柄有效,且执行ngx_init_cycle时不关闭监听端口,
    // 为0时则正常关闭。该标志位框架代码会自动设置
    unsigned            open:1;
    // 标志位,为1表示使用已有的ngx_cycle_t来初始化新的ngx_cycle_t结构体时,不关闭
    // 原先打开的监听端口,这对运行中升级程序很有用,remain为0时,表示正常关闭
    // 曾经打开的监听端口。该标志位框架代码会自动设置
    unsigned            remain:1;
    // 标志位,为1时表示跳过设置当前ngx_listening_t结构体中的套接字,为0时正常
    // 初始化套接字。该标志位框架代码会自动设置
    unsigned            ignore:1;

    // 表示是否已经绑定。
    unsigned            bound:1;       /* already bound */
    // 表示当前监听套接字是否来自前一个进程(如升级Nginx),如果为1,则表示来自前
    // 一个进程。一般会保留之前已经设置好的套接字,不做改变
    unsigned            inherited:1;   /* inherited from previous process */
    unsigned            nonblocking_accept:1;
    // 标志位,为1时表示当前结构体对应的套接字已经监听
    unsigned            listen:1;
    // 表示套接字是否是非阻塞的
    unsigned            nonblocking:1;
    unsigned            shared:1;    /* shared between threads or processes */
    // 标志位,为1时表示Nginx会将网络地址转变为字符串形式的地址
    unsigned            addr_ntop:1;
    unsigned            wildcard:1;

#if (NGX_HAVE_INET6)
    unsigned            ipv6only:1;
#endif
    unsigned            reuseport:1;
    unsigned            add_reuseport:1;
    unsigned            keepalive:2;

    unsigned            deferred_accept:1;
    unsigned            delete_deferred:1;
    unsigned            add_deferred:1;
#if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER)
    char               *accept_filter;
#endif
#if (NGX_HAVE_SETFIB)
    int                 setfib;
#endif

#if (NGX_HAVE_TCP_FASTOPEN)
    int                 fastopen;
#endif
};

2. ngx_cycle_t 结构体

typedef struct ngx_cycle_s           ngx_cycle_t;

struct ngx_cycle_s {
    /*
     * 保存着所有模块存储配置项的结构体的指针,它首先是一个数组,每个数组
     * 成员又是一个指针,这个指针指向另一个存储着指针的数组
     */
    void                  ****conf_ctx;
    /*
     * 用于该 ngx_cycle_t 的内存池
     */
    ngx_pool_t               *pool;

    /*
     * 日志模块中提供了生成基本ngx_lot_t日志对象的功能,这里的log实际上是在还没有执行
     * ngx_init_cycle 方法前,也就是还没有解析配置前,如果有信息需要输出到日志,就会
     * 暂时使用log对象,它会输出到屏幕。在ngx_init_cycle方法执行后,将会根据nginx.conf
     * 配置文件中的配置项,构造出正确的日志文件,此时会对log重新赋值.
     */
    ngx_log_t                *log;
    /* 
     * 由 nginx.conf 配置文件读取到日志文件路径后,将开始初始化 error_log 日志文件,
     * 由于 log 对象还在用于输出日志到屏幕,这时会用new_log对象暂时性地替代log日志,
     * 待初始化完成后,会用 new_log 的地址覆盖上面的log指针 
     */
    ngx_log_t                 new_log;

    ngx_uint_t                log_use_stderr;  /* unsigned  log_use_stderr:1; */

    /*
     * 对于 poll、rtsig 这样的事件模块,会以有效文件句柄数来预先建立这些 ngx_connection_t
     * 结构体,以加速事件的收集、分发。这时 files 就会保存所有 ngx_connection_t 的指针
     * 组成的数组,files_n 就是指针的总数,而文件句柄的值用来访问 files 数组成员
     */
    ngx_connection_t        **files;
    /*
     * 可用连接池
     */
    ngx_connection_t         *free_connections;
    /*
     * 可用连接池中连接的总数
     */
    ngx_uint_t                free_connection_n;

    /*
     * 保存着当前 Nginx 所编译进来的所有模块 ngx_module_t 结构体的指针
     * 它是一个数组,每个数组元素是指向 ngx_module_t 的指针
     */
    ngx_module_t            **modules;
    /* modules 数组中元素的个数 */
    ngx_uint_t                modules_n;
    ngx_uint_t                modules_used;    /* unsigned  modules_used:1; */

    ngx_queue_t               reusable_connections_queue;
    ngx_uint_t                reusable_connections_n;

    /*
     * 动态数组,每个数组元素存储着 ngx_listening_t 成员,表示监听端口及相关的参数
     */
    ngx_array_t               listening;
    /*
     * 动态数组容器,它保存着 Nginx 所要操作的目录。如果有目录不存在,则会试图创建,
     * 而创建目录失败将会导致 Nginx 启动失败。例如,上传文件的临时目录也在 pathes
     * 中,如果没有权限创建,则会导致 Nginx 无法启动.
     */
    ngx_array_t               paths;

    ngx_array_t               config_dump;
    ngx_rbtree_t              config_dump_rbtree;
    ngx_rbtree_node_t         config_dump_sentinel;

    /*
     * 单链表容器,元素类型是 ngx_open_file_t 结构体,它表示 Nginx 已经打开的所有
     * 文件。事实上,Nginx 框架不会向 open_files 链表中添加文件,而是由对此感兴趣
     * 的模块向其中添加文件路径名,Nginx 框架会在 ngx_init_cycle 方法中打开这些
     * 文件.
     */
    ngx_list_t                open_files;
    /*
     * 单链表容器,元素类型是 ngx_shm_zone_t 结构体,每个元素表示一块共享内存
     */
    ngx_list_t                shared_memory;

    /*
     * 当前进程中所有连接对象的总数
     */
    ngx_uint_t                connection_n;
    ngx_uint_t                files_n;

    /*
     * 指向当前进程中的所有连接对象
     */
    ngx_connection_t         *connections;
    /*
     * 指向当前进程中的所有读事件对象,connection_n 同时表示所有读事件的总数
     */
    ngx_event_t              *read_events;
    /*
     * 指向当前进程中的所有写事件对象,connection_n 同时表示所有写事件的总数
     */
    ngx_event_t              *write_events;

    /*
     * 旧的 ngx_cycle_t 对象用于引用上一个 ngx_cycle_t 对象中的成员。例如
     * ngx_init_cycle 方法,在启动初期,需要建立一个临时的 ngx_cycle_t 对象
     * 保存一些变量,再调用 ngx_init_cycle 方法时就可以把旧的 ngx_cycle_t
     * 对象传进去,而这时 old_cycle 对象就会保存这个前期的 ngx_cycle_t 对象
     */
    ngx_cycle_t              *old_cycle;

    /*
     * 配置文件相对于安装目录的路径名称
     */
    ngx_str_t                 conf_file;
    /* 
     * Nginx 处理配置文件时需要特殊处理的在命令行携带的参数,一般是 
     * -g 选项携带的参数
     */
    ngx_str_t                 conf_param;
    /*
     * Nginx 配置文件所在目录的路径
     */
    ngx_str_t                 conf_prefix;
    /*
     * Nginx 安装目录的路径
     */
    ngx_str_t                 prefix;
    /*
     * 用于进程间同步的文件锁名称
     */
    ngx_str_t                 lock_file;
    /*
     * 使用 gethostname 系统调用得到的主机名
     */
    ngx_str_t                 hostname;
};

3. ngx_init_cycle

/*
 * @old_cycle: 表示临时的 ngx_cycle_t 指针,一般仅用来传递 ngx_cycle_t 结构体中
 * 的配置文件路径等参数.
 *
 * 返回初始化成功的完整的 ngx_cycle_t 结构体,该函数将会负责初始化 ngx_cycle_t 
 * 中的数据结构、解析配置文件、加载所有模块、打开监听端口、初始化进程间通信方式
 * 等工作。如果失败,则返回 NULL 空指针.
 */
ngx_cycle_t *
ngx_init_cycle(ngx_cycle_t *old_cycle)
{
    void                *rv;
    char               **senv;
    ngx_uint_t           i, n;
    ngx_log_t           *log;
    ngx_time_t          *tp;
    ngx_conf_t           conf;
    ngx_pool_t          *pool;
    ngx_cycle_t         *cycle, **old;
    ngx_shm_zone_t      *shm_zone, *oshm_zone;
    ngx_list_part_t     *part, *opart;
    ngx_open_file_t     *file;
    ngx_listening_t     *ls, *nls;
    ngx_core_conf_t     *ccf, *old_ccf;
    ngx_core_module_t   *module;
    char                 hostname[NGX_MAXHOSTNAMELEN];

    /* 更新时区 */
    ngx_timezone_update();

    /* force localtime update with a new timezone */

    tp = ngx_timeofday();
    tp->sec = 0;

    /* 更新缓存时间 */
    ngx_time_update();


    log = old_cycle->log;

    /* 为 ngx_cycle_t 创建一个 16k 大小内存池 */
    pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log);
    if (pool == NULL) {
        return NULL;
    }
    pool->log = log;

    /* 为 ngx_cycle_t 分配内存 */
    cycle = ngx_pcalloc(pool, sizeof(ngx_cycle_t));
    if (cycle == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    /* 设置该 ngx_cycle_t 使用的内存池 */
    cycle->pool = pool;
    cycle->log = log;
    /* old_cycle 一般仅用来传递 ngx_cycle_t 结构体中的配置文件路径等参数. */
    cycle->old_cycle = old_cycle;

    /* 假设设置 --prefix=/usr/local/nginx */
    
    cycle->conf_prefix.len = old_cycle->conf_prefix.len;
    /* Nginx 配置文件所在目录的路径: /usr/local/nginx/conf/ */
    cycle->conf_prefix.data = ngx_pstrdup(pool, &old_cycle->conf_prefix);
    if (cycle->conf_prefix.data == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    cycle->prefix.len = old_cycle->prefix.len;
    /* Nginx 安装目录的路径: /usr/local/nginx/ */
    cycle->prefix.data = ngx_pstrdup(pool, &old_cycle->prefix);
    if (cycle->prefix.data == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    cycle->conf_file.len = old_cycle->conf_file.len;
    /* 配置文件相对于安装目录的路径名称: /usr/local/nginx/conf/nginx.conf */
    cycle->conf_file.data = ngx_pnalloc(pool, old_cycle->conf_file.len + 1);
    if (cycle->conf_file.data == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }
    ngx_cpystrn(cycle->conf_file.data, old_cycle->conf_file.data,
                old_cycle->conf_file.len + 1);

    /* Nginx 处理配置文件时需要特殊处理的在命令行携带的参数,
     * 一般是 -g 选项所携带的参数 */
    cycle->conf_param.len = old_cycle->conf_param.len;
    cycle->conf_param.data = ngx_pstrdup(pool, &old_cycle->conf_param);
    if (cycle->conf_param.data == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    /*
     * 动态数组容器,它保存着 Nginx 所有要操作的目录。如果有目录不能存在,
     * 则会试图创建,而创建目录失败将会导致 Nginx 启动失败。如,上传文件
     * 的临时目录也在 pathes 中,如果没有权限创建,则会导致 Nginx 无法启动.
     * 
     * 这里,若 old->cycle->paths 中没有元素,则默认为 10
     */
    n = old_cycle->paths.nelts ? old_cycle->paths.nelts : 10;

    /* 创建 cycle->paths 数组 */
    if (ngx_array_init(&cycle->paths, pool, n, sizeof(ngx_path_t *))
        != NGX_OK)
    {
        ngx_destroy_pool(pool);
        return NULL;
    }

    ngx_memzero(cycle->paths.elts, n * sizeof(ngx_path_t *));

    if (ngx_array_init(&cycle->config_dump, pool, 1, sizeof(ngx_conf_dump_t))
        != NGX_OK)
    {
        ngx_destroy_pool(pool);
        return NULL;
    }

    /* 初始化一棵红黑树 config_dump_rbtree */
    ngx_rbtree_init(&cycle->config_dump_rbtree, &cycle->config_dump_sentinel,
                    ngx_str_rbtree_insert_value);

    if (old_cycle->open_files.part.nelts) {
        n = old_cycle->open_files.part.nelts;
        for (part = old_cycle->open_files.part.next; part; part = part->next) {
            n += part->nelts;
        }

    /* 若 old_cycle->open_files 链表为空,则默认设置下面创建的 open_files 链表
     * 元素个数为 20 */
    } else {
        n = 20;
    }

    /* 创建 open_files 链表,元素类型是 ngx_open_file_t 结构体,它表示 Nginx 已经
     * 打开的所有文件。事实上,Nginx 框架不会向 open_files 链表中添加文件,而是
     * 由对此感兴趣的模块向其中添加文件路径名,Nginx框架会在 ngx_init_cycle 方法
     * 中打开这些文件 */
    if (ngx_list_init(&cycle->open_files, pool, n, sizeof(ngx_open_file_t))
        != NGX_OK)
    {
        ngx_destroy_pool(pool);
        return NULL;
    }

    
    if (old_cycle->shared_memory.part.nelts) {
        n = old_cycle->shared_memory.part.nelts;
        for (part = old_cycle->shared_memory.part.next; part; part = part->next)
        {
            n += part->nelts;
        }

    /* 若 old_cycle->shared_memory 链表文件,则默认下面创建的 shared_memory 链表
     * 元素个数为 1 */
    } else {
        n = 1;
    }

    /* 创建 shared_memory 链表,元素类型是 ngx_shm_zone_t 结构体,每个元素表示
     * 一块共享内存 */
    if (ngx_list_init(&cycle->shared_memory, pool, n, sizeof(ngx_shm_zone_t))
        != NGX_OK)
    {
        ngx_destroy_pool(pool);
        return NULL;
    }

    n = old_cycle->listening.nelts ? old_cycle->listening.nelts : 10;

    /* 创建 listening 数组,每个数组元素存储着 ngx_listening_t 成员,表示监听端口
     * 及相关的参数 */
    if (ngx_array_init(&cycle->listening, pool, n, sizeof(ngx_listening_t))
        != NGX_OK)
    {
        ngx_destroy_pool(pool);
        return NULL;
    }

    ngx_memzero(cycle->listening.elts, n * sizeof(ngx_listening_t));


    /* 初始化 reusable_connections_queue 双向链表容器,元素类型是 ngx_connection_t
     * 结构体,表示可重复使用连接队列 */
    ngx_queue_init(&cycle->reusable_connections_queue);

    
    /* conf_ctx 保存着所有模块存储配置项的结构体的指针,它首先是一个数组,每个数组成员
     * 又是一个指针,这个指针指向另一个存储着指针的数组。该数组的最大值 ngx_max_module
     * 在 ngx_preinit_modules 函数中确定 */
    cycle->conf_ctx = ngx_pcalloc(pool, ngx_max_module * sizeof(void *));
    if (cycle->conf_ctx == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }


    /* 获取本地主机名 */
    if (gethostname(hostname, NGX_MAXHOSTNAMELEN) == -1) {
        ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "gethostname() failed");
        ngx_destroy_pool(pool);
        return NULL;
    }

    /* on Linux gethostname() silently truncates name that does not fit */

    hostname[NGX_MAXHOSTNAMELEN - 1] = '\0';
    cycle->hostname.len = ngx_strlen(hostname);

    cycle->hostname.data = ngx_pnalloc(pool, cycle->hostname.len);
    if (cycle->hostname.data == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    /* 将获取到的主机名按小写方式保存到 cycle->hostname 中 */
    ngx_strlow(cycle->hostname.data, (u_char *) hostname, cycle->hostname.len);

    /* 将全局变量 ngx_modules 数组所包含的所有模块都复制到 cycle->modules 中 
     * 该 modules 数组的元素个数为 cycle->modules_n */
    if (ngx_cycle_modules(cycle) != NGX_OK) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    /* 遍历所有的核心模块 */
    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

        /* 获取该模块对象的上下文结构体,对于核心模块
         * 其上下文结构体固定为 ngx_core_module_t */
        module = cycle->modules[i]->ctx;

        if (module->create_conf) {
            /* 调用核心模块的 create_conf 函数,创建实际的配置信息存储空间
             * 并初始化该配置信息结构体 */
            rv = module->create_conf(cycle);
            if (rv == NULL) {
                ngx_destroy_pool(pool);
                return NULL;
            }
            /* 将返回的配置信息结构体保存到该核心模块在 cycle->conf_ctx 数组
             * 对应下标处 */
            cycle->conf_ctx[cycle->modules[i]->index] = rv;
        }
    }


    senv = environ;


    ngx_memzero(&conf, sizeof(ngx_conf_t));
    /* STUB: init array ? */
    conf.args = ngx_array_create(pool, 10, sizeof(ngx_str_t));
    if (conf.args == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }

    conf.temp_pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log);
    if (conf.temp_pool == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }


    /* 指向保存着所有 Nginx 模块的配置结构体数组 */
    conf.ctx = cycle->conf_ctx;
    /* 指向当前的核心结构体 ngx_cycle_t */
    conf.cycle = cycle;
    /* 指向当前核心结构体 ngx_cycle_t 所用的内存池 */
    conf.pool = pool;
    conf.log = log;
    /* 默认初始化当前模块的类型为核心模块 */
    conf.module_type = NGX_CORE_MODULE;
    conf.cmd_type = NGX_MAIN_CONF;

#if 0
    log->log_level = NGX_LOG_DEBUG_ALL;
#endif

    /* 解析通过命令行传入的参数,若没有,则可忽略 */
    if (ngx_conf_param(&conf) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

    /* 开始解析配置文件中的所有配置项, conf_file 保存着配置文件
     * 的绝对路径 */
    if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

    if (ngx_test_config && !ngx_quiet_mode) {
        ngx_log_stderr(0, "the configuration file %s syntax is ok",
                       cycle->conf_file.data);
    }

    /* 遍历所有非核心模块 */
    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

        module = cycle->modules[i]->ctx;

        if (module->init_conf) {
            /* init_conf 是用于对上面解析完配置文件后对用户没有
             * 设置的核心模块配置指令设置默认值 */
            if (module->init_conf(cycle,
                                  cycle->conf_ctx[cycle->modules[i]->index])
                == NGX_CONF_ERROR)
            {
                environ = senv;
                ngx_destroy_cycle_pools(&conf);
                return NULL;
            }
        }
    }

    if (ngx_process == NGX_PROCESS_SIGNALLER) {
        return cycle;
    }

    /* 从cycle->conf_ctx数组中取出ngx_core_module的配置信息结构体 */
    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (ngx_test_config) {

        if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) {
            goto failed;
        }

    } else if (!ngx_is_init_cycle(old_cycle)) {

        /*
         * we do not create the pid file in the first ngx_init_cycle() call
         * because we need to write the demonized process pid
         */

        old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx,
                                                   ngx_core_module);
        if (ccf->pid.len != old_ccf->pid.len
            || ngx_strcmp(ccf->pid.data, old_ccf->pid.data) != 0)
        {
            /* new pid file name */

            if (ngx_create_pidfile(&ccf->pid, log) != NGX_OK) {
                goto failed;
            }

            ngx_delete_pidfile(old_cycle);
        }
    }

    /* 若当前系统不支持原子操作时则检测用于文件锁的文件是否打开,
     * 若失败,则返回 error */
    if (ngx_test_lockfile(cycle->lock_file.data, log) != NGX_OK) {
        goto failed;
    }

    /* 生成目录 */
    if (ngx_create_paths(cycle, ccf->user) != NGX_OK) {
        goto failed;
    }


    if (ngx_log_open_default(cycle) != NGX_OK) {
        goto failed;
    }

    /* open the new files */

    part = &cycle->open_files.part;
    file = part->elts;

    for (i = 0; /* void */ ; i++) {

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }
            part = part->next;
            file = part->elts;
            i = 0;
        }

        if (file[i].name.len == 0) {
            continue;
        }

        file[i].fd = ngx_open_file(file[i].name.data,
                                   NGX_FILE_APPEND,
                                   NGX_FILE_CREATE_OR_OPEN,
                                   NGX_FILE_DEFAULT_ACCESS);

        ngx_log_debug3(NGX_LOG_DEBUG_CORE, log, 0,
                       "log: %p %d \"%s\"",
                       &file[i], file[i].fd, file[i].name.data);

        if (file[i].fd == NGX_INVALID_FILE) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_errno,
                          ngx_open_file_n " \"%s\" failed",
                          file[i].name.data);
            goto failed;
        }

#if !(NGX_WIN32)
        if (fcntl(file[i].fd, F_SETFD, FD_CLOEXEC) == -1) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_errno,
                          "fcntl(FD_CLOEXEC) \"%s\" failed",
                          file[i].name.data);
            goto failed;
        }
#endif
    }

    cycle->log = &cycle->new_log;
    pool->log = &cycle->new_log;


    /* create shared memory */

    /* 该 shared_memory 是由配置有启用共享内存的模块来添加的 */
    part = &cycle->shared_memory.part;
    shm_zone = part->elts;

    /* 该 for 循环是检测新的将要创建的共享内存是否与旧的共享内存
     * 有冲突 */
    for (i = 0; /* void */ ; i++) {

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }
            part = part->next;
            shm_zone = part->elts;
            i = 0;
        }

        if (shm_zone[i].shm.size == 0) {
            ngx_log_error(NGX_LOG_EMERG, log, 0,
                          "zero size shared memory zone \"%V\"",
                          &shm_zone[i].shm.name);
            goto failed;
        }

        shm_zone[i].shm.log = cycle->log;

        opart = &old_cycle->shared_memory.part;
        oshm_zone = opart->elts;

        for (n = 0; /* void */ ; n++) {

            if (n >= opart->nelts) {
                if (opart->next == NULL) {
                    break;
                }
                opart = opart->next;
                oshm_zone = opart->elts;
                n = 0;
            }

            if (shm_zone[i].shm.name.len != oshm_zone[n].shm.name.len) {
                continue;
            }

            if (ngx_strncmp(shm_zone[i].shm.name.data,
                            oshm_zone[n].shm.name.data,
                            shm_zone[i].shm.name.len)
                != 0)
            {
                continue;
            }

            if (shm_zone[i].tag == oshm_zone[n].tag
                && shm_zone[i].shm.size == oshm_zone[n].shm.size
                && !shm_zone[i].noreuse)
            {
                shm_zone[i].shm.addr = oshm_zone[n].shm.addr;
#if (NGX_WIN32)
                shm_zone[i].shm.handle = oshm_zone[n].shm.handle;
#endif

                if (shm_zone[i].init(&shm_zone[i], oshm_zone[n].data)
                    != NGX_OK)
                {
                    goto failed;
                }

                goto shm_zone_found;
            }

            /* 销毁旧的共享内存 */
            ngx_shm_free(&oshm_zone[n].shm);

            break;
        }

        /* mmap 映射一块共享内存 */
        if (ngx_shm_alloc(&shm_zone[i].shm) != NGX_OK) {
            goto failed;
        }

        /* 调用 slab 机制划分该共享内存 */
        if (ngx_init_zone_pool(cycle, &shm_zone[i]) != NGX_OK) {
            goto failed;
        }

        /* 每个模块的共享内存都有自己特有的属性,因此调用各自的
         * 共享内存初始化函数 */
        if (shm_zone[i].init(&shm_zone[i], NULL) != NGX_OK) {
            goto failed;
        }

    shm_zone_found:

        continue;
    }


    /* handle the listening sockets */

    if (old_cycle->listening.nelts) {
        ls = old_cycle->listening.elts;
        for (i = 0; i < old_cycle->listening.nelts; i++) {
            ls[i].remain = 0;
        }

        nls = cycle->listening.elts;
        for (n = 0; n < cycle->listening.nelts; n++) {

            for (i = 0; i < old_cycle->listening.nelts; i++) {
                if (ls[i].ignore) {
                    continue;
                }

                if (ls[i].remain) {
                    continue;
                }

                if (ls[i].type != nls[n].type) {
                    continue;
                }

                if (ngx_cmp_sockaddr(nls[n].sockaddr, nls[n].socklen,
                                     ls[i].sockaddr, ls[i].socklen, 1)
                    == NGX_OK)
                {
                    nls[n].fd = ls[i].fd;
                    nls[n].previous = &ls[i];
                    ls[i].remain = 1;

                    if (ls[i].backlog != nls[n].backlog) {
                        nls[n].listen = 1;
                    }

#if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER)

                    /*
                     * FreeBSD, except the most recent versions,
                     * could not remove accept filter
                     */
                    nls[n].deferred_accept = ls[i].deferred_accept;

                    if (ls[i].accept_filter && nls[n].accept_filter) {
                        if (ngx_strcmp(ls[i].accept_filter,
                                       nls[n].accept_filter)
                            != 0)
                        {
                            nls[n].delete_deferred = 1;
                            nls[n].add_deferred = 1;
                        }

                    } else if (ls[i].accept_filter) {
                        nls[n].delete_deferred = 1;

                    } else if (nls[n].accept_filter) {
                        nls[n].add_deferred = 1;
                    }
#endif

#if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT)

                    if (ls[i].deferred_accept && !nls[n].deferred_accept) {
                        nls[n].delete_deferred = 1;

                    } else if (ls[i].deferred_accept != nls[n].deferred_accept)
                    {
                        nls[n].add_deferred = 1;
                    }
#endif

#if (NGX_HAVE_REUSEPORT)
                    if (nls[n].reuseport && !ls[i].reuseport) {
                        nls[n].add_reuseport = 1;
                    }
#endif

                    break;
                }
            }

            if (nls[n].fd == (ngx_socket_t) -1) {
                nls[n].open = 1;
#if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER)
                if (nls[n].accept_filter) {
                    nls[n].add_deferred = 1;
                }
#endif
#if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT)
                if (nls[n].deferred_accept) {
                    nls[n].add_deferred = 1;
                }
#endif
            }
        }

    } else {
        /* listening: 动态数组,每个数组元素存储着ngx_listening_t成员,
         * 表示监听端口及相关的参数 */
        ls = cycle->listening.elts;
        for (i = 0; i < cycle->listening.nelts; i++) {
            
            /* 标志位,为1则表示在当前监听句柄有效,且执行ngx_init_cycle时
             * 不关闭监听端口,为0时则正常关闭。 */
            ls[i].open = 1;
#if (NGX_HAVE_DEFERRED_ACCEPT && defined SO_ACCEPTFILTER)
            if (ls[i].accept_filter) {
                ls[i].add_deferred = 1;
            }
#endif
#if (NGX_HAVE_DEFERRED_ACCEPT && defined TCP_DEFER_ACCEPT)
            if (ls[i].deferred_accept) {
                ls[i].add_deferred = 1;
            }
#endif
        }
    }

    /* 遍历nginx.conf中配置的所有需要监听的端口,创建socket */
    if (ngx_open_listening_sockets(cycle) != NGX_OK) {
        goto failed;
    }

    if (!ngx_test_config) {
        ngx_configure_listening_sockets(cycle);
    }


    /* commit the new cycle configuration */

    if (!ngx_use_stderr) {
        (void) ngx_log_redirect_stderr(cycle);
    }

    pool->log = cycle->log;

    /* 调用所有模块的init_module方法 */
    if (ngx_init_modules(cycle) != NGX_OK) {
        /* fatal */
        exit(1);
    }


    /* close and delete stuff that lefts from an old cycle */

    /* free the unnecessary shared memory */

    opart = &old_cycle->shared_memory.part;
    oshm_zone = opart->elts;

    for (i = 0; /* void */ ; i++) {

        if (i >= opart->nelts) {
            if (opart->next == NULL) {
                goto old_shm_zone_done;
            }
            opart = opart->next;
            oshm_zone = opart->elts;
            i = 0;
        }

        part = &cycle->shared_memory.part;
        shm_zone = part->elts;

        for (n = 0; /* void */ ; n++) {

            if (n >= part->nelts) {
                if (part->next == NULL) {
                    break;
                }
                part = part->next;
                shm_zone = part->elts;
                n = 0;
            }

            if (oshm_zone[i].shm.name.len == shm_zone[n].shm.name.len
                && ngx_strncmp(oshm_zone[i].shm.name.data,
                               shm_zone[n].shm.name.data,
                               oshm_zone[i].shm.name.len)
                == 0)
            {
                goto live_shm_zone;
            }
        }

        ngx_shm_free(&oshm_zone[i].shm);

    live_shm_zone:

        continue;
    }

old_shm_zone_done:


    /* close the unnecessary listening sockets */

    ls = old_cycle->listening.elts;
    for (i = 0; i < old_cycle->listening.nelts; i++) {

        if (ls[i].remain || ls[i].fd == (ngx_socket_t) -1) {
            continue;
        }

        if (ngx_close_socket(ls[i].fd) == -1) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno,
                          ngx_close_socket_n " listening socket on %V failed",
                          &ls[i].addr_text);
        }

#if (NGX_HAVE_UNIX_DOMAIN)

        if (ls[i].sockaddr->sa_family == AF_UNIX) {
            u_char  *name;

            name = ls[i].addr_text.data + sizeof("unix:") - 1;

            ngx_log_error(NGX_LOG_WARN, cycle->log, 0,
                          "deleting socket %s", name);

            if (ngx_delete_file(name) == NGX_FILE_ERROR) {
                ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_socket_errno,
                              ngx_delete_file_n " %s failed", name);
            }
        }

#endif
    }


    /* close the unnecessary open files */

    part = &old_cycle->open_files.part;
    file = part->elts;

    for (i = 0; /* void */ ; i++) {

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }
            part = part->next;
            file = part->elts;
            i = 0;
        }

        if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) {
            continue;
        }

        if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_errno,
                          ngx_close_file_n " \"%s\" failed",
                          file[i].name.data);
        }
    }

    ngx_destroy_pool(conf.temp_pool);

    /* 若为 master_process 模式 */
    if (ngx_process == NGX_PROCESS_MASTER || ngx_is_init_cycle(old_cycle)) {

        ngx_destroy_pool(old_cycle->pool);
        cycle->old_cycle = NULL;

        return cycle;
    }


    if (ngx_temp_pool == NULL) {
        ngx_temp_pool = ngx_create_pool(128, cycle->log);
        if (ngx_temp_pool == NULL) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, 0,
                          "could not create ngx_temp_pool");
            exit(1);
        }

        n = 10;

        if (ngx_array_init(&ngx_old_cycles, ngx_temp_pool, n,
                           sizeof(ngx_cycle_t *))
            != NGX_OK)
        {
            exit(1);
        }

        ngx_memzero(ngx_old_cycles.elts, n * sizeof(ngx_cycle_t *));

        ngx_cleaner_event.handler = ngx_clean_old_cycles;
        ngx_cleaner_event.log = cycle->log;
        ngx_cleaner_event.data = &dumb;
        dumb.fd = (ngx_socket_t) -1;
    }

    ngx_temp_pool->log = cycle->log;

    old = ngx_array_push(&ngx_old_cycles);
    if (old == NULL) {
        exit(1);
    }
    *old = old_cycle;

    if (!ngx_cleaner_event.timer_set) {
        ngx_add_timer(&ngx_cleaner_event, 30000);
        ngx_cleaner_event.timer_set = 1;
    }

    return cycle;


failed:

    if (!ngx_is_init_cycle(old_cycle)) {
        old_ccf = (ngx_core_conf_t *) ngx_get_conf(old_cycle->conf_ctx,
                                                   ngx_core_module);
        if (old_ccf->environment) {
            environ = old_ccf->environment;
        }
    }

    /* rollback the new cycle configuration */

    part = &cycle->open_files.part;
    file = part->elts;

    for (i = 0; /* void */ ; i++) {

        if (i >= part->nelts) {
            if (part->next == NULL) {
                break;
            }
            part = part->next;
            file = part->elts;
            i = 0;
        }

        if (file[i].fd == NGX_INVALID_FILE || file[i].fd == ngx_stderr) {
            continue;
        }

        if (ngx_close_file(file[i].fd) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_errno,
                          ngx_close_file_n " \"%s\" failed",
                          file[i].name.data);
        }
    }

    if (ngx_test_config) {
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

    ls = cycle->listening.elts;
    for (i = 0; i < cycle->listening.nelts; i++) {
        if (ls[i].fd == (ngx_socket_t) -1 || !ls[i].open) {
            continue;
        }

        if (ngx_close_socket(ls[i].fd) == -1) {
            ngx_log_error(NGX_LOG_EMERG, log, ngx_socket_errno,
                          ngx_close_socket_n " %V failed",
                          &ls[i].addr_text);
        }
    }

    ngx_destroy_cycle_pools(&conf);

    return NULL;
}

猜你喜欢

转载自www.cnblogs.com/jimodetiantang/p/9199525.html