Nginx 配置解析

╰半夏微凉° 2022-08-06 09:30 313阅读 0赞

概述

在上一篇文章《 Nginx 启动初始化过程》简单介绍了 Nginx 启动的过程,并分析了其启动过程的源码。在启动过程中有一个步骤非常重要,就是调用函数 ngx_init_cycle(),该函数的调用为配置解析提供了接口。配置解析接口大概可分为两个阶段:准备数据阶段配置解析阶段

准备数据阶段包括:

  • 准备内存;
  • 准备错误日志;
  • 准备所需数据结构;

配置解析阶段是调用函数:

  1. /* 配置文件解析 */
  2. if (ngx_conf_param(&conf) != NGX_CONF_OK) {/* 带有命令行参数'-g' 加入的配置 */
  3. environ = senv;
  4. ngx_destroy_cycle_pools(&conf);
  5. return NULL;
  6. }
  7. if (ngx_conf_parse(&conf, &cycle->conf_file) != NGX_CONF_OK) {/* 解析配置文件*/
  8. environ = senv;
  9. ngx_destroy_cycle_pools(&conf);
  10. return NULL;
  11. }

配置解析

ngx_conf_t 结构体

该结构体用于 Nginx 在解析配置文件时描述每个指令的属性,也是Nginx 程序中非常重要的一个数据结构,其定义于文件:src/core/ngx_conf_file.h

  1. /* 解析配置时所使用的结构体 */
  2. struct ngx_conf_s {
  3. char *name; /* 当前解析到的指令 */
  4. ngx_array_t *args; /* 当前指令所包含的所有参数 */
  5. ngx_cycle_t *cycle; /* 待解析的全局变量ngx_cycle_t */
  6. ngx_pool_t *pool; /* 内存池 */
  7. ngx_pool_t *temp_pool;/* 临时内存池,分配一些临时数组或变量 */
  8. ngx_conf_file_t *conf_file;/* 待解析的配置文件 */
  9. ngx_log_t *log; /* 日志信息 */
  10. void *ctx; /* 描述指令的上下文 */
  11. ngx_uint_t module_type;/* 当前解析的指令的模块类型 */
  12. ngx_uint_t cmd_type; /* 当前解析的指令的指令类型 */
  13. ngx_conf_handler_pt handler; /* 模块自定义的handler,即指令自定义的处理函数 */
  14. char *handler_conf;/* 自定义处理函数需要的相关配置 */
  15. };

配置文件信息 conf_file

conf_file 是存放 Nginx 配置文件的相关信息。ngx_conf_file_t 结构体的定义如下:

  1. typedef struct {
  2. ngx_file_t file; /* 文件的属性 */
  3. ngx_buf_t *buffer; /* 文件的内容 */
  4. ngx_uint_t line; /* 文件的行数 */
  5. } ngx_conf_file_t;

配置上下文 ctx

Nginx 的配置文件是分块配置的,常见的有http 块、server 块、location 块以及upsteam 块和 mail 块等。每一个这样的配置块代表一个作用域。高一级配置块的作用域包含了多个低一级配置块的作用域,也就是有作用域嵌套的现象。这样,配置文件中的许多指令都会同时包含在多个作用域内。比如,http 块中的指令都可能同时处于http 块、server 块和location 块等三层作用域内。

在 Nginx 程序解析配置文件时,每一条指令都应该记录自己所属的作用域范围,而配置文件上下文ctx 变量就是用来存放当前指令所属的作用域的。在Nginx 配置文件的各种配置块中,http 块可以包含子配置块,这在存储结构上比较复杂。

指令类型 type

Nginx 程序中的不同的指令类型以宏的形式定义在不同的源码头文件中,指令类型是core 模块类型的定义在文件:src/core/ngx_conf_file.h

  1. #define NGX_DIRECT_CONF 0x00010000
  2. #define NGX_MAIN_CONF 0x01000000
  3. #define NGX_ANY_CONF 0x0F000000

这些是 core 类型模块支持的指令类型。其中的 NGX_DIRECT_CONF类指令在 Nginx 程序进入配置解析函数之前已经初始化完成,所以在进入配置解析函数之后可以将它们直接解析并存储到实际的数据结构中,从配置文件的结构上来看,它们一般指的就是那些游离于配置块之外、处于配置文件全局块部分的指令。 NGX_MAIN_CONF 类指令包括 event、 http、 mail、 upstream 等可以形成配置块的指令,它们没有自己的初始化函数。 Nginx 程序在解析配置文件时如果遇到 NGX_MAIN_CONF 类指令,将转入对下一级指令的解析。

以下是 event 类型模块支持的指令类型。

  1. #define NGX_EVENT_CONF 0x02000000

以下是 http 类型模块支持的指令类型,其定义在文件:src/http/ngx_http_config.h

  1. #define NGX_HTTP_MAIN_CONF 0x02000000
  2. #define NGX_HTTP_SRV_CONF 0x04000000
  3. #define NGX_HTTP_LOC_CONF 0x08000000
  4. #define NGX_HTTP_UPS_CONF 0x10000000
  5. #define NGX_HTTP_SIF_CONF 0x20000000
  6. #define NGX_HTTP_LIF_CONF 0x40000000
  7. #define NGX_HTTP_LMT_CONF 0x80000000

通用模块配置解析

配置解析模块在 src/core/ngx_conf_file.c 中实现。模块提供的接口函数主要是ngx_conf_parse。另外,模块提供另一个单独的接口ngx_conf_param,用来解析命令行传递的配置,这个接口也是对ngx_conf_parse 的包装。首先看下配置解析函数 ngx_conf_parse,其定义如下:

  1. /*
  2. * 函数功能:配置文件解析;
  3. * 支持三种不同的解析类型:
  4. * 1、解析配置文件;
  5. * 2、解析block块设置;
  6. * 3、解析命令行配置;
  7. */
  8. char *
  9. ngx_conf_parse(ngx_conf_t *cf, ngx_str_t *filename)
  10. {
  11. char *rv;
  12. ngx_fd_t fd;
  13. ngx_int_t rc;
  14. ngx_buf_t buf;
  15. ngx_conf_file_t *prev, conf_file;
  16. enum {
  17. parse_file = 0,
  18. parse_block,
  19. parse_param
  20. } type;
  21. #if (NGX_SUPPRESS_WARN)
  22. fd = NGX_INVALID_FILE;
  23. prev = NULL;
  24. #endif
  25. if (filename) {/* 若解析的是配置文件 */
  26. /* open configuration file */
  27. /* 打开配置文件 */
  28. fd = ngx_open_file(filename->data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0);
  29. if (fd == NGX_INVALID_FILE) {
  30. ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno,
  31. ngx_open_file_n " \"%s\" failed",
  32. filename->data);
  33. return NGX_CONF_ERROR;
  34. }
  35. prev = cf->conf_file;
  36. cf->conf_file = &conf_file;
  37. if (ngx_fd_info(fd, &cf->conf_file->file.info) == NGX_FILE_ERROR) {
  38. ngx_log_error(NGX_LOG_EMERG, cf->log, ngx_errno,
  39. ngx_fd_info_n " \"%s\" failed", filename->data);
  40. }
  41. cf->conf_file->buffer = &buf;
  42. buf.start = ngx_alloc(NGX_CONF_BUFFER, cf->log);
  43. if (buf.start == NULL) {
  44. goto failed;
  45. }
  46. buf.pos = buf.start;
  47. buf.last = buf.start;
  48. buf.end = buf.last + NGX_CONF_BUFFER;
  49. buf.temporary = 1;
  50. /* 复制文件属性及文件内容 */
  51. cf->conf_file->file.fd = fd;
  52. cf->conf_file->file.name.len = filename->len;
  53. cf->conf_file->file.name.data = filename->data;
  54. cf->conf_file->file.offset = 0;
  55. cf->conf_file->file.log = cf->log;
  56. cf->conf_file->line = 1;
  57. type = parse_file; /* 解析的类型是配置文件 */
  58. } else if (cf->conf_file->file.fd != NGX_INVALID_FILE) {
  59. type = parse_block; /* 解析的类型是block块 */
  60. } else {
  61. type = parse_param; /* 解析的类型是命令行配置 */
  62. }
  63. for ( ;; ) {
  64. /* 语法分析函数 */
  65. rc = ngx_conf_read_token(cf);
  66. /*
  67. * ngx_conf_read_token() may return
  68. *
  69. * NGX_ERROR there is error
  70. * NGX_OK the token terminated by ";" was found
  71. * NGX_CONF_BLOCK_START the token terminated by "{" was found
  72. * NGX_CONF_BLOCK_DONE the "}" was found
  73. * NGX_CONF_FILE_DONE the configuration file is done
  74. */
  75. if (rc == NGX_ERROR) {
  76. goto done;
  77. }
  78. /* 解析block块设置 */
  79. if (rc == NGX_CONF_BLOCK_DONE) {
  80. if (type != parse_block) {
  81. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"}\"");
  82. goto failed;
  83. }
  84. goto done;
  85. }
  86. /* 解析配置文件 */
  87. if (rc == NGX_CONF_FILE_DONE) {
  88. if (type == parse_block) {
  89. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  90. "unexpected end of file, expecting \"}\"");
  91. goto failed;
  92. }
  93. goto done;
  94. }
  95. if (rc == NGX_CONF_BLOCK_START) {
  96. if (type == parse_param) {
  97. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  98. "block directives are not supported "
  99. "in -g option");
  100. goto failed;
  101. }
  102. }
  103. /* rc == NGX_OK || rc == NGX_CONF_BLOCK_START */
  104. /* 自定义指令处理函数 */
  105. if (cf->handler) {
  106. /*
  107. * the custom handler, i.e., that is used in the http's
  108. * "types { ... }" directive
  109. */
  110. if (rc == NGX_CONF_BLOCK_START) {
  111. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"{\"");
  112. goto failed;
  113. }
  114. /* 命令行配置处理函数 */
  115. rv = (*cf->handler)(cf, NULL, cf->handler_conf);
  116. if (rv == NGX_CONF_OK) {
  117. continue;
  118. }
  119. if (rv == NGX_CONF_ERROR) {
  120. goto failed;
  121. }
  122. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, rv);
  123. goto failed;
  124. }
  125. /* 若自定义指令处理函数handler为NULL,则调用Nginx内建的指令解析机制 */
  126. rc = ngx_conf_handler(cf, rc);
  127. if (rc == NGX_ERROR) {
  128. goto failed;
  129. }
  130. }
  131. failed:
  132. rc = NGX_ERROR;
  133. done:
  134. if (filename) {/* 若是配置文件 */
  135. if (cf->conf_file->buffer->start) {
  136. ngx_free(cf->conf_file->buffer->start);
  137. }
  138. if (ngx_close_file(fd) == NGX_FILE_ERROR) {
  139. ngx_log_error(NGX_LOG_ALERT, cf->log, ngx_errno,
  140. ngx_close_file_n " %s failed",
  141. filename->data);
  142. return NGX_CONF_ERROR;
  143. }
  144. cf->conf_file = prev;
  145. }
  146. if (rc == NGX_ERROR) {
  147. return NGX_CONF_ERROR;
  148. }
  149. return NGX_CONF_OK;
  150. }

从配置解析函数的源码可以看出,该函数分为两个阶段: 语法分析指令解析。语法分析由 ngx_conf_read_token()函数完成。指令解析有两种方式:一种是 Nginx 内建的指令解析机制;另一种是自定义的指令解析机制。自定义指令解析源码如下所示:

  1. /* 自定义指令处理函数 */
  2. if (cf->handler) {
  3. /*
  4. * the custom handler, i.e., that is used in the http's
  5. * "types { ... }" directive
  6. */
  7. if (rc == NGX_CONF_BLOCK_START) {
  8. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"{\"");
  9. goto failed;
  10. }
  11. /* 命令行配置处理函数 */
  12. rv = (*cf->handler)(cf, NULL, cf->handler_conf);
  13. if (rv == NGX_CONF_OK) {
  14. continue;
  15. }
  16. if (rv == NGX_CONF_ERROR) {
  17. goto failed;
  18. }
  19. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, rv);
  20. goto failed;
  21. }

而 Nginx 内置解析机制有函数 ngx_conf_handler() 实现。其定义如下:

  1. /* Nginx内建的指令解析机制 */
  2. static ngx_int_t
  3. ngx_conf_handler(ngx_conf_t *cf, ngx_int_t last)
  4. {
  5. char *rv;
  6. void *conf, **confp;
  7. ngx_uint_t i, found;
  8. ngx_str_t *name;
  9. ngx_command_t *cmd;
  10. name = cf->args->elts;
  11. found = 0;
  12. for (i = 0; ngx_modules[i]; i++) {
  13. cmd = ngx_modules[i]->commands;
  14. if (cmd == NULL) {
  15. continue;
  16. }
  17. for ( /* void */ ; cmd->name.len; cmd++) {
  18. if (name->len != cmd->name.len) {
  19. continue;
  20. }
  21. if (ngx_strcmp(name->data, cmd->name.data) != 0) {
  22. continue;
  23. }
  24. found = 1;
  25. /*
  26. * 只处理模块类型为NGX_CONF_MODULE 或是当前正在处理的模块类型;
  27. */
  28. if (ngx_modules[i]->type != NGX_CONF_MODULE
  29. && ngx_modules[i]->type != cf->module_type)
  30. {
  31. continue;
  32. }
  33. /* is the directive's location right ? */
  34. if (!(cmd->type & cf->cmd_type)) {
  35. continue;
  36. }
  37. /* 非block块指令必须以";"分号结尾,否则出错返回 */
  38. if (!(cmd->type & NGX_CONF_BLOCK) && last != NGX_OK) {
  39. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  40. "directive \"%s\" is not terminated by \";\"",
  41. name->data);
  42. return NGX_ERROR;
  43. }
  44. /* block块指令必须后接"{"大括号,否则出粗返回 */
  45. if ((cmd->type & NGX_CONF_BLOCK) && last != NGX_CONF_BLOCK_START) {
  46. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  47. "directive \"%s\" has no opening \"{\"",
  48. name->data);
  49. return NGX_ERROR;
  50. }
  51. /* is the directive's argument count right ? */
  52. /* 验证指令参数个数是否正确 */
  53. if (!(cmd->type & NGX_CONF_ANY)) {
  54. /* 指令携带的参数只能是 1 个,且其参数值只能是 on 或 off */
  55. if (cmd->type & NGX_CONF_FLAG) {
  56. if (cf->args->nelts != 2) {
  57. goto invalid;
  58. }
  59. } else if (cmd->type & NGX_CONF_1MORE) {/* 指令携带的参数必须超过 1 个 */
  60. if (cf->args->nelts < 2) {
  61. goto invalid;
  62. }
  63. } else if (cmd->type & NGX_CONF_2MORE) {/* 指令携带的参数必须超过 2 个 */
  64. if (cf->args->nelts < 3) {
  65. goto invalid;
  66. }
  67. } else if (cf->args->nelts > NGX_CONF_MAX_ARGS) {
  68. goto invalid;
  69. } else if (!(cmd->type & argument_number[cf->args->nelts - 1]))
  70. {
  71. goto invalid;
  72. }
  73. }
  74. /* set up the directive's configuration context */
  75. conf = NULL;
  76. if (cmd->type & NGX_DIRECT_CONF) {/* 在core模块使用 */
  77. conf = ((void **) cf->ctx)[ngx_modules[i]->index];
  78. } else if (cmd->type & NGX_MAIN_CONF) {/* 指令配置项出现在全局配置中,不属于任何{}配置块 */
  79. conf = &(((void **) cf->ctx)[ngx_modules[i]->index]);
  80. } else if (cf->ctx) {/* 除了core模块,其他模块都是用该项 */
  81. confp = *(void **) ((char *) cf->ctx + cmd->conf);
  82. if (confp) {
  83. conf = confp[ngx_modules[i]->ctx_index];
  84. }
  85. }
  86. /* 执行指令解析回调函数 */
  87. rv = cmd->set(cf, cmd, conf);
  88. if (rv == NGX_CONF_OK) {
  89. return NGX_OK;
  90. }
  91. if (rv == NGX_CONF_ERROR) {
  92. return NGX_ERROR;
  93. }
  94. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  95. "\"%s\" directive %s", name->data, rv);
  96. return NGX_ERROR;
  97. }
  98. }
  99. if (found) {
  100. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  101. "\"%s\" directive is not allowed here", name->data);
  102. return NGX_ERROR;
  103. }
  104. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  105. "unknown directive \"%s\"", name->data);
  106. return NGX_ERROR;
  107. invalid:
  108. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
  109. "invalid number of arguments in \"%s\" directive",
  110. name->data);
  111. return NGX_ERROR;
  112. }

HTTP 模块配置解析

  这里主要是结构体 ngx_command_t ,我们在文章 《Nginx 模块开发》 对该结构体作了介绍,其定义如下:

  1. struct ngx_command_s {
  2. /* 配置项名称 */
  3. ngx_str_t name;
  4. /* 配置项类型,type将指定配置项可以出现的位置以及携带参数的个数 */
  5. ngx_uint_t type;
  6. /* 处理配置项的参数 */
  7. char *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
  8. /* 在配置文件中的偏移量,conf与offset配合使用 */
  9. ngx_uint_t conf;
  10. ngx_uint_t offset;
  11. /* 配置项读取后的处理方法,必须指向ngx_conf_post_t 结构 */
  12. void *post;
  13. };

若在上面的通用配置解析中,定义了如下的 http 配置项结构,则回调用http 配置项,并对该http 配置项进行解析。此时,解析的是http block 块设置。

  1. static ngx_command_t ngx_http_commands[] = {
  2. { ngx_string("http"),
  3. NGX_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS,
  4. ngx_http_block,
  5. 0,
  6. 0,
  7. NULL },
  8. ngx_null_command
  9. };

http 是作为一个 core 模块被 nginx 通用解析过程解析的,其核心就是http{} 块指令回调,它完成了http 解析的整个功能,从初始化到计算配置结果。http{} 块指令的流程是:

  • 创建并初始化上下文结构;
  • 调用通用模块配置解析流程解析;
  • 根据解析结果进行配置项合并处理;

创建并初始化上下文结构

  当 Nginx 检查到 http{…} 配置项时,HTTP 配置模型就会启动,则会建立一个ngx_http_conf_ctx_t 结构,该结构定义在文件中:src/http/ngx_http_config.h

  1. typedef struct{
  2.   /* 指针数组,数组中的每个元素指向所有 HTTP 模块 create_main_conf 方法产生的结构体 */
  3. void **main_conf;
  4. /* 指针数组,数组中的每个元素指向所有 HTTP 模块 create_srv_conf 方法产生的结构体 */
  5. void **srv_conf;
  6. /* 指针数组,数组中的每个元素指向所有 HTTP 模块 create_loc_conf 方法产生的结构体 */
  7. void **loc_conf;
  8. }ngx_http_conf_ctx_t;

  此时,HTTP 框架为所有 HTTP 模块建立 3 个数组,分别存放所有 HTTP 模块的create_main_confcreate_srv_confcreate_loc_conf 方法返回的地址指针。ngx_http_conf_ctx_t 结构的三个成员分别指向这 3 个数组。例如下面的例子是设置 create_main_confcreate_srv_confcreate_loc_conf 返回的地址。

  1. ngx_http_conf_ctx *ctx;
  2. /* HTTP 框架生成 1 个 ngx_http_conf_ctx_t 结构变量 */
  3. ctx = ngx_pcalloc(cf->pool, sizeof(ngx_http_conf_ctx_t));
  4. *(ngx_http_conf_ctx_t **) conf = ctx;
  5. ...
  6. /* 分别生成 3 个数组存储所有的 HTTP 模块的 create_main_conf、create_srv_conf、create_loc_conf 方法返回的地址 */
  7. ctx->main_conf = ngx_pcalloc(cf->pool,
  8. sizeof(void *) * ngx_http_max_module);
  9. ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  10. ctx->loc_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_http_max_module);
  11. /* 遍历所有 HTTP 模块 */
  12. for (m = 0; ngx_modules[m]; m++) {
  13. if (ngx_modules[m]->type != NGX_HTTP_MODULE) {
  14. continue;
  15. }
  16. module = ngx_modules[m]->ctx;
  17. mi = ngx_modules[m]->ctx_index;
  18. /* 若实现了create_main_conf 方法,则调用该方法,并把返回的地址存储到 main_conf 中 */
  19. if (module->create_main_conf) {
  20. ctx->main_conf[mi] = module->create_main_conf(cf);
  21. }
  22. /* 若实现了create_srv_conf 方法,则调用该方法,并把返回的地址存储到 srv_conf 中 */
  23. if (module->create_srv_conf) {
  24. ctx->srv_conf[mi] = module->create_srv_conf(cf);
  25. }
  26. /* 若实现了create_loc_conf 方法,则调用该方法,并把返回的地址存储到 loc_conf 中 */
  27. if (module->create_loc_conf) {
  28. ctx->loc_conf[mi] = module->create_loc_conf(cf);
  29. }
  30. }
  31. pcf = *cf;
  32. cf->ctx = ctx;
  33. for (m = 0; ngx_modules[m]; m++) {
  34. if (ngx_modules[m]->type != NGX_HTTP_MODULE) {
  35. continue;
  36. }
  37. module = ngx_modules[m]->ctx;
  38. if (module->preconfiguration) {
  39. if (module->preconfiguration(cf) != NGX_OK) {
  40. return NGX_CONF_ERROR;
  41. }
  42. }
  43. }

调用通用模块配置解析流程解析

从源码 src/http/ngx_http.c中可以看到,http 块的配置解析是调用通用模块的配置解析函数,其实现如下:

  1. /* 调用通用模块配置解析 */
  2. /* parse inside the http{} block */
  3. cf->module_type = NGX_HTTP_MODULE;
  4. cf->cmd_type = NGX_HTTP_MAIN_CONF;
  5. rv = ngx_conf_parse(cf, NULL);
  6. if (rv != NGX_CONF_OK) {
  7. goto failed;
  8. }

根据解析结果进行配置项合并处理

  1. /* 根据解析结构进行合并处理 */
  2. /*
  3. * init http{} main_conf's, merge the server{}s' srv_conf's
  4. * and its location{}s' loc_conf's
  5. */
  6. cmcf = ctx->main_conf[ngx_http_core_module.ctx_index];
  7. cscfp = cmcf->servers.elts;
  8. for (m = 0; ngx_modules[m]; m++) {
  9. if (ngx_modules[m]->type != NGX_HTTP_MODULE) {
  10. continue;
  11. }
  12. module = ngx_modules[m]->ctx;
  13. mi = ngx_modules[m]->ctx_index;
  14. /* init http{} main_conf's */
  15. if (module->init_main_conf) {
  16. rv = module->init_main_conf(cf, ctx->main_conf[mi]);
  17. if (rv != NGX_CONF_OK) {
  18. goto failed;
  19. }
  20. }
  21. rv = ngx_http_merge_servers(cf, cmcf, module, mi);
  22. if (rv != NGX_CONF_OK) {
  23. goto failed;
  24. }
  25. }
  26. /* create location trees */
  27. for (s = 0; s < cmcf->servers.nelts; s++) {
  28. clcf = cscfp[s]->ctx->loc_conf[ngx_http_core_module.ctx_index];
  29. if (ngx_http_init_locations(cf, cscfp[s], clcf) != NGX_OK) {
  30. return NGX_CONF_ERROR;
  31. }
  32. if (ngx_http_init_static_location_trees(cf, clcf) != NGX_OK) {
  33. return NGX_CONF_ERROR;
  34. }
  35. }
  36. if (ngx_http_init_phases(cf, cmcf) != NGX_OK) {
  37. return NGX_CONF_ERROR;
  38. }
  39. if (ngx_http_init_headers_in_hash(cf, cmcf) != NGX_OK) {
  40. return NGX_CONF_ERROR;
  41. }
  42. for (m = 0; ngx_modules[m]; m++) {
  43. if (ngx_modules[m]->type != NGX_HTTP_MODULE) {
  44. continue;
  45. }
  46. module = ngx_modules[m]->ctx;
  47. if (module->postconfiguration) {
  48. if (module->postconfiguration(cf) != NGX_OK) {
  49. return NGX_CONF_ERROR;
  50. }
  51. }
  52. }
  53. if (ngx_http_variables_init_vars(cf) != NGX_OK) {
  54. return NGX_CONF_ERROR;
  55. }
  56. /*
  57. * http{}'s cf->ctx was needed while the configuration merging
  58. * and in postconfiguration process
  59. */
  60. *cf = pcf;
  61. if (ngx_http_init_phase_handlers(cf, cmcf) != NGX_OK) {
  62. return NGX_CONF_ERROR;
  63. }
  64. /* optimize the lists of ports, addresses and server names */
  65. if (ngx_http_optimize_servers(cf, cmcf, cmcf->ports) != NGX_OK) {
  66. return NGX_CONF_ERROR;
  67. }
  68. return NGX_CONF_OK;
  69. failed:
  70. *cf = pcf;
  71. return rv;

HTTP 配置解析流程

从上面的分析中可以总结出 HTTP 配置解析的流程如下:

  • Nginx 进程进入主循环,在主循环中调用配置解析器解析配置文件nginx.conf;
  • 在配置文件中遇到 http{} 块配置,则 HTTP 框架开始初始化并启动,其由函数 ngx_http_block() 实现;
  • HTTP 框架初始化所有 HTTP 模块的序列号,并创建 3 个类型为 ngx_http_conf_ctx_t结构的数组用于存储所有HTTP 模块的create_main_confcreate_srv_confcreate_loc_conf方法返回的指针地址;
  • 调用每个 HTTP 模块的 preconfiguration 方法;
  • HTTP 框架调用函数 ngx_conf_parse() 开始循环解析配置文件 nginx.conf 中的http{}块里面的所有配置项;
  • HTTP 框架处理完毕 http{} 配置项,根据解析配置项的结果,必要时进行配置项合并处理;
  • 继续处理其他 http{} 块之外的配置项,直到配置文件解析器处理完所有配置项后通知Nginx 主循环配置项解析完毕。此时,Nginx 才会启动Web 服务器;

合并配置项

HTTP 框架解析完毕 http{} 块配置项时,会根据解析的结果进行合并配置项操作,即合并 http{}、server{}、location{} 不同块下各HTTP 模块生成的存放配置项的结构体。其合并过程如下所示:

  • 若 HTTP 模块实现了 merge_srv_conf 方法,则将 http{} 块下create_srv_conf 生成的结构体与遍历每一个 server{}配置块下的结构体进行merge_srv_conf 操作;
  • 若 HTTP 模块实现了 merge_loc_conf 方法,则将 http{} 块下create_loc_conf 生成的结构体与嵌套每一个server{} 配置块下的结构体进行merge_loc_conf 操作;
  • 若 HTTP 模块实现了 merge_loc_conf 方法,则将server{} 块下create_loc_conf 生成的结构体与嵌套每一个location{}配置块下的结构体进行merge_loc_conf 操作;
  • 若 HTTP 模块实现了 merge_loc_conf 方法,则将location{} 块下create_loc_conf 生成的结构体与嵌套每一个location{}配置块下的结构体进行merge_loc_conf 操作;

以下是合并配置项操作的源码实现:

  1. /* 合并配置项操作 */
  2. static char *
  3. ngx_http_merge_servers(ngx_conf_t *cf, ngx_http_core_main_conf_t *cmcf,
  4. ngx_http_module_t *module, ngx_uint_t ctx_index)
  5. {
  6. char *rv;
  7. ngx_uint_t s;
  8. ngx_http_conf_ctx_t *ctx, saved;
  9. ngx_http_core_loc_conf_t *clcf;
  10. ngx_http_core_srv_conf_t **cscfp;
  11. cscfp = cmcf->servers.elts;
  12. ctx = (ngx_http_conf_ctx_t *) cf->ctx;
  13. saved = *ctx;
  14. rv = NGX_CONF_OK;
  15. /* 遍历每一个server{}块 */
  16. for (s = 0; s < cmcf->servers.nelts; s++) {
  17. /* merge the server{}s' srv_conf's */
  18. ctx->srv_conf = cscfp[s]->ctx->srv_conf;
  19. /*
  20. * 若定义了merge_srv_conf 方法;
  21. * 则进行http{}块下create_srv_conf 生成的结构体与遍历server{}块配置项生成的结构体进行merge_srv_conf操作;
  22. */
  23. if (module->merge_srv_conf) {
  24. rv = module->merge_srv_conf(cf, saved.srv_conf[ctx_index],
  25. cscfp[s]->ctx->srv_conf[ctx_index]);
  26. if (rv != NGX_CONF_OK) {
  27. goto failed;
  28. }
  29. }
  30. /*
  31. * 若定义了merge_loc_conf 方法;
  32. * 则进行http{}块下create_loc_conf 生成的结构体与嵌套server{}块配置项生成的结构体进行merge_loc_conf操作;
  33. */
  34. if (module->merge_loc_conf) {
  35. /* merge the server{}'s loc_conf */
  36. ctx->loc_conf = cscfp[s]->ctx->loc_conf;
  37. rv = module->merge_loc_conf(cf, saved.loc_conf[ctx_index],
  38. cscfp[s]->ctx->loc_conf[ctx_index]);
  39. if (rv != NGX_CONF_OK) {
  40. goto failed;
  41. }
  42. /* merge the locations{}' loc_conf's */
  43. /*
  44. * 若定义了merge_loc_conf 方法;
  45. * 则进行server{}块下create_loc_conf 生成的结构体与嵌套location{}块配置项生成的结构体进行merge_loc_conf操作;
  46. */
  47. clcf = cscfp[s]->ctx->loc_conf[ngx_http_core_module.ctx_index];
  48. rv = ngx_http_merge_locations(cf, clcf->locations,
  49. cscfp[s]->ctx->loc_conf,
  50. module, ctx_index);
  51. if (rv != NGX_CONF_OK) {
  52. goto failed;
  53. }
  54. }
  55. }
  56. failed:
  57. *ctx = saved;
  58. return rv;
  59. }
  60. static char *
  61. ngx_http_merge_locations(ngx_conf_t *cf, ngx_queue_t *locations,
  62. void **loc_conf, ngx_http_module_t *module, ngx_uint_t ctx_index)
  63. {
  64. char *rv;
  65. ngx_queue_t *q;
  66. ngx_http_conf_ctx_t *ctx, saved;
  67. ngx_http_core_loc_conf_t *clcf;
  68. ngx_http_location_queue_t *lq;
  69. if (locations == NULL) {
  70. return NGX_CONF_OK;
  71. }
  72. ctx = (ngx_http_conf_ctx_t *) cf->ctx;
  73. saved = *ctx;
  74. /*
  75. * 若定义了merge_loc_conf 方法;
  76. * 则进行location{}块下create_loc_conf 生成的结构体与嵌套location{}块配置项生成的结构体进行merge_loc_conf操作;
  77. */
  78. for (q = ngx_queue_head(locations);
  79. q != ngx_queue_sentinel(locations);
  80. q = ngx_queue_next(q))
  81. {
  82. lq = (ngx_http_location_queue_t *) q;
  83. clcf = lq->exact ? lq->exact : lq->inclusive;
  84. ctx->loc_conf = clcf->loc_conf;
  85. rv = module->merge_loc_conf(cf, loc_conf[ctx_index],
  86. clcf->loc_conf[ctx_index]);
  87. if (rv != NGX_CONF_OK) {
  88. return rv;
  89. }
  90. /*
  91. * 递归调用该函数;
  92. * 因为location{}继续内嵌location{}
  93. */
  94. rv = ngx_http_merge_locations(cf, clcf->locations, clcf->loc_conf,
  95. module, ctx_index);
  96. if (rv != NGX_CONF_OK) {
  97. return rv;
  98. }
  99. }
  100. *ctx = saved;
  101. return NGX_CONF_OK;
  102. }

处理自定义的配置

在文章中 《Nginx 模块开发》,我们给出了“Hello World” 的开发例子,在这个开发例子中,我们定义了自己的配置项,配置项名称的结构体定义如下:

  1. typedef struct
  2. {
  3. ngx_str_t hello_string;
  4. ngx_int_t hello_counter;
  5. }ngx_http_hello_loc_conf_t;

为了处理我们定义的配置项结构,因此,我们把 ngx_command_t 结构体定义如下:

  1. static ngx_command_t ngx_http_hello_commands[] = {
  2. {
  3. ngx_string("hello_string"),
  4. NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS|NGX_CONF_TAKE1,
  5. ngx_http_hello_string,
  6. NGX_HTTP_LOC_CONF_OFFSET,
  7. offsetof(ngx_http_hello_loc_conf_t, hello_string),
  8. NULL },
  9. {
  10. ngx_string("hello_counter"),
  11. NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
  12. ngx_http_hello_counter,
  13. NGX_HTTP_LOC_CONF_OFFSET,
  14. offsetof(ngx_http_hello_loc_conf_t, hello_counter),
  15. NULL },
  16. ngx_null_command
  17. };

处理方法 ngx_http_hello_stringngx_http_hello_counter 定义如下:

  1. static char *
  2. ngx_http_hello_string(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
  3. {
  4. ngx_http_hello_loc_conf_t* local_conf;
  5. local_conf = conf;
  6. char* rv = ngx_conf_set_str_slot(cf, cmd, conf);
  7. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "hello_string:%s", local_conf->hello_string.data);
  8. return rv;
  9. }
  10. static char *ngx_http_hello_counter(ngx_conf_t *cf, ngx_command_t *cmd,
  11. void *conf)
  12. {
  13. ngx_http_hello_loc_conf_t* local_conf;
  14. local_conf = conf;
  15. char* rv = NULL;
  16. rv = ngx_conf_set_flag_slot(cf, cmd, conf);
  17. ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "hello_counter:%d", local_conf->hello_counter);
  18. return rv;
  19. }

error 日志

Nginx 日志模块为其他模块提供了基本的日志记录功能,日志模块定义如下:src/core/ngx_log.c

  1. static ngx_command_t ngx_errlog_commands[] = {
  2. {ngx_string("error_log"),
  3. NGX_MAIN_CONF|NGX_CONF_1MORE,
  4. ngx_error_log,
  5. 0,
  6. 0,
  7. NULL},
  8. ngx_null_command
  9. };
  10. static ngx_core_module_t ngx_errlog_module_ctx = {
  11. ngx_string("errlog"),
  12. NULL,
  13. NULL
  14. };
  15. ngx_module_t ngx_errlog_module = {
  16. NGX_MODULE_V1,
  17. &ngx_errlog_module_ctx, /* module context */
  18. ngx_errlog_commands, /* module directives */
  19. NGX_CORE_MODULE, /* module type */
  20. NULL, /* init master */
  21. NULL, /* init module */
  22. NULL, /* init process */
  23. NULL, /* init thread */
  24. NULL, /* exit thread */
  25. NULL, /* exit process */
  26. NULL, /* exit master */
  27. NGX_MODULE_V1_PADDING
  28. };

Nginx 日志模块对于支持可变参数提供了三个接口,这三个接口定义在文件:src/core/ngx_log.h

  1. #define ngx_log_error(level, log, ...) \
  2. if ((log)->log_level >= level) ngx_log_error_core(level, log, __VA_ARGS__)
  3. void ngx_log_error_core(ngx_uint_t level, ngx_log_t *log, ngx_err_t err,
  4. const char *fmt, ...);
  5. #define ngx_log_debug(level, log, ...) \
  6. if ((log)->log_level & level) \
  7. ngx_log_error_core(NGX_LOG_DEBUG, log, __VA_ARGS__)

Nginx 日志模块记录日志的核心功能是由 ngx_log_error_core 方法实现, ngx_log_error 和 ngx_log_debug 宏定义只是对其进行简单的封装,一般情况下日志调用只需要这两个宏定义。

ngx_log_error 和 ngx_log_debug 宏定义都包括参数 level、log、err、fmt,下面分别对这些参数进行简单的介绍:

level 参数:对于 ngx_log_error 宏来说,level 表示当前日志的级别,其取值如下所示:

  1. /* ngx_log_error中level参数的取值;下面 9 个日志的级别依次从高到低 */
  2. #define NGX_LOG_STDERR 0 /* 最高级别日志,将日志输出到标准错误设备 */
  3. #define NGX_LOG_EMERG 1
  4. #define NGX_LOG_ALERT 2
  5. #define NGX_LOG_CRIT 3
  6. #define NGX_LOG_ERR 4
  7. #define NGX_LOG_WARN 5
  8. #define NGX_LOG_NOTICE 6
  9. #define NGX_LOG_INFO 7
  10. #define NGX_LOG_DEBUG 8 /* 最低级别日志,属于调试级别 */

使用 ngx_log_error 宏记录日志时,若传入的 level 级别小于或等于 log 参数中的日志级别,就会输出日志内容,否则忽略该日志。

在使用 ngx_log_debug 宏时,参数level 不同于ngx_log_error 宏的level 参数,它表达的不是日志级别,而是日志类型。ngx_log_debug 宏记录日志时必须是NGX_LOG_DEBUG 调试级别,这里的level 取值如下:

  1. /* ngx_log_debug中level参数的取值 */
  2. #define NGX_LOG_DEBUG_CORE 0x010 /* nginx核心模块的调试日志 */
  3. #define NGX_LOG_DEBUG_ALLOC 0x020 /* nginx在分配内存时使用的调试日志 */
  4. #define NGX_LOG_DEBUG_MUTEX 0x040 /* nginx在使用进程锁时使用的调试日志 */
  5. #define NGX_LOG_DEBUG_EVENT 0x080 /* nginx event模块的调试日志 */
  6. #define NGX_LOG_DEBUG_HTTP 0x100 /* nginx http模块的调试日志 */
  7. #define NGX_LOG_DEBUG_MAIL 0x200 /* nginx mail模块的调试日志 */
  8. #define NGX_LOG_DEBUG_MYSQL 0x400 /* 与MySQL相关的nginx模块所使用的调试日志 */

当 HTTP 模块调用 ngx_log_debug 宏记录日志时,传入的 level 参数是 NGX_LOG_DEBUG_HTTP,此时,若 log 参数不属于 HTTP 模块,若使用 event 事件模块的 log,则不会输出任何日志。

log 参数:log 参数的结构定义如下:src/core/ngx_log.h;从其结构中可以知道,若只想把相应的信息记录到日志文件中,则不需要关系参数 log 的构造。

  1. /* ngx_log_t 结构的定义 */
  2. struct ngx_log_s {
  3. /* 日志级别或日志类型 */
  4. ngx_uint_t log_level;
  5. /* 日志文件 */
  6. ngx_open_file_t *file;
  7. /* 连接数,不为0时会输出到日志文件中 */
  8. ngx_atomic_uint_t connection;
  9. /* 记录日志时的回调方法,不是DEBUG调试级别才会被调用 */
  10. ngx_log_handler_pt handler;
  11. /* 模块的data */
  12. void *data;
  13. /*
  14. * we declare "action" as "char *" because the actions are usually
  15. * the static strings and in the "u_char *" case we have to override
  16. * their types all the time
  17. */
  18. char *action;
  19. /* 指向日志链表的下一个日志 */
  20. ngx_log_t *next;
  21. };

err 参数:err 参数是错误编码,一般是执行系统调用失败后取得的errno 参数。当err 不为 0 时,Nginx 日志模块将会在正常日志输出这个错误编码以及其对应的字符串形成的错误信息。

fmt 参数:fmt 参数类似于C 语言中的printf 函数的输出格式。

参考资料:

《深入理解 Nginx 》

《 nginx 启动阶段》

《Nginx高性能Web服务器详解》

发表评论

表情:
评论列表 (有 0 条评论,313人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Nginx 配置

    概述 在上一篇文章《 [ Nginx 启动初始化过程][Nginx]》简单介绍了 Nginx 启动的过程,并分析了其启动过程的源码。在启动过程中有一个步骤非常重要,就是调