nginx源码分析之配置图解

jopen 11年前

nginx配置结构清晰,层次分明,这得益于整个架构的模块化设计,文本将揭示配置文件如何被处理和应用。

nginx源码分析之配置图解

 

整个配置文件解析后的结果如图这样存储。

一、解析的核心机制
nginx源码里,ngx_conf_t是解析的关键结构体
ngx_conf_handler函数里:

/* set up the directive's configuration context */  conf = NULL;  /* direct指令,一般是core类型模块指令,比如 daemon, work_processes */  if (cmd->type & NGX_DIRECT_CONF) {      conf = ((void **) cf->ctx)[ngx_modules[i]->index]; /* 直接存储,比如 ngx_core_conf_t */    /* main指令,比如 events, http,此时指向它的地址,这样才能分配数组指针,存储属于它的结构体们。 */  } else if (cmd->type & NGX_MAIN_CONF) {      conf = &(((void **) cf->ctx)[ngx_modules[i]->index]); /* 参考图片 */    } else if (cf->ctx) {      confp = *(void **) ((char *) cf->ctx + cmd->conf);        /* 有移位的,因此http有三个部分,main, srv, conf,这个就为此而设计的,继续下面的sendfile指令 */       if (confp) {          conf = confp[ngx_modules[i]->ctx_index];      }  }    rv = cmd->set(cf, cmd, conf);    比如sendfile指令:  { ngx_string("sendfile"),    NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF                      |NGX_CONF_FLAG,    ngx_conf_set_flag_slot,    NGX_HTTP_LOC_CONF_OFFSET,  /* 这个对应上面理解,正因有这个offset,它才找到loc部分的配置 */    offsetof(ngx_http_core_loc_conf_t, sendfile),    NULL }

 二、配置的应用
1、最简单形式,direct方式

/* 定义获取配置文件的宏 */  #define ngx_get_conf(conf_ctx, module)  conf_ctx[module.index]    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);  if (ccf->master && ngx_process == NGX_PROCESS_SINGLE) {      ngx_process = NGX_PROCESS_MASTER;  }

2、稍微复杂点形式,main方式

/* 定义获取配置文件的宏,注意指针 */  #define ngx_event_get_conf(conf_ctx, module)                                  \               (*(ngx_get_conf(conf_ctx, ngx_events_module))) [module.ctx_index];    ngx_epoll_conf_t  *epcf;    epcf = ngx_event_get_conf(cycle->conf_ctx, ngx_epoll_module);    nevents = epcf->events;

3、不简单的http配置

/* 宏定义,r是什么,稍后解释 */  #define ngx_http_get_module_loc_conf(r, module)  (r)->loc_conf[module.ctx_index]    ngx_http_log_loc_conf_t  *lcf;    lcf = ngx_http_get_module_loc_conf(r, ngx_http_log_module);  ...      /* r是请求,它是这么来的,在ngx_http_init_request函数里(ngx_http_request.c文件)*/    r = ...;  cscf = addr_conf->default_server;    r->main_conf = cscf->ctx->main_conf;  r->srv_conf = cscf->ctx->srv_conf;  r->loc_conf = cscf->ctx->loc_conf;

还有个要提的,http配置分main, src, loc,下级的配置可以覆盖上级,很明显,上级只是默认设置值而已。

三、重提模块化设计
学着用模块化的角度去看nginx的整体设计,一切以模块为核心,配置依赖于模块,即模块本身就携带着它的配置。正因为这样的设计的,配置文件的解析,使用非常简单。避免过多使用全局变量好像成为一种共识,但是在nginx世界里,全局变量可不少,每个模块都是个全局变量,为什么这样设计呢?因为模块之间是有依赖性的,所以需要互相访问。

配置文件解析这块的代码极具借鉴,本文只管窥般分析了配置文件,不能剥夺读者阅读源码的享受,点到即止。

 

来自:http://my.oschina.net/fqing/blog/80867