基于管道通知的百万并发长连接server模型

时间:2024-01-10 17:38:56

0、前言

最近突然想了解怎样设计一个支持百万连接的后台server架构。

要设计一个支持百万连接的后台server,我们首先要知道会有哪些因素限制后台server的高并发连接,这里想到的因素有以下几点:

1、操作系统的参数设置能否支持百万并发连接;

2、操作系统维持百万并发长连接需要多少内存;

3、应用层面上维持百万并发长连接需要多少内存;

4、百万并发长连接的吞吐量是否超过了硬件网卡的限制。

在学习的过程中,主要针对的是1、2、4,第3点一般跟业务相关,这里暂时没有考虑。

本篇文章估计需要多次才能完成,现在初步的想法是先写一个demo程序,然后后面再慢慢测试优化。

1、后台设计

1.1 后台设计图

如下为后台的设计结构:

1、首先主进程根据机器CPU个数,创建对应数量的管道;

2、创建完对应的管道之后,再创建一样数量的线程,每个线程绑定一个CPU;

3、主进程开始初始化socket,然后accept,当接收到一个客户端连接时,就把conn_fd写到某个pipe中;

3、每个线程创建epoll,然后监听对应pipe的写端fd,当监听到pipe中有数据时,就读取该数据,格式化为fd,将该fd加入epoll进行监听。

基于管道通知的百万并发长连接server模型

1.2 编码实现

根据1.1的设计,我们编写代码,包括server模块和worker模块。server模块负责创建pipe、线程、和监听客户端连接;worker模块负责处理每个客户端的连接。代码如下所示:

1.2.0 common

 #ifndef _SERV_COMMON_H
#define _SERV_COMMON_H typedef struct {
int id;
int fd;
} thread_arg; #define SERV_PORT 9876
#define MAX_LINE 1024 #endif

1.2.1 worker

worker.h

 #ifndef _SERV_WORKER_H
#define _SERV_WORKER_H void *worker(void *arg); #endif

worker.cc

 #include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <pthread.h>
#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h> #include "common.h" #define MAXFDS 1000000
#define EVENTSIZE 1000 int taskset_thread_core(int core_id)
{
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset); pthread_t curr_tid = pthread_self();
return pthread_setaffinity_np(curr_tid, sizeof(cpu_set_t), &cpuset);
} int setnonblocking(int fd)
{
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFD, ) | O_NONBLOCK) == -) {
printf("fd %d set non blocking failed\n", fd);
return -;
} return ;
} void handle_req(int cli_fd)
{
char in_buff[MAX_LINE];
int ret, rs = ; while (rs) {
ret = recv(cli_fd, in_buff, , ); if (ret < ) {
if (errno == EAGAIN) {
printf("EAGAIN\n");
break;
} else {
printf("recv error: %d\n", errno);
close(cli_fd);
break;
}
} else if (ret == ) {
rs = ;
} if (ret == sizeof(in_buff))
rs = ;
else
rs = ;
} if (ret > ) {
send(cli_fd, in_buff, strlen(in_buff), );
}
} void run_epoll(int epfd, int pipe_fd)
{
int i, cli_fd, nfds;
struct epoll_event ev, events[EVENTSIZE];
char buff[]; ev.events = EPOLLIN | EPOLLET; while () {
nfds = epoll_wait(epfd, events, EVENTSIZE , -);
for (i = ; i < nfds; i++) {
// pipe msg, add connected fd to epoll
if (events[i].data.fd == pipe_fd) {
read(pipe_fd, buff, );
cli_fd = atoi(buff);
setnonblocking(cli_fd);
ev.data.fd = cli_fd; if (epoll_ctl(epfd, EPOLL_CTL_ADD, cli_fd, &ev) < ) {
printf("epoll add fd %d failed\n", cli_fd);
}
} else { // socket msg
cli_fd = events[i].data.fd;
handle_req(cli_fd);
}
}
}
} void *worker(void *arg)
{
int epfd, pipe_fd;
struct epoll_event ev; taskset_thread_core(((thread_arg*) arg)->id); pipe_fd = ((thread_arg*) arg)->fd;
epfd = epoll_create(MAXFDS);
setnonblocking(pipe_fd);
ev.data.fd = pipe_fd;
ev.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, pipe_fd, &ev) < ) {
printf("epoll add mq fail\n");
} run_epoll(epfd, pipe_fd); return ;
}

1.2.2 server

 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/socket.h> #include "common.h"
#include "worker.h" int start_listen()
{
int fd, opt = ;
struct sockaddr_in servaddr; bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY); if ((fd = socket(AF_INET, SOCK_STREAM, )) < ) {
printf("open socket failed!\n");
exit();
} setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); if ((bind(fd, (struct sockaddr*) &servaddr, sizeof(servaddr))) < ) {
printf("bind failed!\n");
exit();
} if (listen(fd, SOMAXCONN) < ) {
printf("listen failed!\n");
exit();
} return fd;
} int main(int argc, char **argv)
{
int i, num_cores, listen_fd, cli_fd;
char name[]; listen_fd = start_listen(); num_cores = sysconf(_SC_NPROCESSORS_ONLN);
printf("core num: %d\n", num_cores); int pipe_fd[num_cores][];
thread_arg targ[num_cores];
pthread_t tid[num_cores];
pthread_attr_t attr; if (pthread_attr_init(&attr) != ) {
perror("pthrad attr init error: ");
exit();
} if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != ) {
perror("pthread set attr detached error: ");
exit();
} for (i = ; i < num_cores; i++) {
pipe(pipe_fd[i]);
targ[i] = (thread_arg) {i, pipe_fd[i][]}; if (pthread_create(&tid[i], &attr, worker, &targ[i]) != ) {
perror("pthread create error: ");
exit();
}
} pthread_attr_destroy(&attr);
sleep();
printf("server started\n\n"); while ((cli_fd = accept(listen_fd, NULL, NULL)) > ) {
sprintf(name, "%d", cli_fd);
i = cli_fd % num_cores;
write(pipe_fd[i][], name, strlen(name));
} close(listen_fd); for (i = ; i < num_cores; i++) {
close(pipe_fd[i][]);
} return ;
}

写完后台代码之后,开始测试能支持多少连接,但测试过程中一直有问题,会报如下的错误:error: Cannot assign requested address。

google了一下,说是因为短时间内大量短连接造成TIME_WAIT耗尽端口问题,不明白我的测试代码怎么是短连接,而不是长连接。

我的客户端代码如下,不知道是哪里出问题了。

#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h> void process_conn_svr(const char *svr_ip, int svr_port); int connections = ; #define MAX_CONN 1005000
int fd[MAX_CONN]; int main(int argc, char **argv)
{
if (argc <= ) {
printf("usage: %s ip port\n", argv[]);
exit();
}
const char *ip = argv[];
int port = atoi(argv[]); pid_t pid = fork();
if (pid == ) {
process_conn_svr(ip, port);
} const char buf[] = "keepalive!";
for (;;) {
usleep(*);
for (int i = ; i < MAX_CONN; ++i) {
if (fd[i] != ) {
send(fd[i], buf, sizeof(buf), );
}
}
}
return ; } void process_conn_svr(const char *svr_ip, int svr_port)
{
int conn_idx = ;
for (;;) {
struct sockaddr_in serv_addr;
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
inet_pton(AF_INET, svr_ip, &serv_addr.sin_addr); serv_addr.sin_port = htons(svr_port);
int cli_fd = socket(AF_INET, SOCK_STREAM, );
if (cli_fd == -) {
goto sock_err;
} if (connect(cli_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -) {
goto sock_err;
} fd[conn_idx] = cli_fd;
conn_idx++; connections++;
printf("connections: %d, fd: %d\n", connections, cli_fd); if (connections % == ) {
printf("press Enter to continue: ");
getchar();
}
usleep(*);
} sock_err:
printf("error: %s\n", strerror(errno));
}