Nginx源码分析 - 主流程篇 - 解析配置文件(13)

深入理解Nginx线程池【内附原理讲解以及源码分析】 本篇博客将从什么是并发编程、为什么要使用线程池、线程池的组成以及线程池的使用这4个方面对Nginx线程池进行刨析,相信耐心看完会对您有所帮助。 阅读详情
AI摘要

本文详细解析了Nginx配置文件nginx.conf的处理流程,包括数据结构、命令集及核心配置解析过程。

目录

一、Nginx的配置文件nginx.conf

二、数据结构逻辑关系图

三、相关数据结构

1. ngx_cycle_s的conf_ctx和modules

2. ngx_module_s的index和commands

3. ngx_command_s 命令集的结构

四、核心模块的定义

1. 核心模块在nginx.c的文件头部

2. 核心模块的配置结构ngx_core_conf_t

五、具体解析流程

1. 创建核心模块配置文件数据结构ngx_core_conf_t

2. 创建一个临时的ngx_conf_s结构

3. 调用解析配置函数ngx_conf_param和ngx_conf_parse

4. 配置文件核心解析函数ngx_conf_parse

5. 命令token解析 ngx_conf_read_token


Nginx源码中比较重要的一块就是配置文件的解析。一般是解析/usr/local/nginx/conf/nginx.conf文件中的配置信息。

前一篇文章,我们介绍了Nginx的模块化。Nginx的功能模块都是通过cycle->modules 模块进行管理的。而每个模块都会有自己的配置文件。

一、Nginx的配置文件nginx.conf


  • Nginx的配置文件每一行就是一条命令。
  • 最外层的为核心模块的配置参数(类型:NGX_CORE_MODULE);内部嵌套的为各个子模块的配置。
  • events {} 为事件模块(类型:NGX_EVENT_MODULE)
  • http {} 为HTTP模块 (类型:NGX_HTTP_MODULE)
  • http模块内还会嵌套多层
  • 多层嵌套会在后续的event模块中介绍。这里只介绍最顶层的core模块的解析。

配置的层次结构如下图:

 

               Main CODE
          /                     \

 

               Events                     Http

          /            \                        /            \

                          epoll            kqueue                 Server          Server

                                                                                  /             \                   \

                                                                                         Location     Location      Location

 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

二、数据结构逻辑关系图


三、相关数据结构


1. ngx_cycle_s的conf_ctx和modules


cycle->conf_ctx :配置文件上下文数组。每个模块的配置文件数据结构的指针地址都会按照模块的index索引放置在cycle->conf_ctx数组中。

cycle->modules:模块数组。模块也会按照模块的索引index放在cycle->modules数组上。具体可以参考《Nginx源码分析 - 主流程篇 - 模块的初始化 》中ngx_cycle_modules方法。

/**
 * Nginx全局变量cycle
 */
struct ngx_cycle_s {
    void                  ****conf_ctx; /* 配置文件 上下文的数组,每个模块的配置信息*/
    ngx_pool_t               *pool;	/* 内存池地址 */
   
    ...
    ngx_module_t            **modules;	/* 模块数组 */
    ngx_uint_t                modules_n;	/* 模块个数 */
    ngx_uint_t                modules_used;    /* unsigned  modules_used:1; */
    ...
};

2. ngx_module_s的index和commands


  • index:是模块的索引值。

  • commands:模块支持的命令集。主要用于将配置信息设置到每个模块的配置文件数据结构上(例如核心模块的ngx_core_conf_t)。

/**
 * 业务模块数据结构
 */
struct ngx_module_s {
    ngx_uint_t            ctx_index;
    ngx_uint_t            index; /* 模块的唯一标识符号 */

    char                 *name;  /* 模块名称 */
    ...
    void                 *ctx;	/* 模块上下文 */
    ngx_command_t        *commands; /* 模块支持的命令集 */
    ngx_uint_t            type;	/* 模块类型 */
    ...
};

3. ngx_command_s 命令集的结构


set:为回调函数。最终设置值的时候,都会调用set的回调函数。

/**
 * 模块支持的命令集结构
 */
struct ngx_command_s {
    ngx_str_t             name; /* 命令名称 */
    ngx_uint_t            type; /* 命令类别 */
    char               *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); /* set回调函数 */
    ngx_uint_t            conf;
    ngx_uint_t            offset; /* 偏移量,命令长度 */
    void                 *post; /* 支持的回调方法;大多数情况为NULL*/
};

 

四、核心模块的定义


从上面的数据结构我们知道,每个模块都必须定义一个模块的数据结构ngx_module_s,主要用于管理每个模块的具体信息;每个模块也会定义一个ngx_command_t数组,主要用于存放需要解析的命令集的规则。

而最终的配置文件信息,由于每个模块的配置结构不同,所以在cycle->conf_ctx只保存每个模块配置文件数据结构的指针地址。

1. 核心模块在nginx.c的文件头部


核心模块

/**
 * 定义核心配置模块命令集ngx_command_t结构
 */
static ngx_command_t  ngx_core_commands[] = {

    { ngx_string("daemon"), /* 命令名称 */
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_FLAG, /* 类型 */
      ngx_conf_set_flag_slot, /* 回调方法 */
      0,
      offsetof(ngx_core_conf_t, daemon), /* 偏移量;使用这个偏移量后,可以参考 ngx_core_module_create_conf*/
      NULL },

    { ngx_string("master_process"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_FLAG,
      ngx_conf_set_flag_slot,
      0,
      offsetof(ngx_core_conf_t, master),
      NULL },

    { ngx_string("timer_resolution"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_msec_slot,
      0,
      offsetof(ngx_core_conf_t, timer_resolution),
      NULL },

    { ngx_string("pid"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_slot,
      0,
      offsetof(ngx_core_conf_t, pid),
      NULL },

    { ngx_string("lock_file"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_slot,
      0,
      offsetof(ngx_core_conf_t, lock_file),
      NULL },

    { ngx_string("worker_processes"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_set_worker_processes,
      0,
      0,
      NULL },

    { ngx_string("debug_points"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_enum_slot,
      0,
      offsetof(ngx_core_conf_t, debug_points),
      &ngx_debug_points },

    { ngx_string("user"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE12,
      ngx_set_user,
      0,
      0,
      NULL },

    { ngx_string("worker_priority"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_set_priority,
      0,
      0,
      NULL },

    { ngx_string("worker_cpu_affinity"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_1MORE,
      ngx_set_cpu_affinity,
      0,
      0,
      NULL },

    { ngx_string("worker_rlimit_nofile"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_num_slot,
      0,
      offsetof(ngx_core_conf_t, rlimit_nofile),
      NULL },

    { ngx_string("worker_rlimit_core"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_off_slot,
      0,
      offsetof(ngx_core_conf_t, rlimit_core),
      NULL },

    { ngx_string("working_directory"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_slot,
      0,
      offsetof(ngx_core_conf_t, working_directory),
      NULL },

    { ngx_string("env"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_set_env,
      0,
      0,
      NULL },

    { ngx_string("load_module"),
      NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
      ngx_load_module,
      0,
      0,
      NULL },

      ngx_null_command
};

/**
 * 核心模块上下文
 * ngx_core_module_create_conf 核心模块创建配置文件
 * ngx_core_module_init_conf 核心模块初始化配置文件
 */
static ngx_core_module_t  ngx_core_module_ctx = {
    ngx_string("core"),
    ngx_core_module_create_conf,
    ngx_core_module_init_conf
};

/**
 * 核心模块
 */
ngx_module_t  ngx_core_module = {
    NGX_MODULE_V1,
    &ngx_core_module_ctx,                  /* module context */
    ngx_core_commands,                     /* module directives */
    NGX_CORE_MODULE,                       /* module type */
    NULL,                                  /* init master */
    NULL,                                  /* init module */
    NULL,                                  /* init process */
    NULL,                                  /* init thread */
    NULL,                                  /* exit thread */
    NULL,                                  /* exit process */
    NULL,                                  /* exit master */
    NGX_MODULE_V1_PADDING
};

说明:

  • ngx_core_module 核心模块。主要管理核心模块的信息。
  • ngx_core_module_ctx 核心模块的上下文。每个模块的上下文都不同,所以模块结构中只给了一个void的指针类型,可以指向不同的数据结构。核心模块的ngx_core_module_ctx主要定义了ngx_core_module_create_conf和ngx_core_module_init_conf回调函数(创建和初始化配置文件)
  • ngx_core_commands 核心模块定义的命令集。当nginx.conf中的命令被拆简后,会通过这个命令集,逐个将核心模块的命令赋值到核心模块的配置文件数据结构上。

2. 核心模块的配置结构ngx_core_conf_t


核心模块的配置结构ngx_core_conf_t。ngx_core_conf_t的指针地址会按照模块的index索引,放在cycle->conf_ctx数组中。

ngx_core_conf_t结构的创建和初始化。ngx_core_module_create_conf和ngx_core_module_init_conf方法。

/**
 * 核心配置文件信息
 * 对应nginx.conf的
 * #user  nobody;
	worker_processes  1;

	#error_log  logs/error.log;
	#error_log  logs/error.log  notice;
	#error_log  logs/error.log  info;

	#pid        logs/nginx.pid;
 */
typedef struct {
    ngx_flag_t                daemon;
    ngx_flag_t                master;

    ngx_msec_t                timer_resolution;

    ngx_int_t                 worker_processes;
    ngx_int_t                 debug_points;

    ngx_int_t                 rlimit_nofile;
    off_t                     rlimit_core;

    int                       priority;

    ngx_uint_t                cpu_affinity_auto;
    ngx_uint_t                cpu_affinity_n;
    ngx_cpuset_t             *cpu_affinity;

    char                     *username;
    ngx_uid_t                 user;
    ngx_gid_t                 group;

    ngx_str_t                 working_directory;
    ngx_str_t                 lock_file;

    ngx_str_t                 pid;
    ngx_str_t                 oldpid;

    ngx_array_t               env;
    char                    **environment;
} ngx_core_conf_t;

五、具体解析流程


我们这边主要讲解核心模块配置信息的解析。通过对核心模块的解析流程的理解,能更好的帮助你了解整个Nginx的模块管理和配置管理的流程。HTTP等模块的配置文件解析会更加复杂一些,但是基本原理是一致的。

1. 创建核心模块配置文件数据结构ngx_core_conf_t


ngx_init_cycle全局变量的初始化中会初始化Nginx的核心模块的配置信息。核心模块的配置参数在nginx.conf文件中最顶层的一些参数配置。

下面这段代码我们可以看到,遍历模块数组,如果是核心模块,则获取核心模块的上下文cycle->modules[i]->ctx,核心模块上下文是一个自定义的数据结构ngx_core_module_ctx,里面包含了配置文件创建的回调函数ngx_core_module_create_conf 

PS:这边只是针对性NGX_CORE_MODULE进行创建配置文件和初始化配置文件。

    /*
     * 核心模块的配置文件创建
     * 配置创建调用nginx.c 中的 ngx_core_module_create_conf
     * 以及其他核心模块的init_conf,例如:ngx_event_core_module_ctx中的ngx_event_core_create_conf
     * */
    for (i = 0; cycle->modules[i]; i++) {
        if (cycle->modules[i]->type != NGX_CORE_MODULE) {
            continue;
        }

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

        if (module->create_conf) {
            rv = module->create_conf(cycle); //模块回调函数,创建模块的配置信息
            if (rv == NULL) {
                ngx_destroy_pool(pool);
                return NULL;
            }
            cycle->conf_ctx[cycle->modules[i]->index] = rv; //配置文件复制
        }
    }

2. 创建一个临时的ngx_conf_s结构


ngx_conf_s主要定义了需要解析的配置文件,需要解析的模块类型以及命令集类型的信息。辅助解析配置文件。

    /* 解析配置文件 */
    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也主要用于解析配置文件的临时变量 */
    conf.temp_pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, log);
    if (conf.temp_pool == NULL) {
        ngx_destroy_pool(pool);
        return NULL;
    }


    conf.ctx = cycle->conf_ctx;
    conf.cycle = cycle;
    conf.pool = pool;
    conf.log = log;
    conf.module_type = NGX_CORE_MODULE; /* 配置文件模块类型 */
    conf.cmd_type = NGX_MAIN_CONF; /* 命令集类型 */

3. 调用解析配置函数ngx_conf_param和ngx_conf_parse


  • ngx_conf_param:主要解析命令行中的核心模块配置参数,例如:nginx -t -c /usr/local/nginx/conf/nginx.conf
  • ngx_conf_parse:主要解析配置文件/usr/local/nginx/conf/nginx.conf 信息
  • ngx_conf_param:最终也是调用ngx_conf_parse
    /* 解析命令行中的配置参数;例如:nginx -t -c /usr/local/nginx/conf/nginx.conf */
    if (ngx_conf_param(&conf) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

    /* 解析配置文件/usr/local/nginx/conf/nginx.conf 信息 */
    if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) {
        environ = senv;
        ngx_destroy_cycle_pools(&conf);
        return NULL;
    }

4. 配置文件核心解析函数ngx_conf_parse


ngx_conf_parse解析命令中的配置信息和文件中的配置信息.

主要工作是按行读取配置文件,并且解析成配置token数组,并将token数组进行模块commend命令集匹配和设置。

其中比较重要的函数:

  • ngx_conf_read_token 按行读取配置文件,并将命令解析成token数组cf->args;
  • ngx_conf_handler 将命令token数组与模块命令集匹配并设置到模块配置文件数据结构上。
/**
 * 解析配置信息核心函数
 * 包含:解析命令中的配置信息和文件中的配置信息
 */
char *
ngx_conf_parse(ngx_conf_t *cf, ngx_str_t *filename)
{
  ...

    /* 打开配置文件: /usr/local/nginx/conf/nginx.conf */
    if (filename) {

        /* open configuration file */

        fd = ngx_open_file(filename->data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0); //只读方式打开文件
        if (fd == NGX_INVALID_FILE) {
            ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno,
                               ngx_open_file_n " \"%s\" failed",
                               filename->data);
            return NGX_CONF_ERROR;
        }

        prev = cf->conf_file;

        cf->conf_file = &conf_file;

        if (ngx_fd_info(fd, &cf->conf_file->file.info) == NGX_FILE_ERROR) {
            ngx_log_error(NGX_LOG_EMERG, cf->log, ngx_errno,
                          ngx_fd_info_n " \"%s\" failed", filename->data);
        }

        /* 配置文件buf,默认大小4096 */
        cf->conf_file->buffer = &buf;

        buf.start = ngx_alloc(NGX_CONF_BUFFER, cf->log);
        if (buf.start == NULL) {
            goto failed;
        }

        buf.pos = buf.start;
        buf.last = buf.start;
        buf.end = buf.last + NGX_CONF_BUFFER;
        buf.temporary = 1;

        /* 读取配置文件数据,保存到cf->conf_file中 */
        cf->conf_file->file.fd = fd;
        cf->conf_file->file.name.len = filename->len;
        cf->conf_file->file.name.data = filename->data;
        cf->conf_file->file.offset = 0;
        cf->conf_file->file.log = cf->log;
        cf->conf_file->line = 1;

        type = parse_file;

        ...
    } else if (cf->conf_file->file.fd != NGX_INVALID_FILE) {

        /**
         * 解析块:events {  worker_connections  1024; }
         */
        type = parse_block;

    } else {
        type = parse_param;
    }

    for ( ;; ) {

    	/* 将配置信息解析成 token;仅仅是将配置文件的数据解析成一个个的单词,按行解析 */
        rc = ngx_conf_read_token(cf);

        /*
         * ngx_conf_read_token() may return
         *
         *    NGX_ERROR             there is error 解析失败
         *    NGX_OK                the token terminated by ";" was found  遇到结尾符号;,则表示解析成功
         *    NGX_CONF_BLOCK_START  the token terminated by "{" was found  遇到{模块配置开始标识
         *    NGX_CONF_BLOCK_DONE   the "}" was found	遇到模块}结束标识
         *    NGX_CONF_FILE_DONE    the configuration file is done 遇到文件解析完毕
         */

        if (rc == NGX_ERROR) {
            goto done;
        }

        /* 一个模块解析结束,则跳到done模块代码 */
        if (rc == NGX_CONF_BLOCK_DONE) {

            if (type != parse_block) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"}\"");
                goto failed;
            }

            goto done;
        }

        /* 一个模块解析结束,则跳到done模块代码 */
        if (rc == NGX_CONF_FILE_DONE) {

            if (type == parse_block) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "unexpected end of file, expecting \"}\"");
                goto failed;
            }

            goto done;
        }

        if (rc == NGX_CONF_BLOCK_START) {

            if (type == parse_param) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "block directives are not supported "
                                   "in -g option");
                goto failed;
            }
        }

        /* rc == NGX_OK || rc == NGX_CONF_BLOCK_START */

        /* 当遇到 NGX_CONF_BLOCK_START 和  NGX_OK*/
        if (cf->handler) {

            /*
             * the custom handler, i.e., that is used in the http's
             * "types { ... }" directive
             */

            if (rc == NGX_CONF_BLOCK_START) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"{\"");
                goto failed;
            }

            rv = (*cf->handler)(cf, NULL, cf->handler_conf);
            if (rv == NGX_CONF_OK) {
                continue;
            }

            if (rv == NGX_CONF_ERROR) {
                goto failed;
            }

            ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, rv);

            goto failed;
        }

        /* 配置文件处理;将配置文件设置到模块上 */
        rc = ngx_conf_handler(cf, rc);

        if (rc == NGX_ERROR) {
            goto failed;
        }
    }

failed:
...

    return NGX_CONF_OK;
}

5. 命令token解析 ngx_conf_read_token


ngx_conf_read_token 主要是将配置文件分解成逐个的单词数组。例如配置文件中遇到“空格”则为分隔符,“;”为结束符。

每一个数组,就是一条配置命令语句。数组会放置到cf->args数组上。

nginx.conf配置文件如下:

user  nfsnobody nfsnobody;
worker_processes 8;
error_log  /usr/local/nginx-1.4.7/nginx_error.log  crit;
pid        /usr/local/nginx-1.4.7/nginx.pid;
#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 65535;
events
{
use epoll;
worker_connections 65535;}

解析成下面的格式:

#分解成逐个单词数组:
user
nfsnobody
nfsnobody

worker_processes
8

error_log
/usr/local/nginx-1.4.7/nginx_error.log
crit

pid
/usr/local/nginx-1.4.7/nginx.pid

worker_rlimit_nofile
65535

events

具体逻辑实现:

/**
 * 读取配置信息
 * 把每次分析的值放到cf->args这个数组里面	碰到{} ; 返回
 * 例如配置文件如下:
 * user  nfsnobody nfsnobody;
 * worker_processes 8;
 * error_log  /usr/local/nginx-1.4.7/nginx_error.log  crit;
 * pid        /usr/local/nginx-1.4.7/nginx.pid;
 * #Specifies the value for maximum file descriptors that can be opened by this process.
 * worker_rlimit_nofile 65535;
 * events
 * {
 * use epoll;
 * worker_connections 65535;}
 *
 * 分解成逐个单词:
 * user
 * nfsnobody
 * nfsnobody
 * worker_processes
 * 8
 * error_log
 * /usr/local/nginx-1.4.7/nginx_error.log
 * crit
 * pid
 * /usr/local/nginx-1.4.7/nginx.pid
 * worker_rlimit_nofile
 * 65535
 * events
 *
 */
static ngx_int_t
ngx_conf_read_token(ngx_conf_t *cf)
{
    u_char      *start, ch, *src, *dst;
    off_t        file_size;
    size_t       len;
    ssize_t      n, size;
    ngx_uint_t   found, need_space, last_space, sharp_comment, variable;
    ngx_uint_t   quoted, s_quoted, d_quoted, start_line;
    ngx_str_t   *word;
    ngx_buf_t   *b, *dump;

    found = 0; //表示找到一个 token
    need_space = 0;
    last_space = 1; //标志位,表示上一个字符为token分隔符
    sharp_comment = 0; //注释 #符号
    variable = 0; //变量符号 $
    quoted = 0;   //标志位,表示上一个字符为反斜杠
    s_quoted = 0; //标志位,表示已扫描一个双引号,期待另一个双引号
    d_quoted = 0; //标志位,表示已扫描一个单引号,期待另一个单引号

    cf->args->nelts = 0;
    b = cf->conf_file->buffer; //buffer 每次4096
    dump = cf->conf_file->dump;
    start = b->pos;
    start_line = cf->conf_file->line;

    file_size = ngx_file_size(&cf->conf_file->file.info);

    for ( ;; ) {

    	/* buf中的数据已经处理完毕,则需要判断是否文件读取完了,如果没有读取完,则继续解析配置文件 */
        if (b->pos >= b->last) {

        	/* 文件已经读取完毕,返回NGX_CONF_FILE_DONE */
            if (cf->conf_file->file.offset >= file_size) {

                if (cf->args->nelts > 0 || !last_space) {

                    if (cf->conf_file->file.fd == NGX_INVALID_FILE) {
                        ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                           "unexpected end of parameter, "
                                           "expecting \";\"");
                        return NGX_ERROR;
                    }

                    ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                  "unexpected end of file, "
                                  "expecting \";\" or \"}\"");
                    return NGX_ERROR;
                }

                return NGX_CONF_FILE_DONE;
            }

            /* buf中已经使用的长度  */
            len = b->pos - start;

            /* 如果len=4096 则表明buf全部读取满了;如果读取了4096个字符,还是没有发现"和'的标示符号,则认为读取失败,参数太长了 */
            if (len == NGX_CONF_BUFFER) {
                cf->conf_file->line = start_line;

                if (d_quoted) {
                    ch = '"';

                } else if (s_quoted) {
                    ch = '\'';

                } else {
                    ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                       "too long parameter \"%*s...\" started",
                                       10, start);
                    return NGX_ERROR;
                }

                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   "too long parameter, probably "
                                   "missing terminating \"%c\" character", ch);
                return NGX_ERROR;
            }

            /* 将数据移动到buf的头部 */
            if (len) {
                ngx_memmove(b->start, start, len);
            }

            /* 如果buf有空闲,则继续读取文件中的数据到buf中 */
            size = (ssize_t) (file_size - cf->conf_file->file.offset);

            if (size > b->end - (b->start + len)) {
                size = b->end - (b->start + len);
            }

            n = ngx_read_file(&cf->conf_file->file, b->start + len, size,
                              cf->conf_file->file.offset);

            if (n == NGX_ERROR) {
                return NGX_ERROR;
            }

            if (n != size) {
                ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                                   ngx_read_file_n " returned "
                                   "only %z bytes instead of %z",
                                   n, size);
                return NGX_ERROR;
            }

            /* 设置b->pos和b->last的位置,并重新设置start的位置 */
            b->pos = b->start + len;
            b->last = b->pos + n;
            start = b->start;

            if (dump) {
                dump->last = ngx_cpymem(dump->last, b->pos, size);
            }
        }

        /* ch字符用于读取配置文件信息 */
        ch = *b->pos++;

        /* 如果遇到换行符号 \n */
        if (ch == LF) {
            cf->conf_file->line++;

            /* 判断改行是否是注释 如果遇到\n结尾,并且是注释,则设置sharp_comment = 0;当sharp_comment=1 则注释字符不处理*/
            if (sharp_comment) {
                sharp_comment = 0;
            }
        }

        /* 注释,则直接跳过 */
        if (sharp_comment) {
            continue;
        }

        /* 如果为反引号,则设置反引号标识,并且不对该字符进行解析   */
        if (quoted) {
            quoted = 0;
            continue;
        }

        /* 上一个字符为单引号或者双引号,期待一个分隔符   */
        if (need_space) {

           ...
        }
    }
}

设值到模块配置文件数据结构上 ngx_conf_handler

ngx_conf_handler方法主要是将拿到的token数组cf->args,按照模块的命令集cycle->modules[i]->commands 设置值。(后面解析event和http头部核心模块的时候,会用到)

  • 通过模块的index索引值,拿到cycle->ctx 模块配置文件数据结构。
  • 通过rv = cmd->set(cf, cmd, conf),调用命令集中定义的设值值的回调方法。

这边会根据模块类型,将配置信息逐个解析到相应的模块上。

/**
 * 配置文件处理
 * cycle->modules
 */
static ngx_int_t
ngx_conf_handler(ngx_conf_t *cf, ngx_int_t last)
{
    char           *rv;
    void           *conf, **confp;
    ngx_uint_t      i, found;
    ngx_str_t      *name;
    ngx_command_t  *cmd;

    name = cf->args->elts;

    found = 0;

    /* 循环配置模块 */
    for (i = 0; cf->cycle->modules[i]; i++) {

        cmd = cf->cycle->modules[i]->commands;
        if (cmd == NULL) {
            continue;
        }

        for ( /* void */ ; cmd->name.len; cmd++) {

            if (name->len != cmd->name.len) {
                continue;
            }

            /* 检查配置名称和token的第一个元素的名称是否一致,如果不一致,则说明命令不一样 */
            if (ngx_strcmp(name->data, cmd->name.data) != 0) {
                continue;
            }

            found = 1;

            if (cf->cycle->modules[i]->type != NGX_CONF_MODULE
                && cf->cycle->modules[i]->type != cf->module_type)
            {
                continue;
            }
            ...

            /* is the directive's argument count right ? */

            if (!(cmd->type & NGX_CONF_ANY)) {
            ...
            }

            /* set up the directive's configuration context */

            conf = NULL;

            /* 设置配置文件的值  设置配置项对外面的配置信息; */
            if (cmd->type & NGX_DIRECT_CONF) {
            	/* ngx_core_module; */
                conf = ((void **) cf->ctx)[cf->cycle->modules[i]->index];

            } else if (cmd->type & NGX_MAIN_CONF) {
                conf = &(((void **) cf->ctx)[cf->cycle->modules[i]->index]);

            } else if (cf->ctx) {
                confp = *(void **) ((char *) cf->ctx + cmd->conf);

                if (confp) {
                    conf = confp[cf->cycle->modules[i]->ctx_index];
                }
            }

            /**
             * 配置文件设置值;
             * conf为配置的指针地址;
             * cmd为命令结构;
             * conf为配置指针地址 一般情况下 conf为模块自定义的配置文件数据结构地址
             *
             */
            rv = cmd->set(cf, cmd, conf);

            if (rv == NGX_CONF_OK) {
                return NGX_OK;
            }

            if (rv == NGX_CONF_ERROR) {
                return NGX_ERROR;
            }

            ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
                               "\"%s\" directive %s", name->data, rv);

            return NGX_ERROR;
        }
    }

    ...

    return NGX_ERROR;
}

nginx_conf_file.c文件中定义了多种配置文件值设值的方法:

char *ngx_conf_set_flag_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_str_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_str_array_slot(ngx_conf_t *cf, ngx_command_t *cmd,
    void *conf);
char *ngx_conf_set_keyval_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_num_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_size_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_off_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_msec_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_sec_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_bufs_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_enum_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
char *ngx_conf_set_bitmask_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);

调用核心模块的配置

通过核心模块ngx_core_module的索引index值,就可以得到核心配置的数据结构 ngx_core_conf_t

    /* 获取核心配置文件的数据结构 ngx_core_conf_t */
    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

 

 

 

 

 

 

 

Nginx底层设计与源码分析(未完) Nginx(发音为“engine-x”)是一个免费、开源、高性能的Web服务器和反向代理软件。它被开发用于处理高流量网站并作为负载均衡器、内容缓存和Web服务器。Nginx旨在轻巧高效,专注于可伸缩性和性能。它采用事件驱动、异步、非阻塞的架构,能高效地同时处理多个连接。这使它成为高流量网站和应用程序的热门选择。Nginx可用于提供静态文件,也可将请求代理到其他Web服务器,如Apache或Tomcat。它还可以用作负载均衡器,将传入流量分布到多个服务器上。 阅读详情

相关推荐

nginx源码分析 (信号机制)

这篇文章讲解nginx的信号机制,因为是信号,所以其他方面的没有深究,放在后面分享出来,欢迎有兴趣的朋友留言交流 nginx运行的进程模式为master-worker的话,那master和worker进程间是通过信号来通信,关于信号相关的知识可以参考下面的链接Linux信号(signal) 机制分析 下面讲解代码执行流程都是以quit命令来执行的 一、信号的安装 nginx启动的过程中,m...

pythonluo的专栏 732

Nginx源码分析(25篇)

Nginx源码分析 - 初探Nginx的架构 Nginx源码分析 - 基础数据结构篇 - 内存池 ngx_palloc.c Nginx源码分析 - 基础数据结构篇 - 数组结构 ngx_array.c Nginx源码分析 - 基础数据结构篇 - 缓冲区结构 ngx_buf.c Nginx源码分析 - 基础数据结构篇 - 双向链表结构 ngx_queue.c Nginx源码分析 ......

奇华资料的博客 9万+

Nginx Upstream模块源码分析(上)

Upstream模块是一个很重要的模块,很多其他模块都会使用它来完成对后端服务器的访问, 达到反向代理和负载均衡的效果。例如Fastcgi、Memcached、SessionSticky等。 如果自己实现这部分功能,采用传统的实现方式,很可能会阻塞Nginx降低其性能,因为Nginx是全异步非阻塞的。 所以要想不破坏其优美的架构,就得按照其规范实现很多回调函数,注册这些钩子到Ngin

西代零零发 8122

Nginx源码解析

Nginx

qq_20999867的博客 640

风力发电机并网模型建立及仿真验证

传统能源日益匮乏,环境污染日趋严重,全球向安全、可靠和环保的可持续能源体系转型迫在眉睫,风电迎来了重要的发展契机。近年来,全球风电迅猛发展,我国已成为世界风电新增装机容量第一的国家。然而,随着风电规模的不断增大,风电场接入对系统影响不容忽视。随着变速恒频风力发电系统优越的性能突出和大容量电力电子技术的成熟,风速随机性引起的功率波动及故障情况下的动态响应,对电能质量,系统电压、频率的稳定性产生的影响需要深入研究。因而,本文结合实际项目,针对变速恒频风力发电系统建模,端口动态特性及对电网电能质量、运行稳定性的影

毕业设计区博客 1639

树莓派计算模块摄像头连接与配置全攻略:从硬件跳线到软件驱动

在嵌入式视觉项目中,摄像头模组的连接与驱动是图像采集和视频分析的基础。其核心原理是通过CSI-2高速串行接口协议传输图像数据,并依赖I2C总线进行传感器寄存器配置。这一技术方案的价值在于为工业控制、机器人等嵌入式设备提供了稳定、高性价比的视觉感知能力。在实际应用中,开发者常面临摄像头无法识别、I2C通信失败等挑战,尤其是在使用树莓派计算模块时,其硬件接口需要通过I/O板引出,配置过程涉及设备树参数调整等关键步骤。本文聚焦于解决这些实际问题,详细拆解了从硬件连接到软件驱动的完整流程,特别是针对CM4、CM3+

weixin_29184075的博客 336

Nginx源码分析 - 主流程篇 - 全局变量cycle初始化(11)

Nginx的大部分初始化工作主要围绕一个类型为ngx_cycle_t类型的全局变量(cycle)展开。本文主要讲解cycle的数据结构以及初始化过程中干了什么事情。 cycle的初始化过程在/src/core/cycle.c文件中。 数据结构 ngx_cycle_t的数据结构 /** * Nginx全局变量cycle */ struct ngx_cycle_s { void

自娱自乐的代码人 1万+

VSCode CMake 安装与配置详解

概述 在windows上使用cmake编译C/C++程序时,首先需要CMake,安装gcc/g++编译环境,然后使用VSCode 以及配置下CMakelist.txt。 所需工具: VSCode (需要安装以下插件) C/C++ C++ Intellisense CMake CMake tools CMake Tools Helper CMake MinGW 安装CMake 下载链接:...

Markus 8万+

nginx源码分析(13)-运维与配置(1)

nginx现在已经支持很多功能,系统内已经实现的模块多达72个,这些模块提供了若干配置指令来设置和控制nginx的相关处理过程。 为了能够更深入的进行接下来的源码分析,利用一些篇幅讨论一下nginx的运维和配置相关的内容,主要参考了nginx的英文wiki资料,按照自己的思路整理成nginx的操作和配置指南,可以作为使用nginx的一个起点。 首先简单介绍一下nginx的编译、启动

啃饼的技术博客 5575

Lumerical官方案例、FDTD时域有限差分法仿真学习(十三)——多模干涉耦合器(MMI)

计算通过 1×2 端口多模干涉 (MMI) 耦合器的宽带传输和光损耗。 使用设备 S 参数在 INTERCONNECT 中创建 MMI 的紧凑模型。 它还展示了如何使用 CML 编译器提取这些参数以生成紧凑模型。 一、概述 了解模拟工作流程和关键结果 低损耗光合路器和分路器是基于 Mach-Zehnder 的光调制器的基本组件,并且是集成电路的关键组成部分。通过在输入/输出波导处使用线性锥形确保输入/输出波导的模式与干涉区域之间的

weixin_45719141的博客 1万+

HTML音乐爱心3D旋转相册完整源码

HTML音乐爱心3D旋转相册完整源码

LilyCoder的博客 1380

nginx 源码(4)主流程

接上文。nginx以单进程在console运行起来,阅读core/nginx.c中的main方法,前面都是初始化的代码,先不仔细看,容易陷入细致魔戒。直接找到ngx_single_process_cycle的定义,在os/unix/ngx_process_cycle.c中。在第一个for循环中添加如下代码: for (i = 0; ngx_modules[i]; i++) {

代码不说谎 894

KRC文件——编程中的重要文件

KRC文件是指KUKA机器人控制器(KUKA Robot Controller)所使用的文件格式。KUKA是一家知名的机器人制造商,其机器人控制器通过KRC文件来管理和执行机器人程序。KRC文件包含了机器人的运动指令、逻辑控制、传感器数据等信息,以及与机器人相关的配置参数。这些文件通常使用KRL(KUKA Robot Language)编写,是一种特定的编程语言。KRC文件具有扩展名为.krc的格式,可以在KUKA机器人控制器上直接加载和执行。

TechProX的博客 2971

nginx源码分析之配置图解

源:       nginx配置结构清晰,层次分明,这得益于整个架构的模块化设计,文本将揭示配置文件如何被处理和应用。   整个配置文件解析后的结果如图这样存储。 一、解析的核心机制 nginx源码里,ngx_conf_t是解析的关键结构体 ngx_conf_handler函数里: 查看源码 打印? 01 /* se

写写画画 729

C#串口通信从入门到精通(27)——高速通信下解决数据处理慢的问题(20ms以内)

本文介绍如何在高速通信情况下解决串口接收的数据来不及处理的问题,由高级工程师多年经验总结而成,绝对是串口领域的实战经验!

qq_34059233的博客 6808

利用pytorch长短期记忆网络LSTM实现股票预测分析

长短时记忆网络(Long Short Term Memory Network, LSTM),是一种改进之后的循环神经网络,可以解决RNN无法处理长距离的依赖的问题,目前比较流行。LSTM主要就是加入了三个门控:第一个开关遗忘门:负责控制继续保存长期状态c;第二个开关输入门:负责控制把即时状态输入到长期状态c;第三个开关输出门:负责控制是否把长期状态c作为当前的LSTM的输出。

优快云 精品推荐 1万+

nginx源码分析之模块初始化

  在nginx启动过程中,模块的初始化是整个启动过程中的重要部分,而且了解了模块初始化的过程对应后面具体分析各个模块会有事半功倍的效果。在我看来,分析源码来了解模块的初始化是最直接不过的了,所以下面主要通过结合源码来分析模块的初始化过程。   稍微了解nginx的人都知道nginx是高度模块化的,各个功能都封装在模块中,而各个模块的初始化则是根据配置文件来进行的,下面我们会看到nginx边解析...

weixin_33691817的博客 104

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Go最新Nginx源码分析 - 初探Nginx的架构(01),行业寒冬

Nginx的源码写的非常漂亮,是c语言学习和进阶的最好的学习资料。我们这里分析的是的版本。

2401_84919754的博客 505

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

nginx 源码分析:启动流程

nginx 启动流程 启动流程假设 nginx 以一个 master 多个 worker 进程的方式工作。 main nginx 进程启动时先执行 main 函数(src/core/nginx.c 中),main 函数先做一些基本的工作,比如处理命令行参数,初始化系统时间,初始化 error 日志等。然后它初始化一个 ngx_cycle_t 结构的局部变量 init_cycle ,接着以init_...

alenliu's blog 1550

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

上一篇: Nginx源码分析 - 主流程篇 - 模块的初始化(12)
下一篇: Nginx源码分析 - 主流程篇 - 多进程实现(14)
老码农zhuli
老码农zhuli 领域专家: 后端开发技术领域 领域专家: 后端开发技术领域
博客等级 码龄14年 2456粉丝 312原创
评论 5
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值