实例胜千言,所以我准备了这个代码供入门参考。
1. 准备模块代码
2. 编写配置文件
3. 运行./configure 编译nginx 程序
4. make & make install
5. 运行测试
甲: 前言
Nginx的模块动态添加,所有的模块都要预先编译进Nginx的二进制可执行文件中。
所以要./configure, make, make install
Nginx模块有3种角色:
1.Handlers(处理模块)----------用于处理Http请求并输出内容
2.Filters(过滤模块) ----------用于过滤Handlers输出的内容
3.Load-balancers(负载均衡模块) or upstream 模块---当多余一台的后端服务器供选择时,选择一台后端服务器并将Http请求转发到该服务器
Nginx模块的处理流程:
客户端发生Http请求到Nginx服务器 -> Nginx基于配置文件选择一个合适的处理模块
-> 负载均衡模块选择一个后端服务器 -> 处理模块并把输出缓冲放到第一个过滤模块上
-> 一直经过了N个过滤模块后 -> 把处理结果发送到客户端。
用一张图最好,不过文本也能说明问题。
乙:准备模块代码
- #include <ngx_config.h>
- #include <ngx_core.h>
- #include <ngx_http.h>
- #include <pthread.h>
- #include <string.h>
- #include <errno.h>
- #define TIMING_BUF_BYTES (2 * 1024 * 1024)
- static ngx_int_t user_init_m3u9(ngx_cycle_t* cycle);
- static void user_uninit_m3u9(ngx_cycle_t* cycle);
- static char* ngx_http_m3u9(ngx_conf_t* cf, ngx_command_t* cmd, void* conf);
- static int read_big_block (int fd, unsigned char *buf, size_t count);
- static int seek_to_pos (int fd, off_t pos);
- static void* init_num_ram(void);
- static int myrand(void);
- static void mysrand(unsigned seed) ;
- // static u_char ngx_m3u9[] = "m3u9, hello, world";
- static unsigned char * g_buf_m3u9 = 0;
- static int g_fd_m3u9 = 0;
- static pthread_mutex_t read_lock;
- static const char *dev_name_m3u9="/dev/sdc";
- //static const char *dev_name_m3u9="/dev/md0";
- static ngx_command_t ngx_http_m3u9_commands[] =
- {
- {
- ngx_string("m3u9"),
- NGX_HTTP_LOC_CONF | NGX_CONF_NOARGS,
- ngx_http_m3u9,
- 0,
- 0,
- NULL
- },
- ngx_null_command
- };
- static ngx_http_module_t ngx_http_m3u9_module_ctx =
- {
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL,
- NULL
- };
- ngx_module_t ngx_http_m3u9_module =
- {
- NGX_MODULE_V1,
- &ngx_http_m3u9_module_ctx,
- ngx_http_m3u9_commands,
- NGX_HTTP_MODULE,
- NULL,
- NULL,
- &user_init_m3u9,
- NULL,
- NULL,
- &user_uninit_m3u9,
- NULL,
- NGX_MODULE_V1_PADDING
- };
- static ngx_int_t user_init_m3u9(ngx_cycle_t* cycle)
- {
- g_buf_m3u9 = (unsigned char *)malloc(TIMING_BUF_BYTES);
- if(!g_buf_m3u9)
- {
- ngx_log_stderr(0,"m3u9: g_buf_m3u9 malloc error");
- return -1;
- }
- pthread_mutex_init(&read_lock, NULL);
- g_fd_m3u9 = open (dev_name_m3u9, O_RDONLY);
- if (g_fd_m3u9 < 0) {
- ngx_log_stderr(0,"m3u9: g_fd_m3u9 open error, g_fd_m3u9:%d", g_fd_m3u9);
- free(g_buf_m3u9);
- g_buf_m3u9 = NULL;
- g_fd_m3u9 = 0;
- return -2;
- }
- // srand(time(NULL));
- // mysrand(time(NULL)) ;
- init_num_ram();
- ngx_log_stderr(0,"m3u9: user_init_m3u9 called,devname:%s", dev_name_m3u9);
- return (ngx_int_t)0;
- }
- void user_uninit_m3u9(ngx_cycle_t* cycle)
- {
- if(g_buf_m3u9)
- {
- free(g_buf_m3u9);
- g_buf_m3u9 = NULL;
- }
- if(g_fd_m3u9)
- {
- close(g_fd_m3u9);
- g_fd_m3u9 = 0;
- }
- ngx_log_stderr(0,"m3u9: user_uninit_m3u9 called");
- }
- static ngx_int_t ngx_http_m3u9_handler(ngx_http_request_t* request)
- {
- ngx_buf_t* b;
- ngx_chain_t out;
- ngx_log_stderr(0,"m3u9: ngx_http_m3u9_handler called");
- request->headers_out.content_type.len = sizeof("text/plain") - 1;
- request->headers_out.content_type.data = (u_char*)"text/plain";
- request->headers_out.status = NGX_HTTP_OK;
- b = ngx_pcalloc(request->pool, sizeof(ngx_buf_t));
- out.buf = b;
- out.next = NULL;
- int ret = 0;
- if (request->args.len > 0)
- {
- // memcpy(param, request->args.data, request->args.len);
- }
- else
- {
- // b->pos = ngx_m3u9;
- // b->last = ngx_m3u9 + sizeof(ngx_m3u9);
- // ret = sizeof(ngx_m3u9);
- int randnum = myrand();
- ngx_log_stderr(0,"m3u9: randnum:%d",randnum);
- off_t offset = (off_t) randnum * TIMING_BUF_BYTES;
- offset &= 0xffffffffff; // 1 T
- pthread_mutex_lock(&read_lock);
- if(seek_to_pos(g_fd_m3u9, offset))
- {
- ngx_log_stderr(0,"m3u9: seek error, offset:0x%lx",offset);
- }
- if(read_big_block(g_fd_m3u9, g_buf_m3u9, TIMING_BUF_BYTES))
- {
- ngx_log_stderr(0,"m3u9: read_big_block error");
- }
- pthread_mutex_unlock(&read_lock);
- b->pos = g_buf_m3u9;
- b->last = g_buf_m3u9 + TIMING_BUF_BYTES;
- ret = TIMING_BUF_BYTES;
- }
- b->memory = 1;
- b->last_buf = 1;
- if (ret >= 0)
- request->headers_out.status = NGX_HTTP_OK;
- else
- {
- request->headers_out.status = NGX_HTTP_NOT_FOUND;
- }
- request->headers_out.content_length_n = ret >= 0 ? ret : 0;
- ngx_http_send_header(request);
- ngx_int_t retFilter = ngx_http_output_filter(request, &out);
- return retFilter;
- }
- static char* ngx_http_m3u9(ngx_conf_t* cf, ngx_command_t* cmd, void* conf)
- {
- ngx_http_core_loc_conf_t* pclcf = NULL;
- pclcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
- pclcf->handler = ngx_http_m3u9_handler;
- ngx_log_stderr(0,"m3u9: handler installer called, devname:%s",dev_name_m3u9);
- return NGX_CONF_OK;
- }
- // TIMING_BUF_BYTES
- static int read_big_block (int fd, unsigned char *buf, size_t count)
- {
- int rc;
- if(fd == -1) return 1;
- if ((rc = read(fd, buf, count)) != (ssize_t)count)
- {
- if (rc)
- {
- if (rc == -1)
- ngx_log_stderr(0,"m3u9: read() failed");
- else
- ngx_log_stderr(0, "m3u9: read(%u) returned %u bytes", TIMING_BUF_BYTES, rc);
- }
- else
- {
- ngx_log_stderr(0,"m3u9: read() hit EOF - device too small", stderr);
- }
- return 1;
- }
- /* access all sectors of buf to ensure the read fully completed */
- /*
- for (i = 0; i < TIMING_BUF_BYTES; i += 512)
- {
- // buf[i] &= 1;
- char randnum = rand() % 0xff;
- buf[i]=randnum;
- }
- */
- return 0;
- }
- static int seek_to_pos (int fd, off_t pos)
- {
- if(fd== -1) return 1;
- ngx_log_stderr(0,"m3u9: fd:%d, pos:%ld",fd, pos); // shit, hex format not supported
- if (lseek(fd, (off_t) pos, SEEK_SET)<0) {
- ngx_log_stderr(0,"m3u9: lseek() failed");
- return 1;
- }
- return 0;
- }
- #define BUF_BYTES (512 * 1024)
- static char *g_pRandRam;
- static off_t g_next=0;
- static int g_num=0;
- void* init_num_ram(void)
- {
- mysrand(time(NULL));
- g_pRandRam=malloc(BUF_BYTES);
- if(!g_pRandRam)
- {
- ngx_log_stderr(0,"error malloc\n");
- return 0;
- }
- ngx_log_stderr(0,"g_pRandRam: %p", g_pRandRam);
- memset(g_pRandRam,0,BUF_BYTES);
- return g_pRandRam;
- }
- int myrand(void)
- {
- if(g_pRandRam == NULL)
- {
- ngx_log_stderr(0,"g_pRandRam: %p", g_pRandRam);
- return 0;
- }
- g_num++;
- if(g_num>=BUF_BYTES)
- {
- g_num = 0;
- memset(g_pRandRam,0,BUF_BYTES);
- }
- g_next = g_next * 1103515245 + 123457;
- unsigned int ret = (unsigned ) (g_next/0x100000) % BUF_BYTES;
- while(1)
- {
- if(g_pRandRam[ret]==0)
- {
- g_pRandRam[ret]=1;
- break;
- }
- else
- {
- ret++;
- if(ret>=BUF_BYTES)
- {
- ret=0;
- }
- }
- }
- return ret;
- }
- void mysrand(unsigned seed)
- {
- g_next = seed;
- }
代码简要注释:
需要定义一个ngx_module_t 变量, 翻译为模块结构体变量
此处命名为ngx_http_m3u9_module
ngx_module_t ngx_http_m3u9_module =
{
NGX_MODULE_V1,
&ngx_http_m3u9_module_ctx,
ngx_http_m3u9_commands,
NGX_HTTP_MODULE,
NULL,
NULL,
&user_init_onprocess,
NULL,
NULL,
&user_uninit_onprocess,
NULL,
NGX_MODULE_V1_PADDING
};
这个变量中,包含了二个变量 ngx_http_m3u9_module_ctx, ngx_http_m3u9_commands,
模块上下文变量,模块命令变量, 更深刻的理解你需要跟踪阅读头文件定义。这里忽略。
user_init_onprocess 是进程创建时用户初始化入口地址
static ngx_int_t init_module_handler(ngx_cycle_t* cycle);
你可以在这里放自己的初始化代码,例如分配内存,打开文件等。
我曾经不知道此处代码的作用,而将初始化代码也放在执行代码 ngx_http_m3u9_handler 中。
当然,为了保证只执行一次,需要用一个变量has_init 标识。
而现在有了这个接口,可见nginx 结构设计还是很切且。
user_uninit_onprocess 是反初始化入口地址。看一下代码更明白
static ngx_command_t ngx_http_m3u9_commands[] =
{
{
ngx_string("m3u9"),
NGX_HTTP_LOC_CONF | NGX_CONF_NOARGS,
ngx_http_m3u9,
0,
0,
NULL
},
ngx_null_command
};
ngx_http_m3u9 是回调函数地址
static char* ngx_http_m3u9(ngx_conf_t* cf, ngx_command_t* cmd, void* conf);
该函数会被调用一次,用以得到重要的,以后url 访问时都会调用的函数地址。
这里定义为 ngx_http_m3u9_handler
pclcf->handler = ngx_http_m3u9_handler;
http 请求的处理就是在ngx_http_m3u9_handler 中进行的。
演示代码是打开设备,读取数据并返回
这里演示一下404 Not Found 页面是如何被传回的。
1. 用字符串定义404 Not Found 页面, 这个是要求被传回的数据
u_char not_find_404[] = "<html><head>\
<meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1252\"><title>404 Not Found</title></head>;\
<body bgcolor=\"white\">\
<center><h1>404 Not Found</h1></center>\
<hr><center>nginx/1.4.0</center>\
\
\
</body></html>";
2. http 传输时需要发送头部信息。ngx 用下列语句
ngx_http_send_header(request);
发送之前,需要准备好header 数据。
request->headers_out.content_type.data = (u_char*)"text/html";
request->headers_out.content_type.len = sizeof("text/html") - 1;
request->headers_out.content_length_n = sizeof(not_find_404)-1;
request->headers_out.status = NGX_HTTP_NOT_FOUND;
可见,它说明了数据类型是text/html, 并包含了数据的长度和页面状态
3. 定义一个ngx_chain_t 变量, 填充好后,调用过滤器,反馈给用户
ngx_chain_t out;
out.next = NULL;
out.buf = b;
ngx_int_t retFilter = ngx_http_output_filter(request, &out);
return retFilter;
4.数据如何付给out.buf, b 是一个ngx_buf_t 结构地址。所以需要填充这个结构
ngx_buf_t* b = ngx_pcalloc(request->pool, sizeof(ngx_buf_t));
// 填充属性等
b->memory = 1;
b->last_buf = 1;
// 填充数据起始地址, 终了地址
b->pos = not_find_404;
b->last = not_find_404 + strlen((char *)not_find_404) ;
经过以上步骤,才把内存中数据传输到客户端。
可见, 它比简单的字符串信息复杂很多。为什么呢?
这是架构所决定的。
1. 要求先发header, 说明类型,内容长度等, 这样可以支持二进制或者其它数据类型
2. 填充结构,说明其它额外信息,不仅仅只是数据地址,长度。
这样它可以应付复杂的数据类型,包括存储类型等。或者还没有考虑到的地方。
static ngx_http_module_t ngx_http_m3u9_module_ctx =
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
};
其它变量都为常数或空,用户可自行查找浏览。
丙. 编写配置文件
1. config
这个 config 是模块目录下文件, 供./configure 使用,内容如下
ngx_addon_name=ngx_http_m3u9_module
HTTP_MODULES="$HTTP_MODULES ngx_http_m3u9_module"
CORE_LIBS="$CORE_LIBS -lrt"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS \
$ngx_addon_dir/src/ngx_http_m3u9_module.c"
关于模块的名字,和代码中模块名字要一致。
补充一下,文件的目录结构为。
nginx/mymodules // dir
nginx/mymodules/config // file, need edit
nginx/mymodules/src // dir
nginx/mymodules/src/ngx_http_m3u9_module.c // file, need edit
2. nginx.conf
Nginx配置文件中的指令一般分为main,server,location,upstream四种;
main: 全局指令,比如本文中 worker_processes 1这些;
server:特定主机相关的配置;
location:特定uri相关的配置;
upstream:上游服务器相关配置,fastcgi,proxy_pass这类都可能用到;
这里我们只有找到 location / 节处,与它并排放一个新的节
location /m3u9
{
m3u9
}
/m3u9是url的访问地址,{}中m3u9 和 commands 定义的字符串要一致。
丁. 运行configure, 生成Makefile
./configure --add-module=./mymodules/m3u9/
后面参数指明模块所在位置。
看到下面输出表示无误了。
dding module in ./mymodules/m3u9/
+ ngx_http_m3u9_module was configured
当时我还手工修改makefile, how silly am I, nginx 都为我们处理好了。
nginx 可以直接支持c 文件, 如果你用了c++代码, 需要手工修改 Makefile
只需将对CPP 的编译改为 g++, 链接也用 g++ 就可以了。
./configure --help 可以看到帮助,
可以用--prefix 设定路径, --add-module 添加模块
戊。编译和安装
make, 当然要通过。
make install , 看清它装哪里了。跟configure 显示的路径是一致的。
己。测试
http://localhost/m3u9/abc.ts
就可以调用到我们的代码了,用两台电脑更好。
我在代码中加了log, 在error 文件中有log记录。
一切都从简了,abc.ts 是虚指,反正我的演示代码不管请求什么文件,都随意返回2M数据
据说在nginx.conf 中把master_process off, daemon off, 可以方便gdb 调试。
由于我的代码很简单,自己的代码在用户层先调好(可以用gdb)
此处就不劳gdb 大架了。有log 就可以应付了。