nginx源码中,ngx_module_s结构体描述了Nginx中一个模块应该包含的基本属性,如下:
struct ngx_module_s {
ngx_uint_t ctx_index;
ngx_uint_t index;
char *name;
ngx_uint_t spare0;
ngx_uint_t spare1;
ngx_uint_t version;
const char *signature;
void *ctx;
ngx_command_t *commands;
ngx_uint_t type;
ngx_int_t (*init_master)(ngx_log_t *log);
ngx_int_t (*init_module)(ngx_cycle_t *cycle);
ngx_int_t (*init_process)(ngx_cycle_t *cycle);
ngx_int_t (*init_thread)(ngx_cycle_t *cycle);
void (*exit_thread)(ngx_cycle_t *cycle);
void (*exit_process)(ngx_cycle_t *cycle);
void (*exit_master)(ngx_cycle_t *cycle);
uintptr_t spare_hook0;
uintptr_t spare_hook1;
uintptr_t spare_hook2;
uintptr_t spare_hook3;
uintptr_t spare_hook4;
uintptr_t spare_hook5;
uintptr_t spare_hook6;
uintptr_t spare_hook7;
};
Nginx中包含了四种不同类型的模块:core、http、event、mail,其中ctx_index用来标示模块所属的类型。
index记录当前模块在全局模块列表数组ngx_modules中的位置。
其中ctx为指向该模块上下文的指针,不同模块的上下文结构是不一样的
例如,http类模块的上下文结构:
typedef struct {
ngx_int_t (*preconfiguration)(ngx_conf_t *cf);
ngx_int_t (*postconfiguration)(ngx_conf_t *cf);
void *(*create_main_conf)(ngx_conf_t *cf);
char *(*init_main_conf)(ngx_conf_t *cf, void *conf);
void *(*create_srv_conf)(ngx_conf_t *cf);
char *(*merge_srv_conf)(ngx_conf_t *cf, void *prev, void *conf);
void *(*create_loc_conf)(ngx_conf_t *cf);
char *(*merge_loc_conf)(ngx_conf_t *cf, void *prev, void *conf);
} ngx_http_module_t;
例如,core类模块的上下文结构
typedef struct {
ngx_str_t name;
void *(*create_conf)(ngx_cycle_t *cycle);
char *(*init_conf)(ngx_cycle_t *cycle, void *conf);
} ngx_core_module_t;
event类模块的上下文结构:
typedef struct {
ngx_str_t *name;
void *(*create_conf)(ngx_cycle_t *cycle);
char *(*init_conf)(ngx_cycle_t *cycle, void *conf);
ngx_event_actions_t actions;
} ngx_event_module_t;
其中ngx_event_actions_t 为一个结构体,定义了一系列的事件回调函数,通过这种同一的接口来支持epoll、select、kqueue等不同的事件驱动模型
模块相关的回调函数:
init_master:master进程初始化时调用
init_module:模块初始化
init_process:worker进程初始化
init_thread:线程初始化
exit_thread:线程推出
exit_process:woker进程退出
exit_master:主进程退出
nginx中,ngx_module_t只记录所有模块的共有信息,包括:各个回调函数,名称、以及包含的命令等。
通过模块上下文对模块进行了大致分类,比如http类的模块有一定的共性,于是定义了ngx_http_module_t