文章目錄
- 一、概述
- 二、Nginx handler模塊開發
- 2.1、代碼實現
- 2.2、編寫config文件
- 2.3、編譯模塊到Nginx源碼中
- 2.4、修改conf文件
- 2.5、執行效果
- 總結
一、概述
上一篇【Nginx模塊開發之http handler實現流量統計(1)】使用數組在單進程實現了IP的流量統計,這一篇將進行優化,使用紅黑樹的數據結構以及共享內存的方式實現進程間通信。
進程間通信的方式:
(1)進程在不同的機器中,使用網絡進行通信。
(2)進程在同一個機器,并且進程間的關系是父子進程關系,可以使用共享內存。
(3)使用unix_sock,比如文件soket。在MySQL使用的就是這種進程通信方式。
(4)pipe,管道。
二、Nginx handler模塊開發
2.1、代碼實現
在重點地方添加了注釋,主要是紅黑樹的添加和使用,以及共享內存的使用。
核心:
1.nginx獲取請求。ngx_command_t中設置ngx_http_pagecount_set。
2.conf文件解析到模塊的cmd時,初始化共享內存以及互斥鎖。
3.紅黑樹的初始化。
4.組織網頁時,需要遍歷紅黑樹找到IP并做流量統計。
#include <ngx_http.h>
#include <ngx_config.h>
#include <ngx_core.h>#define ENABLE_RBTREE 1static char *ngx_http_pagecount_set(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_pagecount_handler(ngx_http_request_t *r);
static ngx_int_t ngx_http_pagecount_init(ngx_conf_t *cf);
static void *ngx_http_pagecount_create_location_conf(ngx_conf_t *cf);
static ngx_int_t ngx_http_pagecount_shm_init (ngx_shm_zone_t *zone, void *data);
static void ngx_http_pagecount_rbtree_insert_value(ngx_rbtree_node_t *temp,ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel);// 命令解析
static ngx_command_t count_commands[] = {{ngx_string("count"),NGX_HTTP_LOC_CONF | NGX_CONF_NOARGS,ngx_http_pagecount_set,//遇到模塊命令時調用NGX_HTTP_LOC_CONF_OFFSET,0, NULL},ngx_null_command
};static ngx_http_module_t count_ctx = {NULL,ngx_http_pagecount_init,//初始化NULL,NULL,NULL,NULL,// conf文件解析到location時調用ngx_http_pagecount_create_location_conf,NULL,
};//ngx_http_count_module
ngx_module_t ngx_http_pagecount_module = {NGX_MODULE_V1,&count_ctx,count_commands,NGX_HTTP_MODULE,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NGX_MODULE_V1_PADDING
};typedef struct {int count; //count
} ngx_http_pagecount_node_t;typedef struct {ngx_rbtree_t rbtree;ngx_rbtree_node_t sentinel;} ngx_http_pagecount_shm_t;// 共享內存結構體
typedef struct
{ssize_t shmsize;ngx_slab_pool_t *shpool;// 互斥鎖ngx_http_pagecount_shm_t *sh;
} ngx_http_pagecount_conf_t;// 共享內存初始化
ngx_int_t ngx_http_pagecount_shm_init (ngx_shm_zone_t *zone, void *data) {ngx_http_pagecount_conf_t *conf;ngx_http_pagecount_conf_t *oconf = data;conf = (ngx_http_pagecount_conf_t*)zone->data;if (oconf) {conf->sh = oconf->sh;conf->shpool = oconf->shpool;return NGX_OK;}//printf("ngx_http_pagecount_shm_init 0000\n");// 初始化鎖conf->shpool = (ngx_slab_pool_t*)zone->shm.addr;conf->sh = ngx_slab_alloc(conf->shpool, sizeof(ngx_http_pagecount_shm_t));if (conf->sh == NULL) {return NGX_ERROR;}conf->shpool->data = conf->sh;//printf("ngx_http_pagecount_shm_init 1111\n");// 共享內存創建完之后初始化紅黑樹,// 要提供插入函數ngx_rbtree_init(&conf->sh->rbtree, &conf->sh->sentinel, ngx_http_pagecount_rbtree_insert_value);return NGX_OK;}static char *ngx_http_pagecount_set(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {ngx_shm_zone_t *shm_zone;ngx_str_t name = ngx_string("pagecount_slab_shm");ngx_http_pagecount_conf_t *mconf = (ngx_http_pagecount_conf_t*)conf;ngx_http_core_loc_conf_t *corecf;//ngx_log_error(NGX_LOG_EMERG, cf->log, ngx_errno, "ngx_http_pagecount_set000");// 設置共享內存的大小mconf->shmsize = 1024*1024;shm_zone = ngx_shared_memory_add(cf, &name, mconf->shmsize, &ngx_http_pagecount_module);if (NULL == shm_zone) {return NGX_CONF_ERROR;}shm_zone->init = ngx_http_pagecount_shm_init;shm_zone->data = mconf;corecf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);// 計數統計主函數corecf->handler = ngx_http_pagecount_handler;return NGX_CONF_OK;
}ngx_int_t ngx_http_pagecount_init(ngx_conf_t *cf) {return NGX_OK;
}// conf文件解析到location時進入此函數。
// 此函數為模塊創建所需要的結構體, 后面會使用。
void *ngx_http_pagecount_create_location_conf(ngx_conf_t *cf) {ngx_http_pagecount_conf_t *conf;// 共享內存的結構體conf = ngx_palloc(cf->pool, sizeof(ngx_http_pagecount_conf_t));if (NULL == conf) {return NULL;}// 初始化共享內存的大小conf->shmsize = 0;//ngx_log_error(NGX_LOG_EMERG, cf->log, ngx_errno, "ngx_http_pagecount_create_location_conf");// init conf data// ... return conf;}// 紅黑樹的插入函數
static void
ngx_http_pagecount_rbtree_insert_value(ngx_rbtree_node_t *temp,ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)
{ngx_rbtree_node_t **p;//ngx_http_testslab_node_t *lrn, *lrnt;for (;;){if (node->key < temp->key){p = &temp->left;}else if (node->key > temp->key) {p = &temp->right;}else{return ;}// 沒有找到,直接返回if (*p == sentinel){break;}temp = *p;}*p = node;node->parent = temp;node->left = sentinel;node->right = sentinel;ngx_rbt_red(node);
}// 查找IP和訪問計數統計
static ngx_int_t ngx_http_pagecount_lookup(ngx_http_request_t *r, ngx_http_pagecount_conf_t *conf, ngx_uint_t key) {ngx_rbtree_node_t *node, *sentinel;node = conf->sh->rbtree.root;sentinel = conf->sh->rbtree.sentinel;ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_errno, " ngx_http_pagecount_lookup 111 --> %x\n", key);while (node != sentinel) {if (key < node->key) {node = node->left;continue;} else if (key > node->key) {node = node->right;continue;} else { // key == nodenode->data ++;return NGX_OK;}}ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_errno, " ngx_http_pagecount_lookup 222 --> %x\n", key);// insert rbtreenode = ngx_slab_alloc_locked(conf->shpool, sizeof(ngx_rbtree_node_t));if (NULL == node) {return NGX_ERROR;}node->key = key;node->data = 1;ngx_rbtree_insert(&conf->sh->rbtree, node);ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_errno, " insert success\n");return NGX_OK;
}static int ngx_encode_http_page_rb(ngx_http_pagecount_conf_t *conf, char *html) {sprintf(html, "<h1>Source Insight </h1>");strcat(html, "<h2>");//ngx_rbtree_traversal(&ngx_pv_tree, ngx_pv_tree.root, ngx_http_count_rbtree_iterator, html);ngx_rbtree_node_t *node = ngx_rbtree_min(conf->sh->rbtree.root, conf->sh->rbtree.sentinel);do {char str[INET_ADDRSTRLEN] = {0};char buffer[128] = {0};sprintf(buffer, "req from : %s, count: %d <br/>",inet_ntop(AF_INET, &node->key, str, sizeof(str)), node->data);strcat(html, buffer);node = ngx_rbtree_next(&conf->sh->rbtree, node);} while (node);strcat(html, "</h2>");return NGX_OK;
}static ngx_int_t ngx_http_pagecount_handler(ngx_http_request_t *r) {u_char html[1024] = {0};int len = sizeof(html);ngx_rbtree_key_t key = 0;struct sockaddr_in *client_addr = (struct sockaddr_in*)r->connection->sockaddr;ngx_http_pagecount_conf_t *conf = ngx_http_get_module_loc_conf(r, ngx_http_pagecount_module);key = (ngx_rbtree_key_t)client_addr->sin_addr.s_addr;ngx_log_error(NGX_LOG_EMERG, r->connection->log, ngx_errno, " ngx_http_pagecount_handler --> %x\n", key);ngx_shmtx_lock(&conf->shpool->mutex);ngx_http_pagecount_lookup(r, conf, key); ngx_shmtx_unlock(&conf->shpool->mutex);ngx_encode_http_page_rb(conf, (char*)html);//headerr->headers_out.status = 200;ngx_str_set(&r->headers_out.content_type, "text/html");ngx_http_send_header(r);//bodyngx_buf_t *b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));ngx_chain_t out;out.buf = b;out.next = NULL;b->pos = html;b->last = html+len;b->memory = 1;b->last_buf = 1;return ngx_http_output_filter(r, &out);}
2.2、編寫config文件
創建:
touch config
內容:
ngx_addon_name=ngx_http_pagecount_module
HTTP_MODULES="$HTTP_MODULES ngx_http_pagecount_module"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $ngx_addon_dir/ngx_http_pagecount_module.c"
注意,config文件要和模塊的代碼在相同目錄。
2.3、編譯模塊到Nginx源碼中
(1)配置中添加模塊:
./configure --prefix=/usr/local/nginx --with-http_realip_module --with-http_addition_module
--with-http_gzip_static_module --with-http_secure_link_module --with-http_stub_status_module
--with-stream --with-pcre=/home/fly/workspace/pcre-8.41 --with-zlib=/home/fly/workspace/zlib-1.2.11
--with-openssl=/home/fly/workspace/openssl-1.1.0g
--add-module=/mnt/hgfs/sourcecode_learning/nginx-module/ngx_http_pagecount_module
注意模塊路徑要正確。出現如下表示成功:
configuring additional modules
adding module in /mnt/hgfs/sourcecode_learning/nginx-module/ngx_http_pagecount_module+ ngx_http_pagecount_module was configured
creating objs/Makefile
(2)編譯安裝:
make && sudo make install
2.4、修改conf文件
編譯安裝完成后,conf文件添加count;
worker_processes 4;events {worker_connections 1024;
}http {upstream backend {server 192.168.7.146:8889;server 192.168.7.146:8890;}server {listen 8888;location / {proxy_pass http://backend;}}server {listen 8889;location / {count;}}server {listen 8890;}server {listen 8891;}}
2.5、執行效果
關閉已啟動的nginx:
sudo /usr/local/nginx/sbin/nginx -s stop
啟動nginx:
sudo /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/fly.conf
在網頁輸入IP和端口,執行效果如下:
總結
- 實現一個基于Nginx的IP統計或訪問流量統計,可以借鑒以上代碼;只要做一些業務上的修改就可以直接使用。可能需改動的地方就是紅黑樹的key、value的數據結構,以及ngx_encode_http_page_rb函數的業務代碼,其他可以基本不用改動就可以二次開發。
- Nginx需要熟悉的數據結構:內存池、queue、list、array、shmem等。同時需要清楚Nginx的11個狀態。
- 在實際應用中,需要掌握Nginx的conf文件配置(https的配置、負載均衡的配置、反向代理、CPU親緣性配置等)以及模塊開發(filter、handler等)。