Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6362183
  • 博文数量: 579
  • 博客积分: 1548
  • 博客等级: 上尉
  • 技术积分: 16634
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-12 15:29
个人简介

http://www.csdn.net/ http://www.arm.com/zh/ https://www.kernel.org/ http://www.linuxpk.com/ http://www.51develop.net/ http://linux.chinaitlab.com/ http://www.embeddedlinux.org.cn http://bbs.pediy.com/

文章分类

全部博文(579)

文章存档

2018年(18)

2015年(91)

2014年(159)

2013年(231)

2012年(80)

分类: 嵌入式

2014-09-10 17:54:52

100万并发连接服务器笔记之准备篇

前言

测试一个非常简单服务器如何达到100万(1M=1024K连接)的并发连接,并且这些连接一旦连接上服务器,就不会断开,一直连着。 
环境受限,没有服务器,刚开始都是在自己的DELL笔记本上测试,凭借16G内存,和优秀的vmware workstation虚拟机配合,另外还得外借别人虚拟机使用,最终还得搭上两台2G内存的台式机(安装centos),最终才完成1M并发连接任务。

  • 测试程序也很简陋,一个C语言所写服务器程序,没有任何业务存在,收到请求后发送一些头部,不断开连接
  • 测试端程序也是使用C语言所写,发送请求,然后等待接收数据,仅此而已
  • 服务器端/测试端内存都受限(8G不够使用),要想完成1024K的目标,需要放弃一些东西,诸如业务不是那么完整
  • 一台分配10G内存Centos服务器,两台分配6G内存Centos测试端,两台2G内存Centos测试端
  • 假如热心的您可以提供丰富的服务器资源,那就再好不过了。
  • 理论上200万的并发连接(IO密集型),加上业务,40G-50G的内存大概能够保证

说明

以前也做过类似的工作,量不大,没记录下来,一些压力测试和调优,随着时间流逝,早已忘记。这次是从零开始,基本上所有过程都会记录,一步一步,每一步都会遇到问题,并且给出相关解决问题的方法,最终完成目标。 
为了方便,服务器端程序和客户端测试程序,都是使用C语言,不用像JAVA一样需要预先指定内存,感觉麻烦。使用较为原始的语言来写,可以避免不必要的调优工作。这中间,可能会穿插Java代码的思考方式。

可能需要懂点Linux,C,Java,假如您有更好的做法,或者建议,请直接告知,谢谢。

Linux系统

测试端和服务器端都选用较为熟悉的64位Centos 6.4,32位系统最多支持4G内存,太受限。IO密集型应用,对CPU要求不是很高。另外服务器确保安装上gcc,那就可以开工了。 
所有端系统一旦安装完之后,默认不做任何设置。

服务器端程序

服务器端程序依赖框架,需要提前编译,然后存放到相应位置。下面是具体服务器端代码:   

点击(此处)折叠或打开

  1. #include <arpa/inet.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <fcntl.h>
  6. #include <errno.h>
  7. #include <err.h>
  8.   
  9. #include <unistd.h>
  10.   
  11. #include "../include/ev.h"
  12.   
  13. #define HTMLFILE_RESPONSE_HEADER \
  14.     "HTTP/1.1 200 OK\r\n" \
  15.     "Connection: keep-alive\r\n" \
  16.     "Content-Type: text/html; charset=utf-8\r\n" \
  17.     "Transfer-Encoding: chunked\r\n" \
  18.     "\r\n"
  19. #define HTMLFILE_RESPONSE_FIRST \
  20.     "htmlfile chunked example
    div\">
"

点击(此处)折叠或打开

  1. static int server_port = 8000;
  2.   
  3. struct ev_loop *loop;
  4. typedef struct {
  5.     int fd;
  6.     ev_io ev_read;
  7. } client_t;
  8.   
  9. ev_io ev_accept;
  10.   
  11. static int usr_num;
  12. static void incr_usr_num() {
  13.     usr_num ++;
  14.     printf("online user %d\n", usr_num);
  15. }
  16.   
  17. static void dec_usr_num() {
  18.     usr_num --;
  19.   
  20.     printf("~online user %d\n", usr_num);
  21. }
  22.   
  23. static void free_res(struct ev_loop *loop, ev_io *ws);
  24.   
  25. int setnonblock(int fd) {
  26.     int flags = fcntl(fd, F_GETFL);
  27.     if (flags < 0)
  28.         return flags;
  29.   
  30.     flags |= O_NONBLOCK;
  31.     if (fcntl(fd, F_SETFL, flags) < 0)
  32.         return -1;
  33.   
  34.     return 0;
  35. }
  36.   
  37. static int format_message(const char *ori_message, char *target_message) {
  38.     return sprintf(target_message, "%X\r\n\r\n", ((int)strlen(ori_message) + 23), ori_message);
  39. }
  40.   
  41. static void write_ori(client_t *client, char *msg) {
  42.     if (client == NULL) {
  43.         fprintf(stderr, "the client is NULL !\n");
  44.         return;
  45.     }
  46.   
  47.     write(client->fd, msg, strlen(msg));
  48. }
  49.   
  50. static void write_body(client_t *client, char *msg) {
  51.     char body_msg[strlen(msg) + 100];
  52.     format_message(msg, body_msg);
  53.   
  54.     write_ori(client, body_msg);
  55. }
  56.   
  57. static void read_cb(struct ev_loop *loop, ev_io *w, int revents) {
  58.     client_t *client = w->data;
  59.     int r = 0;
  60.     char rbuff[1024];
  61.     if (revents & EV_READ) {
  62.         r = read(client->fd, &rbuff, 1024);
  63.     }
  64.   
  65.     if (EV_ERROR & revents) {
  66.         fprintf(stderr, "error event in read\n");
  67.         free_res(loop, w);
  68.         return ;
  69.     }
  70.   
  71.     if (r < 0) {
  72.         fprintf(stderr, "read error\n");
  73.         ev_io_stop(EV_A_ w);
  74.         free_res(loop, w);
  75.         return;
  76.     }
  77.   
  78.     if (r == 0) {
  79.         fprintf(stderr, "client disconnected.\n");
  80.         ev_io_stop(EV_A_ w);
  81.         free_res(loop, w);
  82.         return;
  83.     }
  84.   
  85.     write_ori(client, HTMLFILE_RESPONSE_HEADER);
  86.   
  87.     char target_message[strlen(HTMLFILE_RESPONSE_FIRST) + 20];
  88.     sprintf(target_message, "%X\r\n%s\r\n", (int)strlen(HTMLFILE_RESPONSE_FIRST), HTMLFILE_RESPONSE_FIRST);
  89.   
  90.     write_ori(client, target_message);
  91.     incr_usr_num();
  92. }
  93.   
  94. static void accept_cb(struct ev_loop *loop, ev_io *w, int revents) {
  95.     struct sockaddr_in client_addr;
  96.     socklen_t client_len = sizeof(client_addr);
  97.     int client_fd = accept(w->fd, (struct sockaddr *) &client_addr, &client_len);
  98.     if (client_fd == -1) {
  99.         fprintf(stderr, "the client_fd is NULL !\n");
  100.         return;
  101.     }
  102.   
  103.     client_t *client = malloc(sizeof(client_t));
  104.     client->fd = client_fd;
  105.     if (setnonblock(client->fd) < 0)
  106.         err(1, "failed to set client socket to non-blocking");
  107.   
  108.     client->ev_read.data = client;
  109.   
  110.     ev_io_init(&client->ev_read, read_cb, client->fd, EV_READ);
  111.     ev_io_start(loop, &client->ev_read);
  112. }
  113.   
  114. int main(int argc, char const *argv[]) {
  115.     int ch;
  116.     while ((ch = getopt(argc, argv, "p:")) != -1) {
  117.         switch (ch) {
  118.         case 'p':
  119.             server_port = atoi(optarg);
  120.             break;
  121.         }
  122.     }
  123.   
  124.     printf("start free -m is \n");
  125.     system("free -m");
  126.     loop = ev_default_loop(0);
  127.     struct sockaddr_in listen_addr;
  128.     int reuseaddr_on = 1;
  129.     int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
  130.     if (listen_fd < 0)
  131.         err(1, "listen failed");
  132.     if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_on, sizeof(reuseaddr_on)) == -1)
  133.         err(1, "setsockopt failed");
  134.   
  135.     memset(&listen_addr, 0, sizeof(listen_addr));
  136.     listen_addr.sin_family = AF_INET;
  137.     listen_addr.sin_addr.s_addr = INADDR_ANY;
  138.     listen_addr.sin_port = htons(server_port);
  139.   
  140.     if (bind(listen_fd, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) < 0)
  141.         err(1, "bind failed");
  142.     if (listen(listen_fd, 5) < 0)
  143.         err(1, "listen failed");
  144.     if (setnonblock(listen_fd) < 0)
  145.         err(1, "failed to set server socket to non-blocking");
  146.   
  147.     ev_io_init(&ev_accept, accept_cb, listen_fd, EV_READ);
  148.     ev_io_start(loop, &ev_accept);
  149.     ev_loop(loop, 0);
  150.   
  151.     return 0;
  152. }
  153.   
  154. static void free_res(struct ev_loop *loop, ev_io *w) {
  155.     dec_usr_num();
  156.     client_t *client = w->data;
  157.     if (client == NULL) {
  158.         fprintf(stderr, "the client is NULL !!!!!!");
  159.         return;
  160.     }
  161.   
  162.     ev_io_stop(loop, &client->ev_read);
  163.   
  164.     close(client->fd);
  165.   
  166.     free(client);
  167. }



编译
    gcc server.c -o server ../include/libev.a -lm

运行
    ./server -p 8000

在源码中默认指定了8000端口,可以通过-p进行指定新的端口。 开启了8000端口进行监听请求,http协议处理类似于htmlfile chunked块编码传输。

测试服务器端程序

测试程序使用libevent框架,因其使用简单,提供丰富易用接口,但需要提前下载,手动安装:

wget 
tar xvf libevent-2.0.21-stable.tar.gz
cd libevent-2.0.21-stable
./configure --prefix=/usr
make
make install

注意make和make install需要root用户。

测试端程序

client1.c 源码:

?

点击(此处)折叠或打开

  1. #include <sys/types.h>
  2. #include <sys/time.h>
  3. #include <sys/queue.h>
  4. #include <stdlib.h>
  5. #include <err.h>
  6. #include <event.h>
  7. #include <evhttp.h>
  8. #include <unistd.h>
  9. #include <stdio.h>
  10. #include <sys/socket.h>
  11. #include <netinet/in.h>
  12. #include <time.h>
  13. #include <pthread.h>
  14.   
  15. #define BUFSIZE 4096
  16. #define NUMCONNS 62000
  17. #define SERVERADDR "192.168.190.133"
  18. #define SERVERPORT 8000
  19. #define SLEEP_MS 10
  20.   
  21. char buf[BUFSIZE];
  22.   
  23. int bytes_recvd = 0;
  24. int chunks_recvd = 0;
  25. int closed = 0;
  26. int connected = 0;
  27.   
  28. void chunkcb(struct evhttp_request *req, void *arg) {
  29.     int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
  30.     bytes_recvd += s;
  31.     chunks_recvd++;
  32.     if (connected >= NUMCONNS && chunks_recvd % 10000 == 0)
  33.         printf(">Chunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
  34. }
  35.   
  36. void reqcb(struct evhttp_request *req, void *arg) {
  37.     closed++;
  38. }
  39.   
  40. int main(int argc, char **argv) {
  41.     event_init();
  42.     struct evhttp *evhttp_connection;
  43.     struct evhttp_request *evhttp_request;
  44.     char path[32]; // eg: "/test/123"
  45.     int i;
  46.     for (i = 1; i <= NUMCONNS; i++) {
  47.         evhttp_connection = evhttp_connection_new(SERVERADDR, SERVERPORT);
  48.         evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
  49.         evhttp_request = evhttp_request_new(reqcb, NULL);
  50.         evhttp_request->chunk_cb = chunkcb;
  51.         sprintf(&path, "/test/%d", ++connected);
  52.         if (i % 100 == 0) printf("Req: %s\t->\t%s\n", SERVERADDR, &path);
  53.         evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
  54.         evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
  55.         event_loop( EVLOOP_NONBLOCK );
  56.         if ( connected % 200 == 0 )
  57.             printf("\nChunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
  58.         usleep(SLEEP_MS * 1000);
  59.     }
  60.   
  61.     event_dispatch();
  62.     return 0;
  63. }


备注:这部分代码参考了 ,根据需要有所修改。

编译

gcc -o client1 client1.c -levent

运行

./client1

可能在64位系统会遇到找不到libevent-2.0.so.5情况,需要建立一个软连接

ln -s /usr/lib/libevent-2.0.so.5 /lib64/libevent-2.0.so.5

即可自动连接IP地址为192.168.190.133:8000的服务器端应用。

第一个遇到的问题:文件句柄受限

测试端程序输出

看看测试端程序client1输出的错误信息:

Chunks: 798 Bytes: 402990 Closed: 0
Req: 192.168.190.133 -/test/900
Req: 192.168.190.133 -/test/1000
Chunks: 998 Bytes: 503990 Closed: 0
[warn] socket: Too many open files
[warn] socket: Too many open files
[warn] socket: Too many open files

服务器端程序输出

服务器端最后一条日志为

online user 1018

两边都遇到了文件句柄打开的情况。 
在服务器端查看已经连接,并且端口号为8000的所有连接数量:

netstat -nat|grep -i "8000"|wc -l 
1019

但与服务器端输出数量对不上,增加所有已经建立连接的选项:

netstat -nat|grep -i "8000"|grep ESTABLISHED|wc -l 
1018

那么剩下的一条数据到底是什么呢?

netstat -nat|grep -i "8000"|grep -v ESTABLISHED
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN

也就是server.c监听的端口,数量上对的上。

在测试服务器端,查看测试进程打开的文件句柄数量

lsof -n|grep client1|wc -l
1032

再次执行

ulimit -n
1024

也是就是client1应用程序共打开了1032个文件句柄,而不是1024,为什么? 
把当前进程所有打开的文件句柄保存到文件中,慢慢研究 lsof -n|grep client1 > testconnfinfo.txt

导出的文件可以参考: 
除了第一行,我特意添加上供友善阅读的头部列定义,也就是1032行信息,但是需要注意头部:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
client1 3088 yongboy cwd DIR 253,0 4096 800747 /home/yongboy/workspace/c_socket.io_server/test
client1 3088 yongboy rtd DIR 253,0 4096 2 /test_conn
client1 3088 yongboy txt REG 253,0 9697 799991 /home/yongboy/workspace/c_socket.io_server/test/test_conn_1
client1 3088 yongboy mem REG 253,0 156872 50404 /lib64/ld-2.12.so
client1 3088 yongboy mem REG 253,0 1922152 78887 /lib64/libc-2.12.so
client1 3088 yongboy mem REG 253,0 145720 76555 /lib64/libpthread-2.12.so
client1 3088 yongboy mem REG 253,0 47064 69491 /lib64/librt-2.12.so
client1 3088 yongboy mem REG 253,0 968730 26292 /usr/lib/libevent-2.0.so.5.1.9
client1 3088 yongboy 0u CHR 136,2 0t0 5 /dev/pts/2
client1 3088 yongboy 1u CHR 136,2 0t0 5 /dev/pts/2
client1 3088 yongboy 2u CHR 136,2 0t0 5 /dev/pts/2
client1 3088 yongboy 3u REG 0,9 0 4032 anon_inode
client1 3088 yongboy 4u unix 0xffff88007c82f3c0 0t0 79883 socket
client1 3088 yongboy 5u unix 0xffff880037c34380 0t0 79884 socket
client1 3088 yongboy 6u IPv4 79885 0t0 TCP 192.168.190.134:58693->192.168.190.133:irdmi (ESTABLISHED)
client1 3088 yongboy 7u IPv4 79889 0t0 TCP 192.168.190.134:58694->192.168.190.133:irdmi (ESTABLISHED)
client1 3088 yongboy 8u IPv4 79891 0t0 TCP 192.168.190.134:58695->192.168.190.133:irdmi (ESTABLISHED)
client1 3088 yongboy 9u IPv4 79893 0t0 TCP 192.168.190.134:58696->192.168.190.133:irdmi (ESTABLISHED)

可以看到文件句柄是从0u开始,0u上面的8个(5个mem + 3个启动)进程,1032 - 8 = 1024个文件句柄,这样就和系统限制的值吻合了。

root用户编辑/etc/security/limits.conf文件添加:

* soft nofile 1048576
* hard nofile 1048576
  • soft是一个警告值,而hard则是一个真正意义的阀值,超过就会报错。
  • soft 指的是当前系统生效的设置值。hard 表明系统中所能设定的最大值
  • nofile - 打开文件的最大数目
  • 星号表示针对所有用户,若仅针对某个用户登录ID,请替换星号

注意: 
1024K x 1024 = 1048576K = 1M,1百万多一点。

备注:测试端和服务器端都需要作此设置,保存退出,然后reboot即可生效。

第一个问题,就这样克服了。再次运行 /client1测试程序,就不会出现受打开文件句柄的限制。但大概在测试端打开对外28200个端口时,会出现程序异常,直接退出。

段错误

这个也是程序没有处理端口不够用的异常,但可以通过增加端口进行解决。

备注: 但测试端单机最多只能打开6万多个连接,是一个问题,如何克服,下一篇解决此问题,并且还会遇到文件句柄的受限问题。




100万并发连接服务器笔记之处理端口数量受限问题

第二个遇到的问题:端口数量受限

一般来说,单独对外提供请求的服务不用考虑端口数量问题,监听某一个端口即可。但是向提供代理服务器,就不得不考虑端口数量受限问题了。当前的1M并发连接测试,也需要在客户端突破6万可用端口的限制。

单机端口上限为65536

端口为16进制,那么2的16次方值为65536,在linux系统里面,1024以下端口都是超级管理员用户(如root)才可以使用,普通用户只能使用大于1024的端口值。 
系统提供了默认的端口范围:

cat /proc/sys/net/ipv4/iplocalport_range 
32768 61000

大概也就是共61000-32768=28232个端口可以使用,单个IP对外只能发送28232个TCP请求。 
以管理员身份,把端口的范围区间增到最大:

echo "1024 65535"> /proc/sys/net/ipv4/iplocalport_range

现在有64511个端口可用. 
以上做法只是临时,系统下次重启,会还原。 更为稳妥的做法是修改/etc/sysctl.conf文件,增加一行内容

net.ipv4.iplocalport_range = 1024 65535

保存,然后使之生效:

sysctl -p

现在可以使用的端口达到64510个(假设系统所有运行的服务器是没有占用大于1024的端口的,较为纯净的centos系统可以做到),要想达到50万请求,还得再想办法。

增加IP地址

一般假设本机网卡名称为 eth0,那么手动再添加几个虚拟的IP:

ifconfig eth0:1 192.168.190.151 
ifconfig eth0:2 192.168.190.152 ......

或者偷懒一些:

for i in `seq 1 9`; do ifconfig eth0:$i 192.168.190.15$i up ; done

这些虚拟的IP地址,一旦重启,或者 service network restart 就会丢失。

为了模拟较为真实环境,在测试端,手动再次添加9个vmware虚拟机网卡,每一个网卡固定一个IP地址,这样省去每次重启都要重新设置的麻烦。

192.168.190.134 
192.168.190.143
192.168.190.144
192.168.190.145
192.168.190.146
192.168.190.147
192.168.190.148
192.168.190.149
192.168.190.150
192.168.190.151

在server服务器端,手动添加桥接网卡和NAT方式网卡

192.168.190.230
192.168.190.240
10.95.20.250

要求测试端和服务器端彼此双方都是可以ping通。

网络四元组/网络五元组

四元组是指的是

{源IP地址,源端口,目的IP地址,目的端口}

五元组指的是(多了协议)

{源IP地址,目的IP地址,协议号,源端口,目的端口}

在《UNIX网络编程卷1:套接字联网API(第3版)》一书中,是这样解释:
一个TCP连接的套接字对(socket pari)是一个定义该连接的两个端点的四元组,即本地IP地址、本地TCP端口号、外地IP地址、外地TCP端口号。套接字对唯一标识一个网络上的每个TCP连接。  

......  

标识每个端点的两个值(IP地址和端口号)通常称为一个套接字。

以下以四元组为准。在测试端四元组可以这样认为:

{本机IP地址,本机端口,目的IP地址,目的端口}

请求的IP地址和目的端口基本上是固定的,不会变化,那么只能从本机IP地址和本机端口上考虑,端口的范围一旦指定了,那么增加IP地址,可以增加对外发出的请求数量。假设系统可以使用的端口范围已经如上所设,那么可以使用的大致端口为64000个,系统添加了10个IP地址,那么可以对外发出的数量为 64000 * 10 = 640000,数量很可观。

只有{源IP地址,源端口}确定对外TCP请求数量

经测试,四元组里面,只有{源IP地址,源端口}才能够确定对外发出请求的数量,跟{目的IP地址,目的端口}无关。

测试环境

在server端,并且启动./server两次,分别绑定8000端口和9000端口

./server -p 8000
./server -p 9000

本机IP、端口绑定测试程序

这里写一个简单的测试绑定本机IP地址和指定端口的客户端测试程序。?

点击(此处)折叠或打开

  1. #include <sys/types.h>
  2. #include <sys/time.h>
  3. #include <sys/queue.h>
  4. #include <stdlib.h>
  5. #include <err.h>
  6. #include <event.h>
  7. #include <evhttp.h>
  8. #include <unistd.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <time.h>
  14. #include <pthread.h>
  15. #include <errno.h>
  16.   
  17. #define BUFSIZE 4096
  18. #define SLEEP_MS 10
  19.   
  20. char buf[BUFSIZE];
  21.   
  22. int bytes_recvd = 0;
  23. int chunks_recvd = 0;
  24.   
  25. void chunkcb(struct evhttp_request *req, void *arg) {
  26.     int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
  27.     bytes_recvd += s;
  28.     chunks_recvd++;
  29.     printf(">Chunks: %d\tBytes: %d\n", chunks_recvd, bytes_recvd);
  30. }
  31.   
  32. void reqcb(struct evhttp_request *req, void *arg) {
  33.     fprintf(stderr, ">Now closed\n");
  34.     exit(-1);
  35. }
  36.   
  37. void err_cb(int err){
  38.     fprintf(stderr, "setup failed(errno = %d): %s", errno, strerror(errno));
  39. }
  40.   
  41. int main(int argc, char **argv) {
  42.     char server_ip[16] = "";
  43.     int server_port = 0;
  44.   
  45.     char local_ip[16] = "";
  46.     int local_port = 0;
  47.   
  48.     int ch;
  49.     while ((ch = getopt(argc, argv, "h:p:c:o:")) != -1) {
  50.         switch (ch) {
  51.         case 'h':
  52.             printf("remote host is %s\n", optarg);
  53.             strncpy(server_ip, optarg, 15);
  54.             break;
  55.         case 'p':
  56.             printf("remote port is %s\n", optarg);
  57.             server_port = atoi(optarg);
  58.             break;
  59.         case 'c':
  60.             printf("local ip is %s\n", optarg);
  61.             strncpy(local_ip, optarg, 15);
  62.             break;
  63.         case 'o':
  64.             printf("local port is %s\n", optarg);
  65.             local_port = atoi(optarg);
  66.   
  67.             break;
  68.         }
  69.     }
  70.   
  71.     event_init();
  72.     event_set_fatal_callback(err_cb);
  73.     struct evhttp *evhttp_connection;
  74.     struct evhttp_request *evhttp_request;
  75.     char path[32];
  76.   
  77.     evhttp_connection = evhttp_connection_new(server_ip, server_port);
  78.     evhttp_connection_set_local_address(evhttp_connection, local_ip);
  79.     evhttp_connection_set_local_port(evhttp_connection, local_port);
  80.     evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
  81.     evhttp_request = evhttp_request_new(reqcb, NULL);
  82.     evhttp_request->chunk_cb = chunkcb;
  83.     sprintf(&path, "/test/%d", local_port);
  84.   
  85.     evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
  86.     evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
  87.     event_loop( EVLOOP_NONBLOCK );
  88.   
  89.     usleep(SLEEP_MS * 10);
  90.   
  91.     event_dispatch();
  92.   
  93.     return 0;
  94. }


可以看到libevent-*/include/event2/http.h内置了对绑定本地IP地址的支持:

/** sets the ip address from which http connections are made */
void evhttp_connection_set_local_address(struct evhttp_connection *evcon,
const char *address);

不用担心端口,系统自动自动随机挑选,除非需要特别指定:

/** sets the local port from which http connections are made */
void evhttp_connection_set_local_port(struct evhttp_connection *evcon,
ev_uint16_t port);

编译

gcc -o client3 client3.c -levent

client3运行参数为

  • -h 远程主机IP地址
  • -p 远程主机端口
  • -c 本机指定的IP地址(必须可用)
  • -o 本机指定的端口(必须可用)

测试用例,本机指定同样的IP地址和端口,但远程主机和IP不一样. 
在一个测试端打开一个终端窗口1,切换到 client3对应位置

./client3 -h 192.168.190.230 -p 8000 -c 192.168.190.148 -o 4000

输出为

remote host is 192.168.190.230
remote port is 8000
local ip is 192.168.190.148
local port is 4000
>Chunks: 1 Bytes: 505

再打开一个测试端终端窗口2,执行:

./client3 -h 192.168.190.240 -p 9000 -c 192.168.190.148 -o 4000

窗口2程序,无法执行,自动退出。 
接着在窗口2终端继续输入:

./client3 -h 192.168.190.230 -p 8000 -c 192.168.190.148 -o 4001

注意,和窗口1相比,仅仅改变了端口号为4001。但执行结果,和端口1输出一模一样,在等待接收数据,没有自动退出。

剩下的,无论怎么组合,怎么折腾,只要一对{本机IP,本机端口}被占用,也就意味着对应一个具体的文件句柄,那么其它程序将不能够再次使用。

Java怎么绑定本地IP地址?

java绑定就很简单,但有些限制,不够灵活,单纯从源码中看不出来,api doc可以告诉我们一些事情。 打开JDKAPI1_6zhCN.CHM,查看InetSocketAddress类的构造函数说明:

public InetSocketAddress(InetAddress addr, int port) 
根据 IP 地址和端口号创建套接字地址。 有效端口值介于 0 和 65535 之间。端口号 zero 允许系统在 bind 操作中挑选暂时的端口。

null 地址将分配通配符 地址。

参数: 
addr - IP 地址 
port - 端口号 
抛出: 
IllegalArgumentException - 如果 port 参数超出有效端口值的指定范围。

public InetSocketAddress(String hostname, int port) 
根据主机名和端口号创建套接字地址。 
尝试将主机名解析为 InetAddress。如果尝试失败,则将地址标记为未解析。

如果存在安全管理器,则将主机名用作参数调用其 checkConnect 方法,以检查解析它的权限。这可能会导致 SecurityException 异常。

有效端口值介于 0 和 65535 之间。端口号 zero 允许系统在 bind 操作中挑选暂时的端口。

参数: hostname - 主机名 
port - 端口号 
抛出: 
IllegalArgumentException - 如果 port 参数超出有效端口值的范围,或者主机名参数为 null。 
SecurityException - 如果存在安全管理器,但拒绝解析主机名的权限。 
另请参见: 
isUnresolved()

InetSocketAddress的两个构造函数都支持,看情况使用。注意int port传递值为0,即可做到系统随机挑选端口。追踪一下源代码,发现最终调用

private native void socketBind(InetAddress address, int port) throws IOException;

如何查看socketBind的原始C代码,我就不清楚了,您若知晓,希望指教一下。 构造一个InetSocketAddress对象:

SocketAddress localSocketAddr = new InetSocketAddress("192.168.190.143", 0);

然后传递给需要位置即可。诸如使用netty连接到某个服务器上,在connect时指定远方地址,以及本机地址

ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) Attempts a new connection with the specified remoteAddress and the specified localAddress.

Netty 客户端连接API见: 

Linux支持绑定本机IP、端口原理

说是原理,有些牵强,因为linux C提供了如何绑定函数,框架或者高级语言再怎么封装,在linux平台下面,需要这么调用:

struct sockaddr_in clnt_addr;
....
clnt_addr.sin_family = AF_INET;
clnt_addr.sin_addr.s_addr = INADDR_ANY; //绑定本机IP地址
clnt_addr.sin_port = htons(33333); //绑定本机端口
if (bind(sockfd, (struct sockaddr *) &clnt_addr,
sizeof(clnt_addr)) < 0) error("ERROR on binding");
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting");
.......

构造一个clnt_addr结构体,本地IP或者端口赋值,在connect之前,先bind,就这么简单。

更完整例子,可以参考 

有关端口的更详细解释,请参考《UNIX网络编程卷1:套接字联网API(第3版)》2.9节 端口号部分。

 

有关端口的问题,到此为止,下一篇,回到测试。



100万并发连接服务器笔记之测试端就绪

重新编写测试端程序

测试端程序需要增加绑定本机IP和本地端口的功能,以尽可能的向外发出更多的tcp请求。需要对重构,增加参数传递。 下面是client2.c的代码?

点击(此处)折叠或打开

  1. #include <sys/types.h>
  2. #include <sys/time.h>
  3. #include <sys/queue.h>
  4. #include <stdlib.h>
  5. #include <err.h>
  6. #include <event.h>
  7. #include <evhttp.h>
  8. #include <unistd.h>
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <time.h>
  14. #include <pthread.h>
  15.   
  16. #define BUFSIZE 4096
  17. #define SLEEP_MS 10
  18.   
  19. char buf[BUFSIZE];
  20.   
  21. int bytes_recvd = 0;
  22. int chunks_recvd = 0;
  23. int closed = 0;
  24. int connected = 0;
  25.   
  26. static char ip_array[300] = "192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.151,192.168.190.152";
  27. static char server_ip[16] = "192.168.190.133";
  28. static int server_port = 8000;
  29. static int max_conns = 62000;
  30.   
  31. // called per chunk received
  32. void chunkcb(struct evhttp_request *req, void *arg) {
  33.     int s = evbuffer_remove( req->input_buffer, &buf, BUFSIZE );
  34.     bytes_recvd += s;
  35.     chunks_recvd++;
  36.     if (connected >= max_conns && chunks_recvd % 10000 == 0)
  37.         printf(">Chunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
  38. }
  39.   
  40. // gets called when request completes
  41. void reqcb(struct evhttp_request *req, void *arg) {
  42.     closed++;
  43. }
  44.   
  45. int main(int argc, char **argv) {
  46.     int ch;
  47.     while ((ch = getopt(argc, argv, "o:h:p:m:")) != -1) {
  48.         switch (ch) {
  49.         case 'h':
  50.             printf("host is %s\n", optarg);
  51.             strncpy(server_ip, optarg, 15);
  52.             break;
  53.         case 'p':
  54.             printf("port is %s\n", optarg);
  55.             server_port = atoi(optarg);
  56.             /*strncpy(server_ip, optarg, 15);*/
  57.             break;
  58.         case 'm':
  59.             printf("max_conns is %s\n", optarg);
  60.             max_conns = atoi(optarg);
  61.             /*strncpy(server_ip, optarg, 15);*/
  62.             break;
  63.         case 'o':
  64.             printf("ori_ips is %s\n", optarg);
  65.   
  66.             strncpy(ip_array, optarg, 300 - 1);
  67.             break;
  68.         }
  69.     }
  70.   
  71.     event_init();
  72.     struct evhttp *evhttp_connection;
  73.     struct evhttp_request *evhttp_request;
  74.     char path[32];
  75.     int i;
  76.   
  77.     char delims[] = ",";
  78.     char *ori_ip = NULL;
  79.     ori_ip = strtok( ip_array, delims );
  80.     while (ori_ip != NULL) {
  81.         for (i = 1; i <= max_conns; i++) {
  82.             evhttp_connection = evhttp_connection_new(server_ip, server_port);
  83.             evhttp_connection_set_local_address(evhttp_connection, ori_ip);
  84.             evhttp_set_timeout(evhttp_connection, 864000); // 10 day timeout
  85.             evhttp_request = evhttp_request_new(reqcb, NULL);
  86.             evhttp_request->chunk_cb = chunkcb;
  87.             sprintf(&path, "/test/%d", ++connected);
  88.   
  89.             if (i % 1000 == 0)
  90.                 printf("Req: %s\t->\t%s\n", ori_ip, &path);
  91.   
  92.             evhttp_make_request( evhttp_connection, evhttp_request, EVHTTP_REQ_GET, path );
  93.             evhttp_connection_set_timeout(evhttp_request->evcon, 864000);
  94.             event_loop( EVLOOP_NONBLOCK );
  95.   
  96.             if ( connected % 1000 == 0 )
  97.                 printf("\nChunks: %d\tBytes: %d\tClosed: %d\n", chunks_recvd, bytes_recvd, closed);
  98.   
  99.             usleep(SLEEP_MS * 10);
  100.         }
  101.   
  102.         ori_ip = strtok( NULL, delims );
  103.     }
  104.   
  105.     event_dispatch();
  106.   
  107.     return 0;
  108. }


若不指定端口,系统会随机挑选没有使用到的端口,可以节省些心力。

编译:

gcc -o client2 client2.c -levent

参数解释

  • -h 要连接的服务器IP地址
  • -p 要连接的服务器端口
  • -m 本机IP地址需要绑定的随机端口数量
  • -o 本机所有可用的IP地址列表,注意所有IP地址都应该可用

运行:

./client2 -h 192.168.190.230 -p 8000 -m 64000 -o 192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.150,192.168.190.151

太长了,每次执行都要粘贴过去,直接放在一个client2.sh文件中,执行就很简单方便多了。

#!/bin/sh
./client2 -h 192.168.190.230 -p 8000 -m 64000 -o 192.168.190.134,192.168.190.143,192.168.190.144,192.168.190.145,192.168.190.146,192.168.190.147,192.168.190.148,192.168.190.149,192.168.190.150,192.168.190.151

保存,赋值可运行:

chmod +x client2.sh

启动测试:

sh client2.sh

第三个遇到的问题:fs.file-max的问题

测试端程序client2.c在发出的数量大于某个值(大概为40万时)是,通过dmesg命令查看会得到大量警告信息:

[warn] socket: Too many open files in system

此时,就需要检查/proc/sys/fs/file-max参数了。

查看一下系统对fs.file-max的说明

/proc/sys/fs/file-max
This file defines a system-wide limit on the number of open files for all processes. (See also setrlimit(2), which can be used by a process to set the per-process limit,
RLIMIT_NOFILE, on the number of files it may open.) If you get lots of error messages about running out of file handles, try increasing this value:
echo 100000 > /proc/sys/fs/file-max
The kernel constant NR_OPEN imposes an upper limit on the value that may be placed in file-max.
If you increase /proc/sys/fs/file-max, be sure to increase /proc/sys/fs/inode-max to 3-4 times the new value of /proc/sys/fs/file-max, or you will run out of inodes.

file-max表示系统所有进程最多允许同时打开所有的文件句柄数,系统级硬限制。Linux系统在启动时根据系统硬件资源状况计算出来的最佳的最大同时打开文件数限制,如果没有特殊需要,不用修改,除非打开的文件句柄数超过此值。

在为测试机分配4G内存时,对应的fs.file-max值为386562,很显然打开的文件句柄很受限,38万个左右。 很显然,无论是测试端还是服务端,都应该将此值调大些,一定要大于等于/etc/security/limits.conf送所设置的soft nofile和soft nofile值。 
注意ulimit -n,仅仅设置当前shell以及由它启动的进程的资源限制。

备注:以上参数,具有包含和被包含的关系。

当前会话修改,可以这么做:

echo 1048576 > /proc/sys/fs/file-max

但系统重启后消失。

永久修改,要添加到 /etc/sysctl.conf 文件中:

fs.file-max = 1048576

保存并使之生效:

sysctl -p

再测,就不会出现此问题了。

一台6G内存机器测试机,分配7个网卡,可以做到不占用虚拟内存,对外发出64000 * 7 = 448000个对外持久请求。要完成100万的持久连接,还得再想办法。

最终测试端组成如下:

  • 两台物理机器各自一个网卡,每个发出64000个请求
  • 两个6G左右的centos测试端机器(绑定7个桥接或NAT连接)各自发出64000*7 = 448000请求
  • 共使用了16个网卡(物理网卡+虚拟网卡)
  • 1M ≈ 1024K ≈ 1024000 = (64000) + (64000) + (64000*7) + (64000*7)
  • 共耗费16G内存,16个网卡(物理+虚拟),四台测试机

备注: 
下面就要完成1M持久连接的目标,但在服务端还会遇到最后一个问题。



100万并发连接服务器笔记之1M并发连接目标达成

第四个遇到的问题:tcp_mem

在服务端,连接达到一定数量,诸如50W时,有些隐藏很深的问题,就不断的抛出来。 通过查看dmesg命令查看,发现大量TCP: too many of orphaned sockets错误,也很正常,下面到了需要调整tcp socket参数的时候了。

第一个需要调整的是tcp_rmem,即TCP读取缓冲区,单位为字节,查看默认值

cat /proc/sys/net/ipv4/tcp_rmem
4096 87380 4161536

默认值为87380bit ≈ 86K,最小为4096bit=4K,最大值为4064K。

第二个需要调整的是tcp_wmem,发送缓冲区,单位是字节,默认值

cat /proc/sys/net/ipv4/tcp_wmem
4096 16384 4161536

解释同上

第三个需要调整的tcp_mem,调整TCP的内存大小,其单位是页,1页等于4096字节。系统默认值:

cat /proc/sys/net/ipv4/tcp_mem
932448 1243264 1864896

tcp_mem(3个INTEGER变量):low, pressure, high

  • low:当TCP使用了低于该值的内存页面数时,TCP不会考虑释放内存。
  • pressure:当TCP使用了超过该值的内存页面数量时,TCP试图稳定其内存使用,进入pressure模式,当内存消耗低于low值时则退出pressure状态。
  • high:允许所有tcp sockets用于排队缓冲数据报的页面量,当内存占用超过此值,系统拒绝分配socket,后台日志输出“TCP: too many of orphaned sockets”。

一般情况下这些值是在系统启动时根据系统内存数量计算得到的。 根据当前tcp_mem最大内存页面数是1864896,当内存为(1864896*4)/1024K=7284.75M时,系统将无法为新的socket连接分配内存,即TCP连接将被拒绝。

实际测试环境中,据观察大概在99万个连接左右的时候(零头不算),进程被杀死,触发out of socket memory错误(dmesg命令查看获得)。每一个连接大致占用7.5K内存(下面给出计算方式),大致可算的此时内存占用情况(990000 * 7.5 / 1024K = 7251M)。

这样和tcp_mem最大页面值数量比较吻合,因此此值也需要修改。

三个TCP调整语句为:

echo "net.ipv4.tcp_mem = 786432 2097152 3145728">> /etc/sysctl.conf
echo "net.ipv4.tcp_rmem = 4096 4096 16777216">> /etc/sysctl.conf
echo "net.ipv4.tcp_wmem = 4096 4096 16777216">> /etc/sysctl.conf

备注: 为了节省内存,设置tcp读、写缓冲区都为4K大小,tcp_mem三个值分别为3G 8G 16G,tcp_rmem和tcp_wmem最大值也是16G。

目标达成

经过若干次的尝试,最终达到目标,1024000个持久连接。1024000数字是怎么得来的呢,两台物理机器各自发出64000个请求,两个配置为6G左右的centos测试端机器(绑定7个桥接或NAT连接)各自发出640007 = 448000。也就是 1024000 = (64000) + (64000) + (640007) + (64000*7), 共使用了16个网卡(物理网卡+虚拟网卡)。 
终端输出

......
online user 1023990
online user 1023991
online user 1023992
online user 1023993
online user 1023994
online user 1023995
online user 1023996
online user 1023997
online user 1023998
online user 1023999
online user 1024000

在线用户目标达到1024000个!

服务器状态信息

服务启动时内存占用:

                 total       used       free     shared    buffers     cached
     Mem:         10442        271      10171          0         22         78
     -/+ buffers/cache:        171      10271
     Swap:         8127          0       8127

系统达到1024000个连接后的内存情况(执行三次 free -m 命令,获取三次结果):

                 total       used       free     shared    buffers     cached
     Mem:         10442       7781       2661          0         22         78
     -/+ buffers/cache:       7680       2762
     Swap:         8127          0       8127
 
                  total       used       free     shared    buffers     cached
     Mem:         10442       7793       2649          0         22         78
     -/+ buffers/cache:       7692       2750
     Swap:         8127          0       8127
 
                  total       used       free     shared    buffers     cached
     Mem:         10442       7804       2638          0         22         79
     -/+ buffers/cache:       7702       2740
     Swap:         8127          0       8127
这三次内存使用分别是7680,7692,7702,这次不取平均值,取一个中等偏上的值,定为7701M。那么程序接收1024000个连接,共消耗了 7701M-171M = 7530M内存, 7530M*1024K / 1024000 = 7.53K, 每一个连接消耗内存在为7.5K左右,这和在连接达到512000时所计算较为吻合。 

虚拟机运行Centos内存占用,不太稳定,但一般相差不大,以上数值,仅供参考。

执行top -p 某刻输出信息:

   top - 17:23:17 up 18 min,  4 users,  load average: 0.33, 0.12, 0.11
     Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
     Cpu(s):  0.2%us,  6.3%sy,  0.0%ni, 80.2%id,  0.0%wa,  4.5%hi,  8.8%si,  0.0%st
     Mem:  10693580k total,  6479980k used,  4213600k free,    22916k buffers
     Swap:  8323056k total,        0k used,  8323056k free,    80360k cached
 
       PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                      
      2924 yongboy   20   0 82776  74m  508 R 51.3  0.7   3:53.95 server 

执行vmstate:

vmstat
procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu-----
 r b swpd free buff cache si so bi bo in cs us sy id wa st
 0 0 0 2725572 23008 80360 0 0 21 2 1012 894 0 9 89 2 0

获取当前socket连接状态统计信息:

cat /proc/net/sockstat
sockets: used 1024380
TCP: inuse 1024009 orphan 0 tw 0 alloc 1024014 mem 2
UDP: inuse 11 mem 1
UDPLITE: inuse 0
RAW: inuse 0
FRAG: inuse 0 memory 0

获取当前系统打开的文件句柄:

sysctl -a | grep file
fs.file-nr = 1025216 0 1048576
fs.file-max = 1048576

此时任何类似于下面查询操作都是一个慢,等待若干时间还不见得执行完毕。

netstat -nat|grep -i "8000"|grep ESTABLISHED|wc -l 
netstat -n | grep -i "8000" | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'

以上两个命令在二三十分钟过去了,还未执行完毕,只好停止。

小结

本次从头到尾的测试,所需要有的linux系统需要调整的参数也就是那么几个,汇总一下:

     echo "yongboy soft nofile 1048576" >> /etc/security/limits.conf 
    echo "yongboy hard nofile 1048576" >>  /etc/security/limits.conf
 
     echo "fs.file-max = 1048576" >> /etc/sysctl.conf
     echo "net.ipv4.ip_local_port_range = 1024 65535" >> /etc/sysctl.conf
 
     echo "net.ipv4.tcp_mem = 786432 2097152 3145728" >> /etc/sysctl.conf
     echo "net.ipv4.tcp_rmem = 4096 4096 16777216" >> /etc/sysctl.conf
     echo "net.ipv4.tcp_wmem = 4096 4096 16777216" >> /etc/sysctl.conf

其它没有调整的参数,仅仅因为它们暂时对本次测试没有带来什么影响,实际环境中需要结合需要调整类似于SO_KEEPALIVE、tcpmax_orphans等大量参数。

本文代表一次实践,不足之处,欢迎批评指正。





阅读(7024) | 评论(0) | 转发(7) |
给主人留下些什么吧!~~