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 }</pre>
二、配置的應用
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; }</pre>
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;</pre>
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;</pre>
還有個要提的,http配置分main, src, loc,下級的配置可以覆蓋上級,很明顯,上級只是默認設置值而已。
三、重提模塊化設計
學著用模塊化的角度去看nginx的整體設計,一切以模塊為核心,配置依賴于模塊,即模塊本身就攜帶著它的配置。正因為這樣的設計的,配置文件的解析,使用非常簡單。避免過多使用全局變量好像成為一種共識,但是在nginx世界里,全局變量可不少,每個模塊都是個全局變量,為什么這樣設計呢?因為模塊之間是有依賴性的,所以需要互相訪問。
配置文件解析這塊的代碼極具借鑒,本文只管窺般分析了配置文件,不能剝奪讀者閱讀源碼的享受,點到即止。
來自:http://my.oschina.net/fqing/blog/80867