您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Nginx 基础架构解析(下)

1. 模块

的内部结构是由核心部分和一系列的模块所组成。这样划分是为了使得每个模块的相对简单,便于开发,同时也便于对系统进行扩展。 将各模块组织成一条链,当有请求到达的时候,请求依次经过这条链上的部分或者全部模块,进行处理。例如前面讲到的 http 请求,会有11个处理阶段,而每个阶段有对应着许多在此阶段生效的模块对该 http 请求进行处理。同时, 开放了第三方模块编写,可以模块,控制 http 请求的处理与响应,这种高度可定制化催生了 的大量第三方模块,也使得 定制化开发在各大互联网公司十分流行。

关于 模块的有很多种方式,目前网上中写的较多的是按照进行,有如下几大类:

event 模块: 搭建 独立于操作系统的事件处理机制的框架,以及 提供各种具体事件的处理。代表性的模块有:ngx_events_module, ngx_event_core_module, ngx_epoll_module;

handler 模块: 主要负责处理客户端请求并产生待响应的,比如 ngx_http_static_module 模块,负责客户端的静态请求处理并将对应的磁盘 准备为响应;

filter 模块: 主要 负责处理的,。代表性的模块有: ngx_http_sub_module;

upstream 模块: 该类模块都是用于实现反向代理,将真正的请求转发到后端服务器上,并从后端服务器上读取响应,发回给客户端。比如前面介绍到转发 http、websocket、grpc、rtmp等协议的模块都可以划分为这一类;

均衡模块: 均衡的模块,实现相应算法。这类模块都是用于实现 的均衡。

extend 模块: 又称第三方模块,非 官方提供,由各大企业的开发人员结合自身业务开发而成。 提供了非常好的模块编写机制,遵循相关的标准可以很快定制出符合我们业务场景的模块,而且内部 内部提供的进行处理,使得第三方模块往往都具备很好的

对于官方提供的模块,我们可以直接在上学习,学习的方式和学习其他互联网组件的方式一致,首先学习如何使用,在用至熟练后可以深入分析其源码了解实现背后的原理。

我们以前面介绍到的 的限速模块(limit_req模块)进行说明。首先是掌握该模块的,在该模块的中,有关于该模块的详细介绍,该模块提供的所有指令以及所有变量说明。此外,还有比较丰富的指令用例。在多次使用该指令并自认为掌握了该模块的之后,想了解限速背后的原理以及相关算法时,就可以深入到源码学习了。

进入 的源码目录,使用ls查看源码,限速模块是在 http 目录中的。

[root@server -1.17.6]# cd src/

[root@server src]# ls
core  event  http  mail  misc  os  stream

[root@server src]# ls http/modules/ngx_http_limit_*.c
http/modules/ngx_http_limit_conn_module.c
http/modules/ngx_http_limit_req_module.c

找到 模块对应的后,我们就可以阅读里面的进行学习。往往源码的阅读是枯燥无味的,我们可以借助海量的网络资源辅助我们学习。这里就有一篇,作者深入分析了 的限流模块的源码以及相应限流算法,最后进行了相关的实验测试。通过这样个模块深入学习,最后在使用每 指令时,也会非常熟练,最后成为 高手。

这里我们演示在 中使用第三方模块。 Openresty 社区提供了一款 中的 Echo 模块,即echo--module。在 中了该模块后,我们在中可以使用该模块提供的 echo 指令返回响应,简单方便。该模块的源码在 上,并且有良好的文档和使用示例,非常方便开发者使用。

@H__56@

现在我们在 的源码编译阶段加入该第三方模块,具体操作如下:

[root@server shencong]# pwd/root/shencong[root@server shencong]# mkdir -echo# 下载  源码包和第三方模块的源码包 [root@server shencong]# wget http://.org/download/-1.17.6.tar.gz[root@server shencong]# wget https://github.com/openresty/echo--module/archive/v0.62rc1.tar.gz# 解压[root@server shencong]# tar -xzf -1.17.6.tar.gz[root@server shencong]# tar -xzf v0.62rc1.tar.gz[root@server shencong]# lsecho--module-0.62rc1  -1.17.6  -1.17.6.tar.gz  -echo  v0.62rc1.tar.gz[root@server shencong]# cd -1.17.6# 使用--add-module第三方模块,参数为第三方模块源码[root@server shencong]# ./conure --prefix=/root/shencong/-echo  --add-module=/root/shencong/echo--module-0.62rc1

编译完成后,我们就可以去-echo目录中的 .confecho 指令 。准备如下的配置(可以参参考社区提供的示例):

...http {
   server {listen       ;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;}# 新增测试 echo 指令配置location /timed_hello {default_type text/plain;echo_reset_timer;echo hello world;echo "'hello world' takes about $echo_timer_elapsed sec.";echo hiya igor;echo "'hiya igor' takes about $echo_timer_elapsed sec.";}location /echo_with_sleep {default_type text/plain;echo hello world;echo_flush;  # ensure the client can see prevs output immediatelyecho_sleep   ;  # in sececho "'hello' takes about $echo_timer_elapsed sec.";}}}...

启动 后,我们就可以在浏览器上请求者两个 URI 地址,看到相应 echo 返回的信息了。第二个配置是使用了 echo_sleep 指令,会使得请求在休眠 2.5s 后才返回。

想要编写 模块,首先需要对 模块中的源码以及相关的数据结构有所了解,还要知晓   HTTP 模块的流程。假设我要实现前面第三方模块Echo的最简单形式,即只相应的字符串即可。假定模块的指令还是 echo, 这个 echo 指令需要跟参数,即的字符串。我们需如下几步:

确定模块,以及模块中的指令以及参数,还有运行的环境。这里涉及的结构是 ngx_command_t,它定义了模块里的所有指令格式。下面的表示该模块中只有 echo 指令,它出现的上下文环境为 location,且有参数(NGX_CONF_TAKE1)。当某个配置块中出现echo指令时, 将ngx_http_echo。然后在该中,会设置处理请求的 handler,这个 handler 就是处理请求的。

  static ngx_command_t  ngx_http_echo_commands[] = {  
         { ngx_string("echo"),      /* 指令,利用ngx_string宏定义 */
          NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,  /* 用在 location 指令块内,且有1个参数 */
          ngx_http_echo,            /* 处理回调 */
          NGX_HTTP_LOC_CONF_OFFSET,    
          offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
          NULL },
          ngx_null_command  };

完成请求处理的 handler ,最重要的部分就;

 static char *
 ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
 { ngx_http_core_loc_conf_t  *clcf; /* 找到指令所属的配置块,这里我们限定echo指令的上下文环境只有location */
     clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); /* 指定处理的handler */
     clcf->handler = ngx_http_echo_handler; ...     return NGX_CONF_OK;
 }
 
 static ngx_int_t
 ngx_http_echo_handler(ngx__t *r)
 { ...
     
     /* 向发送相应包 */     return ngx_http_output_filter(r, &out);
 }

一些收尾工作,比如介入 http 请求的哪些阶段等。

  /* Http context of the module */
  static ngx_http_module_t  ngx_http_echo_module_ctx = {  NULL,                                  /* preconuration */  NULL,                                  /* postconuration */  NULL,                                  /* create main conuration */  NULL,                                  /* init main conuration */  NULL,                                  /* create server conuration */  NULL,                                  /* merge server conuration */  ngx_http_echo_create_loc_conf,         /* create location conration */  ngx_http_echo_merge_loc_conf           /* merge location conration */
  };
  /* Module */
  ngx_module_t  ngx_http_echo_module = {  NGX_MODULE_V1,  &ngx_http_echo_module_ctx,             /* module context */  ngx_http_echo_commands,                /* module directives */  NGX_HTTP_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  };

完成以上几步,简易的模块就算大功告成了。接下来我们动手完成第的模块,将其编译进 二进制中并进行测试。

2. 案例

我们来完成简单的 http 模块,来实现前面Echo模块的最简单形式,即使用指令 “hello, world” 字符串。首先新建目录echo--module,然后在目录下新建两个conngx_http_echo_module.c

[root@server echo--module]# pwd
/root/shencong/echo--module

[root@server echo--module]# ls
con  ngx_http_echo_module.c

两个分别如下:

[root@server echo--module]# cat con 
ngx_addon_name=ngx_http_echo_module
# 指定模块
HTTP_MODULES="$HTTP_MODULES ngx_http_echo_module"
# 指定模块源码路径
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_echo_module.c"

[root@server echo--module]# cat ngx_http_echo_module.c
#include <ngx_con.h>
#include <ngx_core.h>
#include <ngx_http.h>

/* Module con */
typedef struct {
    ngx_str_t  ed;
} ngx_http_echo_loc_conf_t;

static char *ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static void *ngx_http_echo_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child);

/* 定义指令 */
static ngx_command_t  ngx_http_echo_commands[] = {
    { ngx_string("echo"),      /* 指令,利用ngx_string宏定义 */
        NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,  /* 用在 location 指令块内,且有1个参数 */
        ngx_http_echo,         /* 处理回调 */
        NGX_HTTP_LOC_CONF_OFFSET,    
        offsetof(ngx_http_echo_loc_conf_t, ed), /* 指定参数读取位置 */
        NULL },
        ngx_null_command
};
/* Http context of the module */
static ngx_http_module_t  ngx_http_echo_module_ctx = {
    NULL,                                  /* preconuration */
    NULL,                                  /* postconuration */
    NULL,                                  /* create main conuration */
    NULL,                                  /* init main conuration */
    NULL,                                  /* create server conuration */
    NULL,                                  /* merge server conuration */
    ngx_http_echo_create_loc_conf,         /* create location conration */
    ngx_http_echo_merge_loc_conf           /* merge location conration */
};
/* Module */
ngx_module_t  ngx_http_echo_module = {
    NGX_MODULE_V1,
    &ngx_http_echo_module_ctx,             /* module context */
    ngx_http_echo_commands,                /* module directives */
    NGX_HTTP_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
};
/* Handler function */
static ngx_int_t
ngx_http_echo_handler(ngx__t *r)
{
    ngx_int_t rc;
    ngx_buf_t *b;
    ngx_chain_t out;
    ngx_http_echo_loc_conf_t *elcf;
    /* 指令的参数 */
    elcf = ngx_http_get_module_loc_conf(r, ngx_http_echo_module);
    if(!(r->method & (NGX_HTTP_HEAD|NGX_HTTP_GET|NGX_HTTP_POST)))
    {
        /* 如果不是 HEAD/GET/PUT 请求,则返回405 Not Allowed */
        return NGX_HTTP_NOT_ALLOWED;
    }
    r->headers_out.content_type.len = sizeof("text/html") - 1;
    r->headers_out.content_type.data = (u_char *) "text/html";
    r->headers_out.status = NGX_HTTP_OK;
    r->headers_out.content_length_n = elcf->ed.len;
    if(r->method == NGX_HTTP_HEAD)
    {
        rc = ngx_http_send_header(r);
        if(rc != NGX_OK)
        {
            return rc;
        }
    }
    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
    if(b == NULL)
    {
        ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, " to allocate response buffer.");
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }
    out.buf = b;
    out.next = NULL;
    b->pos = elcf->ed.data;
    b->last = elcf->ed.data + (elcf->ed.len);
    b->memory = 1;
    b->last_buf = 1;
    rc = ngx_http_send_header(r);
    if(rc != NGX_OK)
    {
        return rc;
    }
    /* 向发送相应包 */
    return ngx_http_output_filter(r, &out);
}
static char *
ngx_http_echo(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
    ngx_http_core_loc_conf_t  *clcf;
    clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
    /* 指定处理的handler */
    clcf->handler = ngx_http_echo_handler;
    ngx_conf_set_str_slot(cf,cmd,conf);
    return NGX_CONF_OK;
}
static void *
ngx_http_echo_create_loc_conf(ngx_conf_t *cf)
{
    ngx_http_echo_loc_conf_t  *conf;
    conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_echo_loc_conf_t));
    if (conf == NULL) {
        return NGX_CONF_ERROR;
    }
    conf->ed.len = 0;
    conf->ed.data = NULL;
    return conf;
}
static char *
ngx_http_echo_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
    ngx_http_echo_loc_conf_t *prev = parent;
    ngx_http_echo_loc_conf_t *conf = child;
    ngx_conf_merge_str_value(conf->ed, prev->ed, "");
    return NGX_CONF_OK;
}

这样第三方模块包就完成了,接下来我们要向之前使用第三方模块一样,将它编译进 ,具体操作如下。

[root@server shencong]# cd -1.17.6/
[root@server -1.17.6]# ./conure --prefix=/root/shencong/-echo --add-module=/root/shencong/echo--module
...
[root@server -1.17.6] # make && make install
...
[root@server -1.17.6]# cd ../-echo/sbin/
[root@server sbin]# ./ -V
 version: /1.17.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) 
conure arguments: --prefix=/root/shencong/-echo --add-module=/root/shencong/echo--module

接下来,我们只要在 .conf 中加入我们的指令,并给参数,就能看到我们的了。

...http {
   ...
   server {   listen       ;   server_name  localhost;   location / {root   html;index  index.html index.htm;   }   
       location /test {echo hello,world;   }   ...
   }}...

最后我们请求主机的80端口,URI=/test,浏览器"hello, world",说明我们的模块成功了!

3. 小结

在 基础架构介绍的最后,主要是介绍了 的模块设计以及相应的模块。最后,我们简单给出了简单编写自己模块的案例作为本章的实战案例。希望这一节之后,大家能对 的模块化设计有所了解,并有兴趣在模块的源码方向深入学习。


联系我
置顶